public DecompilerSettings getDecompilerSettings() { CommandLineOptions options = new CommandLineOptions(); JCommander jCommander = new JCommander(options); // TODO remove dependency on JCommander? String[] args = new String[Settings.values().length * 2]; int index = 0; for (TransformerSettings.Setting setting : Settings.values()) { args[index++] = "--" + setting.getParam(); args[index++] = String.valueOf(setting.isEnabled()); } jCommander.parse(args); DecompilerSettings settings = new DecompilerSettings(); settings.setFlattenSwitchBlocks(options.getFlattenSwitchBlocks()); settings.setForceExplicitImports(!options.getCollapseImports()); settings.setForceExplicitTypeArguments(options.getForceExplicitTypeArguments()); settings.setRetainRedundantCasts(options.getRetainRedundantCasts()); settings.setShowSyntheticMembers(options.getShowSyntheticMembers()); settings.setExcludeNestedTypes(options.getExcludeNestedTypes()); settings.setOutputDirectory(options.getOutputDirectory()); settings.setIncludeLineNumbersInBytecode(options.getIncludeLineNumbers()); settings.setRetainPointlessSwitches(options.getRetainPointlessSwitches()); settings.setUnicodeOutputEnabled(options.isUnicodeOutputEnabled()); settings.setMergeVariables(options.getMergeVariables()); settings.setShowDebugLineNumbers(options.getShowDebugLineNumbers()); settings.setSimplifyMemberReferences(options.getSimplifyMemberReferences()); settings.setDisableForEachTransforms(options.getDisableForEachTransforms()); settings.setTypeLoader(new InputTypeLoader()); if (options.isRawBytecode()) { settings.setLanguage(Languages.bytecode()); } else if (options.isBytecodeAst()) { settings.setLanguage( options.isUnoptimized() ? Languages.bytecodeAstUnoptimized() : Languages.bytecodeAst()); } return settings; }
public static void main(String[] args) throws Throwable { StreamFile2RDF streamfile2rdf = new StreamFile2RDF(); JCommander com = new JCommander(streamfile2rdf, args); com.setProgramName("stream2file"); if (streamfile2rdf.parameters.size() == 1) { System.err.println("No output file specified, writing to standard output."); streamfile2rdf.rdfOutput = "stdout"; streamfile2rdf.InputStream = streamfile2rdf.parameters.get(0); } else if (streamfile2rdf.parameters.size() == 2) { streamfile2rdf.InputStream = streamfile2rdf.parameters.get(0); streamfile2rdf.rdfOutput = streamfile2rdf.parameters.get(1); } else { com.usage(); System.exit(1); } System.out.println( "Converting '" + streamfile2rdf.InputStream + "' to Stream File'" + streamfile2rdf.rdfOutput + "'"); streamfile2rdf.execute(); System.out.println("Bye!"); System.exit(0); }
@Override public int run(String[] args) throws Exception { try { jc.parse(args); } catch (ParameterException pe) { System.err.println(pe.getMessage()); return 1; } if ("help".equals(jc.getParsedCommand())) { return help.usage(jc, COMMANDS); } Command cmd = COMMANDS.get(jc.getParsedCommand()); if (cmd == null) { return help.usage(jc, COMMANDS); } try { return cmd.execute(getConf()); } catch (CommandException ce) { System.err.println("Command Error: " + ce.getMessage()); return 1; } catch (IllegalArgumentException e) { System.err.println("Argument Error: " + e.getMessage()); return 1; } catch (IllegalStateException e) { System.err.println("State Error: " + e.getMessage()); return 1; } }
static Configuration parseConfiguration(String[] args) { Configuration configuration = new Configuration(); JCommander jCommander; List<String> crateArgs = new ArrayList<>(); List<String> safeArgs = new ArrayList<>(args.length); for (String arg : args) { if (HELP_OPTIONS.contains(arg)) { jCommander = new JCommander(configuration); jCommander.usage(); System.exit(1); } if (arg.startsWith("-Des.")) { String argKey = arg.split("\\=")[0]; if (PROTECTED_CRATE_ARGS.contains(argKey)) { throw new IllegalArgumentException( String.format( "Argument \"%s\" is protected and managed by the framework. " + "It cannot be set by the user", argKey)); } else { crateArgs.add(arg); } } else { safeArgs.add(arg); } } jCommander = new JCommander(configuration, safeArgs.toArray(new String[safeArgs.size()])); configuration.crateArgs(crateArgs); LOGGER.debug("args: {}", configuration); return configuration; }
public Main() { jc = new JCommander(this); jc.addCommand("help", help, "-help", "--help"); for (Map.Entry<String, Command> e : COMMANDS.entrySet()) { jc.addCommand(e.getKey(), e.getValue()); } }
public static Parameters parseArgs(String[] args) { Parameters parameters = new Parameters(); JCommander jc = new JCommander(parameters, args); jc.setProgramName(name); if (parameters.help) { jc.usage(); } return parameters; }
TrackAnalyzer(String[] args) throws Exception { JCommander jcommander = new JCommander(c, args); jcommander.setProgramName("TrackAnalyzer"); if ((c.filenames.size() == 0 && Utils.isEmpty(c.filelist)) || c.help) { jcommander.usage(); System.exit(-1); } if (c.debug) { Logger.getLogger(TrackAnalyzer.class.getName()).setLevel(Level.ALL); } else { Logger.getLogger(TrackAnalyzer.class.getName()).setLevel(Level.WARNING); } // we have a list, read all the filenames in the list and // collect them in 'filenames' if (!Utils.isEmpty(c.filelist)) { try { // use buffering, reading one line at a time // FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader(new File(c.filelist))); try { String line = null; // not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while ((line = input.readLine()) != null) { filenames.add(line); } } finally { input.close(); } } catch (IOException ex) { ex.printStackTrace(); System.exit(-1); } } // add filenames from command line filenames.addAll(c.filenames); if (!Utils.isEmpty(c.writeList)) { try { writeListWriter = new BufferedWriter(new FileWriter(c.writeList)); } catch (IOException ex) { Logger.getLogger(TrackAnalyzer.class.getName()).log(Level.SEVERE, null, ex); } } k = new KeyFinder(); p = new Parameters(); p.setHopSize(8192); }
public static void main(String[] args) { /* Parse and validate command line parameters */ CommandLineParameters params = new CommandLineParameters(); try { JCommander jc = new JCommander(params, args); if (params.help) { jc.setProgramName("java -Xmx[several]G -jar otp.jar"); jc.usage(); System.exit(0); } params.infer(); } catch (ParameterException pex) { LOG.error("Parameter error: {}", pex.getMessage()); System.exit(1); } OTPConfigurator configurator = new OTPConfigurator(params); // start graph builder, if asked for GraphBuilderTask graphBuilder = configurator.builderFromParameters(); if (graphBuilder != null) { graphBuilder.run(); // Inform configurator which graph is to be used for in-memory handoff. if (params.inMemory) configurator.makeGraphService(graphBuilder.getGraph()); } // start visualizer, if asked for GraphVisualizer graphVisualizer = configurator.visualizerFromParameters(); if (graphVisualizer != null) { graphVisualizer.run(); } // start web server, if asked for GrizzlyServer grizzlyServer = configurator.serverFromParameters(); if (grizzlyServer != null) { while (true) { // Loop to restart server on uncaught fatal exceptions. try { grizzlyServer.run(); return; } catch (Throwable throwable) { throwable.printStackTrace(); LOG.error( "An uncaught {} occurred inside OTP. Restarting server.", throwable.getClass().getSimpleName()); } } } if (graphBuilder == null && graphVisualizer == null && grizzlyServer == null) { LOG.info("Nothing to do. Use --help to see available tasks."); ; } }
private void showHelpForOneCommand(List<ICommand> commands, PrintWriter pw) { String commandName = commandNames.get(0); for (ICommand command : commands) { if (commandName.equals(command.getName())) { JCommander commander = new JCommander(); commander.setProgramName(command.getName()); commander.addObject(command); StringBuilder sb = new StringBuilder(); sb.append("\n"); commander.usage(sb); pw.println(sb.toString()); } } }
/** * @param args * @throws Exception */ public static void main(String[] args) throws RuntimeException, Exception { is = new ImageSimilarity(); jc = new JCommander(is); jc.setProgramName("ImageSimilarity"); try { jc.parse(args); } catch (ParameterException pe) { System.out.println("Wrong console parameters. See usage of ImageSimilarity below:"); jc.usage(); } is.setup(); }
public static void main(String[] args) throws Exception { System.setProperty("javax.net.debug", "none"); App app = new App(); AppParameters params = new AppParameters(); JCommander jcmd = new JCommander(params); try { jcmd.parse(args); app.setParams(params); app.scepCLI(); } catch (ParameterException e) { jcmd.usage(); } }
public static void main(String[] args) { PublishNanopub obj = new PublishNanopub(); JCommander jc = new JCommander(obj); try { jc.parse(args); } catch (ParameterException ex) { jc.usage(); System.exit(1); } try { obj.run(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } }
private void run() { try { graph = Graph.load(new File(graphPath), Graph.LoadLevel.DEBUG); } catch (Exception e) { LOG.error("Exception while loading graph from " + graphPath); e.printStackTrace(); return; } LOG.info("done loading graph."); if (outPath != null) { try { writer = new HTMLWriter(outPath); } catch (FileNotFoundException ex) { java.util.logging.Logger.getLogger(AnnotationsToHTML.class.getName()) .log(Level.SEVERE, null, ex); LOG.error("Exception while opening output file {}:{}", outPath, ex.getMessage()); return; } } else { writer = new HTMLWriter(System.out); } String command = jc.getParsedCommand(); if (command.equals("annotate")) { annotationEndpoints.run(); } if (outPath != null) { LOG.info("HTML is in {}", outPath); } writer.close(); }
public static void main(String[] args) throws Exception { Options opts = new Options(); JCommander jcmd = new JCommander(opts); jcmd.setProgramName("itunesclone"); jcmd.parse(args); if (opts.help) { jcmd.usage(); return; } RunType runType = opts.dryRun ? RunType.DRY_RUN : RunType.THE_REAL_DEAL; CloneProgressReporter progressReporter = null; CountingProgressReporter counter = null; switch (opts.logLevel) { case 0: progressReporter = new SilentProgressReporter(); break; case 1: counter = new CountingProgressReporter(); progressReporter = counter; break; case 2: TextProgressReporter tpr = new TextProgressReporter(System.out, false); counter = new CountingProgressReporter(); progressReporter = new ChainedProgressReporter(tpr, counter); break; } assert (progressReporter != null); FFMPEGMetadataCache.getInstance().setCacheDirectory(opts.cache.toPath()); (new DirCloner(runType, opts.codec)) .clone(opts.src.toPath(), opts.dest.toPath(), progressReporter); if (opts.logLevel != 0) { counter.printStatistics(System.out); FFMPEGMetadataCache.getInstance().printStatistics(System.out); } }
private static void initParameters(String[] args) { Parameters parameters = new Parameters(); JCommander jCommander = new JCommander(parameters); try { jCommander.parse(args); precision = parameters.getPrecision() + 1; tasks = parameters.getTasks(); quiet = parameters.getQuiet(); fileName = parameters.getFileName(); } catch (ParameterException ex) { System.out.println(MESSAGE_COULD_NOT_GET_PARAMETERS); jCommander.usage(); } }
public AnnotationsToHTML(String[] args) { jc = new JCommander(this); jc.addCommand(annotationEndpoints); try { jc.parse(args); } catch (Exception e) { System.out.println(e.getMessage()); jc.usage(); System.exit(1); } if (help || jc.getParsedCommand() == null) { jc.usage(); System.exit(0); } }
/** * Test method for {@link * org.verapdf.cli.VeraPdfCliProcessor#createProcessorFromArgs(org.verapdf.cli.commands.VeraCliArgParser)} * . * * @throws IOException * @throws FileNotFoundException * @throws ProfileException * @throws JAXBException */ @Test public final void testCreateProcessorFromArgsNewProfile() throws ProfileException, FileNotFoundException, IOException, JAXBException { VeraCliArgParser parser = new VeraCliArgParser(); JCommander jCommander = VeraPdfCliProcessorTest.initialiseJCommander(parser); jCommander.parse(new String[] {}); VeraPdfCliProcessor proc = VeraPdfCliProcessor.createProcessorFromArgs(parser); assertTrue(proc.validator.getProfile().getPDFAFlavour() == PDFAFlavour.PDFA_1_B); ProfileDirectory directory = Profiles.getVeraProfileDirectory(); assertTrue(directory.getValidationProfiles().size() > 0); for (ValidationProfile profile : directory.getValidationProfiles()) { File tmpProfile = File.createTempFile("verapdf", "profile"); try (OutputStream os = new FileOutputStream(tmpProfile)) { Profiles.profileToXml(profile, os, Boolean.FALSE); testWithProfileFile(profile.getPDFAFlavour(), tmpProfile); } } }
private void go(String[] args) throws IOException, JSONException, TemplateException { Arguments arguments = new Arguments(); JCommander jCommander = new JCommander(arguments, args); jCommander.setProgramName("GenerateAndroidProvider"); if (arguments.help) { jCommander.usage(); return; } getConfig(arguments.inputDir); loadModel(arguments.inputDir); generateColumns(arguments); generateWrappers(arguments); generateContentProvider(arguments); generateSqliteHelper(arguments); }
public static void main(String[] argv) { CopyToHdfs obj = new CopyToHdfs(); JCommander cmdr = new JCommander(obj, argv); // Dump the help screen if we have to if (obj.help || argv.length == 0) { cmdr.usage(); return; } try { obj.copy_jsonlog(); } catch (RuntimeException re_ex) { Writer result = new StringWriter(); PrintWriter printWriter = new PrintWriter(result); re_ex.printStackTrace(printWriter); new Syslog().error(result.toString()); } }
/** @param args */ public static void main(String... args) { Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler()); GigawordIngesterRunner run = new GigawordIngesterRunner(); JCommander jc = new JCommander(run, args); jc.setProgramName(GigawordIngesterRunner.class.getSimpleName()); if (run.delegate.help) { jc.usage(); } try { Path outpath = Paths.get(run.delegate.outputPath); IngesterParameterDelegate.prepare(outpath); GigawordDocumentConverter conv = new GigawordDocumentConverter(); for (String pstr : run.delegate.paths) { LOGGER.debug("Running on file: {}", pstr); Path p = Paths.get(pstr); new ExistingNonDirectoryFile(p); Path outWithExt = outpath.resolve(p.getFileName().toString().split("\\.")[0] + ".tar.gz"); if (Files.exists(outWithExt)) { if (!run.delegate.overwrite) { LOGGER.info( "File: {} exists and overwrite disabled. Not running.", outWithExt.toString()); continue; } else { Files.delete(outWithExt); } } try (OutputStream os = Files.newOutputStream(outWithExt); GzipCompressorOutputStream gout = new GzipCompressorOutputStream(os); TarArchiver arch = new TarArchiver(gout)) { Iterator<Communication> iter = conv.gzToStringIterator(p); while (iter.hasNext()) { arch.addEntry(new ArchivableCommunication(iter.next())); } } } } catch (NotFileException | IOException e) { LOGGER.error("Caught exception processing.", e); } }
/** * Parses command line arguments and populates this command line instance. * * <p>If the command line arguments include the "help" argument, or if the arguments have * incorrect values or order, then usage information is printed to {@link System#out} and the * program terminates. * * @param args the command line arguments * @return an instance of the parsed arguments object */ public Arguments parse(String[] args) { JCommander jCommander = new JCommander(this); jCommander.setProgramName("jsonschema2pojo"); try { jCommander.parse(args); if (this.showHelp) { jCommander.usage(); exit(EXIT_OKAY); } } catch (ParameterException e) { System.err.println(e.getMessage()); jCommander.usage(); exit(EXIT_ERROR); } return this; }
private static void testWithProfileFile(final PDFAFlavour flavour, final File profileFile) throws ProfileException, FileNotFoundException, IOException, JAXBException { String[] argVals = new String[] {"-p", "--profile"}; VeraCliArgParser parser = new VeraCliArgParser(); JCommander jCommander = VeraPdfCliProcessorTest.initialiseJCommander(parser); for (String arg : argVals) { jCommander.parse(new String[] {arg, profileFile.getAbsolutePath()}); VeraPdfCliProcessor proc = VeraPdfCliProcessor.createProcessorFromArgs(parser); try (InputStream is = new FileInputStream(profileFile)) { ValidationProfile profile = Profiles.profileFromXml(is); assertEquals(flavour, proc.validator.getProfile().getPDFAFlavour()); assertTrue(profile != proc.validator.getProfile()); assertEquals( Profiles.profileToXml(profile, Boolean.TRUE) + "\n" + Profiles.profileToXml(proc.validator.getProfile(), Boolean.TRUE), profile.getRules(), proc.validator.getProfile().getRules()); } } }
public static void main(String... args) throws Exception { Main main = new Main(); JCommander commander = new JCommander(main); commander.setProgramName(Main.class.getName()); try { commander.parse(args); } catch (ParameterException pe) { commander.usage(); System.exit(-1); } if (main.help) { commander.usage(); System.exit(0); } main.run(); }
public static void main(String[] args) { final Options options = new Options(); JCommander jCommander = new JCommander(options); jCommander.setProgramName("java -jar ColorBleeding.jar"); try { String inPath = "/tmp/images"; String[] argv = { /* "-overwrite", */ "-dir", inPath, "-debug", "-maxiterations", "2", "-outdir", "/tmp/result", "-numthreads", "8" }; if (System.getProperty("overrideArgs", "false").equals("true")) { args = argv; } jCommander.parse(args); execute(options); } catch (ParameterException e) { logger.error(e.getMessage()); if (jCommander != null) { jCommander.usage(); } } catch (IOException e) { logger.error("Error while processing images", e); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static void main(String... args) { CommandLineArgs parsedArgs = new CommandLineArgs(); JCommander jc = new JCommander(parsedArgs); try { jc.parse(args); } catch (ParameterException e) { StringBuilder out = new StringBuilder(e.getLocalizedMessage()).append("\n\n"); jc.usage(out); System.err.println(out.toString()); System.exit(1); return; } if (parsedArgs.help) { jc.usage(); return; } SpoonRunner spoonRunner = new SpoonRunner.Builder() // .setTitle(parsedArgs.title) .setApplicationApk(parsedArgs.apk) .setInstrumentationApk(parsedArgs.testApk) .setOutputDirectory(parsedArgs.output) .setDebug(parsedArgs.debug) .setAndroidSdk(parsedArgs.sdk) .setNoAnimations(parsedArgs.noAnimations) .setTestSize(parsedArgs.size) .setAdbTimeout(parsedArgs.adbTimeoutSeconds * 1000) .setClassName(parsedArgs.className) .setMethodName(parsedArgs.methodName) .useAllAttachedDevices() .build(); if (!spoonRunner.run() && parsedArgs.failOnFailure) { System.exit(1); } }
public static void main(String[] args) { JCommanderTwitterStream jcts = new JCommanderTwitterStream(); new JCommander(jcts, args); if (jcts.isHelp()) { JCommander jc = new JCommander(jcts, args); jc.usage(); return; } String stringKeywords = jcts.getKeywords().stream().collect(joining(" ")); if (jcts.isStream()) { try { if (jcts.getLimit() < Integer.MAX_VALUE) { throw new ParameterException("You can't have stream with limit."); } streamTweets(stringKeywords, jcts.getLocation(), jcts.isHideRetweets()); } catch (URLs.ConnectionException | URLs.HTTPQueryException | MalformedURLException | ParameterException | GeolocationSearch.NoKeyException | GeolocationSearch.SearchLocationException e) { System.err.println(e.getMessage()); System.exit(1); } } else { try { printTweets(stringKeywords, jcts.getLocation(), jcts.getLimit(), jcts.isHideRetweets()); } catch (TwitterException | URLs.ConnectionException | GeolocationSearch.SearchLocationException | MalformedURLException | GeolocationSearch.NoKeyException | URLs.HTTPQueryException e) { System.err.println(e.getMessage()); System.exit(1); } } }
public static void main(String[] args) throws Exception { EncoderConfig config = new EncoderConfig(); JCommander jCommander = new JCommander(config, args); jCommander.setProgramName(CommandLineEncoder.class.getSimpleName()); if (config.help) { jCommander.usage(); return; } String outFileString = config.outputFileBase; if (EncoderConfig.DEFAULT_OUTPUT_FILE_BASE.equals(outFileString)) { outFileString += '.' + config.imageFormat.toLowerCase(Locale.ENGLISH); } Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class); if (config.errorCorrectionLevel != null) { hints.put(EncodeHintType.ERROR_CORRECTION, config.errorCorrectionLevel); } BitMatrix matrix = new MultiFormatWriter() .encode( config.contents.get(0), config.barcodeFormat, config.width, config.height, hints); MatrixToImageWriter.writeToPath(matrix, config.imageFormat, Paths.get(outFileString)); }
protected static HelpCommand addCommands( final ResourceBundle bundle, final JCommander commander) { final HelpCommand result = new HelpCommand(commander, bundle); commander.addCommand(result); commander.addCommand(new StartCommand()); commander.addCommand(new StopCommand()); commander.addCommand(new StatusCommand()); commander.addCommand(new SamplerCommand()); commander.addCommand(new MetadataCommand()); commander.addCommand(new CheckCommand()); commander.addCommand(new TestCommand()); fixResourceBundleBug(commander, bundle); return result; }
protected static JCommander createCommander(final ResourceBundle bundle) { final JCommander result = new JCommander(); result.setAcceptUnknownOptions(false); result.setCaseSensitiveOptions(false); result.setProgramName("metrics-sampler"); result.setColumnSize(120); result.setDescriptionsBundle(bundle); return result; }
public void printUsage() { JCommander jc = new JCommander(this); // print usage in not sorted fields order (by default its sorted by description) PrintStream out = System.out; out.println(); out.println("jadx - dex to java decompiler, version: " + JadxDecompiler.getVersion()); out.println(); out.println("usage: jadx [options] " + jc.getMainParameterDescription()); out.println("options:"); List<ParameterDescription> params = jc.getParameters(); Map<String, ParameterDescription> paramsMap = new LinkedHashMap<String, ParameterDescription>(params.size()); int maxNamesLen = 0; for (ParameterDescription p : params) { paramsMap.put(p.getParameterized().getName(), p); int len = p.getNames().length(); if (len > maxNamesLen) { maxNamesLen = len; } } Field[] fields = JadxCLIArgs.class.getDeclaredFields(); for (Field f : fields) { String name = f.getName(); ParameterDescription p = paramsMap.get(name); if (p == null) { continue; } StringBuilder opt = new StringBuilder(); opt.append(' ').append(p.getNames()); addSpaces(opt, maxNamesLen - opt.length() + 2); opt.append("- ").append(p.getDescription()); out.println(opt); } out.println("Example:"); out.println(" jadx -d out classes.dex"); }