Example usage for org.apache.commons.io FilenameUtils removeExtension

List of usage examples for org.apache.commons.io FilenameUtils removeExtension

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils removeExtension.

Prototype

public static String removeExtension(String filename) 

Source Link

Document

Removes the extension from a filename.

Usage

From source file:io.proleap.cobol.asg.runner.impl.CobolParserRunnerImpl.java

protected String getCompilationUnitName(final File inputFile) {
    return StringUtils.capitalize(FilenameUtils.removeExtension(inputFile.getName()));
}

From source file:de.uzk.hki.da.convert.CLIConversionStrategy.java

/**
 * Tokenizes commandLine and replaces certain strings.
 * "input" and "output" get replaced by paths of source and destination file.
 * strings beginning with "{" and ending with "}" get replaced by the contents of additionalParams of the ConversionInstruction.
 * Each of the {}-surrounded string gets replaced by exactly one token of additional params.
 *
 * @param ci the ci/* w  w  w.j  a v a  2s.c  om*/
 * @param repName the rep name
 * @return The processed command as list of tokens. The tokenized string has the right format
 * for a call in Runtime.getRuntime().exec(commandToExecute). This holds especially true
 * for filenames (which replace the input/output parameters) that are separated by
 * whitespaces. "file 2.jpg" is represented as one token only.
 */
protected String[] assemble(WorkArea wa, ConversionInstruction ci, String repName) {

    String commandLine_ = commandLine;

    // replace additional params
    List<String> ap = tokenize(ci.getAdditional_params(), ",");
    for (String s : ap) {

        Pattern pattern = Pattern.compile("\\{.*?\\}");
        Matcher matcher = pattern.matcher(commandLine_);
        commandLine_ = matcher.replaceFirst(s);
    }

    // tokenize before replacement to group original tokens together
    // (to prevent wrong tokenization like two tokens for "file" "2.jpg"
    //  which can result from replacement)
    String[] tokenizedCmd = tokenize(commandLine_);

    String targetSuffix = ci.getConversion_routine().getTarget_suffix();
    if (targetSuffix.equals("*"))
        targetSuffix = FilenameUtils.getExtension(wa.toFile(ci.getSource_file()).getAbsolutePath());
    StringUtilities.replace(tokenizedCmd, "input", wa.toFile(ci.getSource_file()).getAbsolutePath());
    StringUtilities.replace(tokenizedCmd, "output",
            wa.dataPath() + "/" + repName + "/" + StringUtilities.slashize(ci.getTarget_folder())
                    + FilenameUtils.removeExtension(Matcher.quoteReplacement(
                            FilenameUtils.getName(wa.toFile(ci.getSource_file()).getAbsolutePath())))
                    + "." + targetSuffix);

    return tokenizedCmd;
}

From source file:com.moviejukebox.scanner.BDRipScanner.java

