List of usage examples for java.io File listFiles
public File[] listFiles(FileFilter filter)
From source file:com.tamingtext.qa.WikipediaWexIndexer.java
public static void main(String[] args) throws Exception { DefaultOptionBuilder obuilder = new DefaultOptionBuilder(); ArgumentBuilder abuilder = new ArgumentBuilder(); GroupBuilder gbuilder = new GroupBuilder(); Option wikipediaFileOpt = obuilder.withLongName("wikiFile").withRequired(true) .withArgument(abuilder.withName("wikiFile").withMinimum(1).withMaximum(1).create()) .withDescription("The path to the wikipedia dump file. " + "May be a directory containing wikipedia dump files. " + "If a directory is specified, files starting with the prefix " + "freebase-segment- are used.") .withShortName("w").create(); Option numDocsOpt = obuilder.withLongName("numDocs").withRequired(false) .withArgument(abuilder.withName("numDocs").withMinimum(1).withMaximum(1).create()) .withDescription("The number of docs to index").withShortName("n").create(); Option solrURLOpt = obuilder.withLongName("solrURL").withRequired(false) .withArgument(abuilder.withName("solrURL").withMinimum(1).withMaximum(1).create()) .withDescription("The URL where Solr lives").withShortName("s").create(); Option solrBatchOpt = obuilder.withLongName("batch").withRequired(false) .withArgument(abuilder.withName("batch").withMinimum(1).withMaximum(1).create()) .withDescription("The number of docs to include in each indexing batch").withShortName("b") .create();/*from w w w . j av a2 s . c o m*/ Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h") .create(); Group group = gbuilder.withName("Options").withOption(wikipediaFileOpt).withOption(numDocsOpt) .withOption(solrURLOpt).withOption(solrBatchOpt).withOption(helpOpt).create(); Parser parser = new Parser(); parser.setGroup(group); try { CommandLine cmdLine = parser.parse(args); if (cmdLine.hasOption(helpOpt)) { CommandLineUtil.printHelp(group); return; } File file; file = new File(cmdLine.getValue(wikipediaFileOpt).toString()); File[] dumpFiles; if (file.isDirectory()) { dumpFiles = file.listFiles(new FilenameFilter() { public boolean accept(File file, String s) { return s.startsWith("freebase-segment-"); } }); } else { dumpFiles = new File[] { file }; } int numDocs = Integer.MAX_VALUE; if (cmdLine.hasOption(numDocsOpt)) { numDocs = Integer.parseInt(cmdLine.getValue(numDocsOpt).toString()); } String url = DEFAULT_SOLR_URL; if (cmdLine.hasOption(solrURLOpt)) { url = cmdLine.getValue(solrURLOpt).toString(); } int batch = 100; if (cmdLine.hasOption(solrBatchOpt)) { batch = Integer.parseInt(cmdLine.getValue(solrBatchOpt).toString()); } WikipediaWexIndexer indexer = new WikipediaWexIndexer(new CommonsHttpSolrServer(url)); int total = 0; for (int i = 0; i < dumpFiles.length && total < numDocs; i++) { File dumpFile = dumpFiles[i]; log.info("Indexing: " + file + " Num files to index: " + (numDocs - total)); long start = System.currentTimeMillis(); int totalFile = indexer.index(dumpFile, numDocs - total, batch); long finish = System.currentTimeMillis(); if (log.isInfoEnabled()) { log.info("Indexing " + dumpFile + " took " + (finish - start) + " ms"); } total += totalFile; log.info("Done Indexing: " + file + ". Indexed " + totalFile + " docs for that file and " + total + " overall."); } log.info("Indexed " + total + " docs overall."); } catch (OptionException e) { log.error("Exception", e); CommandLineUtil.printHelp(group); return; } }
From source file:com.msopentech.odatajclient.engine.performance.PerfTestReporter.java
public static void main(final String[] args) throws Exception { // 1. check input directory final File reportdir = new File(args[0] + File.separator + "target" + File.separator + "surefire-reports"); if (!reportdir.isDirectory()) { throw new IllegalArgumentException("Expected directory, got " + args[0]); }/*from www .j av a 2s . c om*/ // 2. read test data from surefire output final File[] xmlReports = reportdir.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { return name.endsWith("-output.txt"); } }); final Map<String, Map<String, Double>> testData = new TreeMap<String, Map<String, Double>>(); for (File xmlReport : xmlReports) { final BufferedReader reportReader = new BufferedReader(new FileReader(xmlReport)); try { while (reportReader.ready()) { String line = reportReader.readLine(); final String[] parts = line.substring(0, line.indexOf(':')).split("\\."); final String testClass = parts[0]; if (!testData.containsKey(testClass)) { testData.put(testClass, new TreeMap<String, Double>()); } line = reportReader.readLine(); testData.get(testClass).put(parts[1], Double.valueOf(line.substring(line.indexOf(':') + 2, line.indexOf('[')))); } } finally { IOUtils.closeQuietly(reportReader); } } // 3. build XSLX output (from template) final HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(args[0] + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + XLS)); for (Map.Entry<String, Map<String, Double>> entry : testData.entrySet()) { final Sheet sheet = workbook.getSheet(entry.getKey()); int rows = 0; for (Map.Entry<String, Double> subentry : entry.getValue().entrySet()) { final Row row = sheet.createRow(rows++); Cell cell = row.createCell(0); cell.setCellValue(subentry.getKey()); cell = row.createCell(1); cell.setCellValue(subentry.getValue()); } } final FileOutputStream out = new FileOutputStream( args[0] + File.separator + "target" + File.separator + XLS); try { workbook.write(out); } finally { IOUtils.closeQuietly(out); } }
From source file:com.hp.test.framework.Utlis.java
public static void main(String ar[]) throws IOException { ArrayList<String> runs_list = new ArrayList<String>(); String basepath = replacelogs(); String path = basepath + "ATU Reports\\Results"; File directory = new File(path); File[] subdirs = directory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY); for (File dir : subdirs) { log.info("Directory: " + dir.getName()); runs_list.add(dir.getName());//w w w. j a va2s . c om } Map<String, List<String>> runCounts = GetCountsrunsWise(runs_list, path); int success = replaceCounts(runCounts, path); if (success == 0) { File SourceFile = new File(path + "\\lineChart_temp.js"); File RenameFile = new File(path + "\\lineChart.js"); renameOriginalFile(SourceFile, RenameFile); File SourceFile1 = new File(path + "\\barChart_temp.js"); File RenameFile1 = new File(path + "\\barChart.js"); renameOriginalFile(SourceFile1, RenameFile1); String Reports_path = basepath + "ATU Reports\\"; int LatestRun = Utlis.getLastRun(Reports_path); Utlis.getpaths(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun)); try { Utlis.replaceMainTable(false, new File(Reports_path + "index.html")); Utlis.replaceMainTable(true, new File(Reports_path + "results\\" + "ConsolidatedPage.html")); Utlis.replaceMainTable(true, new File(Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html")); fileList.add( new File(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html")); for (File f : fileList) { Utlis.replaceMainTable(true, f); } } catch (Exception ex) { log.error("Error in updating Report format" + ex.getMessage()); } } }
From source file:Main.java
public static void main(String[] args) { File f = new File("c:/test"); FilenameFilter fileNameFilter = new FilenameFilter() { @Override// www. j av a 2s . com public boolean accept(File dir, String name) { if (name.lastIndexOf('.') > 0) { int lastIndex = name.lastIndexOf('.'); String str = name.substring(lastIndex); if (str.equals(".txt")) { return true; } } return false; } }; File[] paths = f.listFiles(fileNameFilter); for (File path : paths) { System.out.println(path); } }
From source file:licenseUtil.LicenseUtil.java
public static void main(String[] args) throws IOException, IncompleteLicenseObjectException { if (args.length == 0) { logger.error("Missing parameters. Use --help to get a list of the possible options."); } else if (args[0].equals("--addPomToTsv")) { if (args.length < 4) logger.error(/* w w w.j a v a 2 s .c om*/ "Missing arguments for option --addPomToTsv. Please specify <pomFileName> <licenses.stub.tsv> <currentVersion> or use the option --help for further information."); String pomFN = args[1]; String spreadSheetFN = args[2]; String currentVersion = args[3]; MavenProject project = null; try { project = Utils.readPom(new File(pomFN)); } catch (XmlPullParserException e) { logger.error("Could not parse pom file: \"" + pomFN + "\""); } LicensingList licensingList = new LicensingList(); File f = new File(spreadSheetFN); if (f.exists() && !f.isDirectory()) { licensingList.readFromSpreadsheet(spreadSheetFN); } licensingList.addMavenProject(project, currentVersion); licensingList.writeToSpreadsheet(spreadSheetFN); } else if (args[0].equals("--writeLicense3rdParty")) { if (args.length < 4) logger.error( "Missing arguments for option --writeLicense3rdParty. Please provide <licenses.enhanced.tsv> <processModule> <currentVersion> [and <targetDir>] or use the option --help for further information."); String spreadSheetFN = args[1]; String processModule = args[2]; String currentVersion = args[3]; HashMap<String, String> targetDirs = new HashMap<>(); if (args.length > 4) { File targetDir = new File(args[4]); logger.info("scan pom files in direct subdirectories of \"" + targetDir.getPath() + "\" to obtain target locations for 3rd party license files..."); File[] subdirs = targetDir.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY); for (File subdir : subdirs) { File pomFile = new File(subdir.getPath() + File.separator + POM_FN); if (!pomFile.exists()) continue; MavenProject mavenProject; try { mavenProject = Utils.readPom(pomFile); } catch (Exception e) { logger.warn("Could not read from pom file: \"" + pomFile.getPath() + "\" because of " + e.getMessage()); continue; } targetDirs.put(mavenProject.getModel().getArtifactId(), subdir.getAbsolutePath()); } } LicensingList licensingList = new LicensingList(); licensingList.readFromSpreadsheet(spreadSheetFN); if (processModule.toUpperCase().equals("ALL")) { for (String module : licensingList.getNonFixedHeaders()) { try { writeLicense3rdPartyFile(module, licensingList, currentVersion, targetDirs.get(module)); } catch (NoLicenseTemplateSetException e) { logger.error("Could not write file for module \"" + module + "\". There is no template specified for \"" + e.getLicensingObject() + "\". Please add an existing template filename to the column \"" + LicensingObject.ColumnHeader.LICENSE_TEMPLATE.value() + "\" of \"" + spreadSheetFN + "\"."); } } } else { try { writeLicense3rdPartyFile(processModule, licensingList, currentVersion, targetDirs.get(processModule)); } catch (NoLicenseTemplateSetException e) { logger.error("Could not write file for module \"" + processModule + "\". There is no template specified for \"" + e.getLicensingObject() + "\". Please add an existing template filename to the column \"" + LicensingObject.ColumnHeader.LICENSE_TEMPLATE.value() + "\" of \"" + spreadSheetFN + "\"."); } } } else if (args[0].equals("--buildEffectivePom")) { Utils.writeEffectivePom(new File(args[1]), (new File(EFFECTIVE_POM_FN)).getAbsolutePath()); } else if (args[0].equals("--updateTsvWithProjectsInFolder")) { if (args.length < 4) logger.error( "Missing arguments for option --processProjectsInFolder. Please provide <superDirectory> <licenses.stub.tsv> and <currentVersion> or use the option --help for further information."); File directory = new File(args[1]); String spreadSheetFN = args[2]; String currentVersion = args[3]; LicensingList licensingList = new LicensingList(); File f = new File(spreadSheetFN); if (f.exists() && !f.isDirectory()) { licensingList.readFromSpreadsheet(spreadSheetFN); } licensingList.addAll(processProjectsInFolder(directory, currentVersion, false)); licensingList.writeToSpreadsheet(spreadSheetFN); } else if (args[0].equals("--purgeTsv")) { if (args.length < 3) logger.error( "Missing arguments for option --purgeTsv. Please provide <spreadSheetIN.tsv>, <spreadSheetOUT.tsv> and <currentVersion> or use the option --help for further information."); String spreadSheetIN = args[1]; String spreadSheetOUT = args[2]; String currentVersion = args[3]; LicensingList licensingList = new LicensingList(); licensingList.readFromSpreadsheet(spreadSheetIN); licensingList.purge(currentVersion); licensingList.writeToSpreadsheet(spreadSheetOUT); } else if (args[0].equals("--help")) { InputStream in = LicenseUtil.class.getClassLoader().getResourceAsStream(README_PATH); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } else { logger.error("Unknown parameter: " + args[0] + ". Use --help to get a list of the possible options."); } }
From source file:com.github.s4ke.moar.cli.Main.java
public static void main(String[] args) throws ParseException, IOException { // create Options object Options options = new Options(); options.addOption("rf", true, "file containing the regexes to test against (multiple regexes are separated by one empty line)"); options.addOption("r", true, "regex to test against"); options.addOption("mf", true, "file/folder to read the MOA from"); options.addOption("mo", true, "folder to export the MOAs to (overwrites if existent)"); options.addOption("sf", true, "file to read the input string(s) from"); options.addOption("s", true, "string to test the MOA/Regex against"); options.addOption("m", false, "multiline matching mode (search in string for regex)"); options.addOption("ls", false, "treat every line of the input string file as one string"); options.addOption("t", false, "trim lines if -ls is set"); options.addOption("d", false, "only do determinism check"); options.addOption("help", false, "prints this dialog"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (args.length == 0 || cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("moar-cli", options); return;/*from w w w .ja v a 2s. co m*/ } List<String> patternNames = new ArrayList<>(); List<MoaPattern> patterns = new ArrayList<>(); List<String> stringsToCheck = new ArrayList<>(); if (cmd.hasOption("r")) { String regexStr = cmd.getOptionValue("r"); try { patterns.add(MoaPattern.compile(regexStr)); patternNames.add(regexStr); } catch (Exception e) { System.out.println(e.getMessage()); } } if (cmd.hasOption("rf")) { String fileName = cmd.getOptionValue("rf"); List<String> regexFileContents = readFileContents(new File(fileName)); int emptyLineCountAfterRegex = 0; StringBuilder regexStr = new StringBuilder(); for (String line : regexFileContents) { if (emptyLineCountAfterRegex >= 1) { if (regexStr.length() > 0) { patterns.add(MoaPattern.compile(regexStr.toString())); patternNames.add(regexStr.toString()); } regexStr.setLength(0); emptyLineCountAfterRegex = 0; } if (line.trim().equals("")) { if (regexStr.length() > 0) { ++emptyLineCountAfterRegex; } } else { regexStr.append(line); } } if (regexStr.length() > 0) { try { patterns.add(MoaPattern.compile(regexStr.toString())); patternNames.add(regexStr.toString()); } catch (Exception e) { System.out.println(e.getMessage()); return; } regexStr.setLength(0); } } if (cmd.hasOption("mf")) { String fileName = cmd.getOptionValue("mf"); File file = new File(fileName); if (file.isDirectory()) { System.out.println(fileName + " is a directory, using all *.moar files as patterns"); File[] moarFiles = file.listFiles(pathname -> pathname.getName().endsWith(".moar")); for (File moar : moarFiles) { String jsonString = readWholeFile(moar); patterns.add(MoarJSONSerializer.fromJSON(jsonString)); patternNames.add(moar.getAbsolutePath()); } } else { System.out.println(fileName + " is a single file. using it directly (no check for *.moar suffix)"); String jsonString = readWholeFile(file); patterns.add(MoarJSONSerializer.fromJSON(jsonString)); patternNames.add(fileName); } } if (cmd.hasOption("s")) { String str = cmd.getOptionValue("s"); stringsToCheck.add(str); } if (cmd.hasOption("sf")) { boolean treatLineAsString = cmd.hasOption("ls"); boolean trim = cmd.hasOption("t"); String fileName = cmd.getOptionValue("sf"); StringBuilder stringBuilder = new StringBuilder(); boolean firstLine = true; for (String str : readFileContents(new File(fileName))) { if (treatLineAsString) { if (trim) { str = str.trim(); if (str.length() == 0) { continue; } } stringsToCheck.add(str); } else { if (!firstLine) { stringBuilder.append("\n"); } if (firstLine) { firstLine = false; } stringBuilder.append(str); } } if (!treatLineAsString) { stringsToCheck.add(stringBuilder.toString()); } } if (cmd.hasOption("d")) { //at this point we have already built the Patterns //so just give the user a short note. System.out.println("All Regexes seem to be deterministic."); return; } if (patterns.size() == 0) { System.out.println("no patterns to check"); return; } if (cmd.hasOption("mo")) { String folder = cmd.getOptionValue("mo"); File folderFile = new File(folder); if (!folderFile.exists()) { System.out.println(folder + " does not exist. creating..."); if (!folderFile.mkdirs()) { System.out.println("folder " + folder + " could not be created"); } } int cnt = 0; for (MoaPattern pattern : patterns) { String patternAsJSON = MoarJSONSerializer.toJSON(pattern); try (BufferedWriter writer = new BufferedWriter( new FileWriter(new File(folderFile, "pattern" + ++cnt + ".moar")))) { writer.write(patternAsJSON); } } System.out.println("stored " + cnt + " patterns in " + folder); } if (stringsToCheck.size() == 0) { System.out.println("no strings to check"); return; } boolean multiline = cmd.hasOption("m"); for (String string : stringsToCheck) { int curPattern = 0; for (MoaPattern pattern : patterns) { MoaMatcher matcher = pattern.matcher(string); if (!multiline) { if (matcher.matches()) { System.out.println("\"" + patternNames.get(curPattern) + "\" matches \"" + string + "\""); } else { System.out.println( "\"" + patternNames.get(curPattern) + "\" does not match \"" + string + "\""); } } else { StringBuilder buffer = new StringBuilder(string); int additionalCharsPerMatch = ("<match>" + "</match>").length(); int matchCount = 0; while (matcher.nextMatch()) { buffer.replace(matcher.getStart() + matchCount * additionalCharsPerMatch, matcher.getEnd() + matchCount * additionalCharsPerMatch, "<match>" + string.substring(matcher.getStart(), matcher.getEnd()) + "</match>"); ++matchCount; } System.out.println(buffer.toString()); } } ++curPattern; } }
From source file:net.sf.firemox.xml.XmlConfiguration.java
/** * <ul>//from www . j a v a 2s. com * 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:com.hp.test.framework.Reporting.Utlis.java
public static void main(String ar[]) throws IOException { ArrayList<String> runs_list = new ArrayList<String>(); String basepath = replacelogs(); String path = basepath + "ATU Reports\\Results"; File directory = new File(path); File[] subdirs = directory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY); String htmlReport = basepath + "HTML_Design_Files\\CSS\\HtmlReport.html"; for (File dir : subdirs) { runs_list.add(dir.getName());/*www. j av a2s. com*/ } String Reports_path = basepath + "ATU Reports\\"; int LatestRun = Utlis.getLastRun(Reports_path); String Last_run_path = Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "\\"; HtmlParse.replaceMainTable(false, new File(Last_run_path + "/CurrentRun.html")); HtmlParse.replaceCountsinJSFile(new File("HTML_Design_Files/JS/3dChart.js"), Last_run_path); UpdateTestCaseDesciption.basepath = Last_run_path; UpdateTestCaseDesciption.getTestCaseHtmlPath(Last_run_path + "/CurrentRun.html"); UpdateTestCaseDesciption.replaceDetailsTable(Last_run_path + "/CurrentRun.html"); // GenerateFailReport.genarateFailureReport(new File(htmlReport), Reports_path + "Results\\Run_" + String.valueOf(LatestRun)); genarateFailureReport(new File(htmlReport), Reports_path + "Results\\"); Map<String, List<String>> runCounts = GetCountsrunsWise(runs_list, path); int success = replaceCounts(runCounts, path); if (success == 0) { File SourceFile = new File(path + "\\lineChart_temp.js"); File RenameFile = new File(path + "\\lineChart.js"); renameOriginalFile(SourceFile, RenameFile); File SourceFile1 = new File(path + "\\barChart_temp.js"); File RenameFile1 = new File(path + "\\barChart.js"); renameOriginalFile(SourceFile1, RenameFile1); Utlis.getpaths(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun)); try { Utlis.replaceMainTable(false, new File(Reports_path + "index.html")); Utlis.replaceMainTable(true, new File(Reports_path + "results\\" + "ConsolidatedPage.html")); Utlis.replaceMainTable(true, new File(Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html")); fileList.add( new File(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html")); for (File f : fileList) { Utlis.replaceMainTable(true, f); } } catch (Exception ex) { log.info("Error in updating Report format" + ex.getMessage()); } Last_run_path = Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "\\"; // HtmlParse.replaceMainTable(false, new File(Last_run_path + "/CurrentRun.html")); // HtmlParse.replaceCountsinJSFile(new File("../HTML_Design_Files/JS/3dChart.js"), Last_run_path); ArrayList<String> to_list = new ArrayList<String>(); ReportingProperties reportingproperties = new ReportingProperties(); String temp_eml = reportingproperties.getProperty("TOLIST"); String JenkinsURL = reportingproperties.getProperty("JENKINSURL"); String ScreenShotsDir = reportingproperties.getProperty("ScreenShotsDirectory"); Boolean cleanScreenshotsDir = Boolean.valueOf(reportingproperties.getProperty("CleanPreScreenShots")); Boolean generatescreenshots = Boolean.valueOf(reportingproperties.getProperty("GenerateScreenShots")); String HtmlreportFilePrefix = reportingproperties.getProperty("HtmlreportFilePrefix"); if (cleanScreenshotsDir) { if (!CleanFilesinDir(ScreenShotsDir)) { log.error("Not able to Clean the Previous Run Details in the paht" + ScreenShotsDir); } else { log.info("Cleaning Previous Run Details in the paht" + ScreenShotsDir + "Sucess"); } } List<String> scr_fileList; List<String> html_fileList; if (generatescreenshots) { scr_fileList = GetFileListinDir(ScreenShotsDir, "png"); int len = scr_fileList.size(); len = len + 1; screenshot.generatescreenshot(Last_run_path + "CurrentRun.html", ScreenShotsDir + "screenshot_" + len + ".png"); File source = new File(Reports_path + "Results\\HtmlReport.html"); File dest = new File(ScreenShotsDir + HtmlreportFilePrefix + "_HtmlReport.html"); // Files.copy(f.toPath(), (new File((ScreenShotsDir+HtmlreportFilePrefix+"_HtmlReport.html").toPath(),StandardCopyOption.REPLACE_EXISTING); FileUtils.copyFile(source, dest); scr_fileList.clear(); } scr_fileList = GetFileListinDir(ScreenShotsDir, "png"); html_fileList = GetFileListinDir(ScreenShotsDir, "html"); if (temp_eml.length() > 1) { String[] to_list_temp = temp_eml.split(","); if (to_list_temp.length > 0) { for (String to_list_temp1 : to_list_temp) { to_list.add(to_list_temp1); } } if (to_list.size() > 0) { screenshot.generatescreenshot(Last_run_path + "CurrentRun.html", Last_run_path + "screenshot.png"); // cleanTempDir.cleanandCreate(Reports_path, LatestRun); // ZipUtils.ZipFolder(Reports_path + "temp", Reports_path + "ISTF_Reports.zip"); if (generatescreenshots) { SendingEmail.sendmail(to_list, JenkinsURL, scr_fileList, html_fileList); } else { SendingEmail.sendmail(to_list, JenkinsURL, Reports_path + "/Results/HtmlReport.html", Last_run_path + "screenshot.png"); } // FileUtils.deleteQuietly(new File(Reports_path + "ISTF_Reports.zip")); // FileUtils.deleteDirectory(new File(Reports_path + "temp")); } } } }
From source file:com.p2p.peercds.cli.TorrentMain.java
/** * Torrent reader and creator.//from w w w. j a v a2 s .c o m * * <p> * You can use the {@code main()} function of this class to read or create * torrent files. See usage for details. * </p> * */ public static void main(String[] args) { BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n"))); CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option help = parser.addBooleanOption('h', "help"); CmdLineParser.Option filename = parser.addStringOption('t', "torrent"); CmdLineParser.Option create = parser.addBooleanOption('c', "create"); CmdLineParser.Option announce = parser.addStringOption('a', "announce"); try { parser.parse(args); } catch (CmdLineParser.OptionException oe) { System.err.println(oe.getMessage()); usage(System.err); System.exit(1); } // Display help and exit if requested if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) { usage(System.out); System.exit(0); } String filenameValue = (String) parser.getOptionValue(filename); if (filenameValue == null) { usage(System.err, "Torrent file must be provided!"); System.exit(1); } Boolean createFlag = (Boolean) parser.getOptionValue(create); //For repeated announce urls @SuppressWarnings("unchecked") Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce); String[] otherArgs = parser.getRemainingArgs(); if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) { usage(System.err, "Announce URL and a file or directory must be " + "provided to create a torrent file!"); System.exit(1); } OutputStream fos = null; try { if (Boolean.TRUE.equals(createFlag)) { if (filenameValue != null) { fos = new FileOutputStream(filenameValue); } else { fos = System.out; } //Process the announce URLs into URIs List<URI> announceURIs = new ArrayList<URI>(); for (String url : announceURLs) { announceURIs.add(new URI(url)); } //Create the announce-list as a list of lists of URIs //Assume all the URI's are first tier trackers List<List<URI>> announceList = new ArrayList<List<URI>>(); announceList.add(announceURIs); File source = new File(otherArgs[0]); if (!source.exists() || !source.canRead()) { throw new IllegalArgumentException( "Cannot access source file or directory " + source.getName()); } String creator = String.format("%s (ttorrent)", System.getProperty("user.name")); Torrent torrent = null; if (source.isDirectory()) { File[] files = source.listFiles(Constants.hiddenFilesFilter); Arrays.sort(files); torrent = Torrent.create(source, Arrays.asList(files), announceList, creator); } else { torrent = Torrent.create(source, announceList, creator); } torrent.save(fos); } else { Torrent.load(new File(filenameValue), true); } } catch (Exception e) { logger.error("{}", e.getMessage(), e); System.exit(2); } finally { if (fos != System.out) { IOUtils.closeQuietly(fos); } } }
From source file:ViewImageTest.java
/** * Test image(s) (default : JPEG_example_JPG_RIP_100.jpg) are parsed and * rendered to an output foler. Result can then be checked with program of * your choice./*from w ww . j a va 2s. c om*/ * * @param args * may be empty or contain parameters to override defaults : * <ul> * <li>args[0] : input image file URL or folder containing image * files URL. Default : * viewImageTest/test/JPEG_example_JPG_RIP_100.jpg</li> * <li>args[1] : output format name (for example : "jpg") for * rendered image</li> * <li>args[2] : ouput folder URL</li> * <li>args[3] : max width (in pixels) for rendered image. * Default : no value.</li> * <li>args[4] : max height (in pixels) for rendered image. * Default : no value.</li> * </ul> * @throws IOException * when a read/write error occured */ public static void main(String args[]) throws IOException { File inURL = getInputURL(args); String ext = getEncodingExt(args); File outDir = getOuputDir(args); serverObjects post = makePostParams(args); outDir.mkdirs(); File[] inFiles; if (inURL.isFile()) { inFiles = new File[1]; inFiles[0] = inURL; System.out.println("Testing ViewImage rendering with input file : " + inURL.getAbsolutePath() + " encoded To : " + ext); } else if (inURL.isDirectory()) { FileFilter filter = FileFileFilter.FILE; inFiles = inURL.listFiles(filter); System.out.println("Testing ViewImage rendering with input files in folder : " + inURL.getAbsolutePath() + " encoded To : " + ext); } else { inFiles = new File[0]; } if (inFiles.length == 0) { throw new IllegalArgumentException(inURL.getAbsolutePath() + " is not a valid file or folder url."); } System.out.println("Rendered images will be written in dir : " + outDir.getAbsolutePath()); Map<String, Exception> failures = new HashMap<String, Exception>(); try { for (File inFile : inFiles) { /* Delete eventual previous result file */ File outFile = new File(outDir, inFile.getName() + "." + ext); if (outFile.exists()) { outFile.delete(); } byte[] resourceb = getBytes(inFile); String urlString = inFile.getAbsolutePath(); EncodedImage img = null; Exception error = null; try { img = ViewImage.parseAndScale(post, true, urlString, ext, false, resourceb); } catch (Exception e) { error = e; } if (img == null) { failures.put(urlString, error); } else { FileOutputStream outFileStream = null; try { outFileStream = new FileOutputStream(outFile); img.getImage().writeTo(outFileStream); } finally { if (outFileStream != null) { outFileStream.close(); } img.getImage().close(); } } } displayResults(inFiles, failures); } finally { ConcurrentLog.shutdown(); } }