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:com.buzz.buzzdata.MongoBuzz.java

@Override
public void Insert(String userid, String header, String content, Double lat, Double lng, String tags,
        String[] files) {/*from   w  w w  .j  ava  2  s.  c  o m*/
    BasicDBObject document = new BasicDBObject();
    document.put("userid", userid);
    document.put("header", header);
    document.put("content", content);
    document.put("tags", tags.split(","));
    document.put("created", (new Date()));
    document.put("modified", (new Date()));
    BasicDBObject lng_obj = new BasicDBObject();
    lng_obj.put("lng", lng);
    BasicDBObject lat_obj = new BasicDBObject();
    lat_obj.put("lat", lat);
    document.put("loc", (new Double[] { lng, lat }));
    document.put("FilesCount", files.length);
    DBCollection coll = mongoDB.getCollection("BuzzInfo");
    coll.insert(document);
    ObjectId buzz_id = (ObjectId) document.get("_id");
    int i = 0;
    for (String file : files) {
        try {
            GridFS gridFS = new GridFS(mongoDB);
            InputStream file_stream = getFTPInputStream(file);
            String caption_filename = FilenameUtils.removeExtension(file) + "_caption.txt";
            InputStream caption_stream = getFTPInputStream(caption_filename);
            StringWriter writer = new StringWriter();
            Charset par = null;
            IOUtils.copy(caption_stream, writer, par);
            String caption = writer.toString();
            GridFSInputFile in = gridFS.createFile(file_stream);
            in.setFilename(file);
            in.put("BuzzID", buzz_id);
            in.put("Caption", caption);
            in.put("PicNum", i);
            in.save();
        } catch (IOException ex) {
            Logger.getLogger(MongoBuzz.class.getName()).log(Level.SEVERE, null, ex);
        }
        i++;
    }
}

From source file:cz.lbenda.rcp.IconFactory.java

private String iconName(String base, IconSize iconSize) {
    if (iconSize != null) {
        String ext = FilenameUtils.getExtension(base);
        return FilenameUtils.removeExtension(base) + iconSize.size()
                + (StringUtils.isBlank(ext) ? "" : "." + ext);
    }//from  w ww . ja  v a 2 s.  co  m
    return base;
}

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.//from   w  w w.j ava2s  . com
 * 
 * @param inFile
 *            a list of terms
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@Test(dataProviderClass = TestFileProvider.class, dataProvider = "exactMatchTestFiles", groups = { "functest" })
public void exactMatch(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) {
        log.trace("** matching " + term);
        w.println(index.getExactMatches(term));
    }
    w.flush();
    w.close();

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

From source file:net.sf.mzmine.modules.rawdatamethods.rawdataimport.fileformats.ZipReadTask.java

/**
 * @see java.lang.Runnable#run()/*from  w  w w.jav  a2 s. com*/
 */
