List of usage examples for org.apache.commons.cli CommandLine hasOption
public boolean hasOption(char opt)
From source file:it.polimi.tower4clouds.rules.batch.BatchTool.java
public static void main(String[] args) { Options options = buildOptions();//from w w w . j ava 2 s .co m CommandLineParser parser = new BasicParser(); HelpFormatter formatter = new HelpFormatter(); FileInputStream inputFile = null; try { // parse the command line arguments CommandLine cmd = parser.parse(options, args); if (cmd.getOptions().length != 1) { System.err.println("Parsing failed: Reason: one and only one option is required"); formatter.printHelp("qos-models", options); } else if (cmd.hasOption("h")) { formatter.printHelp("qos-models", options); } else if (cmd.hasOption("v")) { String file = cmd.getOptionValue("v"); inputFile = new FileInputStream(file); MonitoringRules rules = XMLHelper.deserialize(inputFile, MonitoringRules.class); RulesValidator validator = new RulesValidator(); Set<Problem> problems = validator.validateAllRules(rules); printResult(problems); } else if (cmd.hasOption("c")) { String file = cmd.getOptionValue("c"); inputFile = new FileInputStream(file); Constraints constraints = XMLHelper.deserialize(inputFile, Constraints.class); QoSValidator validator = new QoSValidator(); Set<Problem> problems = validator.validateAllConstraints(constraints); printResult(problems); } else if (cmd.hasOption("r")) { String file = cmd.getOptionValue("r"); inputFile = new FileInputStream(file); Constraints constraints = XMLHelper.deserialize(inputFile, Constraints.class); MonitoringRuleFactory factory = new MonitoringRuleFactory(); MonitoringRules rules = factory.makeRulesFromQoSConstraints(constraints); XMLHelper.serialize(rules, System.out); } } catch (ParseException e) { System.err.println("Parsing failed. Reason: " + e.getMessage()); formatter.printHelp("qos-models", options); } catch (FileNotFoundException e) { System.err.println("Could not locate input file: " + e.getMessage()); } catch (JAXBException | SAXException e) { System.err.println("Input file could not be parsed: "); e.printStackTrace(); } catch (Exception e) { System.err.println("Unknown error: "); e.printStackTrace(); } finally { if (inputFile != null) { try { inputFile.close(); } catch (IOException e) { } } } }
From source file:edu.msu.cme.rdp.seqmatch.cli.SeqmatchCheckRevSeq.java
public static void main(String[] args) throws Exception { String trainingFile = null;//www . j a v a2 s . c o m String queryFile = null; String outputFile = null; PrintWriter revOutputWriter = new PrintWriter(System.out); PrintStream correctedQueryOut = System.out; String traineeDesc = null; int numOfResults = 20; boolean checkReverse = false; float diffScoreCutoff = CheckReverseSeq.DIFF_SCORE_CUTOFF; String format = "txt"; // default try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("c")) { checkReverse = true; } if (line.hasOption("t")) { trainingFile = line.getOptionValue("t"); } else { throw new Exception("training file must be specified"); } if (line.hasOption("q")) { queryFile = line.getOptionValue("q"); } else { throw new Exception("query file must be specified"); } if (line.hasOption("o")) { outputFile = line.getOptionValue("o"); } else { throw new Exception("output file must be specified"); } if (line.hasOption("r")) { revOutputWriter = new PrintWriter(line.getOptionValue("r")); } if (line.hasOption("s")) { correctedQueryOut = new PrintStream(line.getOptionValue("s")); } if (line.hasOption("d")) { diffScoreCutoff = Float.parseFloat(line.getOptionValue("d")); } if (line.hasOption("h")) { traineeDesc = line.getOptionValue("h"); } if (line.hasOption("n")) { numOfResults = Integer.parseInt(line.getOptionValue("n")); } if (line.hasOption("f")) { format = line.getOptionValue("f"); if (!format.equals("tab") && !format.equals("dbformat") && !format.equals("xml")) { throw new IllegalArgumentException("Only dbformat, tab or xml format available"); } } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(120, "SeqmatchCheckRevSeq", "", options, "", true); return; } SeqmatchCheckRevSeq theObj = new SeqmatchCheckRevSeq(); if (!checkReverse) { theObj.doUserLibMatch(queryFile, trainingFile, outputFile, numOfResults, format, traineeDesc); } else { theObj.checkRevSeq(queryFile, trainingFile, outputFile, revOutputWriter, correctedQueryOut, diffScoreCutoff, format, traineeDesc); } }
From source file:PlyBounder.java
public static void main(String[] args) { // Get the commandline arguments Options options = new Options(); // Available options Option plyPath = OptionBuilder.withArgName("dir").hasArg() .withDescription("directory containing input .ply files").create("plyPath"); Option boundingbox = OptionBuilder.withArgName("string").hasArg() .withDescription("bounding box in WKT notation").create("boundingbox"); Option outputPlyFile = OptionBuilder.withArgName("file").hasArg().withDescription("output PLY file name") .create("outputPlyFile"); options.addOption(plyPath);//from w w w. ja v a2s . c o m options.addOption(boundingbox); options.addOption(outputPlyFile); String plydir = "."; String boundingboxstr = ""; String outputfilename = ""; CommandLineParser parser = new DefaultParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); boundingboxstr = line.getOptionValue("boundingbox"); outputfilename = line.getOptionValue("outputPlyFile"); if (line.hasOption("plyPath")) { // print the value of block-size plydir = line.getOptionValue("plyPath"); System.out.println("Using plyPath=" + plydir); } else { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("PlyBounder", options); } //System.out.println( "plyPath=" + line.getOptionValue( "plyPath" ) ); } catch (ParseException exp) { System.err.println("Error getting arguments: " + exp.getMessage()); } // input directory // Get list of files File dir = new File(plydir); //System.out.println("Getting all files in " + dir.getCanonicalPath()); List<File> files = (List<File>) FileUtils.listFiles(dir, new String[] { "ply", "PLY" }, false); for (File file : files) { try { System.out.println("file=" + file.getCanonicalPath()); } catch (IOException e) { e.printStackTrace(); } } String sometempfile = "magweg.wkt"; String s = null; // Loop through .ply files in directory for (File file : files) { try { String cmdl[] = { "./ply-tool.py", "intersection", file.getCanonicalPath(), boundingboxstr, sometempfile }; //System.out.println("Running: " + Arrays.toString(cmdl)); Process p = Runtime.getRuntime().exec(cmdl); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command System.out.println("cmdout:\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); } // read any errors from the attempted command System.out.println("cmderr:\n"); while ((s = stdError.readLine()) != null) { System.out.println(s); } } catch (IOException e) { e.printStackTrace(); } } // Write new .ply file //ply-tool write setfile outputPlyFile try { String cmdl = "./ply-tool.py write " + sometempfile + " " + outputfilename; System.out.println("Running: " + cmdl); Process p = Runtime.getRuntime().exec(cmdl); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command System.out.println("cmdout:\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); } // read any errors from the attempted command System.out.println("cmderr:\n"); while ((s = stdError.readLine()) != null) { System.out.println(s); } } catch (IOException e) { e.printStackTrace(); } // Done System.out.println("Done"); }
From source file:com.aestel.chemistry.openEye.fp.FPDictionarySorter.java
public static void main(String... args) throws IOException { long start = System.currentTimeMillis(); int iCounter = 0; int fpCounter = 0; // create command line Options object Options options = new Options(); Option opt = new Option("i", true, "input file [.ism,.sdf,...]"); opt.setRequired(true);/*w w w.jav a 2s.c o m*/ options.addOption(opt); opt = new Option("fpType", true, "fingerPrintType: maccs|linear7|linear7*4"); opt.setRequired(true); options.addOption(opt); opt = new Option("sampleFract", true, "fraction of input molecules to use (Default=1)"); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(e.getMessage()); exitWithHelp(options); } args = cmd.getArgs(); if (cmd.hasOption("d")) { System.err.println("Start debugger and press return:"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } if (args.length != 0) { exitWithHelp(options); } String type = cmd.getOptionValue("fpType"); boolean updateDictionaryFile = false; boolean hashUnknownFrag = false; Fingerprinter fprinter = Fingerprinter.createFingerprinter(type, updateDictionaryFile, hashUnknownFrag); OEMolBase mol = new OEGraphMol(); String inFile = cmd.getOptionValue("i"); oemolistream ifs = new oemolistream(inFile); double fract = 2D; String tmp = cmd.getOptionValue("sampleFract"); if (tmp != null) fract = Double.parseDouble(tmp); Random rnd = new Random(); LearningStrcutureCodeMapper mapper = (LearningStrcutureCodeMapper) fprinter.getMapper(); int dictSize = mapper.getMaxIdx() + 1; int[] freq = new int[dictSize]; while (oechem.OEReadMolecule(ifs, mol)) { iCounter++; if (rnd.nextDouble() < fract) { fpCounter++; Fingerprint fp = fprinter.getFingerprint(mol); for (int bit : fp.getBits()) freq[bit]++; } if (iCounter % 100 == 0) System.err.print("."); if (iCounter % 4000 == 0) { System.err.printf(" %d %d %dsec\n", iCounter, fpCounter, (System.currentTimeMillis() - start) / 1000); } } System.err.printf("FPDictionarySorter: Read %d structures calculated %d fprints in %d sec\n", iCounter, fpCounter, (System.currentTimeMillis() - start) / 1000); mapper.reSortDictionary(freq); mapper.writeDictionary(); fprinter.close(); }
From source file:com.mvdb.etl.actions.ExtractDBChanges.java
public static void main(String[] args) throws JSONException { ActionUtils.setUpInitFileProperty(); // boolean success = ActionUtils.markActionChainBroken("Just Testing"); // System.exit(success ? 0 : 1); ActionUtils.assertActionChainNotBroken(); ActionUtils.assertEnvironmentSetupOk(); ActionUtils.assertFileExists("~/.mvdb", "~/.mvdb missing. Existing."); ActionUtils.assertFileExists("~/.mvdb/status.InitCustomerData.complete", "300init-customer-data.sh not executed yet. Exiting"); //This check is not required as data can be modified any number of times //ActionUtils.assertFileDoesNotExist("~/.mvdb/status.ModifyCustomerData.complete", "ModifyCustomerData already done. Start with 100init.sh if required. Exiting"); ActionUtils.createMarkerFile("~/.mvdb/status.ExtractDBChanges.start", true); //String schemaDescription = "{ 'root' : [{'table' : 'orders', 'keyColumn' : 'order_id', 'updateTimeColumn' : 'update_time'}]}"; String customerName = null;// w w w .ja v a2 s .co m final CommandLineParser cmdLinePosixParser = new PosixParser(); final Options posixOptions = constructPosixOptions(); CommandLine commandLine; try { commandLine = cmdLinePosixParser.parse(posixOptions, args); if (commandLine.hasOption("customer")) { customerName = commandLine.getOptionValue("customer"); } } catch (ParseException parseException) // checked exception { System.err.println( "Encountered exception while parsing using PosixParser:\n" + parseException.getMessage()); } if (customerName == null) { System.err.println("Could not find customerName. Aborting..."); System.exit(1); } ApplicationContext context = Top.getContext(); final OrderDAO orderDAO = (OrderDAO) context.getBean("orderDAO"); final ConfigurationDAO configurationDAO = (ConfigurationDAO) context.getBean("configurationDAO"); final GenericDAO genericDAO = (GenericDAO) context.getBean("genericDAO"); File snapshotDirectory = getSnapshotDirectory(configurationDAO, customerName); try { FileUtils.writeStringToFile(new File("/tmp/etl.extractdbchanges.directory.txt"), snapshotDirectory.getName(), false); } catch (IOException e) { e.printStackTrace(); System.exit(1); return; } long currentTime = new Date().getTime(); Configuration lastRefreshTimeConf = configurationDAO.find(customerName, "last-refresh-time"); Configuration schemaDescriptionConf = configurationDAO.find(customerName, "schema-description"); long lastRefreshTime = Long.parseLong(lastRefreshTimeConf.getValue()); OrderJsonFileConsumer orderJsonFileConsumer = new OrderJsonFileConsumer(snapshotDirectory); Map<String, ColumnMetadata> metadataMap = orderDAO.findMetadata(); //write file schema-orders.dat in snapshotDirectory genericDAO.fetchMetadata("orders", snapshotDirectory); //writes files: header-orders.dat, data-orders.dat in snapshotDirectory JSONObject json = new JSONObject(schemaDescriptionConf.getValue()); JSONArray rootArray = json.getJSONArray("root"); int length = rootArray.length(); for (int i = 0; i < length; i++) { JSONObject jsonObject = rootArray.getJSONObject(i); String table = jsonObject.getString("table"); String keyColumnName = jsonObject.getString("keyColumn"); String updateTimeColumnName = jsonObject.getString("updateTimeColumn"); System.out.println("table:" + table + ", keyColumn: " + keyColumnName + ", updateTimeColumn: " + updateTimeColumnName); genericDAO.fetchAll2(snapshotDirectory, new Timestamp(lastRefreshTime), table, keyColumnName, updateTimeColumnName); } //Unlikely failure //But Need to factor this into a separate task so that extraction does not have to be repeated. //Extraction is an expensive task. try { String sourceDirectoryAbsolutePath = snapshotDirectory.getAbsolutePath(); File sourceRelativeDirectoryPath = getRelativeSnapShotDirectory(configurationDAO, sourceDirectoryAbsolutePath); String hdfsRoot = ActionUtils.getConfigurationValue(ConfigurationKeys.GLOBAL_CUSTOMER, ConfigurationKeys.GLOBAL_HDFS_ROOT); String targetDirectoryFullPath = hdfsRoot + "/data" + sourceRelativeDirectoryPath; ActionUtils.copyLocalDirectoryToHdfsDirectory(sourceDirectoryAbsolutePath, targetDirectoryFullPath); String dirName = snapshotDirectory.getName(); ActionUtils.setConfigurationValue(customerName, ConfigurationKeys.LAST_COPY_TO_HDFS_DIRNAME, dirName); } catch (Throwable e) { e.printStackTrace(); logger.error("Objects Extracted from database. But copy of snapshot directory<" + snapshotDirectory.getAbsolutePath() + "> to hdfs <" + "" + ">failed. Fix the problem and redo extract.", e); System.exit(1); } //Unlikely failure //But Need to factor this into a separate task so that extraction does not have to be repeated. //Extraction is an expensive task. String targetZip = null; try { File targetZipDirectory = new File(snapshotDirectory.getParent(), "archives"); if (!targetZipDirectory.exists()) { boolean success = targetZipDirectory.mkdirs(); if (success == false) { logger.error("Objects copied to hdfs. But able to create archive directory <" + targetZipDirectory.getAbsolutePath() + ">. Fix the problem and redo extract."); System.exit(1); } } targetZip = new File(targetZipDirectory, snapshotDirectory.getName() + ".zip").getAbsolutePath(); ActionUtils.zipFullDirectory(snapshotDirectory.getAbsolutePath(), targetZip); } catch (Throwable e) { e.printStackTrace(); logger.error("Objects copied to hdfs. But zipping of snapshot directory<" + snapshotDirectory.getAbsolutePath() + "> to <" + targetZip + ">failed. Fix the problem and redo extract.", e); System.exit(1); } //orderDAO.findAll(new Timestamp(lastRefreshTime), orderJsonFileConsumer); Configuration updateRefreshTimeConf = new Configuration(customerName, "last-refresh-time", String.valueOf(currentTime)); configurationDAO.update(updateRefreshTimeConf, String.valueOf(lastRefreshTimeConf.getValue())); ActionUtils.createMarkerFile("~/.mvdb/status.ExtractDBChanges.complete", true); }
From source file:com.twitter.heron.scheduler.RuntimeManagerMain.java
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException, ParseException { Options options = constructOptions(); Options helpOptions = constructHelpOptions(); CommandLineParser parser = new DefaultParser(); // parse the help options first. CommandLine cmd = parser.parse(helpOptions, args, true); if (cmd.hasOption("h")) { usage(options);/*from ww w . j av a 2 s. co m*/ return; } try { // Now parse the required options cmd = parser.parse(options, args); } catch (ParseException e) { usage(options); throw new RuntimeException("Error parsing command line options: ", e); } Boolean verbose = false; Level logLevel = Level.INFO; if (cmd.hasOption("v")) { logLevel = Level.ALL; verbose = true; } // init log LoggingHelper.loggerInit(logLevel, false); String cluster = cmd.getOptionValue("cluster"); String role = cmd.getOptionValue("role"); String environ = cmd.getOptionValue("environment"); String heronHome = cmd.getOptionValue("heron_home"); String configPath = cmd.getOptionValue("config_path"); String overrideConfigFile = cmd.getOptionValue("override_config_file"); String releaseFile = cmd.getOptionValue("release_file"); String topologyName = cmd.getOptionValue("topology_name"); String commandOption = cmd.getOptionValue("command"); // Optional argument in the case of restart // TODO(karthik): convert into CLI String containerId = Integer.toString(-1); if (cmd.hasOption("container_id")) { containerId = cmd.getOptionValue("container_id"); } Command command = Command.makeCommand(commandOption); // first load the defaults, then the config from files to override it Config.Builder defaultsConfig = Config.newBuilder().putAll(ClusterDefaults.getDefaults()) .putAll(ClusterConfig.loadConfig(heronHome, configPath, releaseFile)); // add config parameters from the command line Config.Builder commandLineConfig = Config.newBuilder().put(Keys.cluster(), cluster).put(Keys.role(), role) .put(Keys.environ(), environ).put(Keys.verbose(), verbose) .put(Keys.topologyContainerId(), containerId); Config.Builder topologyConfig = Config.newBuilder().put(Keys.topologyName(), topologyName); Config.Builder overrideConfig = Config.newBuilder() .putAll(ClusterConfig.loadOverrideConfig(overrideConfigFile)); // build the final config by expanding all the variables Config config = Config .expand(Config.newBuilder().putAll(defaultsConfig.build()).putAll(overrideConfig.build()) .putAll(commandLineConfig.build()).putAll(topologyConfig.build()).build()); LOG.fine("Static config loaded successfully "); LOG.fine(config.toString()); // Create a new instance of RuntimeManagerMain RuntimeManagerMain runtimeManagerMain = new RuntimeManagerMain(config, command); boolean isSuccessful = runtimeManagerMain.manageTopology(); // Log the result and exit if (!isSuccessful) { throw new RuntimeException(String.format("Failed to %s topology %s", command, topologyName)); } else { LOG.log(Level.FINE, "Topology {0} {1} successfully", new Object[] { topologyName, command }); } }
From source file:com.versusoft.packages.jodl.gui.CommandLineGUI.java
public static void main(String args[]) throws SAXException, IOException { Handler fh = new FileHandler(LOG_FILENAME_PATTERN); fh.setFormatter(new SimpleFormatter()); //removeAllLoggersHandlers(Logger.getLogger("")); Logger.getLogger("").addHandler(fh); Logger.getLogger("").setLevel(Level.FINEST); Options options = new Options(); Option option1 = new Option("in", "ODT file (required)"); option1.setRequired(true);/*w w w. ja v a2 s .co m*/ option1.setArgs(1); Option option2 = new Option("out", "Output file (required)"); option2.setRequired(false); option2.setArgs(1); Option option3 = new Option("pic", "extract pics"); option3.setRequired(false); option3.setArgs(1); Option option4 = new Option("page", "enable pagination processing"); option4.setRequired(false); option4.setArgs(0); options.addOption(option1); options.addOption(option2); options.addOption(option3); options.addOption(option4); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { printHelp(); return; } if (cmd.hasOption("help")) { printHelp(); return; } File outFile = new File(cmd.getOptionValue("out")); OdtUtils utils = new OdtUtils(); utils.open(cmd.getOptionValue("in")); //utils.correctionStep(); utils.saveXML(outFile.getAbsolutePath()); try { if (cmd.hasOption("page")) { OdtUtils.paginationProcessing(outFile.getAbsolutePath()); } OdtUtils.correctionProcessing(outFile.getAbsolutePath()); } catch (ParserConfigurationException ex) { logger.log(Level.SEVERE, null, ex); } catch (SAXException ex) { logger.log(Level.SEVERE, null, ex); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } catch (TransformerConfigurationException ex) { logger.log(Level.SEVERE, null, ex); } catch (TransformerException ex) { logger.log(Level.SEVERE, null, ex); } if (cmd.hasOption("pic")) { String imageDir = cmd.getOptionValue("pic"); if (!imageDir.endsWith("/")) { imageDir += "/"; } try { String basedir = new File(cmd.getOptionValue("out")).getParent().toString() + System.getProperty("file.separator"); OdtUtils.extractAndNormalizeEmbedPictures(cmd.getOptionValue("out"), cmd.getOptionValue("in"), basedir, imageDir); } catch (SAXException ex) { logger.log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { logger.log(Level.SEVERE, null, ex); } catch (TransformerConfigurationException ex) { logger.log(Level.SEVERE, null, ex); } catch (TransformerException ex) { logger.log(Level.SEVERE, null, ex); } } }
From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineTool.java
/** * Main (starting) method of the command line application. * * @param argv Array of command line arguments that are expected to be * filesystem paths to input XML documents with MathML to be unified. * @throws ParserConfigurationException If a XML DOM builder cannot be * created with the configuration requested. *//* ww w. j a v a2s . c o m*/ public static void main(String argv[]) throws ParserConfigurationException { final Options options = new Options(); options.addOption("p", "operator-unification", false, "unify operator in addition to other types of nodes"); options.addOption("h", "help", false, "print help"); final CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, argv); } catch (ParseException ex) { printHelp(options); System.exit(1); } if (line != null) { if (line.hasOption('h')) { printHelp(options); System.exit(0); } operatorUnification = line.hasOption('p'); final List<String> arguments = Arrays.asList(line.getArgs()); if (arguments.size() > 0) { Document outerDocument = DOMBuilder.getDocumentBuilder().newDocument(); Node rootNode = outerDocument.createElementNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ROOT_ELEM); outerDocument.appendChild(rootNode); for (String filepath : arguments) { try { Document doc = DOMBuilder.buildDocFromFilepath(filepath); MathMLUnificator.unifyMathML(doc, operatorUnification); if (arguments.size() == 1) { xmlStdoutSerializer(doc); } else { Node itemNode = rootNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_ELEM); Attr filenameAttr = itemNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_FILEPATH_ATTR); filenameAttr.setTextContent(String.valueOf(filepath)); ((Element) itemNode).setAttributeNodeNS(filenameAttr); itemNode.appendChild( rootNode.getOwnerDocument().importNode(doc.getDocumentElement(), true)); rootNode.appendChild(itemNode); } } catch (SAXException | IOException ex) { Logger.getLogger(MathMLUnificatorCommandLineTool.class.getName()).log(Level.SEVERE, "Failed processing of file: " + filepath, ex); } } if (rootNode.getChildNodes().getLength() > 0) { xmlStdoutSerializer(rootNode.getOwnerDocument()); } } else { printHelp(options); System.exit(0); } } }
From source file:ca.uqac.info.trace.conversion.TraceConverter.java
/** * Main program loop//from ww w.j a va 2s .co m * @param args Command-line arguments */ @SuppressWarnings("static-access") public static void main(String[] args) { // Default values String input_format = "xml", output_format = "smv"; String input_filename = "trace.xml", output_filename = ""; //String event_tag_name = "Event"; // Define and process command line arguments Options options = new Options(); HelpFormatter help_formatter = new HelpFormatter(); Option opt; options.addOption("h", "help", false, "Show help"); opt = OptionBuilder.withArgName("format").hasArg() .withDescription("Input format for trace. Accepted values are csv, xml.").create("i"); opt.setRequired(false); options.addOption(opt); opt = OptionBuilder.withArgName("format").hasArg().withDescription( "Output format for trace. Accepted values are javamop, json, monpoly, smv, sql, xml. Default: smv") .create("t"); opt.setRequired(false); options.addOption(opt); opt = OptionBuilder.withArgName("filename").hasArg().withDescription("Input filename. Default: trace.xml") .create("f"); opt.setRequired(false); options.addOption(opt); opt = OptionBuilder.withArgName("filename").hasArg().withDescription("Output filename").create("o"); opt.setRequired(false); options.addOption(opt); opt = OptionBuilder.withArgName("name").hasArg().withDescription("Event tag name. Default: Event") .create("e"); opt.setRequired(false); options.addOption(opt); opt = OptionBuilder.withArgName("formula").hasArg().withDescription("Formula to translate").create("s"); opt.setRequired(false); options.addOption(opt); CommandLine c_line = parseCommandLine(options, args); if (c_line.hasOption("h")) { help_formatter.printHelp(app_name, options); System.exit(0); } input_filename = c_line.getOptionValue("f"); if (c_line.hasOption("o")) output_filename = c_line.getOptionValue("o"); /*if (c_line.hasOption("e")) event_tag_name = c_line.getOptionValue("e");*/ // Determine the input format if (!c_line.hasOption("i")) { // Guess output format by filename extension input_format = getExtension(input_filename); } if (c_line.hasOption("i")) { // The "t" parameter overrides the filename extension input_format = c_line.getOptionValue("i"); } // Determine which trace reader to initialize TraceReader reader = initializeReader(input_format); if (reader == null) { System.err.println("ERROR: Unrecognized input format"); System.exit(1); } // Instantiate the proper trace reader and checks that the trace exists //reader.setEventTagName(event_tag_name); File in_f = new File(input_filename); if (!in_f.exists()) { System.err.println("ERROR: Input file not found"); System.exit(1); } if (!in_f.canRead()) { System.err.println("ERROR: Input file is not readable"); System.exit(1); } // Determine the output format if (!c_line.hasOption("o") && !c_line.hasOption("t")) { System.err.println("ERROR: At least one of output filename and output format must be given"); System.exit(1); } if (c_line.hasOption("o")) { // Guess output format by filename extension output_filename = c_line.getOptionValue("o"); output_format = getExtension(output_filename); } if (c_line.hasOption("t")) { // The "t" parameter overrides the filename extension output_format = c_line.getOptionValue("t"); } // Determine which translator to initialize Translator trans = initializeTranslator(output_format); if (trans == null) { System.err.println("ERROR: Unrecognized output format"); System.exit(1); } // Translate the trace into the output format EventTrace trace = null; try { trace = reader.parseEventTrace(new FileInputStream(in_f)); } catch (FileNotFoundException ex) { ex.printStackTrace(); System.exit(1); } assert trace != null; trans.setTrace(trace); String out_trace = trans.translateTrace(); if (output_filename.isEmpty()) System.out.println(out_trace); else writeToFile(output_filename, out_trace); // Check if there is a formula to translate if (c_line.hasOption("s")) { String formula = c_line.getOptionValue("s"); try { Operator o = Operator.parseFromString(formula); trans.setFormula(o); System.out.println(trans.translateFormula()); } catch (Operator.ParseException e) { System.err.println("ERROR: parsing input formula"); System.exit(1); } } }
From source file:gov.nasa.jpl.mudrod.xsd2owl.Mapper.java
/** * @param args/*ww w .ja va 2 s. c om*/ */ public static void main(String[] args) { Option sOpt = Option.builder().hasArg(true).numberOfArgs(1).argName("file").required(false) .longOpt(INPUTFILE).desc("A path to a local XSD file.").build(); Options opts = new Options(); opts.addOption(sOpt); DefaultParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(opts, args); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Mapper.class.getSimpleName(), opts); System.exit(-1); } File file = null; if (cmd.hasOption(INPUTFILE)) { try { is = new FileInputStream(cmd.getOptionValue(INPUTFILE)); //file = new File(cmd.getOptionValue(INPUTFILE)); } catch (FileNotFoundException e) { LOG.error("Error processing input XSD from path: {}", e); } } Mapper mapper = new Mapper(); mapper.executeMapping(is); }