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:nc.noumea.mairie.distiller.DistillerTest.java

@Test
public void eCheckDistillation() {
    try {/*from ww w . j  a va  2s.co m*/

        boolean distilled = false;
        String pdfFileName = FilenameUtils.removeExtension(testFileName) + ".pdf";

        logger.info("pdf filename : " + pdfDirectory + pdfFileName);
        SmbFile sFile = new SmbFile(pdfDirectory + pdfFileName, auth);
        distilled = sFile.exists();
        while (distilled == false) {
            sFile = new SmbFile(pdfDirectory + pdfFileName, auth);
            distilled = sFile.exists();
            logger.info("image still being processed by distiller...");
            Thread.sleep(100);
        }
        sFile = new SmbFile(pdfDirectory + pdfFileName, auth);
        Assert.assertTrue(sFile.exists());
        logger.info("image has been been processed by distiller into a pdf.");
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.assertNull(ex);
    }
}

From source file:de.nbi.ontology.test.OntologyMatchTest.java

/**
 * Test, if terms are properly match to concept labels. The a list of terms
 * contains a term in each line./* w w  w . ja v  a  2s .  co m*/
 * 
 * @param inFile
 *            a list of terms
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@Test(dataProviderClass = TestFileProvider.class, dataProvider = "parentTestFiles", groups = { "functest" })
public void parents(File inFile) throws IOException {
    log.info("Processing " + inFile.getName());
    String basename = FilenameUtils.removeExtension(inFile.getAbsolutePath());
    File outFile = new File(basename + ".out");
    File resFile = new File(basename + ".res");

    List<String> terms = FileUtils.readLines(inFile);
    PrintWriter w = new PrintWriter(new FileWriter(outFile));
    for (String term : terms) {
        OntClass clazz = index.getModel().getOntClass(term);
        log.trace("** matching " + term);
        w.println(index.getParents(clazz));
    }
    w.flush();
    w.close();

    Assert.assertTrue(FileUtils.contentEquals(outFile, resFile));
}

From source file:com.jadarstudios.rankcapes.forge.cape.CapePack.java

/**
 * Parses an animated cape JSON node and creates the cape.
 *
 * @param name the name of the cape.// w w  w  .j  av a  2  s  .  c o  m
 * @param node the map of the JSON object that signifies an animated cape.
 */
private void parseAnimatedCapeNode(String name, @SuppressWarnings("rawtypes") Map node) {
    Object framesObj = node.get("frames");
    Object fpsObj = node.get("fps");
    Object onlyAnimateWhenMovingObj = node.get("animateWhenMoving");

    if (framesObj instanceof ArrayList && fpsObj instanceof Double) {
        @SuppressWarnings("unchecked")
        ArrayList<Object> frames = (ArrayList<Object>) framesObj;
        int fps = ((Double) fpsObj).intValue();
        boolean onlyAnimateWhenMoving = false;

        if (onlyAnimateWhenMovingObj instanceof Boolean) {
            onlyAnimateWhenMoving = (Boolean) onlyAnimateWhenMovingObj;
        }

        AnimatedCape cape = new AnimatedCape(name, fps, onlyAnimateWhenMoving);

        for (Object frameObj : frames) {
            if (frameObj instanceof String) {
                String frame = (String) frameObj;

                String fileName = FilenameUtils.removeExtension(frame);
                if (!Strings.isNullOrEmpty(fileName)) {
                    if (this.unprocessedCapes.containsKey(fileName)) {
                        cape.addFrame(this.unprocessedCapes.get(fileName));
                    }
                }
            }
        }
        this.processedCapes.put(name, cape);
    }
}

From source file:jease.cms.service.Imports.java

private static Text newText(String filename, InputStream inputStream) throws IOException {
    Text text = new Text();
    text.setId(Filenames.asId(filename));
    text.setTitle(FilenameUtils.removeExtension(filename));
    text.setLastModified(new Date());
    text.setContent(IOUtils.toString(inputStream, "UTF-8"));
    text.setPlain(true);//from  w ww  . j a v  a  2 s  . com
    return text;
}