public BDFilePropertiesMovie executeGetBDInfo(File mediaRep) {
    try {//  www .j  a  v  a2s. c  o  m

        /* Gets the BDMV path... */
        File selectedFile = mediaRep;

        if ("BDMV".equalsIgnoreCase(selectedFile.getName())) {
            selectedFile = selectedFile.getParentFile();
        }

        File[] list = selectedFile.listFiles();

        String bdmv = "";

        for (int i = 0; i < list.length && !"BDMV".equalsIgnoreCase(bdmv); i++) {
            bdmv = list[i].getName();
        }

        if (!"BDMV".equalsIgnoreCase(bdmv)) {
            return null;
        }

        selectedFile = new File(selectedFile.getAbsolutePath(), bdmv);

        /* Gets the PLAYLIST path... */
        list = selectedFile.listFiles();

        String playlist = "";

        for (int i = 0; i < list.length && !"PLAYLIST".equalsIgnoreCase(playlist); i++) {
            playlist = list[i].getName();
        }

        if (!"PLAYLIST".equalsIgnoreCase(playlist)) {
            return null;
        }

        selectedFile = new File(selectedFile.getAbsolutePath(), playlist);

        /* Get the mpls files */
        list = selectedFile.listFiles();

        BDPlaylistInfo playlistInfo;

        int longestDuration = 0;
        String[] longestFiles = null;

        for (File list1 : list) {
            if (list1.getName().regionMatches(true, list1.getName().lastIndexOf("."), ".mpls", 0, 4)) {
                playlistInfo = getBDPlaylistInfo(list1.getAbsolutePath());
                if (playlistInfo.duration > longestDuration) {
                    longestFiles = playlistInfo.streamList;
                    longestDuration = playlistInfo.duration;
                }
            }
        }

        selectedFile = mediaRep;

        selectedFile = new File(selectedFile.getAbsolutePath(), bdmv);

        // Gets the STREAM path...
        list = selectedFile.listFiles();

        String stream = "";

        for (int i = 0; i < list.length && !"STREAM".equalsIgnoreCase(stream); i++) {
            stream = list[i].getName();
        }

        if (!"STREAM".equalsIgnoreCase(stream)) {
            return null;
        }

        selectedFile = new File(selectedFile.getAbsolutePath(), stream);

        // Get the m2ts files
        list = selectedFile.listFiles();

        BDFilePropertiesMovie ret = new BDFilePropertiesMovie();

        if (longestFiles == null) {
            return null;
        }

        if (longestFiles.length > 0) {
            ret.fileList = new File[longestFiles.length];

            for (File list1 : list) {
                // Go over the playlist file names
                for (int j = 0; j < longestFiles.length; j++) {
                    if (!"MTS,M2TS".contains(FilenameUtils.getExtension(list1.getName()).toUpperCase())) {
                        // Only check the MTS & M2TS file types, skip everything else
                        continue;
                    }
                    // extensions may differ: MTS (AVCHD), m2ts (Blu-ray)
                    if (FilenameUtils.removeExtension(list1.getName())
                            .equalsIgnoreCase(FilenameUtils.removeExtension(longestFiles[j]))) {
                        ret.fileList[j] = list1;
                    }
                }
            }
            ret.duration = longestDuration;
        } else {
            ret.duration = 0;
        }

        return ret;

    } catch (Exception error) {
        LOG.warn("Error processing file {}", mediaRep.getName());
        LOG.error(SystemTools.getStackTrace(error));
        return null;
    }
}

From source file:com.freedomotic.plugins.TrackingReadFile.java

/**
 * Reads room names from file.//from www. ja v a2  s.c o m
 * 
 * @param f file of room names
 */
private void readMoteFileRooms(File f) {
    FileReader fr = null;
    ArrayList<Coordinate> coord = new ArrayList<Coordinate>();
    String userId = FilenameUtils.removeExtension(f.getName());

    try {
        LOG.info("Reading coordinates from file {}", f.getAbsolutePath());
        fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
        String line;
        while ((line = br.readLine()) != null) {
            //tokenize string
            StringTokenizer st = new StringTokenizer(line, ",");
            String roomName = st.nextToken();
            LOG.info("Mote {} coordinate added {}", userId, line);
            ZoneLogic zone = environmentRepository.findAll().get(0).getZone(roomName);
            if (!(zone == null)) {
                FreedomPoint roomCenterCoordinate = getPolygonCenter(zone.getPojo().getShape());
                Coordinate c = new Coordinate();
                c.setUserId(userId);
                c.setX(roomCenterCoordinate.getX());
                c.setY(roomCenterCoordinate.getY());
                c.setTime(new Integer(st.nextToken()));
                coord.add(c);
            } else {
                LOG.warn("Room '{}' not found.", roomName);
            }
        }
        fr.close();
        WorkerThread wt = new WorkerThread(this, coord, ITERATIONS);
        workers.add(wt);
    } catch (FileNotFoundException ex) {
        LOG.error("Coordinates file not found for mote " + userId);
    } catch (IOException ex) {
        LOG.error("IOException: ", ex);
    } finally {
        try {
            fr.close();
        } catch (IOException ex) {
            LOG.error("IOException: ", ex);
        }
    }
}

From source file:com.sustainalytics.crawlerfilter.PDFTitleGeneration.java

/**
 * Driver method for the class// w  ww.  j  ava  2  s. c  o m
 * @param args contains the file path and name
 */
public static void main(String[] args) {
    showBanner();
    File pdfFile = new File(args[0]);
    initiateLogger(pdfFile);

    File textFile = new File(FilenameUtils.removeExtension(args[0]) + ".txt");
    String title = extractTitle(pdfFile);
    String creationDate = extractDate(pdfFile);
    String content = null;
    try {
        content = FileUtils.readFileToString(textFile);
    } catch (IOException e) {
        logger.info("Error reading PDF content\n");
    }
    String digest = getDocumentDigest(content.trim());
    String finalTitle = makeTitle(title, creationDate, digest);
    renameFile(pdfFile, textFile, finalTitle);

}

