List of usage examples for org.apache.commons.cli HelpFormatter printHelp
public void printHelp(int width, String cmdLineSyntax, String header, Options options, String footer)
options
with the specified command line syntax. From source file:com.tomdoel.mpg2dcm.Mpg2Dcm.java
public static void main(String[] args) { try {//from ww w. java 2 s . co m final Options helpOptions = new Options(); helpOptions.addOption("h", false, "Print help for this application"); final DefaultParser parser = new DefaultParser(); final CommandLine commandLine = parser.parse(helpOptions, args); if (commandLine.hasOption('h')) { final String helpHeader = "Converts an mpeg2 video file to Dicom\n\n"; String helpFooter = "\nPlease report issues at github.com/tomdoel/mpg2dcm"; final HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("Mpg2Dcm mpegfile dicomfile", helpHeader, helpOptions, helpFooter, true); } else { final List<String> remainingArgs = commandLine.getArgList(); if (remainingArgs.size() < 2) { throw new org.apache.commons.cli.ParseException("ERROR : Not enough arguments specified."); } final String mpegFileName = remainingArgs.get(0); final String dicomFileName = remainingArgs.get(1); final File mpegFile = new File(mpegFileName); final File dicomOutputFile = new File(dicomFileName); MpegFileConverter.convert(mpegFile, dicomOutputFile); } } catch (org.apache.commons.cli.ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.tomdoel.mpg2dcm.Xml2Dicom.java
public static void main(String[] args) { try {/*from w w w .j av a 2 s . c o m*/ final Options helpOptions = new Options(); helpOptions.addOption("h", false, "Print help for this application"); final DefaultParser parser = new DefaultParser(); final CommandLine commandLine = parser.parse(helpOptions, args); if (commandLine.hasOption('h')) { final String helpHeader = "Converts an endoscopic xml and video files to Dicom\n\n"; String helpFooter = "\nPlease report issues at github.com/tomdoel/mpg2dcm"; final HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("Xml2Dcm xml-file dicom-output-path", helpHeader, helpOptions, helpFooter, true); } else { final List<String> remainingArgs = commandLine.getArgList(); if (remainingArgs.size() < 2) { throw new org.apache.commons.cli.ParseException("ERROR : Not enough arguments specified."); } final String xmlInputFileName = remainingArgs.get(0); final String dicomOutputPath = remainingArgs.get(1); EndoscopicXmlToDicomConverter.convert(new File(xmlInputFileName), dicomOutputPath); } } catch (org.apache.commons.cli.ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } }
From source file:com.ehi.carshare.Main.java
/** * @param args//from w w w . java 2 s .c o m * The commandline arguments * @throws IllegalAccessException * @throws InstantiationException */ public static void main(final String[] args) throws Exception { // create the command line parser CommandLineParser parser = new BasicParser(); // create the Options Options options = new Options(); options.addOption(buildOption("l", "logFormat", "The apache logformat")); options.addOption(buildOption("i", "inputFile", "complete path to the input file")); options.addOption(buildOption("o", "outputFile", "complete path to the output file")); try { // parse the command line arguments CommandLine line = parser.parse(options, args); String logformat = line.getOptionValue('l'); String inputFile = line.getOptionValue('i'); String outputFile = line.getOptionValue('o'); new Main().run(logformat, inputFile, outputFile); } catch (ParseException exp) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("myapp", "", options, "", true); } }
From source file:com.ibm.watson.app.qaclassifier.AddQuestionsToMockClassifier.java
public static void main(String[] args) throws IOException { Option urlOption = CliUtils.createOption(URL_OPTION, URL_OPTION_LONG, true, "The root URL of the application to connect to. If omitted, the default will be used (" + DEFAULT_URL + ")", false, URL_OPTION_LONG); Option pathOption = CliUtils.createOption(FILE_OPTION, FILE_OPTION_LONG, true, "The file to be used as training data, can point to the file system or the class path", true, FILE_OPTION_LONG);//from ww w. j a va2 s . c o m Option userOption = CliUtils.createOption(USER_OPTION, USER_OPTION_LONG, true, "The username for the manage API", true, USER_OPTION_LONG); Option passwordOption = CliUtils.createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true, "The password for the manage API", true, PASSWORD_OPTION_LONG); final Options options = CliUtils.buildOptions(urlOption, pathOption, userOption, passwordOption); CommandLine cmd; try { CommandLineParser parser = new GnuParser(); cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Could not parse cmd line arguments.\n" + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(120, "java " + AddQuestionsToMockClassifier.class.getName(), null, options, null); return; } final String url = cmd.getOptionValue(URL_OPTION, DEFAULT_URL); final String path = cmd.getOptionValue(FILE_OPTION); final String user = cmd.getOptionValue(USER_OPTION); final String password = cmd.getOptionValue(PASSWORD_OPTION); AddQuestionsToMockClassifier mockSetup = new AddQuestionsToMockClassifier(url, path, user, password); System.out.println("Creating mock responses for the questions in " + path + "..."); mockSetup.mockResponsesForTrainingData(); System.out.println("Creating mock responses for the sample questions..."); mockSetup.mockResponse(SampleQuestions.HIGH_CONFIDENCE, "mock_one_answer", HIGH_CONFIDENCE, "This is a question that will be answered by the mock classifier with high confidence"); mockSetup.mockResponse(SampleQuestions.LOW_CONFIDENCE, "mock_multiple_answers", LOW_CONFIDENCE, "This is a question that will be answered by the mock classifier with low confidence"); mockSetup.mockResponse(SampleQuestions.NO_ANSWERS, "mock_no_answers", NO_ANSWER_CONFIDENCE, "This is a question that will be answered by the mock classifier with very low confidence"); System.out.println("Done."); }
From source file:fr.inria.edelweiss.kgdqp.core.FedQueryingCLI.java
@SuppressWarnings("unchecked") public static void main(String args[]) throws ParseException, EngineException { List<String> endpoints = new ArrayList<String>(); String queryPath = null;/*from www . ja v a2 s.c om*/ int slice = -1; Options options = new Options(); Option helpOpt = new Option("h", "help", false, "print this message"); Option queryOpt = new Option("q", "query", true, "specify the sparql query file"); Option endpointOpt = new Option("e", "endpoints", true, "the list of federated sparql endpoint URLs"); Option groupingOpt = new Option("g", "grouping", true, "triple pattern optimisation"); Option slicingOpt = new Option("s", "slicing", true, "size of the slicing parameter"); Option versionOpt = new Option("v", "version", false, "print the version information and exit"); options.addOption(queryOpt); options.addOption(endpointOpt); options.addOption(helpOpt); options.addOption(versionOpt); options.addOption(groupingOpt); options.addOption(slicingOpt); String header = "Corese/KGRAM DQP command line interface"; String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr"; CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("kgdqp", header, options, footer, true); System.exit(0); } if (!cmd.hasOption("e")) { logger.info("You must specify at least the URL of one sparql endpoint !"); System.exit(0); } else { endpoints = new ArrayList<String>(Arrays.asList(cmd.getOptionValues("e"))); } if (!cmd.hasOption("q")) { logger.info("You must specify a path for a sparql query !"); System.exit(0); } else { queryPath = cmd.getOptionValue("q"); } if (cmd.hasOption("s")) { try { slice = Integer.parseInt(cmd.getOptionValue("s")); } catch (NumberFormatException ex) { logger.warn(cmd.getOptionValue("s") + " is not formatted as number for the slicing parameter"); logger.warn("Slicing disabled"); } } if (cmd.hasOption("v")) { logger.info("version 3.0.4-SNAPSHOT"); System.exit(0); } ///////////////// Graph graph = Graph.create(); QueryProcessDQP exec = QueryProcessDQP.create(graph); exec.setGroupingEnabled(cmd.hasOption("g")); if (slice > 0) { exec.setSlice(slice); } Provider sProv = ProviderImplCostMonitoring.create(); exec.set(sProv); for (String url : endpoints) { try { exec.addRemote(new URL(url), WSImplem.REST); } catch (MalformedURLException ex) { logger.error(url + " is not a well-formed URL"); System.exit(1); } } StringBuffer fileData = new StringBuffer(1000); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(queryPath)); } catch (FileNotFoundException ex) { logger.error("Query file " + queryPath + " not found !"); System.exit(1); } char[] buf = new char[1024]; int numRead = 0; try { while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); } catch (IOException ex) { logger.error("Error while reading query file " + queryPath); System.exit(1); } String sparqlQuery = fileData.toString(); // Query q = exec.compile(sparqlQuery, null); // System.out.println(q); StopWatch sw = new StopWatch(); sw.start(); Mappings map = exec.query(sparqlQuery); int dqpSize = map.size(); System.out.println("--------"); long time = sw.getTime(); System.out.println(time + " " + dqpSize); }
From source file:fr.cnrs.sharp.Main.java
public static void main(String args[]) { Options options = new Options(); Option versionOpt = new Option("v", "version", false, "print the version information and exit"); Option helpOpt = new Option("h", "help", false, "print the help"); Option inProvFileOpt = OptionBuilder.withArgName("input_PROV_file_1> ... <input_PROV_file_n") .withLongOpt("input_PROV_files").withDescription("The list of PROV input files, in RDF Turtle.") .hasArgs().create("i"); Option inRawFileOpt = OptionBuilder.withArgName("input_raw_file_1> ... <input_raw_file_n") .withLongOpt("input_raw_files") .withDescription(// w w w. j ava 2s. c o m "The list of raw files to be fingerprinted and possibly interlinked with owl:sameAs.") .hasArgs().create("ri"); Option summaryOpt = OptionBuilder.withArgName("summary").withLongOpt("summary") .withDescription("Materialization of wasInfluencedBy relations.").create("s"); options.addOption(inProvFileOpt); options.addOption(inRawFileOpt); options.addOption(versionOpt); options.addOption(helpOpt); options.addOption(summaryOpt); String header = "SharpTB is a tool to maturate provenance based on PROV inferences"; String footer = "\nPlease report any issue to alban.gaignard@univ-nantes.fr"; try { CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SharpTB", header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { logger.info("SharpTB version 0.1.0"); System.exit(0); } if (cmd.hasOption("ri")) { String[] inFiles = cmd.getOptionValues("ri"); Model model = ModelFactory.createDefaultModel(); for (String inFile : inFiles) { Path p = Paths.get(inFile); if (!p.toFile().isFile()) { logger.error("Cannot find file " + inFile); System.exit(1); } else { //1. fingerprint try { model.add(Interlinking.fingerprint(p)); } catch (IOException e) { logger.error("Cannot fingerprint file " + inFile); } } } //2. genSameAs Model sameAs = Interlinking.generateSameAs(model); sameAs.write(System.out, "TTL"); } if (cmd.hasOption("i")) { String[] inFiles = cmd.getOptionValues("i"); Model data = ModelFactory.createDefaultModel(); for (String inFile : inFiles) { Path p = Paths.get(inFile); if (!p.toFile().isFile()) { logger.error("Cannot find file " + inFile); System.exit(1); } else { RDFDataMgr.read(data, inFile, Lang.TTL); } } Model res = Harmonization.harmonizeProv(data); try { Path pathInfProv = Files.createTempFile("PROV-inf-tgd-egd-", ".ttl"); res.write(new FileWriter(pathInfProv.toFile()), "TTL"); System.out.println("Harmonized PROV written to file " + pathInfProv.toString()); //if the summary option is activated, then save the subgraph and generate a visualization if (cmd.hasOption("s")) { String queryInfluence = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" + "PREFIX prov: <http://www.w3.org/ns/prov#> \n" + "CONSTRUCT { \n" + " ?x ?p ?y .\n" + " ?x rdfs:label ?lx .\n" + " ?y rdfs:label ?ly .\n" + "} WHERE {\n" + " ?x ?p ?y .\n" + " FILTER (?p IN (prov:wasInfluencedBy)) .\n" + " ?x rdfs:label ?lx .\n" + " ?y rdfs:label ?ly .\n" + "}"; Query query = QueryFactory.create(queryInfluence); QueryExecution queryExec = QueryExecutionFactory.create(query, res); Model summary = queryExec.execConstruct(); queryExec.close(); Util.writeHtmlViz(summary); } } catch (IOException ex) { logger.error("Impossible to write the harmonized provenance file."); System.exit(1); } } else { // logger.info("Please fill the -i input parameter."); // HelpFormatter formatter = new HelpFormatter(); // formatter.printHelp("SharpTB", header, options, footer, true); // System.exit(0); } } catch (ParseException ex) { logger.error("Error while parsing command line arguments. Please check the following help:"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SharpToolBox", header, options, footer, true); System.exit(1); } }
From source file:com.ibm.watson.app.qaclassifier.tools.PopulateAnswerStore.java
public static void main(String[] args) throws Exception { Option urlOption = createOption(URL_OPTION, URL_OPTION_LONG, true, "The root URL of the application to connect to. If omitted, the default will be used (" + DEFAULT_URL + ")", false, URL_OPTION_LONG); Option fileOption = createOption(FILE_OPTION, FILE_OPTION_LONG, true, "The file to be used to populate the answers, can point to the file system or the class path", true, FILE_OPTION_LONG);//from w w w . j a v a 2 s .c o m Option dirOption = createOption(DIR_OPTION, DIR_OPTION_LONG, true, "The directory containing the html answer files, can point to the file system or the class path", true, DIR_OPTION_LONG); Option userOption = createOption(USER_OPTION, USER_OPTION_LONG, true, "The username for the manage API", true, USER_OPTION_LONG); Option passwordOption = createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true, "The password for the manage API", true, PASSWORD_OPTION_LONG); final Options options = buildOptions(urlOption, fileOption, dirOption, userOption, passwordOption); CommandLine cmd; try { CommandLineParser parser = new GnuParser(); cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println(MessageKey.AQWQAC24008E_could_not_parse_cmd_line_args_1.getMessage(e.getMessage()) .getFormattedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(120, "java " + PopulateAnswerStore.class.getName(), null, options, null); return; } final String url = cmd.getOptionValue(URL_OPTION, DEFAULT_URL); final String file = cmd.getOptionValue(FILE_OPTION); final String dir = cmd.getOptionValue(DIR_OPTION); final String user = cmd.getOptionValue(USER_OPTION); final String password = cmd.getOptionValue(PASSWORD_OPTION); System.out.println(MessageKey.AQWQAC20002I_checking_answer_store_at_url_2.getMessage(url, DEFAULT_ENDPOINT) .getFormattedMessage()); try { AnswerStoreRestClient client = new AnswerStoreRestClient(url, user, password); // we only want to populate if there is nothing in the database already // start with the assumption that we do want to populate and stop if we find answers in there already boolean doPopulate = true; String answersResult = getAnswers(client); if (answersResult != null && !answersResult.isEmpty()) { Gson gson = new Gson(); Type type = new TypeToken<List<ManagedAnswer>>() { }.getType(); List<ManagedAnswer> answers = gson.fromJson(answersResult, type); if (answers != null && answers.size() > 0) { System.out.println(MessageKey.AQWQAC20006I_found_answers_in_stop_1.getMessage(answers.size()) .getFormattedMessage()); doPopulate = false; } } if (doPopulate) { System.out.println(MessageKey.AQWQAC20003I_populating_answer_store_at_url_2 .getMessage(url, DEFAULT_ENDPOINT).getFormattedMessage()); boolean success = populate(client, file, dir); if (!success) { throw new RuntimeException(MessageKey.AQWQAC24005E_error_populating_answer_store.getMessage() .getFormattedMessage()); } } else { System.out.println(MessageKey.AQWQAC20001I_answer_store_already_populated_doing_nothing.getMessage() .getFormattedMessage()); } System.out.println(MessageKey.AQWQAC20005I_done_population_answers.getMessage().getFormattedMessage()); } catch (IOException e) { System.err.println(MessageKey.AQWQAC24007E_error_populating_answer_store_1.getMessage(e.getMessage()) .getFormattedMessage()); e.printStackTrace(System.err); } }
From source file:com.ibm.watson.app.common.tools.services.classifier.TrainClassifier.java
public static void main(String[] args) throws Exception { Option urlOption = createOption(URL_OPTION, URL_OPTION_LONG, true, "The absolute URL of the NL classifier service to connect to. If omitted, the default will be used (" + DEFAULT_URL + ")", false, "url"); Option usernameOption = createOption(USERNAME_OPTION, USERNAME_OPTION_LONG, true, "The username to use during authentication to the NL classifier service", true, "username"); Option passwordOption = createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true, "The password to use during authentication to the NL classifier service", true, "password"); Option fileOption = createOption(FILE_OPTION, FILE_OPTION_LONG, true, "The filepath to be used as training data", false, "file"); Option deleteOption = createOption(DELETE_OPTION, DELETE_OPTION_LONG, false, "If specified, the classifier instance will be deleted if training is not successful"); final Options options = buildOptions(urlOption, usernameOption, passwordOption, fileOption, deleteOption); CommandLine cmd;/* w ww .j a v a2 s .c o m*/ try { CommandLineParser parser = new GnuParser(); cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println(MessageKey.AQWEGA14016E_could_not_parse_cmd_line_args_1.getMessage(e.getMessage()) .getFormattedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(120, "java " + TrainClassifier.class.getName(), null, options, null); return; } final String url = cmd.hasOption(URL_OPTION) ? cmd.getOptionValue(URL_OPTION) : DEFAULT_URL; final String username = cmd.getOptionValue(USERNAME_OPTION).trim(); final String password = cmd.getOptionValue(PASSWORD_OPTION).trim(); if (username.isEmpty() || password.isEmpty()) { throw new IllegalArgumentException( MessageKey.AQWEGA14014E_username_and_password_cannot_empty.getMessage().getFormattedMessage()); } final NLClassifierRestClient client = new NLClassifierRestClient(url, username, password); listClassifiers(client); System.out.println(MessageKey.AQWEGA10012I_h_help.getMessage().getFormattedMessage()); String userInput; boolean exit = false; NLClassifier classifier = null; boolean isTraining = false; if (cmd.hasOption(FILE_OPTION)) { // File option was specified, go directly to training classifier = train(client, cmd.getOptionValue(FILE_OPTION)); isTraining = true; } try (final Scanner scanner = new Scanner(System.in)) { while (!exit) { System.out.print("> "); userInput = scanner.nextLine().trim(); if (userInput.equals("q") || userInput.equals("quit") || userInput.equals("exit")) { exit = true; } else if (userInput.equals("h") || userInput.equals("help")) { printHelp(); } else if (userInput.equals("l") || userInput.equals("list")) { listClassifiers(client); } else if (userInput.equals("t") || userInput.equals("train")) { if (!isTraining) { System.out.print("Enter filename: "); String filename = scanner.nextLine().trim(); classifier = train(client, filename); isTraining = true; } else { System.err.println(MessageKey.AQWEGA10013I_t_cannot_used_during_training.getMessage() .getFormattedMessage()); } } else if (userInput.equals("s") || userInput.equals("status")) { if (isTraining) { exit = getStatus(client, classifier, cmd.hasOption(DELETE_OPTION)); } else { System.err.println(MessageKey.AQWEGA10014I_s_can_used_during_training.getMessage() .getFormattedMessage()); } } else if (userInput.equals("c") || userInput.equals("classify")) { if (classifier != null && classifier.getStatus().equals(Status.AVAILABLE)) { isTraining = false; System.out.print(MessageKey.AQWEGA10015I_text_classify.getMessage().getFormattedMessage()); String text = scanner.nextLine().trim(); classify(client, classifier, text); } else { System.err.println(MessageKey.AQWEGA10016I_c_can_used_after_training_has_completed .getMessage().getFormattedMessage()); } } else { System.err.println( MessageKey.AQWEGA14017E_unknown_command_1.getMessage(userInput).getFormattedMessage()); } Thread.sleep(100); // Give the out / err consoles time to battle it out before printing the command prompt } } }
From source file:fr.inria.edelweiss.kgdqp.test.TestDQP.java
public static void main(String[] args) throws EngineException, MalformedURLException { Options options = new Options(); Option bgpOpt = new Option("bgp", "modeBGP", false, "specify the evaluation strategy"); Option helpOpt = new Option("h", "help", false, "print this message"); Option centralizeOpt = new Option("c", "centralize", false, "to evualuate in a centralized context"); Option testCaseOpt = new Option("tc", "testCase", true, "chose the test case ( d, g or p)"); Option roundOpt = new Option("r", "round", true, "the roound of the test ( 0, 1 ..., n)"); options.addOption(bgpOpt);/*from w w w . j a v a 2 s.c om*/ options.addOption(helpOpt); options.addOption(centralizeOpt); options.addOption(testCaseOpt); options.addOption(roundOpt); String header = "blabla"; String footer = "\nPlease report any issue to macina@i3s.unice.fr"; TestDQP test = new TestDQP(false); try { CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("kgdqp", header, options, footer, true); System.exit(0); } if (cmd.hasOption("bgp")) { test = new TestDQP(true); } if (cmd.hasOption("r")) { test.setRound(Integer.parseInt(cmd.getOptionValue("r"))); } if (cmd.hasOption("c")) { test.testLocal(); } else { if (cmd.hasOption("tc")) { String tetsCase = cmd.getOptionValue("tc"); test.testDQP(tetsCase); } } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); } catch (IOException ex) { LogManager.getLogger(TestDQP.class.getName()).log(Level.ERROR, "", ex); } }
From source file:fr.inria.edelweiss.kgdqp.core.CentralizedInferrencing.java
public static void main(String args[]) throws ParseException, EngineException, InterruptedException, IOException { List<String> endpoints = new ArrayList<String>(); String queryPath = null;//w w w.jav a 2 s . co m boolean rulesSelection = false; File rulesDir = null; File ontDir = null; ///////////////// Graph graph = Graph.create(); QueryProcess exec = QueryProcess.create(graph); Options options = new Options(); Option helpOpt = new Option("h", "help", false, "print this message"); // Option queryOpt = new Option("q", "query", true, "specify the sparql query file"); // Option endpointOpt = new Option("e", "endpoint", true, "a federated sparql endpoint URL"); Option versionOpt = new Option("v", "version", false, "print the version information and exit"); Option rulesOpt = new Option("r", "rulesDir", true, "directory containing the inference rules"); Option ontOpt = new Option("o", "ontologiesDir", true, "directory containing the ontologies for rules selection"); // Option locOpt = new Option("c", "centralized", false, "performs centralized inferences"); Option dataOpt = new Option("l", "load", true, "data file or directory to be loaded"); // Option selOpt = new Option("s", "rulesSelection", false, "if set to true, only the applicable rules are run"); // options.addOption(queryOpt); // options.addOption(endpointOpt); options.addOption(helpOpt); options.addOption(versionOpt); options.addOption(rulesOpt); options.addOption(ontOpt); // options.addOption(selOpt); // options.addOption(locOpt); options.addOption(dataOpt); String header = "Corese/KGRAM rule engine experiment command line interface"; String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr, olivier.corby@inria.fr"; CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("kgdqp", header, options, footer, true); System.exit(0); } if (cmd.hasOption("o")) { rulesSelection = true; String ontDirPath = cmd.getOptionValue("o"); ontDir = new File(ontDirPath); if (!ontDir.isDirectory()) { logger.warn(ontDirPath + " is not a valid directory path."); System.exit(0); } } if (!cmd.hasOption("r")) { logger.info("You must specify a path for inference rules directory !"); System.exit(0); } if (cmd.hasOption("l")) { String[] dataPaths = cmd.getOptionValues("l"); for (String path : dataPaths) { Load ld = Load.create(graph); ld.load(path); logger.info("Loaded " + path); } } if (cmd.hasOption("v")) { logger.info("version 3.0.4-SNAPSHOT"); System.exit(0); } String rulesDirPath = cmd.getOptionValue("r"); rulesDir = new File(rulesDirPath); if (!rulesDir.isDirectory()) { logger.warn(rulesDirPath + " is not a valid directory path."); System.exit(0); } // Local rules graph initialization Graph rulesG = Graph.create(); Load ld = Load.create(rulesG); if (rulesSelection) { // Ontology loading if (ontDir.isDirectory()) { for (File o : ontDir.listFiles()) { logger.info("Loading " + o.getAbsolutePath()); ld.load(o.getAbsolutePath()); } } } // Rules loading if (rulesDir.isDirectory()) { for (File r : rulesDir.listFiles()) { logger.info("Loading " + r.getAbsolutePath()); ld.load(r.getAbsolutePath()); } } // Rule engine initialization RuleEngine ruleEngine = RuleEngine.create(graph); ruleEngine.set(exec); ruleEngine.setOptimize(true); ruleEngine.setConstructResult(true); ruleEngine.setTrace(true); StopWatch sw = new StopWatch(); logger.info("Federated graph size : " + graph.size()); logger.info("Rules graph size : " + rulesG.size()); // Rule selection logger.info("Rules selection"); QueryProcess localKgram = QueryProcess.create(rulesG); ArrayList<String> applicableRules = new ArrayList<String>(); sw.start(); String rulesSelQuery = ""; if (rulesSelection) { rulesSelQuery = pertinentRulesQuery; } else { rulesSelQuery = allRulesQuery; } Mappings maps = localKgram.query(rulesSelQuery); logger.info("Rules selected in " + sw.getTime() + " ms"); logger.info("Applicable rules : " + maps.size()); // Selected rule loading for (Mapping map : maps) { IDatatype dt = (IDatatype) map.getValue("?res"); String rule = dt.getLabel(); //loading rule in the rule engine // logger.info("Adding rule : "); // System.out.println("-------"); // System.out.println(rule); // System.out.println(""); // if (! rule.toLowerCase().contains("sameas")) { applicableRules.add(rule); ruleEngine.addRule(rule); // } } // Rules application on distributed sparql endpoints logger.info("Rules application (" + applicableRules.size() + " rules)"); ExecutorService threadPool = Executors.newCachedThreadPool(); RuleEngineThread ruleThread = new RuleEngineThread(ruleEngine); sw.reset(); sw.start(); // ruleEngine.process(); threadPool.execute(ruleThread); threadPool.shutdown(); //monitoring loop while (!threadPool.isTerminated()) { // System.out.println("******************************"); // System.out.println(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter, QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter)); // System.out.println("Rule engine running for " + sw.getTime() + " ms"); // System.out.println("Federated graph size : " + graph.size()); System.out.println(sw.getTime() + " , " + graph.size()); Thread.sleep(5000); } logger.info("Federated graph size : " + graph.size()); // logger.info(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter, QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter)); // TripleFormat f = TripleFormat.create(graph, true); // f.write("/tmp/gAll.ttl"); }