use of org.apache.commons.cli.CommandLineParser in project opennms by OpenNMS.
the class SystemReport method main.
/**
* @param args
*/
public static void main(final String[] args) throws Exception {
final String tempdir = System.getProperty("java.io.tmpdir");
// pull out -D defines first
for (final String arg : args) {
if (arg.startsWith("-D") && arg.contains("=")) {
final Matcher m = m_pattern.matcher(arg);
if (m.matches()) {
System.setProperty(m.group(1), m.group(2));
}
}
}
if (System.getProperty("opennms.home") == null) {
System.setProperty("opennms.home", tempdir);
}
if (System.getProperty("rrd.base.dir") == null) {
System.setProperty("rrd.base.dir", tempdir);
}
if (System.getProperty("rrd.binary") == null) {
System.setProperty("rrd.binary", "/usr/bin/rrdtool");
}
final CommandLineParser parser = new PosixParser();
final Options options = new Options();
options.addOption("h", "help", false, "this help");
options.addOption("D", "define", true, "define a java property");
options.addOption("p", "list-plugins", false, "list the available system report plugins");
options.addOption("u", "use-plugins", true, "select the plugins to output");
options.addOption("l", "list-formats", false, "list the available output formats");
options.addOption("f", "format", true, "the format to output");
options.addOption("o", "output", true, "the file to write output to");
final CommandLine line = parser.parse(options, args, false);
final Set<String> plugins = new LinkedHashSet<String>();
final SystemReport report = new SystemReport();
// help
if (line.hasOption("h")) {
final HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("system-report.sh [options]", options);
System.exit(0);
}
// format and output file
if (line.hasOption("f")) {
report.setFormat(line.getOptionValue("f"));
}
if (line.hasOption("o")) {
report.setOutput(line.getOptionValue("o"));
}
if (line.hasOption("u")) {
final String value = line.getOptionValue("u");
if (value != null) {
for (final String s : value.split(",+")) {
plugins.add(s);
}
}
}
// final command
if (line.hasOption("p")) {
report.listPlugins();
} else if (line.hasOption("l")) {
report.listFormats();
} else {
report.writePluginData(plugins);
}
}
use of org.apache.commons.cli.CommandLineParser in project opennms by OpenNMS.
the class VmwareConfigBuilder method main.
public static void main(String[] args) throws ParseException {
String hostname = null;
String username = null;
String password = null;
String rrdRepository = null;
final Options options = new Options();
options.addOption("rrdRepository", true, "set rrdRepository path for generated config files, default: '/opt/opennms/share/rrd/snmp/'");
final CommandLineParser parser = new PosixParser();
final CommandLine cmd = parser.parse(options, args);
@SuppressWarnings("unchecked") List<String> arguments = (List<String>) cmd.getArgList();
if (arguments.size() < 3) {
usage(options, cmd);
System.exit(1);
}
hostname = arguments.remove(0);
username = arguments.remove(0);
password = arguments.remove(0);
if (cmd.hasOption("rrdRepository")) {
rrdRepository = cmd.getOptionValue("rrdRepository");
} else {
rrdRepository = "/opt/opennms/share/rrd/snmp/";
}
TrustManager[] trustAllCerts = new TrustManager[] { new AnyServerX509TrustManager() };
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
VmwareConfigBuilder vmwareConfigBuilder;
vmwareConfigBuilder = new VmwareConfigBuilder(hostname, username, password);
try {
vmwareConfigBuilder.generateData(rrdRepository);
} catch (Exception e) {
e.printStackTrace();
}
}
use of org.apache.commons.cli.CommandLineParser in project opennms by OpenNMS.
the class SpectrumTrapImporter method configureArgs.
private void configureArgs(String[] argv) {
Options opts = new Options();
opts.addOption("d", "dir", true, "Directory where Spectrum custom events are located");
opts.addOption("t", "model-type-asset-field", true, "Name of asset field containing equivalent of Spectrum model type. Defaults to 'manufacturer'.");
opts.addOption("u", "base-uei", true, "Base value for UEI of generated OpenNMS events. Defaults to 'uei.opennms.org/import/Spectrum'.");
opts.addOption("f", "output-file", true, "File to which OpenNMS events will be written. Defaults to standard output.");
opts.addOption("k", "key", true, "Middle part of reduction- and clear-key, after UEI and before discriminators. Defaults to '%dpname%:%nodeid%:%interface%'.");
CommandLineParser parser = new GnuParser();
try {
CommandLine cmd = parser.parse(opts, argv);
if (cmd.hasOption('d')) {
m_customEventsDir = new FileSystemResource(cmd.getOptionValue('d'));
}
if (cmd.hasOption('t')) {
m_modelTypeAssetField = cmd.getOptionValue('t');
} else {
m_modelTypeAssetField = "manufacturer";
}
if (cmd.hasOption('u')) {
m_baseUei = cmd.getOptionValue('u');
} else {
m_baseUei = "uei.opennms.org/import/Spectrum";
}
if (cmd.hasOption('f')) {
m_outputWriter = new PrintWriter(new FileSystemResource(cmd.getOptionValue('f')).getFile());
} else {
m_outputWriter = new PrintWriter(System.out);
}
if (cmd.hasOption('k')) {
m_reductionKeyBody = cmd.getOptionValue('k');
} else {
m_reductionKeyBody = "%dpname%:%nodeid%:%interface%";
}
} catch (ParseException pe) {
printHelp("Failed to parse command line options");
System.exit(1);
} catch (FileNotFoundException fnfe) {
printHelp("Custom events input directory does not seem to exist");
}
}
use of org.apache.commons.cli.CommandLineParser in project opennms by OpenNMS.
the class CheckWmi method main.
/**
* <p>main</p>
*
* @param args an array of {@link java.lang.String} objects.
* @throws org.apache.commons.cli.ParseException if any.
*/
public static void main(final String[] args) throws ParseException {
final Options options = new Options();
options.addOption("domain", true, "the NT/AD domain the credentials belong to");
options.addOption("wmiClass", true, "the object class in WMI to query");
options.addOption("wmiNamespace", true, "the namespace in WMI to use (default: " + WmiParams.WMI_DEFAULT_NAMESPACE + ")");
options.addOption("wmiObject", true, "the object to query in WMI");
options.addOption("wmiWql", true, "the query string to execute in WMI");
options.addOption("op", true, "compare operation: NOOP, EQ, NEQ, GT, LT");
options.addOption("value", true, "the value to compare to");
options.addOption("matchType", true, "type of matching for multiple results: all, none, some, one");
final CommandLineParser parser = new PosixParser();
final CommandLine cmd = parser.parse(options, args);
@SuppressWarnings("unchecked") List<String> arguments = (List<String>) cmd.getArgList();
if (arguments.size() < 3) {
usage(options, cmd);
System.exit(1);
}
final String host = arguments.remove(0);
final String user = arguments.remove(0);
final String pass = arguments.remove(0);
String wmiClass = "";
if (cmd.hasOption("wmiClass")) {
wmiClass = cmd.getOptionValue("wmiClass");
}
/* else {
usage(options, cmd);
System.exit(1);
}*/
String wmiObject = "";
if (cmd.hasOption("wmiObject")) {
wmiObject = cmd.getOptionValue("wmiObject");
} else {
usage(options, cmd);
System.exit(1);
}
String wmiNamespace = WmiParams.WMI_DEFAULT_NAMESPACE;
if (cmd.hasOption("wmiNamespace")) {
wmiNamespace = cmd.getOptionValue("wmiNamespace");
}
String wmiWql = "";
if (cmd.hasOption("wmiWql")) {
wmiWql = cmd.getOptionValue("wmiWql");
}
/*else {
usage(options, cmd);
System.exit(1);
} */
String compVal = "";
if (cmd.hasOption("value")) {
compVal = cmd.getOptionValue("value");
} else {
usage(options, cmd);
System.exit(1);
}
String compOp = "";
if (cmd.hasOption("op")) {
compOp = cmd.getOptionValue("op");
} else {
usage(options, cmd);
System.exit(1);
}
String domain = "";
if (cmd.hasOption("domain")) {
domain = cmd.getOptionValue("domain");
}
String matchType = "all";
if (cmd.hasOption("matchType")) {
matchType = cmd.getOptionValue("matchType");
}
try {
// Hold the WMI objects from the results.
List<Object> wmiObjects;
// Create the check parameters holder.
WmiParams clientParams;
if (wmiWql == null || wmiWql.length() == 0)
clientParams = new WmiParams(WmiParams.WMI_OPERATION_INSTANCEOF, compVal, compOp, wmiClass, wmiObject);
else
clientParams = new WmiParams(WmiParams.WMI_OPERATION_WQL, compVal, compOp, wmiWql, wmiObject);
// Create the WMI Manager
final WmiManager mgr = new WmiManager(host, user, pass, domain, matchType);
mgr.setNamespace(wmiNamespace);
// Connect to the WMI server.
mgr.init();
// Perform the operation specified in the parameters.
final WmiResult result = mgr.performOp(clientParams);
// And retrieve the WMI objects from the results.
wmiObjects = result.getResponse();
// Now output a brief report of the check results.
System.out.println("Checking: " + wmiWql + " for " + wmiObject + " Op: " + compOp + " Val: " + compVal);
System.out.println("Check results: " + WmiResult.convertStateToString(result.getResultCode()) + " (" + wmiObjects.size() + ")");
for (int i = 0; i < wmiObjects.size(); i++) {
System.out.println("Result for (" + (i + 1) + ") " + wmiClass + "\\" + wmiObject + ": " + wmiObjects.get(i));
}
// Disconnect when we're done.
mgr.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
use of org.apache.commons.cli.CommandLineParser in project shifu by ShifuML.
the class ShifuCLI method main.
public static void main(String[] args) {
// get -D parameters at first and set it in Environment then clean args
List<String> cleanedArgsList = new ArrayList<String>();
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("-D")) {
// remove '-D' at first
String keyValue = args[i].substring(2, args[i].length());
int index = keyValue.indexOf("=");
String key = keyValue.substring(0, index);
String value = "";
if (keyValue.length() >= index + 1) {
value = keyValue.substring(index + 1, keyValue.length());
}
// set to Environment for others to read
Environment.setProperty(key.trim(), value.trim());
// such parameter will also be set in system properties for later reference in correlation and others
System.setProperty(key.trim(), value.trim());
cleanedArgsList.add(args[i]);
}
}
String[] cleanedArgs = cleanedArgsList.toArray(new String[0]);
// invalid input and help options
if (cleanedArgs.length < 1 || (isHelpOption(cleanedArgs[0]))) {
printUsage();
System.exit(cleanedArgs.length < 1 ? -1 : 0);
}
// process -v and -version conditions manually
if (isVersionOption(cleanedArgs[0])) {
printLogoAndVersion();
System.exit(0);
}
CommandLineParser parser = new GnuParser();
Options opts = buildModelSetOptions(cleanedArgs);
CommandLine cmd = null;
try {
cmd = parser.parse(opts, cleanedArgs);
} catch (ParseException e) {
log.error("Invalid command options. Please check help message.");
printUsage();
System.exit(1);
}
int status = 0;
try {
if (cleanedArgs[0].equals(NEW) && cleanedArgs.length >= 2 && StringUtils.isNotEmpty(cleanedArgs[1])) {
// modelset step
String modelName = cleanedArgs[1];
status = createNewModel(modelName, cmd.getOptionValue(MODELSET_CMD_TYPE), cmd.getOptionValue(MODELSET_CMD_M));
if (status == 0) {
printModelSetCreatedSuccessfulLog(modelName);
} else {
log.warn("Error in create new model set, please check your shifu config or report issue");
}
System.exit(status);
// copyModel(manager, cmd.getOptionValues(MODELSET_CMD_CP));
} else {
if (cleanedArgs[0].equals(MODELSET_CMD_CP) && cleanedArgs.length >= 3 && StringUtils.isNotEmpty(cleanedArgs[1]) && StringUtils.isNotEmpty(cleanedArgs[2])) {
String newModelSetName = cleanedArgs[2];
// modelset step
copyModel(new String[] { cleanedArgs[1], newModelSetName });
printModelSetCopiedSuccessfulLog(newModelSetName);
} else if (cleanedArgs[0].equals(INIT_CMD)) {
// init step
if (cmd.getOptions() == null || cmd.getOptions().length == 0) {
status = initializeModel();
if (status == 0) {
log.info("ModelSet initilization is successful. Please continue next step by using 'shifu stats'.");
} else {
log.warn("Error in ModelSet initilization, please check your shifu config or report issue");
}
} else if (cmd.hasOption(INIT_CMD_MODEL)) {
initializeModelParam();
} else {
log.error("Invalid command, please check help message.");
printUsage();
}
} else if (cleanedArgs[0].equals(STATS_CMD)) {
Map<String, Object> params = new HashMap<String, Object>();
params.put(StatsModelProcessor.IS_COMPUTE_CORR, cmd.hasOption(CORRELATION) || cmd.hasOption("c"));
params.put(StatsModelProcessor.IS_REBIN, cmd.hasOption(REBIN));
params.put(StatsModelProcessor.REQUEST_VARS, cmd.getOptionValue(VARS));
params.put(StatsModelProcessor.EXPECTED_BIN_NUM, cmd.getOptionValue(N));
params.put(StatsModelProcessor.IV_KEEP_RATIO, cmd.getOptionValue(IVR));
params.put(StatsModelProcessor.MINIMUM_BIN_INST_CNT, cmd.getOptionValue(BIC));
// stats step
status = calModelStats(params);
if (status == 0) {
if (cmd.hasOption(CORRELATION) || cmd.hasOption("c")) {
log.info("Do model set correlation computing successfully. Please continue next step by using 'shifu normalize or shifu norm'. For tree ensemble model, no need do norm, please continue next step by using 'shifu varsel'");
} else {
log.info("Do model set statistic successfully. Please continue next step by using 'shifu normalize or shifu norm'. For tree ensemble model, no need do norm, please continue next step by using 'shifu varsel'");
}
} else {
log.warn("Error in model set stats computation, please report issue on http:/github.com/shifuml/shifu/issues.");
}
} else if (cleanedArgs[0].equals(NORMALIZE_CMD) || cleanedArgs[0].equals(NORM_CMD)) {
// normalize step
status = normalizeTrainData(cmd.hasOption(SHUFFLE));
if (status == 0) {
log.info("Do model set normalization successfully. Please continue next step by using 'shifu varselect or shifu varsel'.");
} else {
log.warn("Error in model set stats computation, please report issue on http:/github.com/shifuml/shifu/issues.");
}
} else if (cleanedArgs[0].equals(VARSELECT_CMD) || cleanedArgs[0].equals(VARSEL_CMD)) {
// variable selected step
status = selectModelVar(cmd.hasOption(RESET), cmd.hasOption(LIST));
if (status == 0) {
log.info("Do model set variables selection successfully. Please continue next step by using 'shifu train'.");
} else {
log.info("Do variable selection with error, please check error message or report issue.");
}
} else if (cleanedArgs[0].equals(TRAIN_CMD)) {
// train step
status = trainModel(cmd.hasOption(TRAIN_CMD_DRY), cmd.hasOption(TRAIN_CMD_DEBUG), cmd.hasOption(SHUFFLE));
if (status == 0) {
log.info("Do model set training successfully. Please continue next step by using 'shifu posttrain' or if no need posttrain you can go through with 'shifu eval'.");
} else {
log.info("Do model training with error, please check error message or report issue.");
}
} else if (cleanedArgs[0].equals(CMD_COMBO)) {
if (cmd.hasOption(MODELSET_CMD_NEW)) {
log.info("Create new commbo models");
status = createNewCombo(cmd.getOptionValue(MODELSET_CMD_NEW));
} else if (cmd.hasOption(INIT_CMD)) {
log.info("Init commbo models");
status = initComboModels();
} else if (cmd.hasOption(EVAL_CMD_RUN)) {
log.info("Run combo model - with toShuffle: {}, with toResume: {}", opts.hasOption(SHUFFLE), opts.hasOption(RESUME));
status = runComboModels(cmd.hasOption(SHUFFLE), cmd.hasOption(RESUME));
// train combo models
} else if (cmd.hasOption(EVAL_CMD)) {
log.info("Eval combo model.");
// eval combo model performance
status = evalComboModels(cmd.hasOption(RESUME));
} else {
log.error("Invalid command usage.");
printUsage();
}
} else if (cleanedArgs[0].equals(POSTTRAIN_CMD)) {
// post train step
status = postTrainModel();
if (status == 0) {
log.info("Do model set post-training successfully. Please configurate your eval set in ModelConfig.json and continue next step by using 'shifu eval' or 'shifu eval -new <eval set>' to create a new eval set.");
} else {
log.info("Do model post training with error, please check error message or report issue.");
}
} else if (cleanedArgs[0].equals(SAVE)) {
String newModelSetName = cleanedArgs.length >= 2 ? cleanedArgs[1] : null;
saveCurrentModel(newModelSetName);
} else if (cleanedArgs[0].equals(SWITCH)) {
String newModelSetName = cleanedArgs[1];
switchCurrentModel(newModelSetName);
} else if (cleanedArgs[0].equals(SHOW)) {
ManageModelProcessor p = new ManageModelProcessor(ModelAction.SHOW, null);
p.run();
} else if (cleanedArgs[0].equals(EVAL_CMD)) {
// eval step
if (cleanedArgs.length == 1) {
// run everything
status = runEvalSet(cmd.hasOption(TRAIN_CMD_DRY));
if (status == 0) {
log.info("Run eval performance with all eval sets successfully.");
} else {
log.info("Do evaluation with error, please check error message or report issue.");
}
} else if (cmd.getOptionValue(MODELSET_CMD_NEW) != null) {
// create new eval
createNewEvalSet(cmd.getOptionValue(MODELSET_CMD_NEW));
log.info("Create eval set successfully. You can configurate EvalConfig.json or directly run 'shifu eval -run <evalSetName>' to get performance info.");
} else if (cmd.hasOption(EVAL_CMD_RUN)) {
runEvalSet(cmd.getOptionValue(EVAL_CMD_RUN), cmd.hasOption(TRAIN_CMD_DRY));
log.info("Finish run eval performance with eval set {}.", cmd.getOptionValue(EVAL_CMD_RUN));
} else if (cmd.hasOption(SCORE)) {
// run score
runEvalScore(cmd.getOptionValue(SCORE));
log.info("Finish run score with eval set {}.", cmd.getOptionValue(SCORE));
} else if (cmd.hasOption(CONFMAT)) {
// run confusion matrix
runEvalConfMat(cmd.getOptionValue(CONFMAT));
log.info("Finish run confusion matrix with eval set {}.", cmd.getOptionValue(CONFMAT));
} else if (cmd.hasOption(PERF)) {
// run perfermance
runEvalPerf(cmd.getOptionValue(PERF));
log.info("Finish run performance maxtrix with eval set {}.", cmd.getOptionValue(PERF));
} else if (cmd.hasOption(LIST)) {
// list all evaluation sets
listEvalSet();
} else if (cmd.hasOption(DELETE)) {
// delete some evaluation set
deleteEvalSet(cmd.getOptionValue(DELETE));
} else if (cmd.hasOption(NORM)) {
runEvalNorm(cmd.getOptionValue(NORM));
} else {
log.error("Invalid command, please check help message.");
printUsage();
}
} else if (cleanedArgs[0].equals(CMD_EXPORT)) {
Map<String, Object> params = new HashMap<String, Object>();
params.put(ExportModelProcessor.IS_CONCISE, cmd.hasOption(EXPORT_CONCISE));
params.put(ExportModelProcessor.REQUEST_VARS, cmd.getOptionValue(VARS));
params.put(ExportModelProcessor.EXPECTED_BIN_NUM, cmd.getOptionValue(N));
params.put(ExportModelProcessor.IV_KEEP_RATIO, cmd.getOptionValue(IVR));
params.put(ExportModelProcessor.MINIMUM_BIN_INST_CNT, cmd.getOptionValue(BIC));
status = exportModel(cmd.getOptionValue(MODELSET_CMD_TYPE), params);
if (status == 0) {
log.info("Export models/columnstats to PMML/csv format successfully in current folder.");
} else {
log.warn("Export models/columnstats to PMML/csv format with error, please check or report issue.");
}
} else {
log.error("Invalid command, please check help message.");
printUsage();
}
}
// for some case jvm cannot stop
System.exit(status);
} catch (ShifuException e) {
// need define error code in each step.
log.error(e.getError().toString(), e.getCause());
exceptionExit(e);
} catch (Exception e) {
exceptionExit(e);
}
}
Aggregations