From source file:main.BasicGenSystemTest.java

/**
 * Test the generation of report by date.
 *///  ww  w . j a v a2  s .c o m
@Test
public void testGeneratedReportByDate() {
    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_DATE_FILENAME.getKey())).exists());
    assertTrue(new File(config.getProperty(AJPropertyConstants.FILES_LOCATION.getKey()) + File.separator
            + FilenameUtils.removeExtension(
                    config.getProperty(AJPropertyConstants.LATEX_REPORT_BY_DATE_FILENAME.getKey()))
            + ".pdf").exists());
}

From source file:com.blackducksoftware.integration.hub.detect.detector.clang.DependenciesListFileManager.java

private String getFilenameBase(final String filePathString) {
    final Path filePath = new File(filePathString).toPath();
    return FilenameUtils.removeExtension(filePath.getFileName().toString());
}

From source file:com.moviejukebox.scanner.WatchedScanner.java

/**
 * Calculate the watched state of a movie based on the files
 * {filename}.watched & {filename}.unwatched
 *
 * Always assumes that the file is unwatched if nothing is found.
 * /* ww w.  ja  v  a  2  s  .  c om*/
 * Also TraktTV watched check can be done.
 *
 * @param jukebox
 * @param movie
 * @return
 */
public static boolean checkWatched(Jukebox jukebox, Movie movie) {

    if (WATCH_FILES && !warned && (LOCATION == WatchedWithLocation.CUSTOM)) {
        LOG.warn("Custom file location not supported for watched scanner");
        warned = Boolean.TRUE;
    }

    TrackedShow trackedShow = null;
    TrackedMovie trackedMovie = null;
    boolean watchTraktTV = WATCH_TRAKTTV;
    if (watchTraktTV) {
        if (movie.isTVShow()) {
            if (TraktTV.getInstance().isPreloadWatchedShows()) {
                // get matching show
                trackedShow = getMatchingShow(movie);
            } else {
                // disable watching if preLoading failed
                watchTraktTV = false;
            }
        } else if (!movie.isExtra()) {
            if (TraktTV.getInstance().isPreloadWatchedMovies()) {
                // get matching movie
                trackedMovie = getMatchingMovie(movie);
            } else {
                // disable watching if preLoading failed
                watchTraktTV = false;
            }
        } else {
            // disable watching for extras
            watchTraktTV = false;
        }
    }

    // assume no changes
    boolean returnStatus = Boolean.FALSE;
    // check if media file watched has changed
    boolean movieFileWatchChanged = Boolean.FALSE;
    // the number of watched files found        
    int fileWatchedCount = 0;

    File foundFile = null;
    boolean movieWatchedFile = Boolean.TRUE;

    for (MovieFile mf : movie.getFiles()) {
        // Check that the file pointer is valid
        if (mf.getFile() == null) {
            continue;
        }

        if (MovieJukebox.isJukeboxPreserve() && !mf.getFile().exists()) {
            fileWatchedCount++;
        } else {
            boolean fileWatched = Boolean.FALSE;
            long fileWatchedDate = mf.getWatchedDate();

            // check for watched/unwatched files on file system
            if (WATCH_FILES) {

                String filename;
                // BluRay stores the file differently to DVD and single files, so we need to process the path a little
                if (movie.isBluray()) {
                    filename = new File(FileTools.getParentFolder(mf.getFile())).getName();
                } else {
                    filename = mf.getFile().getName();
                }

                if (WITH_EXTENSION == WatchedWithExtension.EXTENSION
                        || WITH_EXTENSION == WatchedWithExtension.BOTH || movie.isBluray()) {
                    if (LOCATION == WatchedWithLocation.WITHJUKEBOX) {
                        foundFile = FileTools.findFilenameInCache(filename, EXTENSIONS, jukebox, Boolean.TRUE);
                    } else {
                        foundFile = FileTools.findFilenameInCache(filename, EXTENSIONS, jukebox, Boolean.FALSE);
                    }
                }

                if (foundFile == null && (WITH_EXTENSION == WatchedWithExtension.NOEXTENSION
                        || WITH_EXTENSION == WatchedWithExtension.BOTH) && !movie.isBluray()) {
                    // Remove the extension from the filename
                    filename = FilenameUtils.removeExtension(filename);
                    // Check again without the extension
                    if (LOCATION == WatchedWithLocation.WITHJUKEBOX) {
                        foundFile = FileTools.findFilenameInCache(filename, EXTENSIONS, jukebox, Boolean.TRUE);
                    } else {
                        foundFile = FileTools.findFilenameInCache(filename, EXTENSIONS, jukebox, Boolean.FALSE);
                    }
                }

                if (foundFile != null) {
                    fileWatchedCount++;
                    fileWatchedDate = new DateTime(foundFile.lastModified()).withMillisOfSecond(0).getMillis();
                    fileWatched = StringUtils.endsWithAny(foundFile.getName().toLowerCase(),
                            EXTENSIONS.toArray(new String[0]));
                }
            }

            // check for watched status from Trakt.TV
            if (watchTraktTV) {

                // always increase file counter
                fileWatchedCount++;

                long traktWatchedDate = 0;
                if (movie.isTVShow()) {
                    // get watched date for episode
                    traktWatchedDate = watchedDate(trackedShow, movie, mf);
                } else {
                    // get watched date for movie
                    traktWatchedDate = watchedDate(trackedMovie, movie);
                }

                // watched date only set if movie/episode has been watched
                if (traktWatchedDate > 0) {
                    fileWatched = Boolean.TRUE;
                    fileWatchedDate = Math.max(traktWatchedDate, fileWatchedDate);
                }
            } else if (WATCH_TRAKTTV || movie.isExtra()) {
                // the file watch status has not changed if watching is disabled
                // due to preLoad error or if movie is an extra
                fileWatched = mf.isWatched();
            }

            if (mf.setWatched(fileWatched, fileWatchedDate)) {
                movieFileWatchChanged = Boolean.TRUE;
            }
        }

        // as soon as there is an unwatched file, the whole movie becomes unwatched
        movieWatchedFile = movieWatchedFile && mf.isWatched();
    }

    if (movieFileWatchChanged) {
        // set dirty flag if movie file watched status has changed
        movie.setDirty(DirtyFlag.WATCHED, Boolean.TRUE);
    }

    // change the watched status if:
    //  - we found at least 1 file and watched file has change
    //  - no files are found and the movie is watched
    if ((fileWatchedCount > 0 && movie.isWatchedFile() != movieWatchedFile)
            || (fileWatchedCount == 0 && movie.isWatchedFile())) {
        movie.setWatchedFile(movieWatchedFile);
        movie.setDirty(DirtyFlag.WATCHED, Boolean.TRUE);

        // Issue 1949 - Force the artwork to be overwritten (those that can have icons on them)
        movie.setDirty(DirtyFlag.POSTER, Boolean.TRUE);
        movie.setDirty(DirtyFlag.BANNER, Boolean.TRUE);

        returnStatus = Boolean.TRUE;
    }

    // build the final return status
    returnStatus |= movieFileWatchChanged;
    if (returnStatus) {
        LOG.debug("The video has one or more files that have changed status.");
    }
    return returnStatus;
}

