List of usage examples for org.apache.commons.cli Option Option
public Option(String opt, String description) throws IllegalArgumentException
From source file:com.ibm.zurich.Main.java
public static void main(String[] args) throws NoSuchAlgorithmException, IOException { Option help = new Option(HELP, "print this message"); Option version = new Option(VERSION, "print the version information"); Options options = new Options(); Option useCurve = Option.builder(USECURVE).hasArg().argName("curve") .desc("Specify the BN Curve. Options: " + curveOptions()).build(); Option isskeygen = Option.builder(IKEYGEN).numberOfArgs(3).argName("ipk><isk><RL") .desc("Generate Issuer key pair and empty revocation list and store it in files").build(); Option join1 = Option.builder(JOIN1).numberOfArgs(3).argName("ipk><authsk><msg1") .desc("Create an authenticator secret key and perform the first step of the join protocol").build(); Option join2 = Option.builder(JOIN2).numberOfArgs(4).argName("ipk><isk><msg1><msg2") .desc("Complete the join protocol").build(); Option verify = Option.builder(VERIFY).numberOfArgs(5).argName("ipk><sig><krd><appId><RL") .desc("Verify a signature").build(); Option sign = Option.builder(SIGN).numberOfArgs(6).argName("ipk><authsk><msg2><appId><krd><sig") .desc("create a signature").build(); options.addOption(help);//from w w w . j a v a 2s. c o m options.addOption(version); options.addOption(useCurve); options.addOption(isskeygen); options.addOption(sign); options.addOption(verify); options.addOption(join1); options.addOption(join2); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new DefaultParser(); //FIXME Choose a proper instantiation of SecureRandom depending on the platform SecureRandom random = new SecureRandom(); Base64.Encoder encoder = Base64.getUrlEncoder(); Base64.Decoder decoder = Base64.getUrlDecoder(); try { CommandLine line = parser.parse(options, args); BNCurveInstantiation instantiation = null; BNCurve curve = null; if (line.hasOption(HELP) || line.getOptions().length == 0) { formatter.printHelp(USAGE, options); } else if (line.hasOption(VERSION)) { System.out.println("Version " + Main.class.getPackage().getImplementationVersion()); } else if (line.hasOption(USECURVE)) { instantiation = BNCurveInstantiation.valueOf(line.getOptionValue(USECURVE)); curve = new BNCurve(instantiation); } else { System.out.println("Specify the curve to use."); return; } if (line.hasOption(IKEYGEN)) { String[] optionValues = line.getOptionValues(IKEYGEN); // Create secret key IssuerSecretKey sk = Issuer.createIssuerKey(curve, random); // Store pk writeToFile((new IssuerPublicKey(curve, sk, random)).toJSON(curve), optionValues[0]); // Store sk writeToFile(sk.toJson(curve), optionValues[1]); // Create empty revocation list and store HashSet<BigInteger> rl = new HashSet<BigInteger>(); writeToFile(Verifier.revocationListToJson(rl, curve), optionValues[2]); } else if (line.hasOption(SIGN)) { //("ipk><authsk><msg2><appId><krd><sig") String[] optionValues = line.getOptionValues(SIGN); IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0])); BigInteger authsk = curve.bigIntegerFromB(decoder.decode(readFromFile(optionValues[1]))); JoinMessage2 msg2 = new JoinMessage2(curve, readStringFromFile(optionValues[2])); // setup a new authenticator Authenticator auth = new Authenticator(curve, ipk, authsk); auth.EcDaaJoin1(curve.getRandomModOrder(random)); if (auth.EcDaaJoin2(msg2)) { EcDaaSignature sig = auth.EcDaaSign(optionValues[3]); // Write krd to file writeToFile(sig.krd, optionValues[4]); // Write signature to file writeToFile(sig.encode(curve), optionValues[5]); System.out.println("Signature written to " + optionValues[5]); } else { System.out.println("JoinMsg2 invalid"); } } else if (line.hasOption(VERIFY)) { Verifier ver = new Verifier(curve); String[] optionValues = line.getOptionValues(VERIFY); String pkFile = optionValues[0]; String sigFile = optionValues[1]; String krdFile = optionValues[2]; String appId = optionValues[3]; String rlPath = optionValues[4]; byte[] krd = Files.readAllBytes(Paths.get(krdFile)); IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(pkFile)); EcDaaSignature sig = new EcDaaSignature(Files.readAllBytes(Paths.get(sigFile)), krd, curve); boolean valid = ver.verify(sig, appId, pk, Verifier.revocationListFromJson(readStringFromFile(rlPath), curve)); System.out.println("Signature is " + (valid ? "valid." : "invalid.")); } else if (line.hasOption(JOIN1)) { String[] optionValues = line.getOptionValues(JOIN1); IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0])); // Create authenticator key BigInteger sk = curve.getRandomModOrder(random); writeToFile(encoder.encodeToString(curve.bigIntegerToB(sk)), optionValues[1]); Authenticator auth = new Authenticator(curve, ipk, sk); JoinMessage1 msg1 = auth.EcDaaJoin1(curve.getRandomModOrder(random)); writeToFile(msg1.toJson(curve), optionValues[2]); } else if (line.hasOption(JOIN2)) { String[] optionValues = line.getOptionValues(JOIN2); // create issuer with the specified key IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0])); IssuerSecretKey sk = new IssuerSecretKey(curve, readStringFromFile(optionValues[1])); Issuer iss = new Issuer(curve, sk, pk); JoinMessage1 msg1 = new JoinMessage1(curve, readStringFromFile(optionValues[2])); // Note that we do not check for nonce freshness. JoinMessage2 msg2 = iss.EcDaaIssuerJoin(msg1, false); if (msg2 == null) { System.out.println("Join message invalid."); } else { System.out.println("Join message valid, msg2 written to file."); writeToFile(msg2.toJson(curve), optionValues[3]); } } } catch (ParseException e) { System.out.println("Error parsing input."); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.ibm.soatf.SOATestingFramework.java
/** * SOA Testing Framework main static method. * * @param args Main input parameters./*ww w . jav a2 s.c o m*/ */ public static void main(String[] args) { Options options = new Options(); options.addOption(new Option("gui", "Display a GUI")); options.addOption(OptionBuilder.withArgName("environment").hasArg() .withDescription("Environment to run the tests on").create("env")); // has a value options.addOption(OptionBuilder.withArgName("project").hasArg() .withDescription("Project to run the tests on").create("p")); // has a value options.addOption(OptionBuilder.withArgName("interface").hasArg() .withDescription("Interface to run the tests on").create("i")); // has a value CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); validate(cmd); if (cmd.hasOption("gui")) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { if (false) { //disabled the OS Look'n'Feel UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } else { for (UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } UIManager.getLookAndFeelDefaults().put("nimbusOrange", (new Color(0, 128, 255))); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { logger.error("Cannot set look and feel", ex); } //</editor-fold> final SOATestingFrameworkGUI soatfgui = new SOATestingFrameworkGUI(); java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { soatfgui.setVisible(true); } }); } else { //<editor-fold defaultstate="collapsed" desc="Command line mode"> try { // Initialization of configuration manager. ConfigurationManager.getInstance().init(); String env = cmd.getOptionValue("env", null); String ifaceName; boolean inboundOnly = false; if (cmd.hasOption("p")) { String projectName = cmd.getOptionValue("p"); MasterConfiguration masterConfig = ConfigurationManager.getInstance().getMasterConfig(); List<SOATestingFrameworkMasterConfiguration.Interfaces.Interface> interfaces = masterConfig .getInterfaces(); all: for (Interface iface : interfaces) { List<Project> projects = iface.getProjects().getProject(); for (Project project : projects) { if (project.getName().equals(projectName)) { inboundOnly = "INBOUND".equalsIgnoreCase(project.getDirection()); ifaceName = iface.getName(); break all; } } } throw new FrameworkExecutionException( "No such project found in master configuration: " + projectName); } else { ifaceName = cmd.getOptionValue("i"); inboundOnly = false; } DirectoryStructureManager.checkFrameworkDirectoryStructure(ifaceName); FlowExecutor flowExecutor = new FlowExecutor(inboundOnly, env, ifaceName); flowExecutor.execute(); } catch (FrameworkConfigurationException ex) { logger.fatal("Configuration corrupted. See the exception stack trace for details.", ex); } catch (FrameworkException ex) { logger.fatal(ex); } //</editor-fold> } } catch (ParseException ex) { logger.fatal("Could not parse the command line arguments. Reason: " + ex); printUsage(); } catch (Throwable ex) { logger.fatal("Unexpected error occured: ", ex); printUsage(); System.exit(-1); } }
From source file:io.s4.tools.loadgenerator.LoadGenerator.java
public static void main(String args[]) { Options options = new Options(); boolean warmUp = false; options.addOption(//from w w w . ja v a 2s . co m OptionBuilder.withArgName("rate").hasArg().withDescription("Rate (events per second)").create("r")); options.addOption(OptionBuilder.withArgName("display_rate").hasArg() .withDescription("Display Rate at specified second boundary").create("d")); options.addOption(OptionBuilder.withArgName("adapter_address").hasArg() .withDescription("Address of client adapter").create("a")); options.addOption(OptionBuilder.withArgName("listener_application_name").hasArg() .withDescription("Listener application name").create("g")); options.addOption( OptionBuilder.withArgName("sleep_overhead").hasArg().withDescription("Sleep overhead").create("o")); options.addOption(new Option("w", "Warm-up")); CommandLineParser parser = new GnuParser(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); System.exit(1); } int expectedRate = 250; if (line.hasOption("r")) { try { expectedRate = Integer.parseInt(line.getOptionValue("r")); } catch (Exception e) { System.err.println("Bad expected rate specified " + line.getOptionValue("r")); System.exit(1); } } int displayRateIntervalSeconds = 20; if (line.hasOption("d")) { try { displayRateIntervalSeconds = Integer.parseInt(line.getOptionValue("d")); } catch (Exception e) { System.err.println("Bad display rate value specified " + line.getOptionValue("d")); System.exit(1); } } int updateFrequency = 0; if (line.hasOption("f")) { try { updateFrequency = Integer.parseInt(line.getOptionValue("f")); } catch (Exception e) { System.err.println("Bad query udpdate frequency specified " + line.getOptionValue("f")); System.exit(1); } System.out.printf("Update frequency is %d\n", updateFrequency); } String clientAdapterAddress = null; String clientAdapterHost = null; int clientAdapterPort = -1; if (line.hasOption("a")) { clientAdapterAddress = line.getOptionValue("a"); String[] parts = clientAdapterAddress.split(":"); if (parts.length != 2) { System.err.println("Bad adapter address specified " + clientAdapterAddress); System.exit(1); } clientAdapterHost = parts[0]; try { clientAdapterPort = Integer.parseInt(parts[1]); } catch (NumberFormatException nfe) { System.err.println("Bad adapter address specified " + clientAdapterAddress); System.exit(1); } } long sleepOverheadMicros = -1; if (line.hasOption("o")) { try { sleepOverheadMicros = Long.parseLong(line.getOptionValue("o")); } catch (NumberFormatException e) { System.err.println("Bad sleep overhead specified " + line.getOptionValue("o")); System.exit(1); } System.out.printf("Specified sleep overhead is %d\n", sleepOverheadMicros); } if (line.hasOption("w")) { warmUp = true; } List loArgs = line.getArgList(); if (loArgs.size() < 1) { System.err.println("No input file specified"); System.exit(1); } String inputFilename = (String) loArgs.get(0); LoadGenerator loadGenerator = new LoadGenerator(); loadGenerator.setInputFilename(inputFilename); loadGenerator.setDisplayRateInterval(displayRateIntervalSeconds); loadGenerator.setExpectedRate(expectedRate); loadGenerator.setClientAdapterHost(clientAdapterHost); loadGenerator.setClientAdapterPort(clientAdapterPort); loadGenerator.run(); System.exit(0); }
From source file:io.anserini.search.SearchTweets.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(RM3_OPTION, "apply relevance feedback with rm3")); options.addOption(/*w ww . j a v a2 s . c o m*/ OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return") .create(NUM_RESULTS_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("file containing topics in TREC format").create(QUERIES_OPTION)); options.addOption(OptionBuilder.withArgName("similarity").hasArg() .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(QUERIES_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(SearchTweets.class.getName(), options); System.exit(-1); } File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION)); if (!indexLocation.exists()) { System.err.println("Error: " + indexLocation + " does not exist!"); System.exit(-1); } String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG; String topicsFile = cmdline.getOptionValue(QUERIES_OPTION); int numResults = 1000; try { if (cmdline.hasOption(NUM_RESULTS_OPTION)) { numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION)); } } catch (NumberFormatException e) { System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION)); System.exit(-1); } String similarity = "LM"; if (cmdline.hasOption(SIMILARITY_OPTION)) { similarity = cmdline.getOptionValue(SIMILARITY_OPTION); } PrintStream out = new PrintStream(System.out, true, "UTF-8"); IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexLocation.getAbsolutePath()))); IndexSearcher searcher = new IndexSearcher(reader); if (similarity.equalsIgnoreCase("BM25")) { searcher.setSimilarity(new BM25Similarity()); } else if (similarity.equalsIgnoreCase("LM")) { searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); } MicroblogTopicSet topics = MicroblogTopicSet.fromFile(new File(topicsFile)); for (MicroblogTopic topic : topics) { Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, topic.getQueryTweetTime(), true, true); Query query = AnalyzerUtils.buildBagOfWordsQuery(StatusField.TEXT.name, IndexTweets.ANALYZER, topic.getQuery()); TopDocs rs = searcher.search(query, filter, numResults); RerankerContext context = new RerankerContext(searcher, query, topic.getQuery(), filter); RerankerCascade cascade = new RerankerCascade(context); if (cmdline.hasOption(RM3_OPTION)) { cascade.add(new Rm3Reranker(IndexTweets.ANALYZER, StatusField.TEXT.name)); cascade.add(new RemoveRetweetsTemporalTiebreakReranker()); } else { cascade.add(new RemoveRetweetsTemporalTiebreakReranker()); } ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher)); for (int i = 0; i < docs.documents.length; i++) { String qid = topic.getId().replaceFirst("^MB0*", ""); out.println(String.format("%s Q0 %s %d %f %s", qid, docs.documents[i].getField(StatusField.ID.name).numericValue(), (i + 1), docs.scores[i], runtag)); } } reader.close(); out.close(); }
From source file:de.prozesskraft.pkraft.Startinstance.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { /*---------------------------- get options from ini-file/*w ww .j a va 2 s.c o m*/ ----------------------------*/ java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Startinstance.class) + "/" + "../etc/pkraft-startinstance.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option obasedir = OptionBuilder.withArgName("DIR").hasArg() .withDescription("[optional, default .] base directory where instance shourd run.") // .isRequired() .create("basedir"); Option odefinition = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[optional] definition file of the process you want to start an instance from.") // .isRequired() .create("definition"); Option onostart = OptionBuilder.withArgName("") // .hasArg() .withDescription( "[optional] oppresses the start of the instance. (only create the process-instance)") // .isRequired() .create("nostart"); Option opdomain = OptionBuilder.withArgName("STRING").hasArg() .withDescription("[optional] domain of the process (mandatory if you omit -definition)") // .isRequired() .create("pdomain"); Option opname = OptionBuilder.withArgName("STRING").hasArg().withDescription( "[optional] name of the process you want to start an instance from (mandatory if you omit -definition)") // .isRequired() .create("pname"); Option opversion = OptionBuilder.withArgName("STRING").hasArg().withDescription( "[optional] version of the process you want to start an instance from (mandatory if you omit -definition)") // .isRequired() .create("pversion"); Option ocommitfile = OptionBuilder.withArgName("KEY=FILE; FILE").hasArg() .withDescription("[optional] this file will be committed as file. omit KEY= if KEY==FILENAME.") // .isRequired() .create("commitfile"); Option ocommitvariable = OptionBuilder.withArgName("KEY=VALUE; VALUE").hasArg() .withDescription("[optional] this string will be committed as a variable. omit KEY= if KEY==VALUE") // .isRequired() .create("commitvariable"); Option ocommitfiledummy = OptionBuilder.withArgName("KEY=FILE; FILE").hasArg().withDescription( "[optional] use this parameter like --commitfile. the file will not be checked against the process interface and therefore allows to commit files which are not expected by the process definition. use this parameter only for test purposes e.g. to commit dummy output files for accelerated tests of complex processes or the like.") // .isRequired() .create("commitfiledummy"); Option ocommitvariabledummy = OptionBuilder.withArgName("KEY=VALUE; VALUE").hasArg().withDescription( "[optional] use this parameter like --commitvariable. the variable will not be checked against the process interface and therefore allows to commit variables which are not expected by the process definition. use this parameter only for test purposes e.g. to commit dummy output variables for accelerated tests of complex processes or the like.") // .isRequired() .create("commitvariabledummy"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(obasedir); options.addOption(odefinition); options.addOption(onostart); options.addOption(opname); options.addOption(opversion); options.addOption(ocommitfile); options.addOption(ocommitvariable); options.addOption(ocommitfiledummy); options.addOption(ocommitvariabledummy); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); // parse the command line arguments commandline = parser.parse(options, args); /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("startinstance", options); System.exit(0); } if (commandline.hasOption("v")) { System.out.println("author: alexander.vogel@caegroup.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("definition")) && (!(commandline.hasOption("pname")) || !(commandline.hasOption("pversion")) || !(commandline.hasOption("pdomain")))) { System.err.println("option -definition or the options -pname & -pversion & -pdomain are mandatory"); exiter(); } if ((commandline.hasOption("definition") && ((commandline.hasOption("pversion")) || (commandline.hasOption("pname")) || (commandline.hasOption("pdomain"))))) { System.err.println("you must not use option -definition with -pversion or -pname or -pdomain"); exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ Process p1 = new Process(); String pathToDefinition = ""; if (commandline.hasOption("definition")) { pathToDefinition = commandline.getOptionValue("definition"); } else if (commandline.hasOption("pname") && commandline.hasOption("pversion") && commandline.hasOption("pdomain")) { pathToDefinition.replaceAll("/+$", ""); pathToDefinition = ini.get("process", "domain-installation-directory") + "/" + commandline.getOptionValue("pdomain") + "/" + commandline.getOptionValue("pname") + "/" + commandline.getOptionValue("pversion") + "/process.xml"; } else { System.err.println("option -definition or the options -pname & -pversion & -pdomain are mandatory"); exiter(); } // check ob das ermittelte oder uebergebene xml-file ueberhaupt existiert java.io.File xmlDefinition = new java.io.File(pathToDefinition); if (!(xmlDefinition.exists()) || !(xmlDefinition.isFile())) { System.err.println("process definition does not exist: " + pathToDefinition); exiter(); } p1.setInfilexml(xmlDefinition.getCanonicalPath()); Process p2 = null; try { p2 = p1.readXml(); } catch (JAXBException e1) { System.err.println(e1.getMessage()); } // das processBinary vorneweg schon mal erstellen, da es sein kann das das committen laenger dauert und ein pradar-attend den neuen prozess schon mal aufnehmen will // root-verzeichnis erstellen if (commandline.hasOption("basedir")) { p2.setBaseDir(commandline.getOptionValue("basedir")); } p2.makeRootdir(); // den pfad fuers binary setzen p2.setOutfilebinary(p2.getRootdir() + "/process.pmb"); System.err.println("info: writing process instance " + p2.getOutfilebinary()); // binary schreiben p2.writeBinary(); // step, an den die commits gehen, soll 'root' sein. Step stepRoot = p2.getRootStep(); // committen von files (ueber einen glob) if (commandline.hasOption("commitfile")) { for (String actOptionCommitfile : commandline.getOptionValues("commitfile")) { String[] parts = actOptionCommitfile.split("="); File userFile = new File(); if (parts.length == 1) { userFile.setKey(new java.io.File(parts[0]).getName()); userFile.setGlob(parts[0]); } else if (parts.length == 2) { userFile.setKey(parts[0]); userFile.setGlob(parts[1]); } else { System.err.println("error in option -commitfile " + actOptionCommitfile); exiter(); } // die auf der kommandozeile uebergebenen Informationen sollen in die vorhandenen commits im rootStep gemappt werden // alle vorhandenen commits in step root durchgehen und dem passenden file zuordnen for (Commit actCommit : stepRoot.getCommit()) { // alle files des aktuellen commits for (File actFile : actCommit.getFile()) { if (actFile.getKey().equals(userFile.getKey())) { // wenn actFile schon ein valider eintrag ist, dann soll ein klon befuellt werden if (actFile.getGlob() != null) { // wenn die maximale erlaubte anzahl noch nicht erreicht ist if (actCommit.getFile(actFile.getKey()).size() < actFile.getMaxoccur()) { File newFile = actFile.clone(); newFile.setGlob(userFile.getGlob()); System.err.println("entering file into commit '" + actCommit.getName() + "' (" + newFile.getKey() + "=" + newFile.getGlob() + ")"); actCommit.addFile(newFile); break; } else { System.err.println("fatal: you only may commit " + actFile.getMaxoccur() + " " + actFile.getKey() + "-files into commit " + actCommit.getName()); exiter(); } } // ansonsten das bereits vorhandene file im commit mit den daten befuellen else { actFile.setGlob(userFile.getGlob()); actFile.setGlobdir(p2.getBaseDir()); System.err.println("entering file into commit '" + actCommit.getName() + "' (" + actFile.getKey() + "=" + actFile.getGlob() + ")"); break; } } } } } } // committen von files (ueber einen glob) if (commandline.hasOption("commitfiledummy")) { // diese files werden nicht in bestehende commits der prozessdefinition eingetragen, sondern in ein spezielles commit Commit commitFiledummy = new Commit(); commitFiledummy.setName("fileDummy"); stepRoot.addCommit(commitFiledummy); for (String actOptionCommitfiledummy : commandline.getOptionValues("commitfiledummy")) { String[] parts = actOptionCommitfiledummy.split("="); File userFile = new File(); commitFiledummy.addFile(userFile); if (parts.length == 1) { userFile.setKey(new java.io.File(parts[0]).getName()); userFile.setGlob(parts[0]); } else if (parts.length == 2) { userFile.setKey(parts[0]); userFile.setGlob(parts[1]); } else { System.err.println("error in option -commitfiledummy " + actOptionCommitfiledummy); exiter(); } userFile.setGlobdir(p2.getBaseDir()); System.err.println("entering (dummy-)file into commit '" + commitFiledummy.getName() + "' (" + userFile.getKey() + "=" + userFile.getGlob() + ")"); } } if (commandline.hasOption("commitvariable")) { for (String actOptionCommitvariable : commandline.getOptionValues("commitvariable")) { if (actOptionCommitvariable.matches(".+=.+")) { String[] parts = actOptionCommitvariable.split("="); Variable userVariable = new Variable(); if (parts.length == 1) { userVariable.setKey("default"); userVariable.setValue(parts[0]); } else if (parts.length == 2) { userVariable.setKey(parts[0]); userVariable.setValue(parts[1]); } else { System.err.println("error in option -commitvariable"); exiter(); } // commit.addVariable(variable); // die auf der kommandozeile uebergebenen Informationen sollen in die vorhandenen commits im rootStep gemappt werden // alle vorhandenen commits in step root durchgehen und dem passenden file zuordnen for (Commit actCommit : stepRoot.getCommit()) { // alle files des aktuellen commits for (Variable actVariable : actCommit.getVariable()) { if (actVariable.getKey().equals(userVariable.getKey())) { // wenn actFile schon ein valider eintrag ist, dann soll ein klon befuellt werden if (actVariable.getGlob() != null) { // wenn die maximale erlaubte anzahl noch nicht erreicht ist if (actCommit.getVariable(actVariable.getKey()).size() < actVariable .getMaxoccur()) { Variable newVariable = actVariable.clone(); newVariable.setValue(userVariable.getValue()); System.err.println("entering variable into commit '" + actCommit.getName() + "' (" + newVariable.getKey() + "=" + newVariable.getValue() + ")"); actCommit.addVariable(newVariable); break; } else { System.err.println("fatal: you only may commit " + actVariable.getMaxoccur() + " " + actVariable.getKey() + "-variable(s) into commit " + actCommit.getName()); exiter(); } } // ansonsten das bereits vorhandene file im commit mit den daten befuellen else { actVariable.setValue(userVariable.getValue()); System.err.println("entering variable into commit '" + actCommit.getName() + "' (" + actVariable.getKey() + "=" + actVariable.getValue() + ")"); break; } } } } } else { System.err.println("-commitvariable " + actOptionCommitvariable + " does not match pattern \"NAME=VALUE\"."); exiter(); } } } if (commandline.hasOption("commitvariabledummy")) { // diese files werden nicht in bestehende commits der prozessdefinition eingetragen, sondern in ein spezielles commit Commit commitVariabledummy = new Commit(); commitVariabledummy.setName("variableDummy"); stepRoot.addCommit(commitVariabledummy); for (String actOptionCommitvariabledummy : commandline.getOptionValues("commitvariabledummy")) { String[] parts = actOptionCommitvariabledummy.split("="); Variable userVariable = new Variable(); commitVariabledummy.addVariable(userVariable); if (parts.length == 1) { userVariable.setKey(parts[0]); userVariable.setValue(parts[0]); } else if (parts.length == 2) { userVariable.setKey(parts[0]); userVariable.setValue(parts[1]); } else { System.err.println("error in option -commitvariabledummy"); exiter(); } System.err.println("entering variable into commit '" + commitVariabledummy.getName() + "' (" + userVariable.getKey() + "=" + userVariable.getValue() + ")"); } } // if (commandline.hasOption("basedir")) // { // p2.setBaseDir(commandline.getOptionValue("basedir")); // } // commit.doIt(); stepRoot.commit(); // root-verzeichnis erstellen p2.makeRootdir(); // den pfad fuers binary setzen // p2.setOutfilebinary(p2.getRootdir() + "/process.pmb"); System.err.println("info: writing process instance " + p2.getOutfilebinary()); // binary schreiben p2.writeBinary(); try { Thread.sleep(1500, 0); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Runtime.getRuntime().exec("process-manager -help"); // starten nur, falls es nicht abgewaehlt wurde if (!commandline.hasOption("nostart")) { System.err.println("info: starting processmanager for instance " + p2.getOutfilebinary()); String aufrufString = ini.get("apps", "pkraft-manager") + " -instance " + p2.getOutfilebinary(); System.err.println("calling: " + aufrufString); ArrayList<String> processSyscallWithArgs = new ArrayList<String>( Arrays.asList(aufrufString.split(" "))); ProcessBuilder pb = new ProcessBuilder(processSyscallWithArgs); // ProcessBuilder pb = new ProcessBuilder("processmanager -instance "+p2.getOutfilebinary()); // Map<String,String> env = pb.environment(); // String path = env.get("PATH"); // System.out.println("PATH: "+path); // java.lang.Process p = pb.start(); System.err.println("pid: " + p.hashCode()); } else { System.err.println("info: NOT starting processmanager for instance " + p2.getOutfilebinary()); } }
From source file:fdtutilscli.Main.java
/** * /* w ww.j av a 2s . com*/ * @param args the command line arguments */ public static void main(String[] args) { CommandLineParser parser = new PosixParser(); CommandLine line = null; Options options = new Options(); OptionGroup optCommand = new OptionGroup(); OptionGroup optOutput = new OptionGroup(); HelpFormatter formatter = new HelpFormatter(); TRACE trace = TRACE.DEFAULT; optCommand.addOption(OptionBuilder.withArgName("ndf odf nif key seperator").hasArgs(5) .withValueSeparator(' ').withDescription("Description").create("delta")); optCommand.addOption(OptionBuilder.withArgName("dupsfile key seperator").hasArgs(3) .withDescription("Description").create("duplicates")); optCommand.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message.").create("h")); optCommand.addOption( OptionBuilder.withLongOpt("version").withDescription("print version information.").create("V")); optOutput.addOption(new Option("verbose", "be extra verbose")); optOutput.addOption(new Option("quiet", "be extra quiet")); optOutput.addOption(new Option("silent", "same as --quiet")); options.addOptionGroup(optCommand); options.addOptionGroup(optOutput); try { line = parser.parse(options, args); if (line.hasOption("verbose")) { trace = TRACE.VERBOSE; } else if (line.hasOption("quiet") || line.hasOption("silent")) { trace = TRACE.QUIET; } if (line.hasOption("h")) { formatter.printHelp(HELP_SYNTAX, HELP_HEADER, options, null, true); return; } else if (line.hasOption("V")) { System.out.println(APP_NAME + " version " + VERSION); System.out.println("fDTDeltaBuilder version " + DTDeltaBuilder.version()); System.out.println("DTDuplicateKeyFinder version " + DTDuplicateKeyFinder.version()); return; } else if (line.hasOption("delta")) { String ndf = line.getOptionValues("delta")[0]; String odf = line.getOptionValues("delta")[1]; String nif = line.getOptionValues("delta")[2]; Integer key = (line.getOptionValues("delta").length <= 3) ? DEFAULT_KEY : new Integer(line.getOptionValues("delta")[3]); String seperator = (line.getOptionValues("delta").length <= 4) ? DEFAULT_SEPERATOR : line.getOptionValues("delta")[4]; doDelta(ndf, odf, nif, key.intValue(), seperator, trace); return; } else if (line.hasOption("duplicates")) { String dupsFile = line.getOptionValues("duplicates")[0]; Integer key = (line.getOptionValues("duplicates").length <= 1) ? DEFAULT_KEY : new Integer(line.getOptionValues("duplicates")[1]); String seperator = (line.getOptionValues("duplicates").length <= 2) ? DEFAULT_SEPERATOR : line.getOptionValues("duplicates")[2]; doDuplicates(dupsFile, key.intValue(), seperator, trace); return; } else if (args.length == 0) { formatter.printHelp(HELP_SYNTAX, HELP_HEADER, options, null, true); } else { throw new UnrecognizedOptionException(E_MSG_UNREC_OPT); } } catch (UnrecognizedOptionException e) { formatter.printHelp(HELP_SYNTAX, HELP_HEADER, options, HELP_FOOTER + e.getMessage(), true); } catch (ParseException e) { formatter.printHelp(HELP_SYNTAX, HELP_HEADER, options, HELP_FOOTER + e.getMessage(), true); } }
From source file:de.prozesskraft.pkraft.Commitit.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try/*from w w w. j a v a2 s .co m*/ // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ java.io.File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Commitit.class) + "/" + "../etc/pkraft-commitit.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); /*---------------------------- create argument options ----------------------------*/ Option oinstance = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] process instance file") // .isRequired() .create("instance"); Option ostep = OptionBuilder.withArgName("STEPNAME").hasArg() .withDescription("[optional, default: root] process step to commit to") // .isRequired() .create("step"); Option ofile = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[optional] this file will be committed as file. key will be set to 'default'") // .isRequired() .create("file"); Option okey = OptionBuilder.withArgName("KEY").hasArg() .withDescription( "[optional, default: default] this string will be considered as the key for the commit.") // .isRequired() .create("key"); Option ovariable = OptionBuilder.withArgName("VALUE").hasArg() .withDescription("[optional] this string will be committed as a variable.") // .isRequired() .create("variable"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(oinstance); options.addOption(ostep); options.addOption(ofile); options.addOption(okey); options.addOption(ovariable); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("commit", options); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("instance"))) { System.out.println("option -instance is mandatory."); exiter(); } else if (!(commandline.hasOption("dir")) && !(commandline.hasOption("file")) && !(commandline.hasOption("varfile")) && !(commandline.hasOption("varname")) && !(commandline.hasOption("varvalue")) && !(commandline.hasOption("variable"))) { System.out.println( "at least one of these options needed. -dir -file -varfile -variable -varname -varvalue."); exiter(); } else if ((commandline.hasOption("varname") && !(commandline.hasOption("varvalue"))) || (!(commandline.hasOption("varname")) && commandline.hasOption("varvalue"))) { System.out.println("use options -varname and -varvalue only in combination with each other."); exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ // setzen des steps String stepname = "root"; if (commandline.hasOption("step")) { stepname = commandline.getOptionValue("step"); } // setzen des key String key = "default"; if (commandline.hasOption("key")) { key = commandline.getOptionValue("key"); } Process p1 = new Process(); p1.setInfilebinary(commandline.getOptionValue("instance")); System.out.println("info: reading process instance " + commandline.getOptionValue("instance")); Process p2 = p1.readBinary(); p2.setOutfilebinary(commandline.getOptionValue("instance")); // step ueber den namen heraussuchen Step step = p2.getStep(stepname); if (step == null) { System.err.println("step not found: " + stepname); exiter(); } // den Commit 'by-process-commitit' heraussuchen oder einen neuen Commit dieses Namens erstellen Commit commit = step.getCommit("by-hand"); if (commit == null) { commit = new Commit(step); commit.setName("by-process-commitit"); } // committen if (commandline.hasOption("file")) { File file = new File(); file.setKey(key); file.setGlob(commandline.getOptionValue("file")); commit.addFile(file); commit.doIt(); } if (commandline.hasOption("variable")) { Variable variable = new Variable(); variable.setKey(key); variable.setValue(commandline.getOptionValue("variable")); commit.addVariable(variable); commit.doIt(); } p2.writeBinary(); System.out.println("info: writing process instance " + p2.getOutfilebinary()); }
From source file:de.prozesskraft.pkraft.Wrap.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try//from w ww . j av a 2s . co m // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Wrap.class) + "/" + "../etc/pkraft-wrap.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option ooutput = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory; default: .] file for generated wrapper process.") // .isRequired() .create("output"); Option odefinition = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] process definition file.") // .isRequired() .create("definition"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(ooutput); options.addOption(odefinition); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("wrap", options); System.exit(0); } else if (commandline.hasOption("v")) { System.out.println("web: www.prozesskraft.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("definition"))) { System.err.println("option -definition is mandatory."); exiter(); } if (!(commandline.hasOption("output"))) { System.err.println("option -output is mandatory."); exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ Process p1 = new Process(); java.io.File output = new java.io.File(commandline.getOptionValue("output")); if (output.exists()) { System.err.println("warn: already exists: " + output.getCanonicalPath()); exiter(); } p1.setInfilexml(commandline.getOptionValue("definition")); System.err.println("info: reading process definition " + commandline.getOptionValue("definition")); // dummy process Process p2 = null; try { p2 = p1.readXml(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err.println("error"); exiter(); } // den wrapper process generieren Process p3 = p2.getProcessAsWrapper(); p3.setOutfilexml(output.getAbsolutePath()); // den neuen wrap-process rausschreiben p3.writeXml(); }
From source file:de.prozesskraft.pkraft.Createmap.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try//from w ww. j a va 2 s.c o m // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Createmap.class) + "/" + "../etc/pkraft-createmap.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); /*---------------------------- create argument options ----------------------------*/ Option ooutput = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory; default: process.dot] file for generated map.") // .isRequired() .create("output"); Option odefinition = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] process definition file.") // .isRequired() .create("definition"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ooutput); options.addOption(odefinition); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("createmap", options); System.out.println(""); System.out.println("author: " + author + " | version: " + version + " | date: " + date); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("definition"))) { System.err.println("option -definition is mandatory."); exiter(); } if (!(commandline.hasOption("output"))) { System.err.println("option -output is mandatory."); exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ Process p1 = new Process(); java.io.File output = new java.io.File(commandline.getOptionValue("output")); if (output.exists()) { System.err.println("warn: already exists: " + output.getCanonicalPath()); exiter(); } p1.setInfilexml(commandline.getOptionValue("definition")); System.err.println("info: reading process definition " + commandline.getOptionValue("definition")); // dummy process Process p2 = null; try { p2 = p1.readXml(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err.println("error"); exiter(); } // den wrapper process generieren ArrayList<String> dot = p2.getProcessAsDotGraph(); // dot file rausschreiben writeFile.writeFile(output, dot); }
From source file:cc.twittertools.search.api.RunQueriesThrift.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("string").hasArg().withDescription("host").create(HOST_OPTION)); options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg() .withDescription("file containing topics in TREC format").create(QUERIES_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return") .create(NUM_RESULTS_OPTION)); options.addOption(/* w ww . j av a 2 s.co m*/ OptionBuilder.withArgName("string").hasArg().withDescription("group id").create(GROUP_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("access token").create(TOKEN_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION)); options.addOption(new Option(VERBOSE_OPTION, "print out complete document")); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(HOST_OPTION) || !cmdline.hasOption(PORT_OPTION) || !cmdline.hasOption(QUERIES_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(RunQueriesThrift.class.getName(), options); System.exit(-1); } String queryFile = cmdline.getOptionValue(QUERIES_OPTION); if (!new File(queryFile).exists()) { System.err.println("Error: " + queryFile + " doesn't exist!"); System.exit(-1); } String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG; TrecTopicSet topicsFile = TrecTopicSet.fromFile(new File(queryFile)); int numResults = 1000; try { if (cmdline.hasOption(NUM_RESULTS_OPTION)) { numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION)); } } catch (NumberFormatException e) { System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION)); System.exit(-1); } String group = cmdline.hasOption(GROUP_OPTION) ? cmdline.getOptionValue(GROUP_OPTION) : null; String token = cmdline.hasOption(TOKEN_OPTION) ? cmdline.getOptionValue(TOKEN_OPTION) : null; boolean verbose = cmdline.hasOption(VERBOSE_OPTION); PrintStream out = new PrintStream(System.out, true, "UTF-8"); TrecSearchThriftClient client = new TrecSearchThriftClient(cmdline.getOptionValue(HOST_OPTION), Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)), group, token); for (cc.twittertools.search.TrecTopic query : topicsFile) { List<TResult> results = client.search(query.getQuery(), query.getQueryTweetTime(), numResults); int i = 1; Set<Long> tweetIds = new HashSet<Long>(); for (TResult result : results) { if (!tweetIds.contains(result.id)) { tweetIds.add(result.id); out.println( String.format("%s Q0 %d %d %f %s", query.getId(), result.id, i, result.rsv, runtag)); if (verbose) { out.println("# " + result.toString().replaceAll("[\\n\\r]+", " ")); } i++; } } } out.close(); }