public void run() {

    // Update task status
    setStatus(TaskStatus.PROCESSING);
    logger.info("Started opening compressed file " + file);

    try {

        // Name of the uncompressed file
        String newName = file.getName();
        if (newName.toLowerCase().endsWith(".zip") || newName.toLowerCase().endsWith(".gz")) {
            newName = FilenameUtils.removeExtension(newName);
        }

        // Create decompressing stream
        FileInputStream fis = new FileInputStream(file);
        InputStream is;
        long decompressedSize = 0;
        switch (fileType) {
        case ZIP:
            ZipInputStream zis = new ZipInputStream(fis);
            ZipEntry entry = zis.getNextEntry();
            newName = entry.getName();
            decompressedSize = entry.getSize();
            if (decompressedSize < 0)
                decompressedSize = 0;
            is = zis;
            break;
        case GZIP:
            is = new GZIPInputStream(fis);
            decompressedSize = (long) (file.length() * 1.5); // Ballpark a
                                                             // decompressedFile
                                                             // size so the
                                                             // GUI can show
                                                             // progress
            if (decompressedSize < 0)
                decompressedSize = 0;
            break;
        default:
            setErrorMessage("Cannot decompress file type: " + fileType);
            setStatus(TaskStatus.ERROR);
            return;
        }

        tmpDir = Files.createTempDir();
        tmpFile = new File(tmpDir, newName);
        logger.finest("Decompressing to file " + tmpFile);
        tmpFile.deleteOnExit();
        tmpDir.deleteOnExit();
        FileOutputStream ous = new FileOutputStream(tmpFile);

        // Decompress the contents
        copy = new StreamCopy();
        copy.copy(is, ous, decompressedSize);

        // Close the streams
        is.close();
        ous.close();

        if (isCanceled())
            return;

        // Find the type of the decompressed file
        RawDataFileType fileType = RawDataFileTypeDetector.detectDataFileType(tmpFile);
        logger.finest("File " + tmpFile + " type detected as " + fileType);

        if (fileType == null) {
            setErrorMessage("Could not determine the file type of file " + newName);
            setStatus(TaskStatus.ERROR);
            return;
        }

        // Run the import module on the decompressed file
        RawDataFileWriter newMZmineFile = MZmineCore.createNewFile(newName);
        decompressedOpeningTask = RawDataImportModule.createOpeningTask(fileType, project, tmpFile,
                newMZmineFile);

        if (decompressedOpeningTask == null) {
            setErrorMessage("File type " + fileType + " of file " + newName + " is not supported.");
            setStatus(TaskStatus.ERROR);
            return;
        }

        // Run the underlying task
        decompressedOpeningTask.run();

        // Delete the temporary folder
        tmpFile.delete();
        tmpDir.delete();

        if (isCanceled())
            return;

    } catch (Throwable e) {
        logger.log(Level.SEVERE, "Could not open file " + file.getPath(), e);
        setErrorMessage(ExceptionUtils.exceptionToString(e));
        setStatus(TaskStatus.ERROR);
        return;
    }

    logger.info("Finished opening compressed file " + file);

    // Update task status
    setStatus(TaskStatus.FINISHED);

}

From source file:com.splunk.shuttl.archiver.importexport.csv.CsvBucketCreator.java

private String removeExtension(File csvFile) {
    String csvFileNameWithoutExtension = FilenameUtils.removeExtension(csvFile.getName());
    return csvFileNameWithoutExtension;
}

From source file:com.doplgangr.secrecy.filesystem.encryption.AES_ECB_Crypter.java

@Override
public CipherOutputStream getCipherOutputStream(File file, String outputFileName)
        throws SecrecyCipherStreamException, FileNotFoundException {
    Cipher c;/*w w w  .j  a  va2s  . c om*/
    try {
        c = Cipher.getInstance(mode);
    } catch (NoSuchAlgorithmException e) {
        throw new SecrecyCipherStreamException("Encryption algorithm not found!");
    } catch (NoSuchPaddingException e) {
        throw new SecrecyCipherStreamException("Selected padding not found!");
    }

    try {
        c.init(Cipher.ENCRYPT_MODE, aesKey);
    } catch (InvalidKeyException e) {
        throw new SecrecyCipherStreamException("Invalid encryption key!");
    }

    String filename = Base64Coder.encodeString(FilenameUtils.removeExtension(file.getName())) + "."
            + FilenameUtils.getExtension(file.getName());
    File outputFile = new File(vaultPath + "/" + filename);

    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputFile),
            Config.BLOCK_SIZE);

    return new CipherOutputStream(bufferedOutputStream, c);
}

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

/**
 * Convert file.//w w w . jav a 2 s .c  om
 *
 * @param ci the ci
 * @return the list
 * @throws FileNotFoundException the file not found exception
 */
@Override
public List<Event> convertFile(ConversionInstruction ci) throws FileNotFoundException {
    if (pkg == null)
        throw new IllegalStateException("Package not set");
    Path.make(object.getDataPath(), object.getPath("newest").getLastElement(), ci.getTarget_folder()).toFile()
            .mkdirs();

    String[] commandAsArray = assemble(ci, object.getPath("newest").getLastElement());
    if (!cliConnector.execute(commandAsArray))
        throw new RuntimeException("convert did not succeed");

    String targetSuffix = ci.getConversion_routine().getTarget_suffix();
    if (targetSuffix.equals("*"))
        targetSuffix = FilenameUtils.getExtension(ci.getSource_file().toRegularFile().getAbsolutePath());
    DAFile result = new DAFile(pkg, object.getPath("newest").getLastElement(),
            ci.getTarget_folder() + "/"
                    + FilenameUtils.removeExtension(Matcher.quoteReplacement(
                            FilenameUtils.getName(ci.getSource_file().toRegularFile().getAbsolutePath())))
                    + "." + targetSuffix);

    Event e = new Event();
    e.setType("CONVERT");
    e.setDetail(Utilities.createString(commandAsArray));
    e.setSource_file(ci.getSource_file());
    e.setTarget_file(result);
    e.setDate(new Date());

    List<Event> results = new ArrayList<Event>();
    results.add(e);
    return results;
}