From source file:com.frostwire.gui.library.DownloadTask.java

private File buildIncompleteFile(File file) {
    String prefix = FilenameUtils.removeExtension(file.getAbsolutePath());
    String ext = FilenameUtils.getExtension(file.getAbsolutePath());
    return new File(prefix + ".Incomplete." + ext);
}

From source file:io.magentys.maven.DonutMojo.java

private void zipDonutReport() throws IOException, ArchiveException {
    Optional<File> file = FileUtils
            .listFiles(outputDirectory, new RegexFileFilter("^(.*)donut-report.html$"), TrueFileFilter.INSTANCE)
            .stream().findFirst();/*  w ww  . ja v  a2  s .  com*/
    if (!file.isPresent())
        throw new FileNotFoundException(
                String.format("Cannot find a donut report in folder: %s", outputDirectory.getAbsolutePath()));
    File zipFile = new File(outputDirectory, FilenameUtils.removeExtension(file.get().getName()) + ".zip");
    try (OutputStream os = new FileOutputStream(zipFile);
            ArchiveOutputStream aos = new ArchiveStreamFactory()
                    .createArchiveOutputStream(ArchiveStreamFactory.ZIP, os);
            BufferedInputStream is = new BufferedInputStream(new FileInputStream(file.get()))) {
        aos.putArchiveEntry(new ZipArchiveEntry(file.get().getName()));
        IOUtils.copy(is, aos);
        aos.closeArchiveEntry();
        aos.finish();
    }
}