1 package net.jaekl.squelch;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.PrintWriter;
7 import java.util.Properties;
9 import net.jaekl.squelch.util.FileUtil;
11 import org.apache.commons.cli.CommandLine;
12 import org.apache.commons.cli.DefaultParser;
13 import org.apache.commons.cli.HelpFormatter;
14 import org.apache.commons.cli.Options;
15 import org.apache.commons.cli.ParseException;
18 private static final String DB_URL = "db.url";
19 private static final String DB_PASSWORD = "db.password";
20 private static final String DB_USER = "db.user";
21 private static final String DEFAULT_CONFIG_FILENAME = "config.properties";
22 public static final String DEFAULT_JDBC_URL = "jdbc:postgresql:postgres"; // default PostgreSQL database
24 private String m_className; // name of the main class that launches this program
25 private boolean m_help;
27 private String m_pass;
28 private String m_user;
30 public Args(String className) {
31 m_className = className;
33 m_url = DEFAULT_JDBC_URL;
38 public boolean isHelp() { return m_help; }
39 public String getUrl() { return m_url; }
40 public String getPass() { return m_pass; }
41 public String getUser() { return m_user; }
43 public Options createOptions()
45 Options opt = new Options();
47 opt.addOption("c", "config", true, "Config file");
48 opt.addOption("h", "help", false, "Show usage information");
49 opt.addOption("r", "url", true, "DB JDBC URL");
50 opt.addOption("p", "password", true, "DB password");
51 opt.addOption("u", "user", true, "DB username");
56 public boolean parseArgs(PrintWriter pw, String[] args) throws IOException
58 Options opt = createOptions();
60 CommandLine line = new DefaultParser().parse(opt, args);
62 String configFilename = (line.hasOption("c")) ? (line.getOptionValue("c")) : (DEFAULT_CONFIG_FILENAME);
63 File configFile = FileUtil.getInst().newFile(configFilename);
64 if (line.hasOption("c") || configFile.canRead()) {
65 readConfigFile(configFile);
68 m_help = line.hasOption("h");
70 if (line.hasOption("p")) {
71 m_pass = line.getOptionValue("p");
73 if (line.hasOption("r")) {
74 m_url = line.getOptionValue("r");
76 if (line.hasOption("u")) {
77 m_user = line.getOptionValue("u");
80 catch (ParseException exc) {
92 void readConfigFile(File configFile) throws IOException
94 Properties props = new Properties();
95 try (InputStream is = FileUtil.getInst().openStream(configFile)) {
99 m_url = props.getProperty(DB_URL, "");
100 m_pass = props.getProperty(DB_PASSWORD, "");
101 m_user = props.getProperty(DB_USER, "");
104 // Note that this leverages commons-cli's HelpFormatter to
105 // generate the usage message. It will always be in English.
106 // If we want to localize that, we'd need to recode this,
107 // and also translate the parameter descriptions in
109 void usage(PrintWriter pw, Options opt)
111 HelpFormatter help = new HelpFormatter();
112 help.printHelp(pw, 80, m_className, "", opt, 0, 0, "", true);