List of usage examples for org.apache.commons.io FilenameUtils removeExtension
public static String removeExtension(String filename)
From source file:main.BasicGenSystemTest.java
/** * Test the generation of report by target. *//*from www.j av a2 s . c o m*/ @Test public void testGeneratedReportByTarget() { System.out.println("Running test " + this.getClass().getSimpleName() + "." + new Object() { }.getClass().getEnclosingMethod().getName()); // tex + pdf assertTrue(new File(config.getProperty(AJPropertyConstants.FILES_LOCATION.getKey()) + File.separator + config.getProperty(AJPropertyConstants.LATEX_REPORT_BY_TARGET_FILENAME.getKey())).exists()); assertTrue(new File(config.getProperty(AJPropertyConstants.FILES_LOCATION.getKey()) + File.separator + FilenameUtils.removeExtension( config.getProperty(AJPropertyConstants.LATEX_REPORT_BY_TARGET_FILENAME.getKey())) + ".pdf").exists()); }
From source file:edu.cornell.med.icb.goby.modes.LastToCompactMode.java
@Override protected int scan(final ReadSet readIndexFilter, final IndexedIdentifier targetIds, final AlignmentWriter writer, final AlignmentTooManyHitsWriter tmhWriter) throws IOException { int currentQueryIndex = -1; final List<Alignments.AlignmentEntry.Builder> sameQueryIndexAlignmentEntries = new ArrayList<Alignments.AlignmentEntry.Builder>(); int numAligns = 0; // remove extension from inputFile if (FilenameUtils.isExtension(inputFile, new String[] { "maf", "counts" })) { inputFile = FilenameUtils.removeExtension(inputFile); }//from w w w.ja va 2 s .c om final String mafInputFile = inputFile + ".maf"; final String countsInputFile = inputFile + ".counts"; // convert MAF to compact alignment if (!onlyCountsFile) { // initialize minimum score & num hits maps final Int2FloatOpenHashMap queryIndexToMaxAlignmentScore = new Int2FloatOpenHashMap(); final Int2IntOpenHashMap queryIndexToNumHitsAtMaxScore = new Int2IntOpenHashMap(); final AlignmentStats stats = new AlignmentStats(); // final int[] readLengths = createReadLengthArray(); IntArrayList targetLengths = new IntArrayList(); // first pass: collect minimum score to keep each queryEntry // second pass: write to compact alignment file for those entries with score above threshold for (final boolean writeAlignment : new boolean[] { false, true }) { assert new File(mafInputFile).exists() : "Missing MAF file: " + mafInputFile; final LastParser parser = new LastParser(new FileReader(mafInputFile)); // final ProgressLogger progress = new ProgressLogger(LOG); progress.start(); numAligns = 0; int removedByQualityFilter = 0; int notBestScore = 0; while (parser.hasNext()) { // parse maf alignment entry parser.next(); final float score = parser.getScore(); final ObjectArrayList<AlignedSequence> alignedSequences = parser.getAlignedSequences(); // retrieve alignment properties final AlignedSequence reference = alignedSequences.get(0); final AlignedSequence query = alignedSequences.get(1); if (flipStrand) { // override the query strand with forceStrand if requested on the command line. query.strand = query.strand == '+' ? '-' : query.strand == '-' ? '+' : '?'; flip(reference.alignment); flip(query.alignment); } if (substituteCharacter) { for (final Substitution sub : substitutions) { query.alignment.replace(sub.from, sub.to); } } final int queryIndex = Integer.parseInt(query.sequenceIdentifier.toString()); if (currentQueryIndex == -1) { currentQueryIndex = queryIndex; } largestQueryIndex = Math.max(queryIndex, largestQueryIndex); int targetIndex = -1; targetIndex = getTargetIndex(targetIds, reference.sequenceIdentifier, thirdPartyInput); final boolean reverseStrand = !(query.strand == reference.strand); final int depth = query.sequenceLength; final int targetPosition = reference.alignedStart; // we have a multiplicity filter. Use it to determine multiplicity. int multiplicity = 1; if (readIndexFilter != null) { /* Multiplicity of a read is the number of times the (exact) sequence * of the read is identically repeated across a sample file. The filter * removes duplicates to avoid repeating the same alignments. Once * aligned, these are recorded multiplicity times. */ multiplicity = readIndexFilter.getMultiplicity(queryIndex); } evaluateStatistics(reference, query, stats); final Alignments.AlignmentEntry.Builder currentEntry = Alignments.AlignmentEntry.newBuilder(); currentEntry.setNumberOfIndels(stats.numberOfIndels); currentEntry.setNumberOfMismatches(stats.numberOfMismatches); currentEntry.setMatchingReverseStrand(reverseStrand); currentEntry.setMultiplicity(multiplicity); currentEntry.setPosition(targetPosition); currentEntry.setQueryAlignedLength(query.alignedLength); currentEntry.setQueryIndex(queryIndex); currentEntry.setScore(score); currentEntry.setTargetAlignedLength(reference.alignedLength); if (targetLengths.size() <= targetIndex) { targetLengths.size(targetIndex + 1); } targetLengths.set(targetIndex, reference.sequenceLength); currentEntry.setTargetIndex(targetIndex); final int queryLength = query.sequenceLength; currentEntry.setQueryLength(queryLength); final int readStartPosition = query.alignedStart; parseSequenceVariations(currentEntry, reference, query, readStartPosition, queryLength, reverseStrand); if (qualityFilter.keepEntry(depth, currentEntry)) { final float currentMax = queryIndexToMaxAlignmentScore.get(queryIndex); final int currentNumHits = queryIndexToNumHitsAtMaxScore.get(queryIndex); // on the first pass, writeAlignment=false if (!writeAlignment) { // save the maximum score per read // and reset the counter to reflect numHits at this new value if (score > currentMax) { queryIndexToMaxAlignmentScore.put(queryIndex, score); queryIndexToNumHitsAtMaxScore.put(queryIndex, 1); } // if query score equals the current max, add 1 to the counter if (score == currentMax) { queryIndexToNumHitsAtMaxScore.put(queryIndex, currentNumHits + 1); } } else { // on the second pass, writeAlignment=true // write the maximum scoring entry (or entries) per read if (score == currentMax) { // only write non-ambiguous entries i.e. currentNumHits <= mParameter if (currentNumHits <= mParameter) { if (currentEntry.getQueryIndex() == currentQueryIndex) { sameQueryIndexAlignmentEntries.add(currentEntry); } else { writeEntries(writer, sameQueryIndexAlignmentEntries); sameQueryIndexAlignmentEntries.add(currentEntry); currentQueryIndex = currentEntry.getQueryIndex(); numAligns += multiplicity; } } // TMH writer adds the alignment entry only if hits > thresh } else { notBestScore++; // System.out.println("Excluding entry "+alignmentEntry); } } } else { removedByQualityFilter++; } progress.lightUpdate(); } parser.close(); if (writeAlignment) { // Write the remaining entries (last query index); writeEntries(writer, sameQueryIndexAlignmentEntries); /*System.out.println("============== LastToCompact dumping targetLengths.."); final DoubleIndexedIdentifier reverse = new DoubleIndexedIdentifier(targetIds); int targetIndex = 0; for (final int length : targetLengths) { if (length != 0) { System.out.printf("target-id %s: index: %d length=%d %n", reverse.getId(targetIndex), targetIndex, length); } targetIndex++; } System.out.println("LastToCompact dumping targetLengths done ============== "); */ writer.setTargetLengths(targetLengths.toIntArray(new int[targetLengths.size()])); if (readIndexFilter != null) { writer.putStatistic("keep-filter-filename", readIndexFilterFile.getName()); } writer.putStatistic("number-of-entries-written", numAligns); writer.setNumQueries(numberOfReads); writer.printStats(System.out); System.out.printf("Removed by quality filter: %d%n", removedByQualityFilter); System.out.printf("Not best score: %d%n", notBestScore); } progress.stop(); } } // convert COUNTS to compact alignment if (!onlyMafFile) { assert new File(countsInputFile).exists() : "Missing COUNTS file: " + countsInputFile; System.out.println("Recording ambiguity-threshold=" + mParameter); System.out.println("Will import length of match."); for (final Map<String, String> line : new TsvLineIterator(countsInputFile)) { final int queryNameToIndex = Integer.parseInt(line.get("query-name")); final int depth = Integer.parseInt(line.get("depth")); final int count = Integer.parseInt(line.get("number-of-matches")); // TMH writer adds the alignment entry only if hits > thresh tmhWriter.append(queryNameToIndex, count, depth); } } return numAligns; }
From source file:com.comcast.magicwand.spells.web.iexplore.IePhoenixDriver.java
/** * {@inheritDoc}/*from w ww. java 2 s . c o m*/ */ public boolean verify(PhoenixDriverIngredients i) { boolean rv = false; Map<String, Object> configs = i.getDriverConfigs(); LOGGER.debug("[version_property, arch_property] = [{}, {}]", (String) configs.get(IE_DRIVER_VERSION_KEY), (String) configs.get(IE_DRIVER_ARCH_KEY)); IePlatformSpecifics ips = this.createIePlatformSpecifics((String) configs.get(IE_DRIVER_VERSION_KEY), (String) configs.get(IE_DRIVER_ARCH_KEY)); if (!ips.isValid()) { LOGGER.error("The IePlatformSpecifics retrieved are not valid."); return false; } try { XPath xpath = XPathFactory.newInstance().newXPath(); String pwd = System.getProperty("user.dir"); String version = ips.getVersion(); String arch = ips.getArch(); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(IE_XML_DRIVER_LISTING_URL); NodeList nodes = (NodeList) xpath.evaluate(IE_XML_DRIVER_LISTING_XPATH, doc, XPathConstants.NODESET); String highestVersion = null; String needle = version + "/IEDriverServer_" + arch + "_"; for (int idx = 0; idx < nodes.getLength(); idx++) { Node n = nodes.item(idx); String text = n.getTextContent(); if (text.startsWith(needle)) { text = text.substring(needle.length(), text.length()); if (IePhoenixDriver.versionGreater(highestVersion, text)) { highestVersion = text; } } } if (null != highestVersion) { highestVersion = FilenameUtils.removeExtension(highestVersion); URL url = new URL(String.format(IE_HTTP_DRIVER_PATH_FORMAT, version, arch, highestVersion)); String zipName = String.format(IE_ZIP_FILE_FORMAT, arch, highestVersion); File ieSaveDir = new File(Paths.get(pwd, "target", "drivers", "iexplore", version).toString()); LOGGER.debug("Will read from \"{}\"", url); File zipFile = new File( Paths.get(pwd, "target", "drivers", "iexplore", version, zipName).toString()); FileUtils.copyURLToFile(url, zipFile); extract(zipFile, ieSaveDir.getAbsolutePath()); File exe = Paths.get(pwd, "target", "drivers", "iexplore", version, IE_EXE_FILE_NAME).toFile(); if (exe.exists()) { exe.setExecutable(true); systemSetProperty("webdriver.ie.driver", exe.getAbsolutePath()); this.webDriver = this.createDriver(i.getDriverCapabilities()); rv = true; } else { LOGGER.error("Extracted zip archive did nto contain \"{}\".", IE_EXE_FILE_NAME); } } else { LOGGER.error("Unable to find any IE Drivers from [{}]", IE_XML_DRIVER_LISTING_XPATH); } } catch (ParserConfigurationException | SAXException | XPathExpressionException err) { throw new RuntimeException(err); } catch (IOException ioe) { LOGGER.error("IO failure: {}", ioe); } return rv; }
From source file:com.quattroresearch.antibody.SequenceFileReader.java
/** * Parses .gp Files <p> Parses all chains found in a gp-formatted file (usually one). Sequence can be upper- or * lower-case letters, chainname is the filename. * /*from w ww .ja v a 2 s . com*/ * @param file .gp-File to parse * @return (List of chainnames, List of chainsequences) */ private List<String>[] readGPFile(File file) { List<String> foundNames = new ArrayList<String>(); List<String> foundChains = new ArrayList<String>(); try { FileInputStream fis = new FileInputStream(file); DataInputStream in = new DataInputStream(fis); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; StringBuilder buildChain = new StringBuilder(); Pattern startofSequence = Pattern.compile("^ORIGIN.*"); Pattern dataline = Pattern.compile("^(\\s*[A-Z]{2,}\\s{3,})|(//).*"); Pattern chain = Pattern.compile("^\\s*\\d+\\s+([A-Za-z ]+)$"); boolean readSequence = false; Matcher matcher; // extract all Chains from file while ((strLine = br.readLine()) != null) { matcher = startofSequence.matcher(strLine); if (matcher.matches()) { readSequence = true; } if (readSequence) { matcher = chain.matcher(strLine.replaceAll("\\*", "")); if (matcher.matches()) { buildChain.append(matcher.group(1).replaceAll(" ", "")); } matcher = dataline.matcher(strLine); if (matcher.matches()) { foundChains.add(buildChain.toString().toUpperCase()); buildChain = new StringBuilder(); readSequence = false; } } } String filename = FilenameUtils.removeExtension(file.getName()); if (foundChains.size() == 1) { foundNames.add(filename); } else { for (int i = 0; i < foundChains.size(); i++) { foundNames.add(filename + String.valueOf(i)); } } in.close(); } catch (IOException x) { System.err.format("IOException: %s%n", x); } List<String>[] result = new List[2]; result[0] = foundNames; result[1] = foundChains; return result; }
From source file:com.wx3.galacdecks.Bootstrap.java
private void importDiscardValidators(GameDatastore datastore, String path) throws IOException { Files.walk(Paths.get(path)).forEach(filePath -> { if (Files.isRegularFile(filePath)) { try { if (FilenameUtils.getExtension(filePath.getFileName().toString()).toLowerCase().equals("js")) { String id = FilenameUtils.removeExtension(filePath.getFileName().toString()); List<String> lines = Files.readAllLines(filePath); if (lines.size() < 3) { throw new RuntimeException( "Script file should have at least 2 lines: description and code."); }/* www . j a va 2s .com*/ String description = lines.get(0).substring(2).trim(); String script = String.join("\n", lines); ValidatorScript validator = ValidatorScript.createValidator(id, script, description); discardValidatorCache.put(id, validator); logger.info("Imported discard validator " + id); } } catch (Exception e) { throw new RuntimeException("Failed to parse " + filePath + ": " + e.getMessage()); } } }); }
From source file:de.teamgrit.grit.checking.testing.JavaProjectTester.java
/** * Creates the fully qualified name of a class based on its location * relative to a base directory./* ww w. ja va 2s. c o m*/ * * @param basePath * the base path * @param subPath * the path to the classfile, must be a located bellow basepath * in the directory tree * @return the fully name of the class */ private String getQuallifiedName(Path basePath, Path subPath) { // relative resolution String quallifiedName = StringUtils.difference(basePath.toString(), subPath.toString()); quallifiedName = quallifiedName.substring(1); quallifiedName = FilenameUtils.removeExtension(quallifiedName); quallifiedName = StringUtils.replaceChars(quallifiedName, '/', '.'); return quallifiedName; }
From source file:com.sustainalytics.crawlerfilter.PDFtoText.java
/** * Method to write the parsed content/*from w ww . ja v a2 s.c om*/ * @param filePath is the PDF file path, String * @param content is the parsed content, String */ public static void writeParsedFile(String filePath, String content) { String fileWithoutExtension = FilenameUtils.removeExtension(filePath); if (content != null) { try { FileUtils.write(new File(fileWithoutExtension + ".txt"), content); } catch (IOException e) { logger.info("Error writing parsed content\n"); } } else { logger.info("Nothing to write as parsed content\n"); } }
From source file:ee.ria.DigiDoc.util.FileUtils.java
public static File incrementFileName(File directory, String containerName) { File file = new File(directory, containerName); int num = 0;/*from w ww . j a v a 2 s . c om*/ while (file.exists()) { num++; String fileName = containerName; fileName = FilenameUtils.removeExtension(fileName) + " (" + num + ")." + FilenameUtils.getExtension(fileName); file = new File(directory, fileName); } return file; }
From source file:de.uni.bremen.monty.moco.Main.java
private static File buildExecutable(String outputFileName, String inputFileName, boolean compileOnly, String llvmCode) throws IOException, InterruptedException { File outputFile = null;/*w w w . j av a 2 s . c o m*/ if (outputFileName != null) { outputFile = new File(outputFileName); } else if (inputFileName != null) { outputFile = new File(FilenameUtils.removeExtension(inputFileName)); } else if (compileOnly) { outputFile = File.createTempFile("output", null, null); outputFile.deleteOnExit(); } else { outputFile = new File("output"); } ProcessBuilder llcProcessBuilder = new ProcessBuilder("llc", "-O=2"); Process llcProcess = llcProcessBuilder.start(); PrintStream llcInput = new PrintStream(llcProcess.getOutputStream()); llcInput.print(llvmCode); llcInput.close(); ProcessBuilder ccProcessBuilder = new ProcessBuilder("cc", "-x", "assembler", "-o", outputFile.getAbsolutePath(), "-"); Process ccProcess = ccProcessBuilder.start(); IOUtils.copy(llcProcess.getInputStream(), ccProcess.getOutputStream()); ccProcess.getOutputStream().close(); System.err.print(IOUtils.toString(llcProcess.getErrorStream())); System.err.print(IOUtils.toString(ccProcess.getErrorStream())); return outputFile; }
From source file:com.s2g.pst.resume.importer.PSTFileHelper.java
/** * *//from w w w .j ava 2s . c o m * * @param basePath * @param fileName * @param count * @return Return unique file name */ public void getUniqueFileName(String basePath, String fileName, int count) { // if (this.uniqueFileName != null) { // return; // } File file = null; if (count <= 0) { file = new File(FilenameUtils.concat(basePath, fileName)); } else { file = new File(basePath + File.separator + FilenameUtils.removeExtension(fileName) + "_" + count + "." + FilenameUtils.getExtension(fileName)); } if (file.exists()) { getUniqueFileName(basePath, fileName, count + 1); } else { this.uniqueFileName = file.getName(); System.out.println("called : " + this.uniqueFileName); } // return ;//this.uniqueFileName; }