List of usage examples for java.io File exists
public boolean exists()
From source file:com.baidu.rigel.biplatform.ma.file.serv.FileServer.java
/** * //from w ww. j a v a 2s . co m * ???server * * @param args */ public static void main(String[] args) throws Exception { // if (args.length != 1) { // LOGGER.error("can not get enough parameters for starting file server"); // printUsage(); // System.exit(-1); // } FileInputStream fis = null; String classLocation = FileServer.class.getProtectionDomain().getCodeSource().getLocation().toString(); final File configFile = new File(classLocation + "/../conf/fileserver.conf"); Properties properties = new Properties(); try { if (configFile.exists()) { fis = new FileInputStream(configFile); } else if (StringUtils.isNotEmpty(args[0])) { fis = new FileInputStream(args[0]); } else { printUsage(); throw new RuntimeException("can't find correct file server configuration file!"); } properties.load(fis); } finally { if (fis != null) { fis.close(); } } int port = -1; try { port = Integer.valueOf(properties.getProperty(PORT_NUM_KEY)); } catch (NumberFormatException e) { LOGGER.error("parameter is not correct, [port = {}]", args[0]); System.exit(-1); } String location = properties.getProperty(ROOT_DIR_KEY); if (StringUtils.isEmpty(location)) { LOGGER.error("the location can not be empty"); System.exit(-1); } File f = new File(location); if (!f.exists() && !f.mkdirs()) { LOGGER.error("invalidation location [{}] please verify the input", args[1]); System.exit(-1); } startServer(location, port); }
From source file:io.anserini.index.UpdateIndex.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option(HELP_OPTION, "show help")); options.addOption(new Option(OPTIMIZE_OPTION, "merge indexes into a single segment")); options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors")); options.addOption(/*from www . j a v a2 s .c o m*/ OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("file with deleted tweetids") .create(DELETES_OPTION)); options.addOption(OptionBuilder.withArgName("id").hasArg().withDescription("max id").create(MAX_ID_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(HELP_OPTION) || !cmdline.hasOption(INDEX_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(UpdateIndex.class.getName(), options); System.exit(-1); } String indexPath = cmdline.getOptionValue(INDEX_OPTION); final FieldType textOptions = new FieldType(); textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); textOptions.setStored(true); textOptions.setTokenized(true); textOptions.setStoreTermVectors(true); LOG.info("index: " + indexPath); File file = new File("PittsburghUserTimeline"); if (!file.exists()) { System.err.println("Error: " + file + " does not exist!"); System.exit(-1); } final StatusStream stream = new JsonStatusCorpusReader(file); Status status; String s; HashMap<Long, String> hm = new HashMap<Long, String>(); try { while ((s = stream.nextRaw()) != null) { try { status = DataObjectFactory.createStatus(s); if (status.getText() == null) { continue; } hm.put(status.getUser().getId(), hm.get(status.getUser().getId()) + status.getText().replaceAll("[\\r\\n]+", " ")); } catch (Exception e) { } } } catch (Exception e) { e.printStackTrace(); } finally { stream.close(); } ArrayList<String> userIDList = new ArrayList<String>(); try (BufferedReader br = new BufferedReader(new FileReader(new File("userID")))) { String line; while ((line = br.readLine()) != null) { userIDList.add(line.replaceAll("[\\r\\n]+", "")); // process the line. } } try { reader = DirectoryReader .open(FSDirectory.open(new File(cmdline.getOptionValue(INDEX_OPTION)).toPath())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } final Directory dir = new SimpleFSDirectory(Paths.get(cmdline.getOptionValue(INDEX_OPTION))); final IndexWriterConfig config = new IndexWriterConfig(ANALYZER); config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); final IndexWriter writer = new IndexWriter(dir, config); IndexSearcher searcher = new IndexSearcher(reader); System.out.println("The total number of docs indexed " + searcher.collectionStatistics(TweetStreamReader.StatusField.TEXT.name).docCount()); for (int city = 0; city < cityName.length; city++) { // Pittsburgh's coordinate -79.976389, 40.439722 Query q_long = NumericRangeQuery.newDoubleRange(TweetStreamReader.StatusField.LONGITUDE.name, new Double(longitude[city] - 0.05), new Double(longitude[city] + 0.05), true, true); Query q_lat = NumericRangeQuery.newDoubleRange(TweetStreamReader.StatusField.LATITUDE.name, new Double(latitude[city] - 0.05), new Double(latitude[city] + 0.05), true, true); BooleanQuery bqCityName = new BooleanQuery(); Term t = new Term("place", cityName[city]); TermQuery query = new TermQuery(t); bqCityName.add(query, BooleanClause.Occur.SHOULD); System.out.println(query.toString()); for (int i = 0; i < cityNameAlias[city].length; i++) { t = new Term("place", cityNameAlias[city][i]); query = new TermQuery(t); bqCityName.add(query, BooleanClause.Occur.SHOULD); System.out.println(query.toString()); } BooleanQuery bq = new BooleanQuery(); BooleanQuery finalQuery = new BooleanQuery(); // either a coordinate match bq.add(q_long, BooleanClause.Occur.MUST); bq.add(q_lat, BooleanClause.Occur.MUST); finalQuery.add(bq, BooleanClause.Occur.SHOULD); // or a place city name match finalQuery.add(bqCityName, BooleanClause.Occur.SHOULD); TotalHitCountCollector totalHitCollector = new TotalHitCountCollector(); // Query hasFieldQuery = new ConstantScoreQuery(new // FieldValueFilter("timeline")); // // searcher.search(hasFieldQuery, totalHitCollector); // // if (totalHitCollector.getTotalHits() > 0) { // TopScoreDocCollector collector = // TopScoreDocCollector.create(Math.max(0, // totalHitCollector.getTotalHits())); // searcher.search(finalQuery, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // HashMap<String, Integer> hasHit = new HashMap<String, Integer>(); // int dupcount = 0; // for (int i = 0; i < hits.length; ++i) { // int docId = hits[i].doc; // Document d; // // d = searcher.doc(docId); // // System.out.println(d.getFields()); // } // } // totalHitCollector = new TotalHitCountCollector(); searcher.search(finalQuery, totalHitCollector); if (totalHitCollector.getTotalHits() > 0) { TopScoreDocCollector collector = TopScoreDocCollector .create(Math.max(0, totalHitCollector.getTotalHits())); searcher.search(finalQuery, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; System.out.println("City " + cityName[city] + " " + collector.getTotalHits() + " hits."); HashMap<String, Integer> hasHit = new HashMap<String, Integer>(); int dupcount = 0; for (int i = 0; i < hits.length; ++i) { int docId = hits[i].doc; Document d; d = searcher.doc(docId); if (userIDList.contains(d.get(IndexTweets.StatusField.USER_ID.name)) && hm.containsKey(Long.parseLong(d.get(IndexTweets.StatusField.USER_ID.name)))) { // System.out.println("Has timeline field?" + (d.get("timeline") != null)); // System.out.println(reader.getDocCount("timeline")); // d.add(new Field("timeline", hm.get(Long.parseLong(d.get(IndexTweets.StatusField.USER_ID.name))), // textOptions)); System.out.println("Found a user hit"); BytesRefBuilder brb = new BytesRefBuilder(); NumericUtils.longToPrefixCodedBytes(Long.parseLong(d.get(IndexTweets.StatusField.ID.name)), 0, brb); Term term = new Term(IndexTweets.StatusField.ID.name, brb.get()); // System.out.println(reader.getDocCount("timeline")); Document d_new = new Document(); // for (IndexableField field : d.getFields()) { // d_new.add(field); // } // System.out.println(d_new.getFields()); d_new.add(new StringField("userBackground", d.get(IndexTweets.StatusField.USER_ID.name), Store.YES)); d_new.add(new Field("timeline", hm.get(Long.parseLong(d.get(IndexTweets.StatusField.USER_ID.name))), textOptions)); // System.out.println(d_new.get()); writer.addDocument(d_new); writer.commit(); // t = new Term("label", "why"); // TermQuery tqnew = new TermQuery(t); // // totalHitCollector = new TotalHitCountCollector(); // // searcher.search(tqnew, totalHitCollector); // // if (totalHitCollector.getTotalHits() > 0) { // collector = TopScoreDocCollector.create(Math.max(0, totalHitCollector.getTotalHits())); // searcher.search(tqnew, collector); // hits = collector.topDocs().scoreDocs; // // System.out.println("City " + cityName[city] + " " + collector.getTotalHits() + " hits."); // // for (int k = 0; k < hits.length; k++) { // docId = hits[k].doc; // d = searcher.doc(docId); // System.out.println(d.get(IndexTweets.StatusField.ID.name)); // System.out.println(d.get(IndexTweets.StatusField.PLACE.name)); // } // } // writer.deleteDocuments(term); // writer.commit(); // writer.addDocument(d); // writer.commit(); // System.out.println(reader.getDocCount("timeline")); // writer.updateDocument(term, d); // writer.commit(); } } } } reader.close(); writer.close(); }
From source file:edu.oregonstate.eecs.mcplan.abstraction.PairDataset.java
/** * @param args/*from w ww . j ava2 s . c o m*/ */ public static void main(final String[] args) { int idx = 0; final String single_filename = args[idx++]; System.out.println("single_filename = " + single_filename); final String keyword = args[idx++]; System.out.println("keyword = " + keyword); final int seed = Integer.parseInt(args[idx++]); System.out.println("seed = " + seed); final int max_pairwise_instances = Integer.parseInt(args[idx++]); System.out.println("max_pairwise_instances = " + max_pairwise_instances); final File single_file = new File(single_filename); System.out.println("Opening '" + single_file.getAbsolutePath() + "'"); assert (single_file.exists()); final Instances single = WekaUtil.readLabeledDataset(single_file); final ArrayList<Attribute> single_attributes = WekaUtil.extractAttributes(single); final InstanceCombiner combiner; if ("difference".equals(keyword)) { combiner = new DifferenceFeatures(single_attributes); } else if ("symmetric".equals(keyword)) { combiner = new SymmetricFeatures(single_attributes); } else { throw new IllegalArgumentException("Unknown keyword '" + keyword + "'"); } // final String pair_name = FilenameUtils.getBaseName( single_filename ) // + "_" + keyword + "_" + max_pairwise_instances; final RandomGenerator rng = new MersenneTwister(seed); System.out.println("Making dataset..."); final Instances pair_instances = makePairDataset(rng, max_pairwise_instances, single, combiner); System.out.println("Writing dataset..."); WekaUtil.writeDataset(single_file.getParentFile(), pair_instances); }
From source file:com.cic.datacrawl.ui.Main.java
/** * Main entry point. Creates a debugger attached to a Rhino * {@link com.cic.datacrawl.ui.shell.Shell} shell session. *//*from www. ja va2s .c o m*/ public static void main(final String[] args) { if (System.getProperties().get("os.name").toString().toLowerCase().indexOf("linux") >= 0) System.setProperty("sun.awt.xembedserver", "true"); try { String path = null; boolean reflash = true; if (args != null && args.length > 0) { if (args[0].equalsIgnoreCase("-h")) { System.out.println("Command Format: \n" + "\t%JAVA_HOME%\\BIN\\JAVA -jar homepageCatcher.jar " + "[-d config path]\n" + "\t%JAVA_HOME%\\BIN\\JAVA -jar homepageCatcher.jar " + "[-d config path_1;path_2;....;path_n]\n"); } int pathIndex = ArrayUtils.indexOf(args, "-d"); if (pathIndex >= 0) { try { path = args[pathIndex + 1]; File f = new File(path); if (!f.exists()) { LOG.warn("Invalid path of configuration. " + "Using default configuration."); } } catch (Throwable e) { LOG.warn("Invalid path of configuration. " + "Using default configuration."); } } // int reflashIndex = ArrayUtils.indexOf(args, "-r"); // // reflash = new Boolean(args[reflashIndex + 1]).booleanValue(); } if (path == null || path.trim().length() == 0) path = Config.INSTALL_PATH + File.separator + "config" + File.separator + "beans"; LOG.debug("Config Path: \"" + path + "\""); // ?IOC // ???? // ? ApplicationContext.initialiaze(path, reflash); System.setProperty(ApplicationContext.CONFIG_PATH, path); // js??? InitializerRegister.getInstance().execute(); // ??? //VerifyCodeInputDialog.init(); // ?? //initTestData(); // ?GUI Thread thread = new Thread(new Runnable() { @Override public void run() { startupGUI(args); } }); thread.setName("UI_Thread"); thread.start(); } catch (Throwable e) { LOG.error(e.getMessage(), e); } }
From source file:com.act.lcms.v2.TraceIndexExtractor.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*from ww w .ja v a 2 s. c o m*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } // Not enough memory available? We're gonna need a bigger heap. long maxMemory = Runtime.getRuntime().maxMemory(); if (maxMemory < 1 << 34) { // 16GB String msg = StringUtils.join( String.format( "You have run this class with a maximum heap size of less than 16GB (%d to be exact). ", maxMemory), "There is no way this process will complete with that much space available. ", "Crank up your heap allocation with -Xmx and try again.", ""); throw new RuntimeException(msg); } File inputFile = new File(cl.getOptionValue(OPTION_SCAN_FILE)); if (!inputFile.exists()) { System.err.format("Cannot find input scan file at %s\n", inputFile.getAbsolutePath()); HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH)); if (rocksDBFile.exists()) { System.err.format("Index file at %s already exists--remove and retry\n", rocksDBFile.getAbsolutePath()); HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } List<Double> targetMZs = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(cl.getOptionValue(OPTION_TARGET_MASSES)))) { String line; while ((line = reader.readLine()) != null) { targetMZs.add(Double.valueOf(line)); } } TraceIndexExtractor extractor = new TraceIndexExtractor(); extractor.processScan(targetMZs, inputFile, rocksDBFile); }
From source file:htmlwordtag.HtmlWordTag.java
public static void main(String[] args) throws RepositoryException, MalformedQueryException, QueryEvaluationException { //get current path String current = System.getProperty("user.dir"); //get html file from internet loadhtml();//from www . j av a 2 s .c om //make director for output verifyArgs(); //translate html file to rdf HtmlWordTag httpClientPost = new HtmlWordTag(); httpClientPost.input = new File("input"); httpClientPost.output = new File("output"); httpClientPost.client = new HttpClient(); httpClientPost.client.getParams().setParameter("http.useragent", "Calais Rest Client"); httpClientPost.run(); //create main memory repository Repository repo = new SailRepository(new MemoryStore()); repo.initialize(); File file = new File(current + "\\output\\website1.html.xml"); RepositoryConnection con = repo.getConnection(); try { con.add(file, null, RDFFormat.RDFXML); } catch (OpenRDFException e) { // handle exception } catch (java.io.IOException e) { // handle io exception } System.out.println(con.isEmpty()); //query entire repostiory String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "PREFIX c: <http://s.opencalais.com/1/type/em/e/>\n" + "PREFIX p: <http://s.opencalais.com/1/pred/>\n" + "PREFIX geo: <http://s.opencalais.com/1/type/er/Geo/>\n" + "SELECT distinct ?s ?n\n" + "WHERE {\n" + "{ ?s rdf:type c:Organization.\n" + " ?s p:name ?n.\n}" + " UNION \n" + "{ ?s rdf:type c:Person.\n" + " ?s p:name ?n.\n}" + " UNION \n" + "{ ?s rdf:type geo:City.\n" + " ?s p:name ?n.\n}" + "}"; //System.out.println(queryString); //insert query through sparql repository connection TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString); TupleQueryResult result = tupleQuery.evaluate(); File queryresultdir = new File(current + "\\queryresult"); if (!queryresultdir.exists()) { if (queryresultdir.mkdir()) { System.out.println("Directory is created!"); } else { System.out.println("Failed to create directory!"); } } File queryresult = null; try { // create new file queryresult = new File(current + "\\queryresult\\queryresult1.txt"); // tries to create new file in the system if (queryresult.exists()) { if (queryresult.delete()) { System.out.println("file queryresult1.txt is already exist."); System.out.println("file queryresult1.txt has been delete."); if (queryresult.createNewFile()) { System.out.println("create queryresult1.txt success"); } else { System.out.println("fail to create queryresult1.txt"); } } else { System.out.println("fail to delete queryresult1.txt."); } } else { if (queryresult.createNewFile()) { System.out.println("create queryresult1.txt success"); } else { System.out.println("fail to create queryresult1.txt"); } } } catch (Exception e) { e.printStackTrace(); } try { PrintWriter outputStream = null; try { outputStream = new PrintWriter(new FileOutputStream(current + "\\queryresult\\queryresult1.txt")); } catch (FileNotFoundException e) { System.out.println("Error to find file queryresult1.txt"); System.exit(0); } //go through all triple in sparql repository while (result.hasNext()) { // iterate over the result BindingSet bindingSet = result.next(); Value valueOfS = bindingSet.getValue("s"); Value valueOfN = bindingSet.getValue("n"); System.out.println(valueOfS + " " + valueOfN); outputStream.println(valueOfS + " " + valueOfN); } outputStream.close(); } finally { result.close(); } //create main memory repository Repository repo2 = new SailRepository(new MemoryStore()); repo2.initialize(); File file2 = new File(current + "\\output\\website2.html.xml"); RepositoryConnection con2 = repo2.getConnection(); try { con2.add(file2, null, RDFFormat.RDFXML); } catch (OpenRDFException e) { // handle exception } catch (java.io.IOException e) { // handle io exception } System.out.println(con2.isEmpty()); //query entire repostiory String queryString2 = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" + "PREFIX c: <http://s.opencalais.com/1/type/em/e/>\n" + "PREFIX p: <http://s.opencalais.com/1/pred/>\n" + "PREFIX geo: <http://s.opencalais.com/1/type/er/Geo/>\n" + "SELECT distinct ?s ?n\n" + "WHERE {\n" + "{ ?s rdf:type c:Organization.\n" + " ?s p:name ?n.\n}" + " UNION \n" + "{ ?s rdf:type c:Person.\n" + " ?s p:name ?n.\n}" + " UNION \n" + "{ ?s rdf:type geo:City.\n" + " ?s p:name ?n.\n}" + "}"; //System.out.println(queryString2); //insert query through sparql repository connection TupleQuery tupleQuery2 = con2.prepareTupleQuery(QueryLanguage.SPARQL, queryString2); TupleQueryResult result2 = tupleQuery2.evaluate(); File queryresult2 = null; try { // create new file queryresult2 = new File(current + "\\queryresult\\queryresult2.txt"); // tries to create new file in the system if (queryresult2.exists()) { if (queryresult2.delete()) { System.out.println("file queryresult2.txt is already exist."); System.out.println("file queryresult2.txt has been delete."); if (queryresult2.createNewFile()) { System.out.println("create queryresult2.txt success"); } else { System.out.println("fail to create queryresult2.txt"); } } else { System.out.println("fail to delete queryresult2.txt."); } } else { if (queryresult2.createNewFile()) { System.out.println("create queryresult2.txt success"); } else { System.out.println("fail to create queryresult2.txt"); } } } catch (Exception e) { e.printStackTrace(); } try { PrintWriter outputStream2 = null; try { outputStream2 = new PrintWriter(new FileOutputStream(current + "\\queryresult\\queryresult2.txt")); } catch (FileNotFoundException e) { System.out.println("Error to find file queryresult2.txt"); System.exit(0); } //go through all triple in sparql repository while (result2.hasNext()) { // iterate over the result BindingSet bindingSet = result2.next(); Value valueOfS = bindingSet.getValue("s"); Value valueOfN = bindingSet.getValue("n"); System.out.println(valueOfS + " " + valueOfN); outputStream2.println(valueOfS + " " + valueOfN); } outputStream2.close(); } finally { result2.close(); } }
From source file:marytts.tools.voiceimport.DatabaseImportMain.java
public static void main(String[] args) throws Exception { File voiceDir = determineVoiceBuildingDir(args); if (voiceDir == null) { throw new IllegalArgumentException("Cannot determine voice building directory."); }// ww w.j a v a2 s. c om File wavDir = new File(voiceDir, "wav"); //System.out.println(System.getProperty("user.dir")+System.getProperty("file.separator")+"wav"); assert wavDir.exists() : "no wav dir at " + wavDir.getAbsolutePath(); /* Read the list of components */ File importMainConfigFile = new File(voiceDir, "importMain.config"); if (!importMainConfigFile.exists()) { FileUtils.copyInputStreamToFile(DatabaseImportMain.class.getResourceAsStream("importMain.config"), importMainConfigFile); } assert importMainConfigFile.exists(); String[][] groups2comps = readComponentList(new FileInputStream(importMainConfigFile)); VoiceImportComponent[] components = createComponents(groups2comps); /* Load DatabaseLayout */ File configFile = new File(voiceDir, "database.config"); DatabaseLayout db = new DatabaseLayout(configFile, components); if (!db.isInitialized()) return; if (args.length > 0) { // non-gui mode: arguments are expected to be component names, in order or application for (String compName : args) { VoiceImportComponent component = null; for (VoiceImportComponent comp : components) { if (comp.getName().equals(compName)) { component = comp; break; } } if (component != null) { System.out.println("Running " + compName); component.compute(); } else { throw new IllegalArgumentException("No such voice import component: " + compName); } } } else { /* Display GUI */ String voicename = db.getProp(db.VOICENAME); DatabaseImportMain importer = new DatabaseImportMain("Database import: " + voicename, components, db, groups2comps); importer.pack(); // Center window on screen: importer.setLocationRelativeTo(null); importer.setVisible(true); } }
From source file:net.sf.firemox.xml.XmlConfiguration.java
/** * <ul>/* w w w . j a v a 2 s. c o m*/ * 2 modes: * <li>Update the a MDB for specified TBS against the XML files (main file, * cards and fragments). Arguments are : TBS_NAME</li> * <li>Rebuild completely the MDB for specified TBS. Arguments are : -full * TBS_NAME</li> * </ul> * * @param args * main arguments. */ public static void main(String... args) { options = new Options(); final CmdLineParser parser = new CmdLineParser(options); try { parser.parseArgument(args); } catch (CmdLineException e) { // Display help info(e.getMessage()); parser.setUsageWidth(80); parser.printUsage(System.out); System.exit(-1); return; } if (options.isVersion()) { // Display version info("Version is " + IdConst.VERSION); System.exit(-1); return; } if (options.isHelp()) { // Display help parser.setUsageWidth(80); parser.printUsage(System.out); System.exit(-1); return; } warning = 0; uncompleted = 0; error = 0; long start = System.currentTimeMillis(); XmlTools.initHashMaps(); MToolKit.tbsName = options.getMdb(); String xmlFile = MToolKit.getFile(IdConst.TBS_DIR + "/" + MToolKit.tbsName + ".xml", false) .getAbsolutePath(); try { if (options.isForce()) { final File recycledDir = MToolKit.getTbsFile("recycled"); if (!recycledDir.exists() || !recycledDir.isDirectory()) { recycledDir.mkdir(); } parseRules(xmlFile, MToolKit.getTbsFile("recycled").getAbsolutePath(), new FileOutputStream(MToolKit.getTbsFile(MToolKit.tbsName + ".mdb", false))); } else { // Check the up-to-date state of MDB final File file = MToolKit .getFile(IdConst.TBS_DIR + "/" + MToolKit.tbsName + "/" + MToolKit.tbsName + ".mdb"); final long lastModifiedMdb; if (file == null) { lastModifiedMdb = 0; } else { lastModifiedMdb = file.lastModified(); } boolean update = false; // Check the up-to-date state of MDB against the main XML file if (MToolKit.getFile(xmlFile).lastModified() > lastModifiedMdb) { // The main XML file is newer than MDB System.out.println("MDB is out of date, " + xmlFile + " is newer"); update = true; } else { final File fragmentDir = MToolKit.getTbsFile(""); for (File frament : fragmentDir.listFiles( (FilenameFilter) FileFilterUtils.andFileFilter(FileFilterUtils.suffixFileFilter("xml"), FileFilterUtils.prefixFileFilter("fragment-")))) { if (frament.lastModified() > lastModifiedMdb) { // One card is newer than MDB System.out.println( "MDB is out of date, at least one fragment found : " + frament.getName()); update = true; break; } } if (!update) { // Check the up-to-date state of MDB against the cards final File recycledDir = MToolKit.getTbsFile("recycled"); if (!recycledDir.exists() || !recycledDir.isDirectory()) { recycledDir.mkdir(); } if (recycledDir.lastModified() > lastModifiedMdb) { // The recycled XML file is newer than MDB System.out.println("MDB is out of date, the recycled directory is new"); update = true; } else { for (File card : recycledDir.listFiles((FilenameFilter) FileFilterUtils.andFileFilter( FileFilterUtils.suffixFileFilter("xml"), FileFilterUtils.notFileFilter( FileFilterUtils.suffixFileFilter(IdConst.FILE_DATABASE_SAVED))))) { if (card.lastModified() > lastModifiedMdb) { // One card is newer than MDB System.out.println("MDB is out of date, at least one new card found : " + card); update = true; break; } } } } } if (!update) { return; } // Need to update the whole MDB parseRules(xmlFile, MToolKit.getTbsFile("recycled").getAbsolutePath(), new FileOutputStream(MToolKit.getTbsFile(MToolKit.tbsName + ".mdb", false))); } } catch (SAXParseException e) { // Ignore this error } catch (Exception e) { e.printStackTrace(); } if (warning > 0) { System.out.println("\t" + warning + " warning" + (warning > 1 ? "s" : "")); } if (error > 0) { System.out.println("\t" + error + " error" + (error > 1 ? "s" : "")); System.out.println("Some cards have not been built correctly. Fix them."); } else { System.out.println("\tSuccessfull build"); } System.out.println("\tTime : " + (System.currentTimeMillis() - start) / 1000 + " s"); }
From source file:de.prozesskraft.ptest.Fingerprint.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try//from ww w . ja va 2 s . com // { // 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(Fingerprint.class) + "/" + "../etc/ptest-fingerprint.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 opath = OptionBuilder.withArgName("PATH").hasArg() .withDescription( "[mandatory; default: .] the root path for the tree you want to make a fingerprint from.") // .isRequired() .create("path"); Option osizetol = OptionBuilder.withArgName("FLOAT").hasArg().withDescription( "[optional; default: 0.02] the sizeTolerance (as factor in percent) of all file entries will be set to this value. [0.0 < sizetol < 1.0]") // .isRequired() .create("sizetol"); Option omd5 = OptionBuilder.withArgName("no|yes").hasArg() .withDescription("[optional; default: yes] should be the md5sum of files determined? no|yes") // .isRequired() .create("md5"); Option oignore = OptionBuilder.withArgName("STRING").hasArgs() .withDescription("[optional] path-pattern that should be ignored when creating the fingerprint") // .isRequired() .create("ignore"); Option oignorefile = OptionBuilder.withArgName("FILE").hasArg().withDescription( "[optional] file with path-patterns (one per line) that should be ignored when creating the fingerprint") // .isRequired() .create("ignorefile"); Option ooutput = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory; default: <path>/fingerprint.xml] fingerprint file") // .isRequired() .create("output"); Option of = new Option("f", "[optional] force overwrite fingerprint file if it already exists"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(opath); options.addOption(osizetol); options.addOption(omd5); options.addOption(oignore); options.addOption(oignorefile); options.addOption(ooutput); options.addOption(of); /*---------------------------- 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("fingerprint", options); System.exit(0); } else if (commandline.hasOption("v")) { System.out.println("web: " + web); System.out.println("author: " + author); System.out.println("version:" + version); System.out.println("date: " + date); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ String path = ""; String sizetol = ""; boolean md5 = false; Float sizetolFloat = null; String output = ""; java.io.File ignorefile = null; ArrayList<String> ignore = new ArrayList<String>(); if (!(commandline.hasOption("path"))) { System.err.println("setting default for -path=."); path = "."; } else { path = commandline.getOptionValue("path"); } if (!(commandline.hasOption("sizetol"))) { System.err.println("setting default for -sizetol=0.02"); sizetol = "0.02"; sizetolFloat = 0.02F; } else { sizetol = commandline.getOptionValue("sizetol"); sizetolFloat = Float.parseFloat(sizetol); if ((sizetolFloat > 1) || (sizetolFloat < 0)) { System.err.println("use only values >=0.0 and <1.0 for -sizetol"); System.exit(1); } } if (!(commandline.hasOption("md5"))) { System.err.println("setting default for -md5=yes"); md5 = true; } else if (commandline.getOptionValue("md5").equals("no")) { md5 = false; } else if (commandline.getOptionValue("md5").equals("yes")) { md5 = true; } else { System.err.println("use only values no|yes for -md5"); System.exit(1); } if (commandline.hasOption("ignore")) { ignore.addAll(Arrays.asList(commandline.getOptionValues("ignore"))); } if (commandline.hasOption("ignorefile")) { ignorefile = new java.io.File(commandline.getOptionValue("ignorefile")); if (!ignorefile.exists()) { System.err.println("warn: ignore file does not exist: " + ignorefile.getCanonicalPath()); } } if (!(commandline.hasOption("output"))) { System.err.println("setting default for -output=" + path + "/fingerprint.xml"); output = path + "/fingerprint.xml"; } else { output = commandline.getOptionValue("output"); } // wenn output bereits existiert -> abbruch java.io.File outputFile = new File(output); if (outputFile.exists()) { if (commandline.hasOption("f")) { outputFile.delete(); } else { System.err .println("error: output file (" + output + ") already exists. use -f to force overwrite."); System.exit(1); } } // 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 ----------------------------*/ Dir dir = new Dir(); dir.setBasepath(path); dir.setOutfilexml(output); // ignore file in ein Array lesen if ((ignorefile != null) && (ignorefile.exists())) { Scanner sc = new Scanner(ignorefile); while (sc.hasNextLine()) { ignore.add(sc.nextLine()); } sc.close(); } // // autoignore hinzufuegen // String autoIgnoreString = ini.get("autoignore", "autoignore"); // ignoreLines.addAll(Arrays.asList(autoIgnoreString.split(","))); // // debug // System.out.println("ignorefile content:"); // for(String actLine : ignore) // { // System.out.println("line: "+actLine); // } try { dir.genFingerprint(sizetolFloat, md5, ignore); } catch (NullPointerException e) { System.err.println("file/dir does not exist " + path); e.printStackTrace(); exiter(); } catch (IOException e) { e.printStackTrace(); exiter(); } System.out.println("writing to file: " + dir.getOutfilexml()); dir.writeXml(); }
From source file:com.sitewhere.web.rest.documentation.RestDocumentationGenerator.java
public static void main(String[] args) { if (args.length < 2) { throw new RuntimeException("Missing arguments needed to create REST documentation."); }/*from ww w. jav a2 s . c o m*/ System.out.println("Generating SiteWhere REST documentation..."); try { // Required since some internal operations require a user to be // logged in. try { SecurityContextHolder.getContext().setAuthentication(SiteWhereServer.getSystemAuthentication()); } catch (SiteWhereException e) { throw new RuntimeException("Unable to set system user.", e); } File resources = new File(args[0]); if (!resources.exists()) { throw new SiteWhereException("Unable to find REST documentation resources folder."); } List<ParsedController> controllers = parseControllers(resources); generateRestDocumentation(controllers, resources, args[1]); } catch (SiteWhereException e) { System.err.println("Unable to generate SiteWhere REST documentation."); e.printStackTrace(System.err); } System.out.println("Finished generating SiteWhere REST documentation..."); }