From source file:com.kagubuzz.servlets.UploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 * /*  ww w .  j a  v a  2s  . c  om*/
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    ApplicationContext applicationContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());

    fileService = (FileService) applicationContext.getBean("fileService");
    JavaFileUtilities fileUtils = new JavaFileUtilities();
    InputStream is = null;
    FileOutputStream os = null;
    Map<String, Object> uploadResult = new HashMap<String, Object>();
    ObjectMapper mapper = new ObjectMapper();

    //TODO:  Mske all these files write to a tmp direcotry for th euploader to be erased when the review button is pushed
    try {
        byte[] buffer = new byte[4096];
        int bytesRead = 0;

        // Make sure image file is less than 4 megs

        if (bytesRead > 1024 * 1024 * 4)
            throw new FileUploadException();

        is = request.getInputStream();

        File tmpFile = File.createTempFile("image-", ".jpg");

        os = new FileOutputStream(tmpFile);

        System.out.println("Saving to " + JavaFileUtilities.getTempFilePath());

        while ((bytesRead = is.read(buffer)) != -1)
            os.write(buffer, 0, bytesRead);

        KaguImage thumbnailImage = new KaguImage(tmpFile);

        thumbnailImage.setWorkingDirectory(JavaFileUtilities.getTempFilePath());
        thumbnailImage.resize(140, 180);

        File thumbnail = thumbnailImage
                .saveAsJPG("thumbnail-" + FilenameUtils.removeExtension(tmpFile.getName()));

        fileService.write(fileUtils.fileToByteArrayOutputStream(tmpFile), tmpFile.getName(),
                fileService.getTempFilePath());
        fileService.write(fileUtils.fileToByteArrayOutputStream(thumbnail), thumbnail.getName(),
                fileService.getTempFilePath());

        response.setStatus(HttpServletResponse.SC_OK);

        uploadResult.put("success", "true");
        uploadResult.put("indexedfilename", fileService.getTempDirectoryURL() + tmpFile.getName());
        uploadResult.put("thumbnailfilename", fileService.getTempDirectoryURL() + thumbnail.getName());
    } catch (FileNotFoundException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        uploadResult.put("success", "false");
        log(UploadServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
    } catch (IOException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        uploadResult.put("success", "false");
        log(UploadServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
    } catch (FileUploadException e) {
        response.setStatus(HttpServletResponse.SC_OK);
        uploadResult.put("success", "false");
        uploadResult.put("indexedfilename", "filetobig");
    } finally {
        try {
            mapper.writeValue(response.getWriter(), uploadResult);
            os.close();
            is.close();
        }

        catch (IOException ignored) {
        }
    }
}

From source file:edu.scripps.fl.pubchem.xmltool.gui.PubChemXMLExtractorGUI.java

public void actionPerformed(ActionEvent e) {
    try {//from w w w.  ja  v a2  s. c  o  m
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        if (e.getSource() == jbnFileXML)
            gc.fileChooser(jtfFileXML, "", "open");
        else if (e.getSource() == jbnRunExtractor) {
            URL template = templateForExcel();
            File fileExcelOutput = extract(template);
            if (fileExcelOutput != null) {
                log.info("Opening excel file through Desktop: " + fileExcelOutput);
                Desktop.getDesktop().open(fileExcelOutput);
            }
        } else if (e.getSource() == jbnCreateReport) {
            URL template = getClass().getClassLoader().getResource("ExcelTemplate.xlsx");
            File fileExcelOutput = extract(template);
            if (fileExcelOutput != null) {
                log.info("Opening report through Desktop: " + fileExcelOutput);
                String fileName = FilenameUtils.removeExtension(fileExcelOutput.getAbsolutePath());
                File filePDFOutput = new File(fileName + ".pdf");
                File fileWordOutput = new File(fileName + ".docx");
                filePDFOutput.deleteOnExit();
                fileWordOutput.deleteOnExit();
                new ReportController().createReport(pcDep, fileExcelOutput, filePDFOutput, fileWordOutput,
                        isInternal);
                gc.openPDF(isInternal, filePDFOutput, this);
                Desktop.getDesktop().open(fileWordOutput);
            }
        }
        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    } catch (Throwable throwable) {
        SwingGUI.handleError(this, throwable);
    }

}

From source file:dk.dma.ais.lib.FileConvert.java

/** {@inheritDoc} */
@Override/*  ww w  .  j a  va  2s .co m*/
protected void run(Injector injector) throws Exception {
    configureFileEnding();

    final EConsumer<String> consumer = new EConsumer<String>() {

        @Override
        public void accept(String s) throws IllegalArgumentException, IllegalAccessException,
                NoSuchFieldException, SecurityException, IOException, InterruptedException {
            Path path = Paths.get(s);
            LOG.debug("Started processing file " + path);

            Path endPath;
            if (keepFileStructure) {
                Path relative;
                relative = path;
                endPath = Paths.get(Paths.get(convertTo).toString(), relative.toString());
                new File(endPath.toString()).mkdirs();
            } else {
                endPath = Paths.get("");
            }

            String filename = path.getFileName().toString();
            if (!filename.endsWith(fileEnding))
                filename = FilenameUtils.removeExtension(filename) + fileEnding;
            Path filePath = Paths.get(endPath.toString(), filename);

            LOG.debug("Output File: " + filePath.toString());

            final OutputStream fos = new FileOutputStream(filePath.toString()); // 2

            final boolean createSituationFolder = !StringUtils.isBlank(kmzSnapshotAt);
            final long snapshotAtEpochMillis = createSituationFolder
                    ? LocalDateTime.parse(kmzSnapshotAt, formatter).toInstant(ZoneOffset.UTC).toEpochMilli()
                    : -1;

            OutputStreamSink<AisPacket> sink;
            if ("kmz".equals(outputSinkFormat)) {
                //AisPacketKMZOutputSink(filter, createSituationFolder, createMovementsFolder, createTracksFolder, isPrimaryTarget, isSecondaryTarget, triggerSnapshot, snapshotDescriptionSupplier, movementInterpolationStep, supplyTitle, supplyDescription, iconHrefSupplier);
                sink = AisPacketOutputSinks.newKmzSink(e -> true, // this.filter = e -> true;
                        createSituationFolder, // this.createSituationFolder = true;
                        true, // createMovementsFolder = true;
                        true, // this.createTracksFolder = true;
                        e -> kmzPrimaryMmsi <= 0 ? false : e.tryGetAisMessage().getUserId() == kmzPrimaryMmsi, // this.isPrimaryTarget = e -> false;
                        e -> kmzSecondaryMmsi <= 0 ? false
                                : e.tryGetAisMessage().getUserId() == kmzSecondaryMmsi, // this.isSecondaryTarget = e -> false;
                        e -> e.getBestTimestamp() >= snapshotAtEpochMillis, // this.triggerSnapshot = e -> false;
                        () -> "Situation at " + kmzSnapshotAt, // this.snapshotDescriptionSupplier = null;
                        () -> 10, // this.title = defaultTitleSupplier;
                        () -> "description", // this.description = defaultDescriptionSupplier;
                        () -> "10", //this.movementInterpolationStep = defaultMovementInterpolationStepSupplier;
                        (shipTypeCargo, navigationalStatus) -> "" // this.iconHrefSupplier = defaultIconHrefSupplier;
                );

            } else
                sink = AisPacketOutputSinks.getOutputSink(outputSinkFormat, columns);

            sink.closeWhenFooterWritten();

            AisPacketReader apis = AisPacketReader.createFromFile(path, false);

            apis.writeTo(fos, sink);
            apis.close();
            fos.close();
        }
    };

    /*
     * Creates a pool of executors, 4 threads. Each thread will open a file using an aispacket reader, 10000 files can be
     * submitted to the queue, afterwards the calling thread will execute the job instead.
     */
    ThreadPoolExecutor threadpoolexecutor = new ThreadPoolExecutor(4, 4, 1, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10000), new ThreadPoolExecutor.CallerRunsPolicy());
    for (final String s : sources) {
        threadpoolexecutor.execute(() -> {
            try {
                consumer.accept(s);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }

    threadpoolexecutor.shutdown();
    threadpoolexecutor.awaitTermination(999, TimeUnit.DAYS);
}

From source file:jenkins.plugins.figtree.FigTreePublisher.java

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener)
        throws InterruptedException, IOException {

    listener.getLogger().println("Executing FigTree...");

    if (StringUtils.isBlank(getTreeFilePattern())) {
        listener.getLogger().println("No tree files pattern defined. Skipping FigTree execution.");
        return Boolean.TRUE;
    }//w w w . j a  v  a  2s .com

    final FigTreeBuildAction figTreeBuildAction = new FigTreeBuildAction();

    build.addAction(figTreeBuildAction);

    final FilePath workspace = build.getWorkspace();

    workspace.act(new FileCallable<Void>() {

        private static final long serialVersionUID = 2488391182467776931L;

        public Void invoke(File file, VirtualChannel channel) throws IOException, InterruptedException {
            String[] treeFiles = scan(file, getTreeFilePattern(), listener);

            listener.getLogger()
                    .println("Found " + (treeFiles != null ? treeFiles.length : 0) + " tree files.");

            Integer width = getWidth();
            Integer height = getHeight();

            if (width == null || width <= 0) {
                width = 800;
            }
            if (height == null || height <= 0) {
                height = 600;
            }

            if (treeFiles != null && treeFiles.length > 0) {
                for (final String treeFile : treeFiles) {
                    listener.getLogger().println("Processing tree [" + treeFile + "].");
                    final String fullTreeFilePath = new File(file, treeFile).getAbsolutePath();
                    final String rawName = FilenameUtils.removeExtension(treeFile);
                    final String graphic = rawName + ".gif";
                    final String output = new File(file, graphic).getAbsolutePath();
                    FigTreeApplication.createGraphic("GIF", width, height, fullTreeFilePath, output);
                    listener.getLogger().println(
                            "Created graphic [" + graphic + "]. width: " + width + ", height: " + height);
                    figTreeBuildAction.addFigTreeGraphicLink(graphic);
                }
            }
            return null;
        }
    });

    return Boolean.TRUE;
}

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

/**
 * Reads room names from file.//from www.  j a va2 s . co  m
 *
 * @param f file of room names
 */
private void readMoteFileRooms(File f) {
    ArrayList<Coordinate> coord = new ArrayList<>();
    String userId = FilenameUtils.removeExtension(f.getName());

    try (FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr);) {
        LOG.info("Reading coordinates from file \"{}\"", f.getAbsolutePath());
        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 = getApi().environments().findAll().get(0).getZone(roomName);
            if (zone != null) {
                FreedomPoint roomCenterCoordinate = Utils.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);
            }
        }
        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);
    }
}

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

