List of usage examples for org.apache.commons.cli BasicParser BasicParser
BasicParser
From source file:gov.noaa.ncdc.iosp.avhrr.util.AvhrrLevel1B2Netcdf.java
/** * @param args/*from w w w . ja v a 2s . c om*/ * the command line arguments */ public static void main(String args[]) throws Exception { // create the Options object Options options = new Options(); options.addOption(OPTION_NOGUI, false, "command line mode"); options.addOption(OPTION_ALLVAR, false, "Process all channels"); options.addOption(OPTION_CH1, false, "Process channel 1"); options.addOption(OPTION_CH2, false, "Process channel 2"); options.addOption(OPTION_CH3, false, "Process channel 3"); options.addOption(OPTION_CH4, false, "Process channel 4"); options.addOption(OPTION_CH5, false, "Process channel 5"); options.addOption(OPTION_DEFAULT, false, "Output All Channels, Brightness Temperature and Latitude and Longitude"); options.addOption(OPTION_TEMP, false, "Output calibrated temperatures/albedos"); options.addOption(OPTION_RAW, false, "Output raw values"); options.addOption(OPTION_RADIANCE, false, "Output radiance values"); options.addOption(OPTION_LATLON, false, "Output latitude and longitude"); options.addOption(OPTION_ALLVAR, false, "Output all variables)"); options.addOption(OPTION_CLOBBER, false, "Overwrite existing netCDF file."); options.addOption(OPTION_CALIBRATION, false, "Output calibration variables"); options.addOption(OPTION_QUALITY, false, "Output quality variables."); options.addOption(OPTION_METADATA, false, "Output metadata variables."); options.addOption("memory", false, "java heap space."); Option logOption = new Option("logFile", true, "Send output to file"); options.addOption(logOption); Option outdirOption = new Option("outputdir", true, "Output Directory."); options.addOption(outdirOption); // 2nd way is by creating an Option and then adding it Option timeOption = new Option(OPTION_AVHRR, true, "Process the Level1B file"); timeOption.setRequired(false); options.addOption(timeOption); // now lets parse the input CommandLineParser parser = new BasicParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException pe) { usage(options); return; } // now lets interrogate the options and execute the relevant parts if (cmd.hasOption(OPTION_NOGUI)) { // process command line args - need to refactor this (doing this // twice--BAD!!!!!) List<String> list = processCommandLineArgs(cmd); String file = cmd.getOptionValue(OPTION_AVHRR); if (null == file) { System.out.println("You must specify a file to convert!! missing -avhrr argument"); usage(options); return; } String outdir = cmd.getOptionValue("outputdir"); if (null == outdir || outdir.trim().length() < 1) { File f = new File("."); outdir = f.getAbsolutePath(); } // try { Avhrr2Netcdf.convert(file, list, outdir); // } catch (Exception e) { // System.out.println("this blew up"); // TODO Auto-generated catch block // e.printStackTrace(); // } } else { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels(); for (int i = 0; i < info.length; i++) { // Get the name of the look and feel that is suitable // for // display to the user String className = info[i].getClassName(); } String javaLF = UIManager.getSystemLookAndFeelClassName(); try { // UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); UIManager.setLookAndFeel(javaLF); } catch (ClassNotFoundException e) { // log.error(e.getMessage()); } catch (InstantiationException e) { // log.error(e.getMessage()); } catch (IllegalAccessException e) { // log.error(e.getMessage()); } catch (UnsupportedLookAndFeelException e) { // log.error(e.getMessage()); } mFrame = new AvhrrLevel1B2Netcdf(); mFrame.setVisible(true); } }); } }
From source file:com.datatorrent.stram.cli.DTCli.java
public void preImpersonationInit(String[] args) throws IOException { Signal.handle(new Signal("INT"), new SignalHandler() { @Override/*from w w w . j a v a 2 s .co m*/ public void handle(Signal sig) { System.out.println("^C"); if (commandThread != null) { commandThread.interrupt(); mainThread.interrupt(); } else { System.out.print(prompt); System.out.flush(); } } }); consolePresent = (System.console() != null); Options options = new Options(); options.addOption("e", true, "Commands are read from the argument"); options.addOption("v", false, "Verbose mode level 1"); options.addOption("vv", false, "Verbose mode level 2"); options.addOption("vvv", false, "Verbose mode level 3"); options.addOption("vvvv", false, "Verbose mode level 4"); options.addOption("r", false, "JSON Raw mode"); options.addOption("p", true, "JSONP padding function"); options.addOption("h", false, "Print this help"); options.addOption("f", true, "Use the specified prompt at all time"); options.addOption("kp", true, "Use the specified kerberos principal"); options.addOption("kt", true, "Use the specified kerberos keytab"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("v")) { verboseLevel = 1; } if (cmd.hasOption("vv")) { verboseLevel = 2; } if (cmd.hasOption("vvv")) { verboseLevel = 3; } if (cmd.hasOption("vvvv")) { verboseLevel = 4; } if (cmd.hasOption("r")) { raw = true; } if (cmd.hasOption("e")) { commandsToExecute = cmd.getOptionValues("e"); consolePresent = false; } if (cmd.hasOption("p")) { jsonp = cmd.getOptionValue("p"); } if (cmd.hasOption("f")) { forcePrompt = cmd.getOptionValue("f"); } if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(DTCli.class.getSimpleName(), options); System.exit(0); } if (cmd.hasOption("kp")) { kerberosPrincipal = cmd.getOptionValue("kp"); } if (cmd.hasOption("kt")) { kerberosKeyTab = cmd.getOptionValue("kt"); } } catch (ParseException ex) { System.err.println("Invalid argument: " + ex); System.exit(1); } if (kerberosPrincipal == null && kerberosKeyTab != null) { System.err.println( "Kerberos key tab is specified but not the kerberos principal. Please specify it using the -kp option."); System.exit(1); } if (kerberosPrincipal != null && kerberosKeyTab == null) { System.err.println( "Kerberos principal is specified but not the kerberos key tab. Please specify it using the -kt option."); System.exit(1); } Level logLevel; switch (verboseLevel) { case 0: logLevel = Level.OFF; break; case 1: logLevel = Level.ERROR; break; case 2: logLevel = Level.WARN; break; case 3: logLevel = Level.INFO; break; default: logLevel = Level.DEBUG; break; } for (org.apache.log4j.Logger logger : new org.apache.log4j.Logger[] { org.apache.log4j.Logger.getRootLogger(), org.apache.log4j.Logger.getLogger(DTCli.class) }) { @SuppressWarnings("unchecked") Enumeration<Appender> allAppenders = logger.getAllAppenders(); while (allAppenders.hasMoreElements()) { Appender appender = allAppenders.nextElement(); if (appender instanceof ConsoleAppender) { ((ConsoleAppender) appender).setThreshold(logLevel); } } } if (commandsToExecute != null) { for (String command : commandsToExecute) { LOG.debug("Command to be executed: {}", command); } } if (kerberosPrincipal != null && kerberosKeyTab != null) { StramUserLogin.authenticate(kerberosPrincipal, kerberosKeyTab); } else { Configuration config = new YarnConfiguration(); StramClientUtils.addDTLocalResources(config); StramUserLogin.attemptAuthentication(config); } }
From source file:com.datatorrent.stram.cli.ApexCli.java
public void preImpersonationInit(String[] args) throws IOException { Signal.handle(new Signal("INT"), new SignalHandler() { @Override/*from ww w . j ava2 s.co m*/ public void handle(Signal sig) { System.out.println("^C"); if (commandThread != null) { commandThread.interrupt(); mainThread.interrupt(); } else { System.out.print(prompt); System.out.flush(); } } }); consolePresent = (System.console() != null); Options options = new Options(); options.addOption("e", true, "Commands are read from the argument"); options.addOption("v", false, "Verbose mode level 1"); options.addOption("vv", false, "Verbose mode level 2"); options.addOption("vvv", false, "Verbose mode level 3"); options.addOption("vvvv", false, "Verbose mode level 4"); options.addOption("r", false, "JSON Raw mode"); options.addOption("p", true, "JSONP padding function"); options.addOption("h", false, "Print this help"); options.addOption("f", true, "Use the specified prompt at all time"); options.addOption("kp", true, "Use the specified kerberos principal"); options.addOption("kt", true, "Use the specified kerberos keytab"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("v")) { verboseLevel = 1; } if (cmd.hasOption("vv")) { verboseLevel = 2; } if (cmd.hasOption("vvv")) { verboseLevel = 3; } if (cmd.hasOption("vvvv")) { verboseLevel = 4; } if (cmd.hasOption("r")) { raw = true; } if (cmd.hasOption("e")) { commandsToExecute = cmd.getOptionValues("e"); consolePresent = false; } if (cmd.hasOption("p")) { jsonp = cmd.getOptionValue("p"); } if (cmd.hasOption("f")) { forcePrompt = cmd.getOptionValue("f"); } if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ApexCli.class.getSimpleName(), options); System.exit(0); } if (cmd.hasOption("kp")) { kerberosPrincipal = cmd.getOptionValue("kp"); } if (cmd.hasOption("kt")) { kerberosKeyTab = cmd.getOptionValue("kt"); } } catch (ParseException ex) { System.err.println("Invalid argument: " + ex); System.exit(1); } if (kerberosPrincipal == null && kerberosKeyTab != null) { System.err.println( "Kerberos key tab is specified but not the kerberos principal. Please specify it using the -kp option."); System.exit(1); } if (kerberosPrincipal != null && kerberosKeyTab == null) { System.err.println( "Kerberos principal is specified but not the kerberos key tab. Please specify it using the -kt option."); System.exit(1); } Level logLevel; switch (verboseLevel) { case 0: logLevel = Level.OFF; break; case 1: logLevel = Level.ERROR; break; case 2: logLevel = Level.WARN; break; case 3: logLevel = Level.INFO; break; default: logLevel = Level.DEBUG; break; } for (org.apache.log4j.Logger logger : new org.apache.log4j.Logger[] { org.apache.log4j.Logger.getRootLogger(), org.apache.log4j.Logger.getLogger(ApexCli.class) }) { /* * Override logLevel specified by user, the same logLevel would be inherited by all * appenders related to logger. */ logger.setLevel(logLevel); @SuppressWarnings("unchecked") Enumeration<Appender> allAppenders = logger.getAllAppenders(); while (allAppenders.hasMoreElements()) { Appender appender = allAppenders.nextElement(); if (appender instanceof ConsoleAppender) { ((ConsoleAppender) appender).setThreshold(logLevel); } } } if (commandsToExecute != null) { for (String command : commandsToExecute) { LOG.debug("Command to be executed: {}", command); } } if (kerberosPrincipal != null && kerberosKeyTab != null) { StramUserLogin.authenticate(kerberosPrincipal, kerberosKeyTab); } else { Configuration config = new YarnConfiguration(); StramClientUtils.addDTLocalResources(config); StramUserLogin.attemptAuthentication(config); } }
From source file:edu.upenn.cis.orchestra.workloadgenerator.Generator.java
public static Map<String, Object> parseCommandLine(String[] args) throws ParseException { // create the command line parser CommandLineParser parser = new BasicParser(); // create the Options Options options = buildOptions();/* w ww . ja va2 s .c o m*/ // parse the command line arguments CommandLine line = parser.parse(options, args); Map<String, Object> params = buildParams(line); if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Generator", buildOptions()); System.exit(0); } return params; }
From source file:net.swigg.talo.TaloCacheBootstrap.java
public static void main(String[] args) throws ConfigurationException, ParseException { Options options = new Options(); options.addOption("help", false, "help"); options.addOption("listenHost", true, "interface to listen on"); options.addOption("listenPort", true, "port to listen on"); options.addOption("targetPrefix", true, "where to proxy to"); CommandLineParser parser = new BasicParser(); CommandLine command = parser.parse(options, args); if (command.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("talocache", options); return;//ww w. j a v a2s .co m } BootstrapConfig config = new BootstrapConfig(); config.listenHost = command.getOptionValue("listenHost", config.listenHost); config.listenPort = Integer.parseInt(command.getOptionValue("listenPort", config.listenPort.toString())); config.targetPrefix = command.getOptionValue("targetPrefix", config.targetPrefix); TaloCacheBootstrap taloCache = new TaloCacheBootstrap(config); taloCache.start(); }
From source file:net.udidb.cli.driver.ConfigBuilder.java
/** * Builds the configuration for udidb from the command line parameters * * @param args the command line arguments * * @return the configuration//from ww w . j av a 2 s. co m * * @throws ParseException if the configuration cannot be created due to invalid parameters * @throws HelpMessageRequested when the user requests the help message */ public Config build(String[] args) throws ParseException, HelpMessageRequested { CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption(helpOption.getOpt())) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("udidb", options, true); throw new HelpMessageRequested(); } // TODO convert options to config return new CommandLineConfigImpl(); }
From source file:net.vhati.modmanager.cli.SlipstreamCLI.java
public static void main(String[] args) { BasicParser parser = new BasicParser(); Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("extract-dats") .withDescription("extract FTL resources into a dir").hasArg().withArgName("DIR").create()); options.addOption(OptionBuilder.withLongOpt("global-panic") .withDescription("patch as if advanced find tags had panic='true'").create()); options.addOption(/*from w w w. j av a2 s . co m*/ OptionBuilder.withLongOpt("list-mods").withDescription("list available mod names").create()); options.addOption(OptionBuilder.withLongOpt("runftl") .withDescription("run the game (standalone or with 'patch')").create()); options.addOption(OptionBuilder.withLongOpt("patch") .withDescription("revert to vanilla and add named mods (if any)").create()); options.addOption( OptionBuilder.withLongOpt("validate").withDescription("check named mods for problems").create()); options.addOption("h", "help", false, "display this help and exit"); options.addOption(OptionBuilder.withLongOpt("version") .withDescription("output version information and exit").create()); CommandLine cmdline = null; try { cmdline = parser.parse(options, args, true); } catch (ParseException e) { System.err.println("Error parsing commandline: " + e.getMessage()); System.exit(1); } if (cmdline.hasOption("h")) { // Exits. HelpFormatter formatter = new HelpFormatter(); String helpHeader = "Perform actions against an FTL installation and/or a list of named mods." + formatter.getNewLine(); String helpFooter = formatter.getNewLine(); helpFooter += "Each MODFILE is a filename in the mods/ dir." + formatter.getNewLine(); helpFooter += "If a named mod is a directory, a temporary zip will be created."; formatter.printHelp("modman [OPTION] [MODFILE]...", helpHeader, options, helpFooter); System.exit(0); } if (cmdline.hasOption("version")) { // Exits. System.out.println(getVersionMessage()); System.exit(0); } DelayedDeleteHook deleteHook = new DelayedDeleteHook(); Runtime.getRuntime().addShutdownHook(deleteHook); if (cmdline.hasOption("validate")) { // Exits (0/1). log.info("Validating..."); StringBuilder resultBuf = new StringBuilder(); ReportFormatter formatter = new ReportFormatter(); boolean anyInvalid = false; for (String modFileName : cmdline.getArgs()) { File modFile = new File(modsDir, modFileName); if (modFile.isDirectory()) { log.info(String.format("Zipping dir: %s/", modFile.getName())); try { modFile = createTempMod(modFile); deleteHook.addDoomedFile(modFile); } catch (IOException e) { log.error(String.format("Error zipping \"%s/\".", modFile.getName()), e); List<ReportMessage> tmpMessages = new ArrayList<ReportMessage>(); tmpMessages.add(new ReportMessage(ReportMessage.SECTION, modFileName)); tmpMessages.add(new ReportMessage(ReportMessage.EXCEPTION, e.getMessage())); formatter.format(tmpMessages, resultBuf, 0); resultBuf.append("\n"); anyInvalid = true; continue; } } Report validateReport = ModUtilities.validateModFile(modFile); formatter.format(validateReport.messages, resultBuf, 0); resultBuf.append("\n"); if (validateReport.outcome == false) anyInvalid = true; } if (resultBuf.length() == 0) { resultBuf.append("No mods were checked."); } System.out.println(); System.out.println(resultBuf.toString()); System.exit(anyInvalid ? 1 : 0); } File configFile = new File("modman.cfg"); Properties config = getConfig(configFile); if (cmdline.hasOption("list-mods")) { // Exits. log.info("Listing mods..."); boolean allowZip = config.getProperty("allow_zip", "false").equals("true"); File[] modFiles = modsDir.listFiles(new ModAndDirFileFilter(allowZip, true)); List<String> dirList = new ArrayList<String>(); List<String> fileList = new ArrayList<String>(); for (File f : modFiles) { if (f.isDirectory()) dirList.add(f.getName() + "/"); else fileList.add(f.getName()); } Collections.sort(dirList); Collections.sort(fileList); for (String s : dirList) System.out.println(s); for (String s : fileList) System.out.println(s); System.exit(0); } File datsDir = null; if (cmdline.hasOption("extract-dats") || cmdline.hasOption("patch") || cmdline.hasOption("runftl")) { datsDir = getDatsDir(config); } if (cmdline.hasOption("extract-dats")) { // Exits (0/1). log.info("Extracting dats..."); String extractPath = cmdline.getOptionValue("extract-dats"); File extractDir = new File(extractPath); File dataDatFile = new File(datsDir, "data.dat"); File resDatFile = new File(datsDir, "resource.dat"); File[] datFiles = new File[] { dataDatFile, resDatFile }; FTLDat.AbstractPack srcP = null; FTLDat.AbstractPack dstP = null; InputStream is = null; try { if (!extractDir.exists()) extractDir.mkdirs(); dstP = new FTLDat.FolderPack(extractDir); for (File datFile : datFiles) { srcP = new FTLDat.FTLPack(datFile, "r"); List<String> innerPaths = srcP.list(); for (String innerPath : innerPaths) { if (dstP.contains(innerPath)) { log.info("While extracting resources, this file was overwritten: " + innerPath); dstP.remove(innerPath); } is = srcP.getInputStream(innerPath); dstP.add(innerPath, is); } srcP.close(); } } catch (IOException e) { log.error("Error extracting dats.", e); System.exit(1); } finally { try { if (is != null) is.close(); } catch (IOException ex) { } try { if (srcP != null) srcP.close(); } catch (IOException ex) { } try { if (dstP != null) dstP.close(); } catch (IOException ex) { } } System.exit(0); } if (cmdline.hasOption("patch")) { // Exits sometimes (1 on failure). log.info("Patching..."); List<File> modFiles = new ArrayList<File>(); for (String modFileName : cmdline.getArgs()) { File modFile = new File(modsDir, modFileName); if (modFile.isDirectory()) { log.info(String.format("Zipping dir: %s/", modFile.getName())); try { modFile = createTempMod(modFile); deleteHook.addDoomedFile(modFile); } catch (IOException e) { log.error(String.format("Error zipping \"%s/\".", modFile.getName()), e); System.exit(1); } } modFiles.add(modFile); } BackedUpDat dataDat = new BackedUpDat(); dataDat.datFile = new File(datsDir, "data.dat"); dataDat.bakFile = new File(backupDir, "data.dat.bak"); BackedUpDat resDat = new BackedUpDat(); resDat.datFile = new File(datsDir, "resource.dat"); resDat.bakFile = new File(backupDir, "resource.dat.bak"); boolean globalPanic = cmdline.hasOption("global-panic"); SilentPatchObserver patchObserver = new SilentPatchObserver(); ModPatchThread patchThread = new ModPatchThread(modFiles, dataDat, resDat, globalPanic, patchObserver); deleteHook.addWatchedThread(patchThread); patchThread.start(); while (patchThread.isAlive()) { try { patchThread.join(); } catch (InterruptedException e) { } } if (!patchObserver.hasSucceeded()) System.exit(1); } if (cmdline.hasOption("runftl")) { // Exits (0/1). log.info("Running FTL..."); File exeFile = FTLUtilities.findGameExe(datsDir); if (exeFile != null) { try { FTLUtilities.launchGame(exeFile); } catch (Exception e) { log.error("Error launching FTL.", e); System.exit(1); } } else { log.error("Could not find FTL's executable."); System.exit(1); } System.exit(0); } System.exit(0); }
From source file:net.zdechov.sharpmz.jmzemu.JMzEmu.java
/** * Main method launching the application. * * @param args arguments//from w ww . ja v a 2 s.c o m */ public static void main(String[] args) { try { preferences = Preferences.userNodeForPackage(JMzEmu.class); } catch (SecurityException ex) { preferences = null; } try { bundle = LanguageUtils.getResourceBundleByClass(JMzEmu.class); // Parameters processing Options opt = new Options(); opt.addOption("h", "help", false, bundle.getString("cl_option_help")); opt.addOption("v", false, bundle.getString("cl_option_verbose")); opt.addOption("dev", false, bundle.getString("cl_option_dev")); BasicParser parser = new BasicParser(); CommandLine cl = parser.parse(opt, args); if (cl.hasOption('h')) { HelpFormatter f = new HelpFormatter(); f.printHelp(bundle.getString("cl_syntax"), opt); } else { verboseMode = cl.hasOption("v"); devMode = cl.hasOption("dev"); Logger logger = Logger.getLogger(""); try { logger.setLevel(Level.ALL); logger.addHandler(new XBHead.XBLogHandler(verboseMode)); } catch (java.security.AccessControlException ex) { // Ignore it in java webstart } XBBaseApplication app = new XBBaseApplication(); app.setAppPreferences(new PreferencesWrapper(preferences)); app.setAppBundle(bundle, LanguageUtils.getResourceBaseNameBundleByClass(JMzEmu.class)); XBApplicationModuleRepository moduleRepository = app.getModuleRepository(); moduleRepository.addClassPathModules(); moduleRepository.addModulesFromManifest(JMzEmu.class); moduleRepository.loadModulesFromPath(new File("plugins").toURI()); moduleRepository.initModules(); app.init(); GuiFrameModuleApi frameModule = moduleRepository.getModuleByInterface(GuiFrameModuleApi.class); GuiEditorModuleApi editorModule = moduleRepository.getModuleByInterface(GuiEditorModuleApi.class); GuiMenuModuleApi menuModule = moduleRepository.getModuleByInterface(GuiMenuModuleApi.class); GuiAboutModuleApi aboutModule = moduleRepository.getModuleByInterface(GuiAboutModuleApi.class); GuiFileModuleApi fileModule = moduleRepository.getModuleByInterface(GuiFileModuleApi.class); GuiOptionsModuleApi optionsModule = moduleRepository .getModuleByInterface(GuiOptionsModuleApi.class); GuiUpdateModuleApi updateModule = moduleRepository.getModuleByInterface(GuiUpdateModuleApi.class); frameModule.createMainMenu(); // try { // updateModule.setUpdateUrl(new URL(bundle.getString("update_url"))); // updateModule.setUpdateDownloadUrl(new URL(bundle.getString("update_download_url"))); // } catch (MalformedURLException ex) { // Logger.getLogger(JMzEmu.class.getName()).log(Level.SEVERE, null, ex); // } updateModule.registerDefaultMenuItem(); aboutModule.registerDefaultMenuItem(); AboutDialogSidePanel sidePanel = new AboutDialogSidePanel(); aboutModule.setAboutDialogSideComponent(sidePanel); frameModule.registerExitAction(); frameModule.registerBarsVisibilityActions(); // Register clipboard editing actions fileModule.registerMenuFileHandlingActions(); fileModule.registerToolBarFileHandlingActions(); fileModule.registerLastOpenedMenuActions(); fileModule.registerCloseListener(); // undoModule.registerMainMenu(); // undoModule.registerMainToolBar(); // undoModule.registerUndoManagerInMainMenu(); // Register clipboard editing actions menuModule.getClipboardActions(); // menuModule.registerMenuClipboardActions(); // menuModule.registerToolBarClipboardActions(); optionsModule.registerMenuAction(); // HexPanel hexPanel = (HexPanel) deltaHexModule.getEditorProvider(); // editorModule.registerEditor("hex", hexPanel); // editorModule.registerUndoHandler(); // undoModule.setUndoHandler(hexPanel.getHexUndoHandler()); // deltaHexModule.registerStatusBar(); // deltaHexModule.registerOptionsPanels(); // deltaHexModule.getTextStatusPanel(); updateModule.registerOptionsPanels(); // deltaHexModule.loadFromPreferences(preferences); ApplicationFrameHandler frameHandler = frameModule.getFrameHandler(); GraphicsModule graphicsModule = new GraphicsModule(); frameHandler.setMainPanel(graphicsModule.getGraphicsComponent()); frameHandler.setDefaultSize(new Dimension(600, 400)); frameHandler.show(); updateModule.checkOnStart(frameHandler.getFrame()); List fileArgs = cl.getArgList(); if (fileArgs.size() > 0) { fileModule.loadFromFile((String) fileArgs.get(0)); } } } catch (ParseException | RuntimeException ex) { Logger.getLogger(JMzEmu.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:nl.imvertor.common.Configurator.java
/** * Create parameters from arguments passed to the java application. * Arguments are parsed by CLI conventions. * Existing argument parameters are replaced. * /*from w w w. j a v a 2 s. c o m*/ * Parameters set from command line option are placed in /config/cli subelement and take the form * /config/cli/parameter[@name]/text() * * @param options Command line options * @throws Exception */ public void setParmsFromOptions(String[] args) throws Exception { CommandLine commandLine = null; File curFile = baseFolder; try { BasicParser parser = new BasicParser(); commandLine = parser.parse(options, args); if (commandLine.hasOption("help")) dieOnCli(commandLine.getOptionValue("help")); } catch (ParseException e) { runner.error(logger, e.getMessage()); dieOnCli("error"); } @SuppressWarnings("unchecked") Iterator<Option> it = commandLine.iterator(); while (it.hasNext()) { Option option = it.next(); String optionName = option.getOpt(); String[] v = commandLine.getOptionValues(optionName); // same option many times returns array of values. if (v.length > 1) throw new Exception("Duplicate argument -" + optionName + " on command line"); if (optionName.equals("arguments")) loadFromPropertyFiles(curFile, v[0]); setParm(workConfiguration, "cli", optionName, v[0], true); setOptionIsReady(optionName, true); } String missing = checkOptionsAreReady(); if (!missing.equals("")) { runner.error(logger, "Missing required parameters: " + missing); dieOnCli("program"); } // record the metamodel used metamodel = getParm(workConfiguration, "cli", "metamodel", false); metamodel = (metamodel == null) ? DEFAULT_METAMODEL : metamodel; // schema rules used schemarules = getParm(workConfiguration, "cli", "schemarules", false); schemarules = (schemarules == null) ? DEFAULT_SCHEMARULES : schemarules; // set the task setParm(workConfiguration, "appinfo", "task", getParm(workConfiguration, "cli", "task", true), true); // If forced compilation, try all steps irrespective of any errors forceCompile = isTrue(getParm(workConfiguration, "cli", "forcecompile", true)); // If documentation release, set the suffix for the application id String docReleaseString = getParm(workConfiguration, "cli", "docrelease", false); // if warnings should be signaled suppressWarnings = isTrue("cli", "suppresswarnings", false); docRelease = docReleaseString != null && !docReleaseString.equals("00000000"); if (docRelease) { setParm("system", "documentation-release", "-" + docReleaseString); } else { setParm("system", "documentation-release", ""); } }
From source file:nl.mikero.turntopassage.commandline.Application.java
private void execute(String[] args) { // Options/* w w w .ja va2 s .co m*/ final Options options = new Options(); Option input = OptionBuilder.hasArg().withArgName("file").withDescription("location of input HTML file") .withLongOpt(OPT_FILE).create('f'); Option output = OptionBuilder.hasArg().withArgName("file").withDescription("location of output EPUB file") .withLongOpt(OPT_OUTPUT).create('o'); options.addOption(input); options.addOption(output); OptionGroup infoGroup = new OptionGroup(); infoGroup.addOption(new Option(OPT_HELP, "display this help and exit")); infoGroup.addOption(new Option(OPT_VERSION, "output version information and exit")); options.addOptionGroup(infoGroup); // Parse CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption(OPT_VERSION)) { System.out.println("TurnToPassage.Transformer 0.0.1"); System.out.println("Copyright (C) 2015 Mike Rombout"); System.out.println("License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>"); System.out.println("This is free software: you are free to change and redistribute it."); System.out.println("There is NO WARRANTY, to the extend permitted by law."); System.exit(0); } else if (cmd.hasOption(OPT_HELP)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("turntopassage", options, true); System.exit(0); } else { InputStream inputStream = System.in; OutputStream outputStream = System.out; if (cmd.hasOption(OPT_FILE)) { String fileArg = cmd.getOptionValue(OPT_FILE); try { inputStream = new BufferedInputStream(new FileInputStream(new File(fileArg))); } catch (FileNotFoundException e) { LOGGER.error("Input file {} could not be found.", fileArg, e); System.exit(1); } } if (cmd.hasOption(OPT_OUTPUT)) { String outputArg = cmd.getOptionValue(OPT_OUTPUT); try { outputStream = new BufferedOutputStream(new FileOutputStream(new File(outputArg))); } catch (FileNotFoundException e) { LOGGER.error("Output file {} could not be found.", outputArg, e); System.exit(1); } } twineService.transform(inputStream, outputStream); System.exit(0); } } catch (ParseException e) { LOGGER.error("Error: {}", e.getMessage(), e); } System.exit(1); }