Currently job artifacts in CI/CD pipelines on LRZ GitLab never expire. Starting from Wed 26.1.2022 the default expiration time will be 30 days (GitLab default). Currently existing artifacts in already completed jobs will not be affected by the change. The latest artifacts for all jobs in the latest successful pipelines will be kept. More information: https://gitlab.lrz.de/help/user/admin_area/settings/continuous_integration.html#default-artifacts-expiration

Commit 25bcc7b9 authored by Daniel Lehmberg's avatar Daniel Lehmberg
Browse files

Merge branch 'argument_parser' into 'master'

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

See merge request !75
parents 1ae05e2b c3ae8c12
Pipeline #132236 passed with stages
in 114 minutes and 43 seconds
package org.vadere.gui.postvisualization; 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.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.Logger;
import org.vadere.util.logging.StdOutErrLog; import org.vadere.util.logging.StdOutErrLog;
public class PostVisualisation { public class PostVisualisation {
// TODO: Move logic to read/write config file to "VadereConfig.java".
private static Logger logger = Logger.getLogger(PostVisualisation.class); private static Logger logger = Logger.getLogger(PostVisualisation.class);
public static void main(String[] args) { public static void main(String[] args) {
StdOutErrLog.addStdOutErrToLog(); StdOutErrLog.addStdOutErrToLog();
logger.info("starting post visualization ..."); logger.info("starting Vadere PostVisualization...");
// load settings
logger.info("preferences started"); VadereArgumentParser vadereArgumentParser = new VadereArgumentParser();
// start main gui 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(); PostvisualizationWindow.start();
logger.info("post visualization started");
} }
} }
...@@ -42,9 +42,6 @@ import java.util.Optional; ...@@ -42,9 +42,6 @@ import java.util.Optional;
/** /**
* Main Window of the new post visualization. * Main Window of the new post visualization.
*
* @Version 1.0
*
*/ */
public class PostvisualizationWindow extends JPanel implements Observer, DropTargetListener { public class PostvisualizationWindow extends JPanel implements Observer, DropTargetListener {
private static final long serialVersionUID = -8177132133860336295L; private static final long serialVersionUID = -8177132133860336295L;
......
package org.vadere.gui.projectview; 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.components.utils.Messages;
import org.vadere.gui.projectview.view.ProjectView; 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.Logger;
import org.vadere.util.logging.StdOutErrLog; import org.vadere.util.logging.StdOutErrLog;
...@@ -20,10 +22,24 @@ public class VadereApplication { ...@@ -20,10 +22,24 @@ public class VadereApplication {
StdOutErrLog.addStdOutErrToLog(); StdOutErrLog.addStdOutErrToLog();
logger.info("starting Vadere GUI..."); 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); Messages.loadLanguageFromPreferences(VadereApplication.class);
// start main gui
ProjectView.start(); ProjectView.start();
} }
......
...@@ -158,12 +158,5 @@ ...@@ -158,12 +158,5 @@
<artifactId>meshing</artifactId> <artifactId>meshing</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>net.sourceforge.argparse4j</groupId>
<artifactId>argparse4j</artifactId>
<version>0.4.3</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
This diff is collapsed.
package org.vadere.simulator.entrypoints.cmd; package org.vadere.simulator.entrypoints.cmd;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments; import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.*;
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 org.vadere.simulator.entrypoints.Version; import org.vadere.simulator.entrypoints.Version;
import org.vadere.simulator.entrypoints.cmd.commands.MigrationSubCommand; import org.vadere.simulator.entrypoints.cmd.commands.MigrationSubCommand;
import org.vadere.simulator.entrypoints.cmd.commands.ProjectRunSubCommand; import org.vadere.simulator.entrypoints.cmd.commands.ProjectRunSubCommand;
import org.vadere.simulator.entrypoints.cmd.commands.ScenarioRunSubCommand; import org.vadere.simulator.entrypoints.cmd.commands.ScenarioRunSubCommand;
import org.vadere.simulator.entrypoints.cmd.commands.SuqSubCommand; import org.vadere.simulator.entrypoints.cmd.commands.SuqSubCommand;
import org.vadere.simulator.utils.scenariochecker.ScenarioChecker; import org.vadere.simulator.utils.scenariochecker.ScenarioChecker;
import org.vadere.util.io.VadereArgumentParser;
import org.vadere.util.logging.Logger; import org.vadere.util.logging.Logger;
import org.vadere.util.logging.StdOutErrLog; import org.vadere.util.logging.StdOutErrLog;
import java.util.Arrays;
/** /**
* Provides the possibility to start Vadere in console mode. * Provides the possibility to start Vadere in console mode.
* Do not use Logging in this Class! The Logging framework needs information generated here * Do not use Logging in this Class! The Logging framework needs information generated here
...@@ -29,62 +21,32 @@ public class VadereConsole { ...@@ -29,62 +21,32 @@ public class VadereConsole {
public static void main(String[] args) { public static void main(String[] args) {
Logger.setMainArguments(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"}; VadereArgumentParser vadereArgumentParser = new VadereArgumentParser();
// args = tmp; ArgumentParser argumentParser = vadereArgumentParser.getArgumentParser();
ArgumentParser parser = createArgumentParser();
addSubCommandsToParser(argumentParser);
try { try {
//if (!CLUtils.isOpenCLSupported()) { Namespace ns = vadereArgumentParser.parseArgsAndProcessOptions(args);
// System.out.println("Warning: OpenCL acceleration disabled, since no OpenCL support could be found!");
//}
Namespace ns = parser.parseArgs(args);
SubCommandRunner sRunner = ns.get("func"); SubCommandRunner sRunner = ns.get("func");
StdOutErrLog.addStdOutErrToLog(); StdOutErrLog.addStdOutErrToLog();
sRunner.run(ns, parser); sRunner.run(ns, argumentParser);
} catch (UnsatisfiedLinkError linkError) { } catch (UnsatisfiedLinkError linkError) {
System.err.println("[LWJGL]: " + linkError.getMessage()); System.err.println("[LWJGL]: " + linkError.getMessage());
} catch (ArgumentParserException e) { } catch (ArgumentParserException e) {
parser.handleError(e); argumentParser.handleError(e);
System.exit(1); System.exit(1);
} catch (Exception e) { } catch (Exception e) {
System.err.println("topographyError in command:" + e.getMessage()); System.err.println("Cannot start vadere-console: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
} }
} }
private static ArgumentParser createArgumentParser() { // TODO: Move this method to "VadereArgumentParser".
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.");
}
private static void addSubCommandsToParser(ArgumentParser parser) { private static void addSubCommandsToParser(ArgumentParser parser) {
Subparsers subparsers = parser.addSubparsers() Subparsers subparsers = parser.addSubparsers()
.title("subcommands") .title("subcommands")
...@@ -94,7 +56,7 @@ public class VadereConsole { ...@@ -94,7 +56,7 @@ public class VadereConsole {
// Run Project // Run Project
Subparser projectRun = subparsers Subparser projectRun = subparsers
.addParser(SubCommand.PROJECT_RUN.getCmdName()) .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()); .setDefault("func", new ProjectRunSubCommand());
projectRun.addArgument("--project-dir", "-p") projectRun.addArgument("--project-dir", "-p")
.required(true) .required(true)
......
...@@ -71,6 +71,11 @@ ...@@ -71,6 +71,11 @@
<classifier>${lwjgl.natives}</classifier> <classifier>${lwjgl.natives}</classifier>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency>
<groupId>net.sourceforge.argparse4j</groupId>
<artifactId>argparse4j</artifactId>
<version>0.4.3</version>
</dependency>
</dependencies> </dependencies>
<!-- end generated by lwjgl --> <!-- end generated by lwjgl -->
<profiles> <profiles>
...@@ -102,4 +107,4 @@ ...@@ -102,4 +107,4 @@
</properties> </properties>
</profile> </profile>
</profiles> </profiles>
</project> </project>
\ No newline at end of file
...@@ -10,13 +10,11 @@ import org.apache.commons.configuration2.ex.ConfigurationException; ...@@ -10,13 +10,11 @@ import org.apache.commons.configuration2.ex.ConfigurationException;
import org.vadere.util.logging.Logger; import org.vadere.util.logging.Logger;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
...@@ -42,14 +40,15 @@ public class VadereConfig { ...@@ -42,14 +40,15 @@ public class VadereConfig {
// Static Variables // Static Variables
private static final Logger LOGGER = Logger.getLogger(VadereConfig.class); private static final Logger LOGGER = Logger.getLogger(VadereConfig.class);
private static final String CONFIG_FILENAME = "vadere.conf"; private static final String DEFAULT_HOME_DIR = System.getProperty("user.home");
private static final String HOME_DIR = System.getProperty("user.home"); private static final String DEFAULT_CONFIG_DIR = ".config";
private static final String CONFIG_DIR = ".config";
private static final Path PATH_TO_CONFIG_DIR = Path.of(HOME_DIR, CONFIG_DIR); // Both variables must not be "final" so that we are able
private static final Path PATH_TO_CONFIG = Path.of(HOME_DIR, CONFIG_DIR, CONFIG_FILENAME); // 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 // Variables
private FileBasedConfiguration vadereConfig; private FileBasedConfiguration vadereConfig;
...@@ -58,10 +57,13 @@ public class VadereConfig { ...@@ -58,10 +57,13 @@ public class VadereConfig {
private VadereConfig() { private VadereConfig() {
createDefaultConfigIfNonExisting(); 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() PropertiesBuilderParameters propertiesParams = new Parameters()
.properties() .properties()
.setFileName(CONFIG_FILENAME) .setFileName(CONFIG_FILENAME)
.setBasePath(PATH_TO_CONFIG.getParent().toString()); .setBasePath(basePath);
FileBasedConfigurationBuilder<FileBasedConfiguration> builder = FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class) new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
...@@ -71,26 +73,26 @@ public class VadereConfig { ...@@ -71,26 +73,26 @@ public class VadereConfig {
try { try {
vadereConfig = builder.getConfiguration(); vadereConfig = builder.getConfiguration();
} catch (ConfigurationException ex) { } 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"); LOGGER.info("Create and use default config");
} }
} }
private void createDefaultConfigIfNonExisting() { private void createDefaultConfigIfNonExisting() {
try { // Ensure that config directory exists. 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) { } 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(); Map<String, String> defaultConfig = getDefaultConfig();
try { 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( Files.write(
PATH_TO_CONFIG, CONFIG_PATH,
defaultConfig defaultConfig
.entrySet() .entrySet()
.stream() .stream()
...@@ -98,12 +100,23 @@ public class VadereConfig { ...@@ -98,12 +100,23 @@ public class VadereConfig {
.sorted(String::compareTo) .sorted(String::compareTo)
.collect(Collectors.toList())); .collect(Collectors.toList()));
} catch (IOException e) { } 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. * Use Apache Common Configuration API on the returned object to retrieve Vadere's config options.
* *
...@@ -112,6 +125,10 @@ public class VadereConfig { ...@@ -112,6 +125,10 @@ public class VadereConfig {
* @return A Configuration object from Apache Common Configuration library. * @return A Configuration object from Apache Common Configuration library.
*/ */
public static Configuration getConfig() { public static Configuration getConfig() {
if (SINGLETON_INSTANCE == null) {
SINGLETON_INSTANCE = new VadereConfig();
}
return SINGLETON_INSTANCE.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 { ...@@ -52,8 +52,8 @@ public class BundleManager {
} }
public void setLanguage(Class<?> clazz){ public void setLanguage(Class<?> clazz){
String language = VadereConfig.getConfig().getString("language", null); String language = VadereConfig.getConfig().getString("Messages.language", null);
Locale locale =defaultLocale; Locale locale = defaultLocale;
if (language != null) { if (language != null) {
switch (language) { switch (language) {
case "de": 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