List of usage examples for org.apache.commons.cli OptionBuilder withDescription
public static OptionBuilder withDescription(String newDescription)
From source file:de.burlov.amazon.s3.dirsync.CLI.java
/** * @param args//from ww w . ja v a 2s . c o m */ @SuppressWarnings("static-access") public static void main(String[] args) { Logger.getLogger("").setLevel(Level.OFF); Logger deLogger = Logger.getLogger("de"); deLogger.setLevel(Level.INFO); Handler handler = new ConsoleHandler(); handler.setFormatter(new VerySimpleFormatter()); deLogger.addHandler(handler); deLogger.setUseParentHandlers(false); // if (true) // { // LogFactory.getLog(CLI.class).error("test msg", new Exception("test extception")); // return; // } Options opts = new Options(); OptionGroup gr = new OptionGroup(); /* * Befehlsgruppe initialisieren */ gr = new OptionGroup(); gr.setRequired(true); gr.addOption(OptionBuilder.withArgName("up|down").hasArg() .withDescription("Upload/Download changed or new files").create(CMD_UPDATE)); gr.addOption(OptionBuilder.withArgName("up|down").hasArg() .withDescription("Upload/Download directory snapshot").create(CMD_SNAPSHOT)); gr.addOption(OptionBuilder.withDescription("Delete remote folder").create(CMD_DELETE_DIR)); gr.addOption(OptionBuilder.withDescription("Delete a bucket").create(CMD_DELETE_BUCKET)); gr.addOption(OptionBuilder.create(CMD_HELP)); gr.addOption(OptionBuilder.create(CMD_VERSION)); gr.addOption(OptionBuilder.withDescription("Prints summary for stored data").create(CMD_SUMMARY)); gr.addOption(OptionBuilder.withDescription("Clean up orphaned objekts").create(CMD_CLEANUP)); gr.addOption(OptionBuilder.withDescription("Changes encryption password").withArgName("new password") .hasArg().create(CMD_CHANGE_PASSWORD)); gr.addOption(OptionBuilder.withDescription("Lists all buckets").create(CMD_LIST_BUCKETS)); gr.addOption(OptionBuilder.withDescription("Lists raw objects in a bucket").create(CMD_LIST_BUCKET)); gr.addOption(OptionBuilder.withDescription("Lists files in remote folder").create(CMD_LIST_DIR)); opts.addOptionGroup(gr); /* * Parametergruppe initialisieren */ opts.addOption(OptionBuilder.withArgName("key").isRequired(false).hasArg().withDescription("S3 access key") .create(OPT_S3S_KEY)); opts.addOption(OptionBuilder.withArgName("secret").isRequired(false).hasArg() .withDescription("Secret key for S3 account").create(OPT_S3S_SECRET)); opts.addOption(OptionBuilder.withArgName("bucket").isRequired(false).hasArg().withDescription( "Optional bucket name for storage. If not specified then an unique bucket name will be generated") .create(OPT_BUCKET)); // opts.addOption(OptionBuilder.withArgName("US|EU").hasArg(). // withDescription( // "Where the new bucket should be created. Default US").create( // OPT_LOCATION)); opts.addOption(OptionBuilder.withArgName("path").isRequired(false).hasArg() .withDescription("Local directory path").create(OPT_LOCAL_DIR)); opts.addOption(OptionBuilder.withArgName("name").isRequired(false).hasArg() .withDescription("Remote directory name").create(OPT_REMOTE_DIR)); opts.addOption(OptionBuilder.withArgName("password").isRequired(false).hasArg() .withDescription("Encryption password").create(OPT_ENC_PASSWORD)); opts.addOption(OptionBuilder.withArgName("patterns").hasArgs() .withDescription("Comma separated exclude file patterns like '*.tmp,*/dir/*.tmp'") .create(OPT_EXCLUDE_PATTERNS)); opts.addOption(OptionBuilder.withArgName("patterns").hasArgs().withDescription( "Comma separated include patterns like '*.java'. If not specified, then all files in specified local directory will be included") .create(OPT_INCLUDE_PATTERNS)); if (args.length == 0) { printUsage(opts); return; } CommandLine cmd = null; try { cmd = new GnuParser().parse(opts, args); if (cmd.hasOption(CMD_HELP)) { printUsage(opts); return; } if (cmd.hasOption(CMD_VERSION)) { System.out.println("s3dirsync version " + Version.CURRENT_VERSION); return; } String awsKey = cmd.getOptionValue(OPT_S3S_KEY); String awsSecret = cmd.getOptionValue(OPT_S3S_SECRET); String bucket = cmd.getOptionValue(OPT_BUCKET); String bucketLocation = cmd.getOptionValue(OPT_LOCATION); String localDir = cmd.getOptionValue(OPT_LOCAL_DIR); String remoteDir = cmd.getOptionValue(OPT_REMOTE_DIR); String password = cmd.getOptionValue(OPT_ENC_PASSWORD); String exclude = cmd.getOptionValue(OPT_EXCLUDE_PATTERNS); String include = cmd.getOptionValue(OPT_INCLUDE_PATTERNS); if (StringUtils.isBlank(awsKey) || StringUtils.isBlank(awsSecret)) { System.out.println("S3 account data required"); return; } if (StringUtils.isBlank(bucket)) { bucket = awsKey + ".dirsync"; } if (cmd.hasOption(CMD_DELETE_BUCKET)) { if (StringUtils.isBlank(bucket)) { System.out.println("Bucket name required"); return; } int deleted = S3Utils.deleteBucket(awsKey, awsSecret, bucket); System.out.println("Deleted objects: " + deleted); return; } if (cmd.hasOption(CMD_LIST_BUCKETS)) { for (String str : S3Utils.listBuckets(awsKey, awsSecret)) { System.out.println(str); } return; } if (cmd.hasOption(CMD_LIST_BUCKET)) { if (StringUtils.isBlank(bucket)) { System.out.println("Bucket name required"); return; } for (String str : S3Utils.listObjects(awsKey, awsSecret, bucket)) { System.out.println(str); } return; } if (StringUtils.isBlank(password)) { System.out.println("Encryption password required"); return; } char[] psw = password.toCharArray(); DirSync ds = new DirSync(awsKey, awsSecret, bucket, bucketLocation, psw); ds.setExcludePatterns(parseSubargumenths(exclude)); ds.setIncludePatterns(parseSubargumenths(include)); if (cmd.hasOption(CMD_SUMMARY)) { ds.printStorageSummary(); return; } if (StringUtils.isBlank(remoteDir)) { System.out.println("Remote directory name required"); return; } if (cmd.hasOption(CMD_DELETE_DIR)) { ds.deleteFolder(remoteDir); return; } if (cmd.hasOption(CMD_LIST_DIR)) { Folder folder = ds.getFolder(remoteDir); if (folder == null) { System.out.println("No such folder found: " + remoteDir); return; } for (Map.Entry<String, FileInfo> entry : folder.getIndexData().entrySet()) { System.out.println(entry.getKey() + " (" + FileUtils.byteCountToDisplaySize(entry.getValue().getLength()) + ")"); } return; } if (cmd.hasOption(CMD_CLEANUP)) { ds.cleanUp(); return; } if (cmd.hasOption(CMD_CHANGE_PASSWORD)) { String newPassword = cmd.getOptionValue(CMD_CHANGE_PASSWORD); if (StringUtils.isBlank(newPassword)) { System.out.println("new password required"); return; } char[] chars = newPassword.toCharArray(); ds.changePassword(chars); newPassword = null; Arrays.fill(chars, ' '); return; } if (StringUtils.isBlank(localDir)) { System.out.println(OPT_LOCAL_DIR + " argument required"); return; } String direction = ""; boolean up = false; boolean snapshot = false; if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_UPDATE))) { direction = cmd.getOptionValue(CMD_UPDATE); } else if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_SNAPSHOT))) { direction = cmd.getOptionValue(CMD_SNAPSHOT); snapshot = true; } if (StringUtils.isBlank(direction)) { System.out.println("Operation direction required"); return; } up = StringUtils.equalsIgnoreCase(OPT_UP, direction); File baseDir = new File(localDir); if (!baseDir.exists() && !baseDir.mkdirs()) { System.out.println("Invalid local directory: " + baseDir.getAbsolutePath()); return; } ds.syncFolder(baseDir, remoteDir, up, snapshot); } catch (DirSyncException e) { System.out.println(e.getMessage()); e.printStackTrace(); } catch (ParseException e) { System.out.println(e.getMessage()); printUsage(opts); } catch (Exception e) { e.printStackTrace(System.err); } }
From source file:executables.Align.java
@SuppressWarnings("static-access") public static void main(String[] args) throws IOException { Options options = new Options() .addOption(OptionBuilder.withArgName("f1").withDescription("Fasta file 1").hasArg().create("f1")) .addOption(OptionBuilder.withArgName("f2").withDescription("Fasta file 2").hasArg().create("f2")) .addOption(OptionBuilder.withArgName("s1").withDescription("sequence 1").hasArg().create("s1")) .addOption(OptionBuilder.withArgName("s2").withDescription("sequence 2").hasArg().create("s2")) .addOption(OptionBuilder.withArgName("gap-linear").withDescription("Linear gap cost").hasArg() .create("gl")) .addOption(OptionBuilder.withArgName("gap-open").withDescription("Affine gap open cost").hasArg() .create("go")) .addOption(OptionBuilder.withArgName("gap-extend").withDescription("Affine gap extend cost") .hasArg().create("ge")) .addOption(OptionBuilder.withArgName("gap-function").withDescription("Gap function file").hasArg() .create("gf")) .addOption(//from w w w . ja va 2s. com OptionBuilder.withArgName("gapless").withDescription("Gapless alignment").create("gapless")) .addOption(OptionBuilder.withArgName("mode") .withDescription("Alignment mode: global,local,freeshift (Default: freeshift)").hasArg() .create('m')) .addOption(OptionBuilder.withArgName("match").withDescription("Match score").hasArg().create("ma")) .addOption(OptionBuilder.withArgName("mismatch").withDescription("Mismatch score").hasArg() .create("mi")) .addOption(OptionBuilder.withDescription("Do not append unaligned flanking sequences") .create("noflank")) .addOption(OptionBuilder.withArgName("check").withDescription("Calculate checkscore").create('c')) .addOption(OptionBuilder.withArgName("format").withDescription( "Output format, see String.format, parameters are: id1,id2,score,alignment (alignment only, if -f is specified); (default: '%s %s %.4f' w/o -f and '%s %s %.4f\n%s' w/ -f)") .hasArg().create("format")) .addOption(OptionBuilder.withArgName("matrix") .withDescription("Output dynamic programming matrix as well").create("matrix")) .addOption(OptionBuilder.withArgName("quasar-format") .withDescription("Scoring matrix in quasar format").hasArg().create('q')) .addOption( OptionBuilder.withArgName("pairs").withDescription("Pairs file").hasArg().create("pairs")) .addOption(OptionBuilder.withArgName("output").withDescription("Output").hasArg().create('o')) .addOption(OptionBuilder.withArgName("seqlib").withDescription("Seqlib file").hasArg() .create("seqlib")) .addOption(OptionBuilder.withArgName("full").withDescription("Full output").create('f')); CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); LongScoring<CharSequence> scoring = createScoring(cmd); AlignmentMode mode = createMode(cmd); if (mode == null) throw new ParseException("Mode unknown: " + cmd.getOptionValue('m')); Iterator<MutablePair<String, String>> idIterator = createSequences(scoring, cmd); GapCostFunction gap = createGapFunction(cmd); String format = getFormat(cmd); LongAligner<CharSequence> aligner; if (gap instanceof AffineGapCostFunction) aligner = new LongAligner<CharSequence>(scoring, ((AffineGapCostFunction) gap).getGapOpen(), ((AffineGapCostFunction) gap).getGapExtend(), mode); else if (gap instanceof LinearGapCostFunction) aligner = new LongAligner<CharSequence>(scoring, ((LinearGapCostFunction) gap).getGap(), mode); else if (gap instanceof InfiniteGapCostFunction) aligner = new LongAligner<CharSequence>(scoring, mode); else throw new RuntimeException("Gap cost function " + gap.toString() + " currently not supported!"); SimpleAlignmentFormatter formatter = cmd.hasOption('f') ? new SimpleAlignmentFormatter().setAppendUnaligned(!cmd.hasOption("noflank")) : null; CheckScore checkscore = cmd.hasOption('c') ? new CheckScore() : null; Alignment alignment = checkscore != null || formatter != null ? new Alignment() : null; float score; String ali; LineOrientedFile out = new LineOrientedFile( cmd.hasOption('o') ? cmd.getOptionValue('o') : LineOrientedFile.STDOUT); Writer wr = out.startWriting(); while (idIterator.hasNext()) { MutablePair<String, String> ids = idIterator.next(); score = alignment == null ? aligner.alignCache(ids.Item1, ids.Item2) : aligner.alignCache(ids.Item1, ids.Item2, alignment); ali = formatter != null ? formatter.format(alignment, scoring, gap, mode, scoring.getCachedSubject(ids.Item1), scoring.getCachedSubject(ids.Item2)) : ""; out.writeLine(String.format(Locale.US, format, ids.Item1, ids.Item2, score, ali)); if (cmd.hasOption("matrix")) { aligner.writeMatrix(wr, aligner.getScoring().getCachedSubject(ids.Item1).toString().toCharArray(), aligner.getScoring().getCachedSubject(ids.Item2).toString().toCharArray()); } if (checkscore != null) checkscore.checkScore(aligner, scoring.getCachedSubject(ids.Item1).length(), scoring.getCachedSubject(ids.Item2).length(), alignment, score); } out.finishWriting(); } catch (ParseException e) { e.printStackTrace(); HelpFormatter f = new HelpFormatter(); f.printHelp("Align", options); } }
From source file:com.hurence.logisland.plugin.PluginManager.java
public static void main(String... args) throws Exception { System.out.println(BannerLoader.loadBanner()); String logislandHome = new File( new File(PluginManager.class.getProtectionDomain().getCodeSource().getLocation().getPath()) .getParent()).getParent(); System.out.println("Using Logisland home: " + logislandHome); Options options = new Options(); OptionGroup mainGroup = new OptionGroup() .addOption(OptionBuilder.withDescription( "Install a component. It can be either a logisland plugin or a kafka connect module.") .withArgName("artifact").hasArgs(1).withLongOpt("install").create("i")) .addOption(OptionBuilder.withDescription( "Removes a component. It can be either a logisland plugin or a kafka connect module.") .withArgName("artifact").hasArgs(1).withLongOpt("remove").create("r")) .addOption(OptionBuilder.withDescription("List installed components.").withLongOpt("list") .create("l")); mainGroup.setRequired(true);/* w ww .java 2 s .c o m*/ options.addOptionGroup(mainGroup); options.addOption(OptionBuilder.withDescription("Print this help.").withLongOpt("help").create("h")); try { CommandLine commandLine = new PosixParser().parse(options, args); System.out.println(commandLine.getArgList()); if (commandLine.hasOption("l")) { listPlugins(); } else if (commandLine.hasOption("i")) { installPlugin(commandLine.getOptionValue("i"), logislandHome); } else if (commandLine.hasOption("r")) { removePlugin(commandLine.getOptionValue("r")); } else { printUsage(options); } } catch (ParseException e) { if (!options.hasOption("h")) { System.err.println(e.getMessage()); System.out.println(); } printUsage(options); } }
From source file:es.eucm.ead.exporter.ExporterMain.java
@SuppressWarnings("all") public static void main(String args[]) { Options options = new Options(); Option help = new Option("h", "help", false, "print this message"); Option quiet = new Option("q", "quiet", false, "be extra quiet"); Option verbose = new Option("v", "verbose", false, "be extra verbose"); Option legacy = OptionBuilder.withArgName("s> <t").hasArgs(3) .withDescription(/*from www .jav a2 s . c om*/ "source is a version 1.x game; must specify\n" + "<simplify> if 'true', simplifies result\n" + "<translate> if 'true', enables translation") .withLongOpt("import").create("i"); Option war = OptionBuilder.withArgName("web-base").hasArg() .withDescription("WAR packaging (web app); " + "must specify\n<web-base> the base WAR directory") .withLongOpt("war").create("w"); Option jar = OptionBuilder.withDescription("JAR packaging (desktop)").withLongOpt("jar").create("j"); Option apk = OptionBuilder.withArgName("props> <adk> <d").hasArgs(3) .withDescription("APK packaging (android); must specify \n" + "<props> (a properties file) \n" + "<adk> (location of the ADK to use) \n" + "<deploy> ('true' to install & deploy)") .withLongOpt("apk").create("a"); // EAD option Option ead = OptionBuilder.withDescription("EAD packaging (eAdventure)").withLongOpt("ead").create("e"); options.addOption(legacy); options.addOption(help); options.addOption(quiet); options.addOption(verbose); options.addOption(jar); options.addOption(war); options.addOption(apk); options.addOption(ead); CommandLineParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException pe) { System.err.println("Error parsing command-line: " + pe.getMessage()); showHelp(options); return; } // general options String[] extras = cmd.getArgs(); if (cmd.hasOption(help.getOpt()) || extras.length < 2) { showHelp(options); return; } if (cmd.hasOption(verbose.getOpt())) { verbosity = Verbose; } if (cmd.hasOption(quiet.getOpt())) { verbosity = Quiet; } // import String source = extras[0]; // optional import step if (cmd.hasOption(legacy.getOpt())) { String[] values = cmd.getOptionValues(legacy.getOpt()); AdventureConverter converter = new AdventureConverter(); if (values.length > 0 && values[0].equalsIgnoreCase("true")) { converter.setEnableSimplifications(true); } if (values.length > 1 && values[1].equalsIgnoreCase("true")) { converter.setEnableTranslations(true); } // set source for next steps to import-target source = converter.convert(source, null); } if (cmd.hasOption(jar.getOpt())) { if (checkFilesExist(cmd, options, source)) { JarExporter e = new JarExporter(); e.export(source, extras[1], verbosity.equals(Quiet) ? new QuietStream() : System.err); } } else if (cmd.hasOption(apk.getOpt())) { String[] values = cmd.getOptionValues(apk.getOpt()); if (checkFilesExist(cmd, options, values[0], values[1], source)) { AndroidExporter e = new AndroidExporter(); Properties props = new Properties(); File propsFile = new File(values[0]); try { props.load(new FileReader(propsFile)); props.setProperty(AndroidExporter.SDK_HOME, props.getProperty(AndroidExporter.SDK_HOME, values[1])); } catch (IOException ioe) { System.err.println("Could not load properties from " + propsFile.getAbsolutePath()); return; } e.export(source, extras[1], props, values.length > 2 && values[2].equalsIgnoreCase("true")); } } else if (cmd.hasOption(war.getOpt())) { if (checkFilesExist(cmd, options, extras[0])) { WarExporter e = new WarExporter(); e.setWarPath(cmd.getOptionValue(war.getOpt())); e.export(source, extras[1]); } } else if (cmd.hasOption(ead.getOpt())) { String destiny = extras[1]; if (!destiny.endsWith(".ead")) { destiny += ".ead"; } FileUtils.zip(new File(destiny), new File(source)); } else { showHelp(options); } }
From source file:bogdanrechi.xmlo.Xmlo.java
/** * Main method./*ww w . j a v a2 s . co m*/ * * @param args * Program arguments. */ @SuppressWarnings("static-access") public static void main(String[] args) { long timeStart = System.currentTimeMillis(); _log = Logger.getLogger(Xmlo.class); Options argOptions = new Options(); OptionGroup operationTypes = new OptionGroup(); operationTypes.addOption( OptionBuilder.withDescription("XPath query").hasArg().withArgName("file").create("xpath")); operationTypes.addOption( OptionBuilder.withDescription("XSLT transformation").hasArg().withArgName("file").create("xslt")); operationTypes.addOption( OptionBuilder.withDescription("XQuery (with $sourceFilePath, see XmlOperations for details)") .hasArg().withArgName("file").create("xquery")); operationTypes .addOption(OptionBuilder.withDescription("XSD verify").hasArgs().withArgName("file").create("xsd")); operationTypes .addOption(OptionBuilder.withDescription("DTD verify").hasArgs().withArgName("file").create("dtd")); argOptions.addOptionGroup(operationTypes); argOptions.addOption(OptionBuilder.withDescription("on screen information while performing") .withLongOpt("verbose").create("v")); argOptions.addOption(OptionBuilder.withDescription("output non-void or invalid-type results only") .withLongOpt("results-only").create("o")); argOptions.addOption(OptionBuilder.withDescription("replicate input structure on the destination side") .withLongOpt("keep-structure").create("k")); argOptions.addOption(OptionBuilder.withDescription("recursive browsing of the target structure") .withLongOpt("resursive").create("r")); argOptions.addOption(OptionBuilder.withDescription("XPath and XQuery results not numbered") .withLongOpt("not-numbered").create("nn")); argOptions.addOption(OptionBuilder.withDescription("destination files extension").hasArg() .withArgName("ext").withLongOpt("extension").create("x")); argOptions.addOption(OptionBuilder.withDescription("target files mask").hasArg().withArgName("files mask") .withLongOpt("target").create("t")); OptionGroup destinationGroup = new OptionGroup(); destinationGroup.addOption(OptionBuilder.withDescription("destination file").hasArg().withArgName("file") .withLongOpt("destination-file").create("df")); destinationGroup.addOption(OptionBuilder.withDescription("destination folder").hasArg() .withArgName("folder").withLongOpt("destination-directory").create("dd")); destinationGroup.addOption(OptionBuilder.withDescription("destination terminal (and verbose)") .withLongOpt("destination-terminal").create("dt")); argOptions.addOptionGroup(destinationGroup); argOptions.addOption(OptionBuilder.withDescription("file containing namespaces aliases").hasArg() .withArgName("file").withLongOpt("namespaces").create("n")); argOptions.addOption(OptionBuilder.withDescription("usage information").withLongOpt("help").create("h")); argOptions.addOption(OptionBuilder.withDescription("show examples").withLongOpt("examples").create("e")); argOptions.addOption(OptionBuilder.withDescription("keep blank nodes while printing") .withLongOpt("keep-blanks").create("b")); argOptions.addOption( OptionBuilder.withDescription("show duration for each file when the verbose option is activated") .withLongOpt("show-duration").create("d")); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(argOptions, args); if (cmd.hasOption('h') || cmd.hasOption('e') || cmd.getOptions().length == 0) { Format.println("\n" + General.getAboutInformation("resources/xmlo/metadata.properties")); if (cmd.hasOption('h') || cmd.getOptions().length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("xmlo", "where:", argOptions, null, true); Format.println(); } if (cmd.hasOption("e")) { String examples = Files.readTextFileFromResources("resources/xmlo/examples.txt", _errorMessage); if (examples != null) Format.println(examples); else { Format.println("Internal error! Please see the log file for detalis."); _log.error(_errorMessage.get()); System.exit(1); } } System.exit(0); return; } Format.println(); // options if (cmd.hasOption('r')) _recursive = true; if (cmd.hasOption('k')) _keepStructure = true; if (cmd.hasOption('o')) _resultsOnly = true; if (cmd.hasOption('v')) _verbose = true; if (cmd.hasOption('b')) _keepBlanks = true; if (cmd.hasOption('d')) _showDuration = true; if (cmd.hasOption('x')) _extension = "." + cmd.getOptionValue('x'); if (cmd.hasOption("nn")) _notNumbered = true; if (cmd.hasOption("df")) { _destination = cmd.getOptionValue("df"); if (Files.isFolder(_destination)) printErrorAndExit("The destination is a folder!"); _destinationIsFile = true; } if (cmd.hasOption("dd")) { _destination = cmd.getOptionValue("dd"); if (!Files.exists(_destination)) printErrorAndExit("The destination folder does not exist!"); if (!Files.isFolder(_destination)) printErrorAndExit("The destination is not a folder!"); } if (cmd.hasOption("dt")) _destinationIsTerminal = _verbose = true; if (cmd.hasOption('t')) _target = cmd.getOptionValue('t'); if (cmd.hasOption('n')) { _namespaces = cmd.getOptionValue('n'); extractNamespacesAliases(); } // operations if (cmd.hasOption("xpath")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_XPATH; doXPath(cmd.getOptionValue("xpath")); } if (cmd.hasOption("xslt")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_XSLT; doXslt(cmd.getOptionValue("xslt")); } if (cmd.hasOption("xquery")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_XQUERY; doXQuery(cmd.getOptionValue("xquery")); } if (cmd.hasOption("xsd")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_XSD; doXsd(cmd.getOptionValues("xsd")); } if (cmd.hasOption("dtd")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_DTD; doDtd(cmd.getOptionValues("dtd")); } } catch (ParseException e) { printErrorAndExit(e.getMessage()); } Format.println("Finished%s.", _showDuration ? " in " + TimeMeasure.printDuration(timeStart) : ""); if (Platform.SYSTEM_IS_LINUX) Format.println(); System.exit(0); }
From source file:edu.harvard.med.screensaver.io.screens.StudyCreator.java
@SuppressWarnings("static-access") public static void main(String[] args) { final CommandLineApplication app = new CommandLineApplication(args); app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("first name") .withLongOpt("lead-screener-first-name").create("lf")); app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("last name") .withLongOpt("lead-screener-last-name").create("ll")); app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("email") .withLongOpt("lead-screener-email").create("le")); app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("first name") .withLongOpt("lab-head-first-name").create("hf")); app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("last name") .withLongOpt("lab-head-last-name").create("hl")); app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("email") .withLongOpt("lab-head-email").create("he")); List<String> desc = new ArrayList<String>(); for (ScreenType t : EnumSet.allOf(ScreenType.class)) desc.add(t.name());//from w w w .j a v a 2s. co m app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("screen type") .withLongOpt("screen-type").withDescription(StringUtils.makeListString(desc, ", ")).create("y")); desc.clear(); for (StudyType t : EnumSet.allOf(StudyType.class)) desc.add(t.name()); app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("study type") .withLongOpt("study-type").withDescription(StringUtils.makeListString(desc, ", ")).create("yy")); app.addCommandLineOption( OptionBuilder.hasArg().isRequired().withArgName("summary").withLongOpt("summary").create("s")); app.addCommandLineOption( OptionBuilder.hasArg().isRequired().withArgName("title").withLongOpt("title").create("t")); app.addCommandLineOption( OptionBuilder.hasArg().withArgName("protocol").withLongOpt("protocol").create("p")); app.addCommandLineOption( OptionBuilder.hasArg().isRequired().withArgName("#").withLongOpt("facilityId").create("i")); app.addCommandLineOption(OptionBuilder.hasArg(false).withLongOpt("replace") .withDescription("replace an existing Screen with the same facilityId").create("r")); app.addCommandLineOption(OptionBuilder.withLongOpt("key-input-by-wellkey") .withDescription("default value is to key by reagent vendor id").create("keyByWellId")); app.addCommandLineOption(OptionBuilder.withLongOpt("key-input-by-facility-id") .withDescription("default value is to key by reagent vendor id").create("keyByFacilityId")); app.addCommandLineOption(OptionBuilder.withLongOpt("key-input-by-compound-name") .withDescription("default value is to key by reagent vendor id").create("keyByCompoundName")); app.addCommandLineOption(OptionBuilder.withDescription( "optional: pivot the input col/rows so that the AT names are in Col1, and the AT well_id/rvi's are in Row1") .withLongOpt("annotation-names-in-col1").create("annotationNamesInCol1")); app.addCommandLineOption(OptionBuilder.hasArg().withArgName("file").withLongOpt("data-file").create("f")); app.addCommandLineOption(OptionBuilder.withArgName("parseLincsSpecificFacilityID") .withLongOpt("parseLincsSpecificFacilityID").create("parseLincsSpecificFacilityID")); app.processOptions(/* acceptDatabaseOptions= */true, /* acceptAdminUserOptions= */true); execute(app); }
From source file:TmlCommandLine.java
@SuppressWarnings("static-access") public static void main(String[] args) { long time = System.nanoTime(); options = new Options(); // Repository options.addOption(OptionBuilder.withDescription( "Full path of the repository folder, where TML will retrieve (or insert) documents. (e.g. /home/user/lucene).") .hasArg().withArgName("folder").isRequired().create("repo")); // Verbosity/*from w ww . j a v a 2 s. c o m*/ options.addOption( OptionBuilder.withDescription("Verbose output in the console (it goes verbose to the log file).") .hasArg(false).isRequired(false).create("v")); // Operation on corpus options.addOption(OptionBuilder.hasArg(false).withDescription("Performs an operation on a corpus.") .isRequired(false).create("O")); // The list of operations options.addOption(OptionBuilder.withDescription( "The list of operations you want to execute on the corpus. (e.g. PassageDistances,PassageSimilarity .") .hasArgs().withValueSeparator(',').withArgName("list").isRequired(false).withLongOpt("operations") .create()); // The file to store the results options.addOption(OptionBuilder.withDescription("Folder where to store the results. (e.g. results/run01/).") .hasArg().withArgName("folder").isRequired(false).withLongOpt("oresults").create()); // The corpus on which operate options.addOption(OptionBuilder.withDescription( "Lucene query that defines the corpus to operate with. (e.g. \"type:sentence AND reference:Document01\").") .hasArg().withArgName("query").isRequired(false).withLongOpt("ocorpus").create()); // The corpus on which operate options.addOption(OptionBuilder.withDescription( "Use all documents in repository as single document corpora, it can be sentence or paragraph based. (e.g. sentence).") .hasArgs().withArgName("type").isRequired(false).withLongOpt("oalldocs").create()); // The properties file for the corpus options.addOption(OptionBuilder.withDescription("Properties file with the corpus parameters (optional).") .hasArg().withArgName("parameter file").isRequired(false).withLongOpt("ocpar").create()); // Background knowledge corpus options.addOption(OptionBuilder.withDescription( "Lucene query that defines a background knowledge on which the corpus will be projected. (e.g. \"type:sentences AND reference:Document*\").") .hasArg().withArgName("query").isRequired(false).withLongOpt("obk").create()); // Background knowledge parameters options.addOption(OptionBuilder.withDescription( "Properties file with the background knowledge corpus parameters, if not set it will use the same as the corpus.") .hasArg().withArgName("parameter file").isRequired(false).withLongOpt("obkpar").create()); // Term selection String criteria = ""; for (TermSelection tsel : TermSelection.values()) { criteria += "," + tsel.name(); } criteria = criteria.substring(1); options.addOption(OptionBuilder.hasArgs().withArgName("name") .withDescription("Name of the Term selection criteria (" + criteria + ").").isRequired(false) .withValueSeparator(',').withLongOpt("otsel").create()); // Term selection threshold options.addOption(OptionBuilder.hasArgs().withArgName("number") .withDescription("Threshold for the tsel criteria option.").withType(Integer.TYPE).isRequired(false) .withValueSeparator(',').withLongOpt("otselth").create()); // Dimensionality reduction criteria = ""; for (DimensionalityReduction dim : DimensionalityReduction.values()) { criteria += "," + dim.name(); } criteria = criteria.substring(1); options.addOption(OptionBuilder.hasArgs().withArgName("list") .withDescription("Name of the Dimensionality Reduction criteria. (e.g. " + criteria + ").") .isRequired(false).withValueSeparator(',').withLongOpt("odim").create()); // Dimensionality reduction threshold options.addOption(OptionBuilder.hasArgs().withArgName("list") .withDescription("Threshold for the dim options. (e.g. 0,1,2).").isRequired(false) .withValueSeparator(',').withLongOpt("odimth").create()); // Local weight criteria = ""; for (LocalWeight weight : LocalWeight.values()) { criteria += "," + weight.name(); } criteria = criteria.substring(1); options.addOption(OptionBuilder.hasArgs().withArgName("list") .withDescription("Name of the Local Weight to apply. (e.g." + criteria + ").").isRequired(false) .withValueSeparator(',').withLongOpt("otwl").create()); // Global weight criteria = ""; for (GlobalWeight weight : GlobalWeight.values()) { criteria += "," + weight.name(); } criteria = criteria.substring(1); options.addOption(OptionBuilder.hasArgs().withArgName("list") .withDescription("Name of the Global Weight to apply. (e.g. " + criteria + ").").isRequired(false) .withValueSeparator(',').withLongOpt("otwg").create()); // Use Lanczos options.addOption(OptionBuilder.hasArg(false).withDescription("Use Lanczos for SVD decomposition.") .isRequired(false).withLongOpt("olanczos").create()); // Inserting documents in repository options.addOption(OptionBuilder.hasArg(false).withDescription("Insert documents into repository.") .isRequired(false).create("I")); // Max documents to insert options.addOption(OptionBuilder.hasArg().withArgName("number") .withDescription("Maximum number of documents to index or use in an operation.") .withType(Integer.TYPE).isRequired(false).withLongOpt("imaxdocs").create()); // Clean repository options.addOption( OptionBuilder.hasArg(false).withDescription("Empties the repository before inserting new ones.") .isRequired(false).withLongOpt("iclean").create()); // Use annotator options.addOption(OptionBuilder.hasArgs() .withDescription( "List of annotators to use when inserting the documents. (e.g. PennTreeAnnotator).") .isRequired(false).withValueSeparator(',').withLongOpt("iannotators").create()); // Documents folder options.addOption(OptionBuilder.hasArg().withArgName("folder") .withDescription("The folder that contains the documens to insert.").isRequired(false) .withLongOpt("idocs").create()); // Initializing the line parser CommandLineParser parser = new PosixParser(); try { line = parser.parse(options, args); } catch (ParseException e) { printHelp(options); return; } // Validate that either inserting or an operation are given if (!line.hasOption("I") && !line.hasOption("O")) { System.out.println("One of the options -I or -O must be present."); printHelp(options); return; } repositoryFolder = line.getOptionValue("repo"); try { if (line.hasOption("I")) { indexing(); } else if (line.hasOption("O")) { operation(); } } catch (ParseException e) { System.out.println(e.getMessage()); printHelp(options); return; } System.out.println("TML finished successfully in " + (System.nanoTime() - time) * 10E-9 + " seconds."); return; }
From source file:edu.harvard.med.iccbl.screensaver.io.screens.ConfirmedPositivesStudyCreator.java
@SuppressWarnings("static-access") public static void main(String[] args) { final ConfirmedPositivesStudyCreator app = new ConfirmedPositivesStudyCreator(args); String[] option = OPTION_STUDY_TITLE; app.addCommandLineOption(/*from w w w . j a v a2 s. c om*/ OptionBuilder.hasArg().withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = OPTION_STUDY_NUMBER; app.addCommandLineOption(OptionBuilder.hasArg().withType(Integer.class).withArgName(option[ARG_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = OPTION_STUDY_SUMMARY; app.addCommandLineOption( OptionBuilder.hasArg().withArgName(option[ARG_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = OPTION_REPLACE; app.addCommandLineOption(OptionBuilder.withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.withDescription(TEST_ONLY[DESCRIPTION_INDEX]) .withLongOpt(TEST_ONLY[LONG_OPTION_INDEX]).create(TEST_ONLY[SHORT_OPTION_INDEX])); app.processOptions(/* acceptDatabaseOptions= */true, /* acceptAdminUserOptions= */true); log.info("==== Running ConfirmedPositivesStudyCreator: " + app.toString() + "======"); final GenericEntityDAO dao = (GenericEntityDAO) app.getSpringBean("genericEntityDao"); final ScreenResultReporter report = (ScreenResultReporter) app.getSpringBean("screenResultReporter"); final ScreenResultsDAO screenResultsDao = (ScreenResultsDAO) app.getSpringBean("screenResultsDao"); final ScreenDAO screenDao = (ScreenDAO) app.getSpringBean("screenDao"); dao.doInTransaction(new DAOTransaction() { public void runTransaction() { try { AdministratorUser admin = app.findAdministratorUser(); boolean replaceStudyIfExists = app.isCommandLineFlagSet(OPTION_REPLACE[SHORT_OPTION_INDEX]); String title = null; String summary = null; String studyFacilityId = ScreensaverConstants.DEFAULT_BATCH_STUDY_ID_CONFIRMATION_SUMMARY; if (app.isCommandLineFlagSet(OPTION_STUDY_NUMBER[SHORT_OPTION_INDEX])) { studyFacilityId = app.getCommandLineOptionValue(OPTION_STUDY_NUMBER[SHORT_OPTION_INDEX], String.class); } title = DEFAULT_STUDY_TITLE; summary = DEFAULT_STUDY_SUMMARY; if (app.isCommandLineFlagSet(OPTION_STUDY_TITLE[SHORT_OPTION_INDEX])) { title = app.getCommandLineOptionValue(OPTION_STUDY_TITLE[SHORT_OPTION_INDEX]); } if (app.isCommandLineFlagSet(OPTION_STUDY_SUMMARY[SHORT_OPTION_INDEX])) { summary = app.getCommandLineOptionValue(OPTION_STUDY_SUMMARY[SHORT_OPTION_INDEX]); } //TODO: refactor this code that checks for the exisiting study Screen study = dao.findEntityByProperty(Screen.class, Screen.facilityId.getPropertyName(), studyFacilityId); if (study != null) { // first check if the study is out of date ScreenResult latestScreenResult = screenResultsDao.getLatestScreenResult(); if (latestScreenResult == null) { log.info("No screen results found in the database"); System.exit(0); } else if (study.getDateCreated().compareTo(latestScreenResult.getDateCreated()) < 1) { screenDao.deleteStudy(study); } else if (replaceStudyIfExists) { screenDao.deleteStudy(study); } else { String msg = "study " + studyFacilityId + " already exists and is up-to-date (as determined by the date of the latest uploaded screen result). " + "Use the --" + OPTION_REPLACE[LONG_OPTION_INDEX] + " flag to delete the existing study first."; log.info(msg); System.exit(0); } } int count = app.createStudy(admin, studyFacilityId, title, summary, dao, report); study = dao.findEntityByProperty(Screen.class, Screen.facilityId.getPropertyName(), studyFacilityId); String subject = "Study created: \"" + study.getTitle() + "\""; //app.getMessages().getMessage("Study generated"); if (app.isCommandLineFlagSet(TEST_ONLY[SHORT_OPTION_INDEX])) { subject = "[TEST ONLY, no commits] " + subject; } String msg = "Study: " + study.getFacilityId() + "\n\"" + study.getTitle() + "\"\n" + study.getSummary() + "\n\nTotal count of Confirmed Positives considered in the study: " + count; app.sendAdminEmails(subject, msg); } catch (MessagingException e) { throw new DAOTransactionRollbackException(e); } if (app.isCommandLineFlagSet(TEST_ONLY[SHORT_OPTION_INDEX])) { throw new DAOTransactionRollbackException("Rollback, testing only"); } } }); log.info("==== finished ConfirmedPositivesStudyCreator ======"); }
From source file:edu.harvard.med.iccbl.screensaver.io.users.UserAgreementExpirationUpdater.java
@SuppressWarnings("static-access") public static void main(String[] args) { final UserAgreementExpirationUpdater app = new UserAgreementExpirationUpdater(args); app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(SCREEN_TYPE_OPTION[ARG_INDEX]) .withDescription(SCREEN_TYPE_OPTION[DESCRIPTION_INDEX]) .withLongOpt(SCREEN_TYPE_OPTION[LONG_OPTION_INDEX]).create(SCREEN_TYPE_OPTION[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.hasArg().withArgName(NOTIFY_DAYS_AHEAD_OPTION[ARG_INDEX]) .withDescription(NOTIFY_DAYS_AHEAD_OPTION[DESCRIPTION_INDEX]) .withLongOpt(NOTIFY_DAYS_AHEAD_OPTION[LONG_OPTION_INDEX]) .create(NOTIFY_DAYS_AHEAD_OPTION[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.hasArg().withArgName(EXPIRATION_TIME_OPTION[ARG_INDEX]) .withDescription(EXPIRATION_TIME_OPTION[DESCRIPTION_INDEX]) .withLongOpt(EXPIRATION_TIME_OPTION[LONG_OPTION_INDEX]) .create(EXPIRATION_TIME_OPTION[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.withDescription(EXPIRE_OPTION[DESCRIPTION_INDEX]) .withLongOpt(EXPIRE_OPTION[LONG_OPTION_INDEX]).create(EXPIRE_OPTION[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.hasArg().withArgName(EXPIRATION_EMAIL_MESSAGE_LOCATION[ARG_INDEX]) .withDescription(EXPIRATION_EMAIL_MESSAGE_LOCATION[DESCRIPTION_INDEX]) .withLongOpt(EXPIRATION_EMAIL_MESSAGE_LOCATION[LONG_OPTION_INDEX]) .create(EXPIRATION_EMAIL_MESSAGE_LOCATION[SHORT_OPTION_INDEX])); app.addCommandLineOption(OptionBuilder.withDescription(TEST_ONLY[DESCRIPTION_INDEX]) .withLongOpt(TEST_ONLY[LONG_OPTION_INDEX]).create(TEST_ONLY[SHORT_OPTION_INDEX])); app.processOptions(true, true);/*from w w w. j a v a2 s . c o m*/ log.info("==== Running UserAgreementExpirationUpdater: " + app.toString() + "======"); final GenericEntityDAO dao = (GenericEntityDAO) app.getSpringBean("genericEntityDao"); app.init(); dao.doInTransaction(new DAOTransaction() { public void runTransaction() { app.setScreenType(app.getCommandLineOptionEnumValue(SCREEN_TYPE_OPTION[SHORT_OPTION_INDEX], ScreenType.class)); int timeToExpireDays = DEFAULT_EXPIRATION_TIME_DAYS; if (app.isCommandLineFlagSet(EXPIRATION_TIME_OPTION[SHORT_OPTION_INDEX])) { timeToExpireDays = app.getCommandLineOptionValue(EXPIRATION_TIME_OPTION[SHORT_OPTION_INDEX], Integer.class); } try { try { if (app.isCommandLineFlagSet(NOTIFY_DAYS_AHEAD_OPTION[SHORT_OPTION_INDEX])) { Integer daysAheadToNotify = app.getCommandLineOptionValue( NOTIFY_DAYS_AHEAD_OPTION[SHORT_OPTION_INDEX], Integer.class); app.notifyAhead(daysAheadToNotify, timeToExpireDays); } else if (app.isCommandLineFlagSet(EXPIRE_OPTION[SHORT_OPTION_INDEX])) { app.expire(timeToExpireDays); } else { app.showHelpAndExit("Must specify either the \"" + NOTIFY_DAYS_AHEAD_OPTION[LONG_OPTION_INDEX] + "\" option or the \"" + EXPIRE_OPTION[LONG_OPTION_INDEX] + "\" option"); } } catch (OperationRestrictedException e) { app.sendErrorMail("OperationRestrictedException: Could not complete expiration service", app.toString(), e); throw new DAOTransactionRollbackException(e); } } catch (MessagingException e) { String msg = "Admin email operation not completed due to MessagingException"; log.error(msg + ":\nApp: " + app.toString(), e); throw new DAOTransactionRollbackException(msg, e); } if (app.isCommandLineFlagSet(TEST_ONLY[SHORT_OPTION_INDEX])) { throw new DAOTransactionRollbackException("Rollback, testing only"); } } }); log.info("==== finished UserAgreementExpirationUpdater ======"); }
From source file:com.samsung.sjs.Compiler.java
@SuppressWarnings("static-access") public static void main(String[] args) throws IOException, SolverException, InterruptedException { boolean debug = false; boolean use_gc = true; CompilerOptions.Platform p = CompilerOptions.Platform.Native; CompilerOptions opts = null;/*from w w w .jav a 2 s. c o m*/ boolean field_opts = false; boolean typecheckonly = false; boolean showconstraints = false; boolean showconstraintsolution = false; String[] decls = null; String[] links = null; String[] objs = null; boolean guest = false; boolean stop_at_c = false; String external_compiler = null; boolean encode_vals = false; boolean x32 = false; boolean validate = true; boolean interop = false; boolean boot_interop = false; boolean oldExpl = false; String explanationStrategy = null; boolean efl = false; Options options = new Options(); options.addOption("debugcompiler", false, "Enable compiler debug spew"); //options.addOption("o", true, "Set compiler output file (must be .c)"); options.addOption(OptionBuilder //.withArgName("o") .withLongOpt("output-file").withDescription("Output file (must be .c)").hasArg().withArgName("file") .create("o")); options.addOption(OptionBuilder.withLongOpt("target") .withDescription("Select target platform: 'native' or 'web'").hasArg().create()); options.addOption(OptionBuilder.withLongOpt("gc") .withDescription("Disable GC: param is 'on' (default) or 'off'").hasArg().create()); options.addOption(OptionBuilder .withDescription("Enable field access optimizations: param is 'true' (default) or 'false'").hasArg() .create("Xfields")); options.addOption(OptionBuilder .withDescription("Compile for encoded values. TEMPORARY. For testing interop codegen").hasArg() .create("XEncodedValues")); options.addOption(OptionBuilder.withLongOpt("typecheck-only") .withDescription("Only typecheck the file, don't compile").create()); options.addOption(OptionBuilder.withLongOpt("show-constraints") .withDescription("Show constraints generated during type inference").create()); options.addOption(OptionBuilder.withLongOpt("show-constraint-solution") .withDescription("Show solution to type inference constraints").create()); options.addOption(OptionBuilder.withLongOpt("extra-decls") .withDescription("Specify extra declaration files, comma-separated").hasArg() .withValueSeparator(',').create()); options.addOption(OptionBuilder.withLongOpt("native-libs") .withDescription("Specify extra linkage files, comma-separated").hasArg().withValueSeparator(',') .create()); Option extraobjs = OptionBuilder.withLongOpt("extra-objs") .withDescription("Specify extra .c/.cpp files, comma-separated").hasArg().withValueSeparator(',') .create(); extraobjs.setArgs(Option.UNLIMITED_VALUES); options.addOption(extraobjs); options.addOption(OptionBuilder.withLongOpt("guest-runtime") .withDescription( "Emit code to be called by another runtime (i.e., main() is written in another language).") .create()); options.addOption(OptionBuilder.withLongOpt("only-c") .withDescription("Generate C code, but do not attempt to compile it").create()); options.addOption(OptionBuilder.withLongOpt("c-compiler") .withDescription("Disable GC: param is 'on' (default) or 'off'").hasArg().create("cc")); options.addOption(OptionBuilder.withLongOpt("runtime-src") .withDescription("Specify path to runtime system source").hasArg().create()); options.addOption(OptionBuilder.withLongOpt("ext-path") .withDescription("Specify path to external dependency dir (GC, etc.)").hasArg().create()); options.addOption(OptionBuilder.withLongOpt("skip-validation") .withDescription("Run the backend without validating the results of type inference").create()); options.addOption(OptionBuilder.withLongOpt("m32").withDescription("Force 32-bit compilation").create()); options.addOption(OptionBuilder.withLongOpt("Xbootinterop") .withDescription("Programs start with global interop dirty flag set (experimental)").create()); options.addOption(OptionBuilder.withLongOpt("Xinterop") .withDescription("Enable (experimental) interoperability backend").create()); options.addOption(OptionBuilder.withDescription("C compiler default optimization level").create("O")); options.addOption(OptionBuilder.withDescription("C compiler optimization level 0").create("O0")); options.addOption(OptionBuilder.withDescription("C compiler optimization level 1").create("O1")); options.addOption(OptionBuilder.withDescription("C compiler optimization level 2").create("O2")); options.addOption(OptionBuilder.withDescription("C compiler optimization level 3").create("O3")); options.addOption( OptionBuilder.withLongOpt("oldExpl").withDescription("Use old error explanations").create()); String explanationStrategyHelp = "default: " + FixingSetFinder.defaultStrategy() + "; other choices: " + FixingSetFinder.strategyNames().stream().filter(s -> !s.equals(FixingSetFinder.defaultStrategy())) .collect(Collectors.joining(", ")); options.addOption(OptionBuilder.withLongOpt("explanation-strategy") .withDescription("Error explanation strategy to use (" + explanationStrategyHelp + ')').hasArg() .create()); options.addOption( OptionBuilder.withLongOpt("efl").withDescription("Set up efl environment in main()").create()); try { CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); String[] newargs = cmd.getArgs(); if (newargs.length != 1) { throw new ParseException("Invalid number of arguments"); } String sourcefile = newargs[0]; if (!sourcefile.endsWith(".js")) { throw new ParseException("Invalid file extension on input file: " + sourcefile); } String gc = cmd.getOptionValue("gc", "on"); if (gc.equals("on")) { use_gc = true; } else if (gc.equals("off")) { use_gc = false; } else { throw new ParseException("Invalid GC option: " + gc); } String fields = cmd.getOptionValue("Xfields", "true"); if (fields.equals("true")) { field_opts = true; } else if (fields.equals("false")) { field_opts = false; } else { throw new ParseException("Invalid field optimization option: " + fields); } String encoding = cmd.getOptionValue("XEncodedValues", "false"); if (encoding.equals("true")) { encode_vals = true; } else if (encoding.equals("false")) { encode_vals = false; } else { throw new ParseException("Invalid value encoding option: " + encode_vals); } String plat = cmd.getOptionValue("target", "native"); if (plat.equals("native")) { p = CompilerOptions.Platform.Native; } else if (plat.equals("web")) { p = CompilerOptions.Platform.Web; } else { throw new ParseException("Invalid target platform: " + plat); } if (cmd.hasOption("cc")) { external_compiler = cmd.getOptionValue("cc"); } if (cmd.hasOption("skip-validation")) { validate = false; } if (cmd.hasOption("typecheck-only")) { typecheckonly = true; } if (cmd.hasOption("show-constraints")) { showconstraints = true; } if (cmd.hasOption("show-constraint-solution")) { showconstraintsolution = true; } if (cmd.hasOption("debugcompiler")) { debug = true; } if (cmd.hasOption("m32")) { x32 = true; } if (cmd.hasOption("Xinterop")) { interop = true; } if (cmd.hasOption("Xbootinterop")) { boot_interop = true; if (!interop) { System.err.println("WARNING: --Xbootinterop enabled without --Xinterop (no effect)"); } } if (cmd.hasOption("oldExpl")) { oldExpl = true; } if (cmd.hasOption("explanation-strategy")) { explanationStrategy = cmd.getOptionValue("explanation-strategy"); } String output = cmd.getOptionValue("o"); if (output == null) { output = sourcefile.replaceFirst(".js$", ".c"); } else { if (!output.endsWith(".c")) { throw new ParseException("Invalid file extension on output file: " + output); } } String runtime_src = cmd.getOptionValue("runtime-src"); String ext_path = cmd.getOptionValue("ext-path"); if (ext_path == null) { ext_path = new File(".").getCanonicalPath() + "/external"; } if (cmd.hasOption("extra-decls")) { decls = cmd.getOptionValues("extra-decls"); } if (cmd.hasOption("native-libs")) { links = cmd.getOptionValues("native-libs"); } if (cmd.hasOption("extra-objs")) { objs = cmd.getOptionValues("extra-objs"); } if (cmd.hasOption("guest-runtime")) { guest = true; } if (cmd.hasOption("only-c")) { stop_at_c = true; } if (cmd.hasOption("efl")) { efl = true; } int coptlevel = -1; // default optimization if (cmd.hasOption("O3")) { coptlevel = 3; } else if (cmd.hasOption("O2")) { coptlevel = 2; } else if (cmd.hasOption("O1")) { coptlevel = 1; } else if (cmd.hasOption("O0")) { coptlevel = 0; } else if (cmd.hasOption("O")) { coptlevel = -1; } else { coptlevel = 3; } if (!Files.exists(Paths.get(sourcefile))) { System.err.println("File " + sourcefile + " was not found."); throw new FileNotFoundException(sourcefile); } String cwd = new java.io.File(".").getCanonicalPath(); opts = new CompilerOptions(p, sourcefile, debug, output, use_gc, external_compiler == null ? "clang" : external_compiler, external_compiler == null ? "emcc" : external_compiler, cwd + "/a.out", // emcc automatically adds .js new File(".").getCanonicalPath(), true, field_opts, showconstraints, showconstraintsolution, runtime_src, encode_vals, x32, oldExpl, explanationStrategy, efl, coptlevel); if (guest) { opts.setGuestRuntime(); } if (interop) { opts.enableInteropMode(); } if (boot_interop) { opts.startInInteropMode(); } opts.setExternalDeps(ext_path); if (decls != null) { for (String s : decls) { Path fname = FileSystems.getDefault().getPath(s); opts.addDeclarationFile(fname); } } if (links != null) { for (String s : links) { Path fname = FileSystems.getDefault().getPath(s); opts.addLinkageFile(fname); } } if (objs == null) { objs = new String[0]; } } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("sjsc", options); } if (opts != null) { // This typechecks, and depending on flags, also generates C compile(opts, typecheckonly, validate); // don't worry about type validation on command line for now if (!typecheckonly && !stop_at_c) { int ret = 0; // Kept around for debugging 32-bit... if (p == CompilerOptions.Platform.Native) { if (opts.m32()) { String[] x = new String[2]; x[0] = "-m32"; x[1] = opts.getExternalDeps() + "/gc/x86/lib/libgc.a"; ret = clang_compile(opts, objs, x); } else { ret = clang_compile(opts, objs, new String[0]); } } else { ret = emcc_compile(opts, objs, new String[0]); } // If clang failed, propagate the failure outwards if (ret != 0) { System.exit(ret); } } } }