/**
 * Search for the NFO file in the library structure
 *
 * @param movie The movie bean to locate the NFO for
 * @return A List structure of all the relevant NFO files
 *//*  w ww  . ja va2s .co m*/
public static List<File> locateNFOs(Movie movie) {
    List<File> nfoFiles = new ArrayList<>();
    GenericFileFilter fFilter;

    File currentDir = movie.getFirstFile().getFile();

    if (currentDir == null) {
        return nfoFiles;
    }

    String baseFileName = currentDir.getName();
    String pathFileName = currentDir.getAbsolutePath();

    // Get the folder if it's a BluRay disk
    if (pathFileName.toUpperCase().contains(File.separator + "BDMV" + File.separator)) {
        currentDir = new File(FileTools.getParentFolder(currentDir));
        baseFileName = currentDir.getName();
        pathFileName = currentDir.getAbsolutePath();
    }

    if (ARCHIVE_SCAN_RAR && pathFileName.toLowerCase().contains(".rar")) {
        currentDir = new File(FileTools.getParentFolder(currentDir));
        baseFileName = currentDir.getName();
        pathFileName = currentDir.getAbsolutePath();
    }

    // If "pathFileName" is a file then strip the extension from the file.
    if (currentDir.isFile()) {
        pathFileName = FilenameUtils.removeExtension(pathFileName);
        baseFileName = FilenameUtils.removeExtension(baseFileName);
    } else {
        // *** First step is to check for VIDEO_TS
        // The movie is a directory, which indicates that this is a VIDEO_TS file
        // So, we should search for the file moviename.nfo in the sub-directory
        checkNFO(nfoFiles, pathFileName + pathFileName.substring(pathFileName.lastIndexOf(File.separator)));
    }

    // TV Show specific scanning
    if (movie.isTVShow()) {
        String nfoFilename;

        // Check for the "tvshow.nfo" filename in the parent directory
        if (movie.getFile().getParentFile().getParent() != null) {
            nfoFilename = StringTools.appendToPath(movie.getFile().getParentFile().getParent(),
                    XBMC_TV_NFO_NAME);
            checkNFO(nfoFiles, nfoFilename);
        }

        // Check for the "tvshow.nfo" filename in the current directory
        nfoFilename = StringTools.appendToPath(movie.getFile().getParent(), XBMC_TV_NFO_NAME);
        checkNFO(nfoFiles, nfoFilename);

        // Check for individual episode files
        if (!SKIP_TV_NFO_FILES) {
            for (MovieFile mf : movie.getMovieFiles()) {
                nfoFilename = mf.getFile().getParent().toUpperCase();

                if (nfoFilename.contains("BDMV")) {
                    nfoFilename = FileTools.getParentFolder(mf.getFile());
                    nfoFilename = nfoFilename.substring(nfoFilename.lastIndexOf(File.separator) + 1);
                } else {
                    nfoFilename = FilenameUtils.removeExtension(mf.getFile().getName());
                }

                checkNFO(nfoFiles, StringTools.appendToPath(mf.getFile().getParent(), nfoFilename));
            }
        }
    }

    // *** Second step is to check for the filename.nfo file
    // This file should be named exactly the same as the video file with an extension of "nfo" or "NFO"
    // E.G. C:\Movies\Bladerunner.720p.avi => Bladerunner.720p.nfo
    checkNFO(nfoFiles, pathFileName);

    if (isValidString(NFO_DIR)) {
        // *** Next step if we still haven't found the nfo file is to
        // search the NFO directory as specified in the moviejukebox.properties file
        String sNFOPath = FileTools.getDirPathWithSeparator(movie.getLibraryPath()) + NFO_DIR;
        checkNFO(nfoFiles, sNFOPath + File.separator + baseFileName);
    }

    // *** Next step is to check for a directory wide NFO file.
    if (ACCEPT_ALL_NFO) {
        /*
         * If any NFO file in this directory will do, then we search for all we can find
         *
         * NOTE: for scanning efficiency, it is better to first search for specific filenames before we start doing
         * filtered "listfiles" which scans all the files;
         *
         * A movie collection with all moviefiles in one directory could take tremendously longer if for each
         * moviefile found, the entire directory must be listed!!
         *
         * Therefore, we first check for specific filenames (cfr. old behaviour) before doing an entire scan of the
         * directory -- and only if the user has decided to accept any NFO file!
         */

        // Check the current directory
        fFilter = new GenericFileFilter(NFO_EXT_REGEX);
        checkRNFO(nfoFiles, currentDir.getParentFile(), fFilter);

        // Also check the directory above, for the case where movies are in a multi-part named directory (CD/PART/DISK/Etc.)
        Matcher allNfoMatch = PART_PATTERN.matcher(currentDir.getAbsolutePath());
        if (allNfoMatch.find()) {
            LOG.debug("Found multi-part directory, checking parent directory for NFOs");
            checkRNFO(nfoFiles, currentDir.getParentFile().getParentFile(), fFilter);
        }
    } else {
        // This file should be named the same as the directory that it is in
        // E.G. C:\TV\Chuck\Season 1\Season 1.nfo
        // We search up through all containing directories up to the library root

        // Check the current directory for the video filename
        fFilter = new GenericFileFilter("(?i)" + movie.getBaseFilename() + NFO_EXT_REGEX);
        checkRNFO(nfoFiles, currentDir, fFilter);
    }

    // Recurse through the directories to the library root looking for NFO files
    String libraryRootPath = new File(movie.getLibraryPath()).getAbsolutePath();
    while (currentDir != null && !currentDir.getAbsolutePath().equals(libraryRootPath)) {
        //fFilter.setPattern("(?i)" + currentDir.getName() + nfoExtRegex);
        //checkRNFO(nfos, currentDir, fFilter);
        currentDir = currentDir.getParentFile();
        if (currentDir != null) {
            final String path = currentDir.getPath();
            // Path is not empty & is not the root
            if (!path.isEmpty() && !path.endsWith(File.separator)) {
                checkNFO(nfoFiles, appendToPath(path, currentDir.getName()));
            }
        }
    }

    // we added the most specific ones first, and we want to parse those the last,
    // so nfo files in sub-directories can override values in directories above.
    Collections.reverse(nfoFiles);

    return nfoFiles;
}