From source file:integration.util.mongodb.BsonReader.java

protected Map<String, List<DBObject>> readBsonDirectory(File directory) {
    final Map<String, List<DBObject>> collections = new HashMap<>();

    File[] collectionListing = directory.listFiles(new FilenameFilter() {
        @Override//from  w w w  . j  a  va2s . co m
        public boolean accept(File dir, String name) {
            return (name.endsWith(".bson") && !name.startsWith("system.indexes."));
        }
    });

    if (collectionListing != null) {
        for (File collection : collectionListing) {
            List<DBObject> collectionData = readBsonFile(collection.getAbsolutePath());
            collections.put(FilenameUtils.removeExtension(collection.getName()), collectionData);
        }
    }

    return collections;
}

From source file:com.jaspersoft.studio.server.dnd.RepositoryDNDHelper.java

public static void performDropOperation(final MResource targetParentResource, final String fullFilename) {
    final File file = new File(fullFilename);
    final String suggestedId = FilenameUtils.removeExtension(file.getName());
    final String suggestedName = FilenameUtils.removeExtension(file.getName());
    final String fileExt = Misc.nvl(FilenameUtils.getExtension(fullFilename)).toLowerCase();

    try {//from  w  w  w  . j a  v  a  2s. c  o m
        ProgressMonitorDialog pm = new ProgressMonitorDialog(UIUtils.getShell());
        pm.run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                try {
                    monitor.beginTask(NLS.bind(Messages.RepositoryDNDHelper_SavingResourceTask, fullFilename),
                            IProgressMonitor.UNKNOWN);
                    // Gets a list of all siblings of the future resource
                    // This will allow to compute correct ID and NAME information for
                    // the
                    // ResourceDescriptor
                    List<ResourceDescriptor> childrenDescriptors = WSClientHelper.listFolder(
                            targetParentResource, WSClientHelper.getClient(monitor, targetParentResource),
                            targetParentResource.getValue().getUriString(), new NullProgressMonitor(), 0);
                    // Create the ResourceDescriptor depending on this kind (use file
                    // extension)
                    ResourceDescriptor newRD = getResourceDescriptor(targetParentResource, fileExt);
                    // Update the NAME and ID for the ResourceDescriptor
                    ResourceDescriptorUtil.setProposedResourceDescriptorIDAndName(childrenDescriptors, newRD,
                            suggestedId, suggestedName);
                    // Create and save the resource
                    final AFileResource fileResource = createNewFileResource(targetParentResource, newRD,
                            fileExt);
                    fileResource.setFile(file);

                    monitor.setTaskName(
                            NLS.bind(Messages.RepositoryDNDHelper_SavingResourceTask, fullFilename));
                    WSClientHelper.saveResource(fileResource, monitor);
                } catch (Throwable e) {
                    throw new InvocationTargetException(e);
                } finally {
                    monitor.done();
                }
            }

        });
    } catch (Exception e) {
        UIUtils.showError(e);
    }
}

From source file:ch.cern.dss.teamcity.agent.util.ArchiveExtractor.java

/**
 * @param archivePath/*from ww  w.  j a  v a 2 s. c  o m*/
 * @return
 * @throws ArchiveException
 * @throws IOException
 * @throws CompressorException
 */
public String decompress(String archivePath) throws ArchiveException, IOException, CompressorException {

    Loggers.AGENT.debug("Decompressing: " + archivePath);
    String tarPath = FilenameUtils.removeExtension(archivePath);

    final BufferedInputStream is = new BufferedInputStream(new FileInputStream(archivePath));
    CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream(is);
    org.apache.commons.compress.utils.IOUtils.copy(in, new FileOutputStream(tarPath));
    in.close();

    return tarPath;
}