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

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

Introduction

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

Prototype

public static String getExtension(String filename) 

Source Link

Document

Gets the extension of a filename.

Usage

From source file:com.igormaznitsa.zxpspritecorrector.files.HOBETAPlugin.java

@Override
public void writeTo(final File file, final ZXPolyData data, final SessionData session) throws IOException {
    final File dir = file.getParentFile();
    final char zxType = data.getInfo().getType();
    String name = file.getName();
    if (FilenameUtils.getExtension(name).isEmpty()) {
        name = name + ".$" + zxType;
    }/*w ww.j  a  v a 2s . c  o m*/

    final String zxName = data.getInfo().getName();

    final FileNameDialog nameDialog = new FileNameDialog(this.mainFrame, "Base file name is " + file.getName(),
            new String[] { addNumberToFileName(name, 0), addNumberToFileName(name, 1),
                    addNumberToFileName(name, 2), addNumberToFileName(name, 3) },
            new String[] { prepareNameForTRD(zxName, 0), prepareNameForTRD(zxName, 1),
                    prepareNameForTRD(zxName, 2), prepareNameForTRD(zxName, 3) },
            new char[] { zxType, zxType, zxType, zxType });
    nameDialog.setVisible(true);

    if (nameDialog.approved()) {
        final String[] fileNames = nameDialog.getFileName();
        final String[] zxNames = nameDialog.getZxName();
        final Character[] types = nameDialog.getZxType();

        for (int i = 0; i < 4; i++) {
            final File savingfile = new File(dir, fileNames[i]);
            if (!writeDataBlockAsHobeta(savingfile, zxNames[i], (byte) types[i].charValue(),
                    data.getInfo().getStartAddress(), data.getDataForCPU(i)))
                break;
        }
    }
}

From source file:eu.edisonproject.training.tfidf.mapreduce.TFIDF.java

@Override
public int run(String[] args) throws Exception {

    if (docs == null) {
        docs = new HashSet<>();
    }/*from   w  w  w .  j ava2s . c om*/

    if (docs.isEmpty()) {
        CharArraySet stopWordArraySet = new CharArraySet(ConfigHelper.loadStopWords(args[3]), true);
        cleanStopWord = new StopWord(stopWordArraySet);
        File docsDir = new File(args[2]);
        for (File f : docsDir.listFiles()) {
            if (FilenameUtils.getExtension(f.getName()).endsWith("txt")) {
                ReaderFile rf = new ReaderFile(f.getAbsolutePath());
                cleanStopWord.setDescription(rf.readFile());
                docs.add(cleanStopWord.execute());
            }
        }
    }

    Configuration conf = new Configuration();
    Job job = Job.getInstance(conf);

    job.setJarByClass(TFIDF.class);
    job.setJobName("IDF");

    Path inPath = new Path(args[0]);
    Path outPath = new Path(args[1]);

    FileInputFormat.setInputPaths(job, inPath);
    FileOutputFormat.setOutputPath(job, outPath);
    outPath.getFileSystem(conf).delete(outPath, true);

    job.setMapperClass(IDFMapper.class);

    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(Text.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);
    job.setReducerClass(IDFReducer.class);
    return (job.waitForCompletion(true) ? 0 : 1);
}

From source file:com.igormaznitsa.nbmindmap.nb.refactoring.elements.RenameFileActionPlugin.java

@Override
protected Problem processFile(final Project project, final int level, final File projectFolder,
        final FileObject fileObject) {
    final MMapURI fileAsURI = MMapURI.makeFromFilePath(projectFolder, fileObject.getPath(), null);

    String newFileName = this.refactoring.getNewName();

    if (newFileName == null) {
        return new Problem(false, "Detected null as new file name for rename refactoring action");
    }/*w  w w .  jav  a2 s .c o  m*/

    if (level == 0 && !fileObject.isFolder()) {
        final String ext = FilenameUtils.getExtension(fileObject.getNameExt());
        if (!ext.isEmpty()) {
            if (!newFileName.toLowerCase(Locale.ENGLISH).endsWith('.' + ext)) {
                newFileName += '.' + ext;
            }
        }
    } else {
        newFileName = newFileName.replace('.', '/');
    }

    final MMapURI newFileAsURI;
    try {
        if (level == 0) {
            newFileAsURI = MMapURI.makeFromFilePath(projectFolder, fileObject.getPath(), null)
                    .replaceName(newFileName);
        } else {
            newFileAsURI = MMapURI.makeFromFilePath(projectFolder,
                    replaceNameInPath(level, fileObject.getPath(), newFileName), null);
        }
    } catch (URISyntaxException ex) {
        LOGGER.error("Can't make new file uri for " + fileObject.getPath(), ex); //NOI18N
        return new Problem(true, BUNDLE.getString("Refactoring.CantMakeURI"));
    }

    for (final FileObject mmap : allMapsInProject(project)) {
        if (isCanceled()) {
            break;
        }
        try {
            if (doesMindMapContainFileLink(project, mmap, fileAsURI)) {
                final RenameElement element = new RenameElement(new MindMapLink(mmap), projectFolder,
                        MMapURI.makeFromFilePath(projectFolder, fileObject.getPath(), null));
                element.setNewFile(newFileAsURI);
                addElement(element);
            }
        } catch (Exception ex) {
            ErrorManager.getDefault().notify(ex);
            return new Problem(true, BUNDLE.getString("Refactoring.CantProcessMindMap"));
        }
    }

    return null;
}

From source file:com.bvvy.photo.web.controller.PgerContoller.java

private String saveImage(MultipartFile mf) {
    Image image = new Image();
    image.setOldName(mf.getOriginalFilename());
    image.setSuffix(FilenameUtils.getExtension(mf.getOriginalFilename()));
    image.setSize(mf.getSize());// w  ww .ja v  a  2  s . com
    image.setType(mf.getContentType());
    String path = FileUploadUtil.getInstance().saveOriginFile(mf);
    image.setNewName(path);
    imageService.add(image);
    return path;
}

From source file:net.grinder.util.GrinderClassPathUtils.java

private static boolean isForeMostJar(String jarFilename) {
    if ("jar".equals(FilenameUtils.getExtension(jarFilename))) {
        for (String jarName : FOREMOST_JAR_LIST) {
            if (jarFilename.contains(jarName)) {
                return true;
            }/*from  w  ww  .ja  v a2s.  com*/
        }
    }
    return false;
}

From source file:com.pamarin.income.controller.SuggestionCtrl.java

private File saveFile() {
    File attachFile = null;/*from w  w w  .ja va 2s .c  om*/
    String errorMessage = "?";

    InputStream inputStream = null;
    OutputStream outputStream = null;

    try {
        String randomName = UUID.randomUUID().toString();
        String extension = FilenameUtils.getExtension(file.getFileName());
        inputStream = file.getInputstream();
        File parentDir = getTempDirectoryDateTime();
        attachFile = new File(parentDir, randomName + "." + extension);

        outputStream = new FileOutputStream(attachFile);
        ByteStreams.copy(inputStream, outputStream);
        getSuggestion().setImage("/" + parentDir.getName() + "/" + randomName + "." + extension);
    } catch (Exception ex) {
        LOG.warn(null, ex);
        attachFile = null;
        throw new UncheckedIOException(errorMessage);
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ex) {
                attachFile = null;
                throw new UncheckedIOException(errorMessage);
            }
        }

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                attachFile = null;
                throw new UncheckedIOException(errorMessage);
            }
        }
    }

    return attachFile;
}

From source file:eu.prestoprime.plugin.p4.AccessTasks.java

@WfService(name = "make_consumer_segment", version = "2.2.0")
public void execute(Map<String, String> sParams, Map<String, String> dParamsString,
        Map<String, File> dParamFile) throws TaskExecutionFailedException {

    if (!Boolean.parseBoolean(dParamsString.get("isSegmented"))) {

        // retrieve static params
        String destVolume = sParams.get("dest.path.volume").trim();
        String destFolder = sParams.get("dest.path.folder").trim();

        // retrieve dynamic params
        String dipID = dParamsString.get("dipID");
        String inputFilePath = dParamsString.get("source.file.path");
        String mimeType = dParamsString.get("source.file.mimetype");
        int startFrame = Integer.parseInt(dParamsString.get("start.frame"));
        int stopFrame = Integer.parseInt(dParamsString.get("stop.frame"));

        String outputFolder = destVolume + File.separator + destFolder;

        try {//ww w.ja  v a  2s .c  o m

            if (dipID == null)
                throw new TaskExecutionFailedException("Missing AIP ID to extract fragment");

            if (mimeType == null)
                throw new TaskExecutionFailedException("Missing MIME Type to extract fragment");

            DIP dip = P4DataManager.getInstance().getDIPByID(dipID);

            if (inputFilePath == null) {

                // trying to retrieve file path from DIP, last chance...

                List<String> videoFileList = dip.getAVMaterial(mimeType, "FILE");

                if (videoFileList.size() == 0) {

                    throw new TaskExecutionFailedException("Missing input file path to extract fragment");

                } else {

                    inputFilePath = videoFileList.get(0);

                }

            }

            File targetDir = new File(outputFolder);
            targetDir.mkdirs();

            if (!targetDir.canWrite())
                throw new TaskExecutionFailedException("Unable to write to output dir " + outputFolder);

            String targetFileName = dipID + "." + startFrame + "." + stopFrame + "."
                    + FilenameUtils.getExtension(inputFilePath);
            File targetFile = new File(targetDir, targetFileName);

            int startSec = startFrame / 25;
            int endSec = stopFrame / 25;
            int durationSec = endSec - startSec;

            String start = Integer.toString(startSec);
            String duration = Integer.toString(durationSec);

            List<String> formats = dip.getDCField(DCField.format);

            StringBuilder formatSB = new StringBuilder();

            for (String format : formats) {

                formatSB.append(format + "\t");

            }

            // extract fragment using ffmbc
            FFmbc ffmbc = new FFmbc();
            ffmbc.extractSegment(inputFilePath, targetFile.getAbsolutePath(), start, duration, mimeType,
                    formatSB.toString(), "2");

            dParamsString.put("isSegmented", "true");
            dParamsString.put("segment.file.path", targetFileName);

            logger.debug("Consumer copy available at: " + targetFile.getAbsolutePath());

        } catch (DataException e) {
            e.printStackTrace();
            throw new TaskExecutionFailedException("Unable to retrieve DIP with id: " + dipID);
        } catch (IPException e) {
            e.printStackTrace();
            throw new TaskExecutionFailedException("Unable to retrieve MQ file");
        } catch (ToolException e) {
            e.printStackTrace();
            throw new TaskExecutionFailedException("Unable to extract segment with FFMBC");
        }
    }
}

From source file:com.aurel.track.exchange.msProject.exchange.MsProjectExchangeBL.java

/**
 * Initializes the MsProjectImporterBean by import
 *
 * @param projectOrReleaseID// www  .j a  v  a 2  s.  c  o  m
 * @param personBean
 * @param file
 * @param locale
 * @return
 * @throws MSProjectImportException
 */
public static MsProjectExchangeDataStoreBean initMsProjectExchangeBeanForImport(Integer projectOrReleaseID,
        TPersonBean personBean, File file, Locale locale) throws MSProjectImportException {
    MsProjectExchangeDataStoreBean msProjectExchangeDataStoreBean = MsProjectExchangeBL
            .createMsProjectExchangeBean(projectOrReleaseID, personBean, file, locale);
    try {
        ProjectReader reader;
        ProjectFile project;
        if ("mpp".equals(FilenameUtils.getExtension(file.getName()).toLowerCase())
                || "mpt".equals(FilenameUtils.getExtension(file.getName()).toLowerCase())) {
            reader = new MPPReader();
            project = reader.read(file);
        } else {
            reader = new MSPDIReader();
            project = reader.read(file);
        }
        msProjectExchangeDataStoreBean.setProject(project);
    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        LOGGER.debug(ExceptionUtils.getStackTrace(ex));
    }
    MsProjectExchangeBL.loadMSProjectData(msProjectExchangeDataStoreBean,
            msProjectExchangeDataStoreBean.getProject());
    List<Task> tasks = msProjectExchangeDataStoreBean.getTasks();
    if (tasks == null || tasks.isEmpty()) {
        throw new MSProjectImportException("admin.actions.importMSProject.err.noTaskFound");
    }
    // project specific data get from msProject's project
    // creation date is important only by import (for conflict handling)
    Date lastSavedDate = msProjectExchangeDataStoreBean.getProject().getProjectHeader().getLastSaved();
    if (lastSavedDate == null) {
        lastSavedDate = new Date();
    }
    msProjectExchangeDataStoreBean.setLastSavedDate(lastSavedDate);
    return msProjectExchangeDataStoreBean;
}

From source file:com.hightern.fckeditor.tool.UtilsFile.java

/**
 * Iterates over a base name and returns the first non-existent file.<br />
 * This method extracts a file's base name, iterates over it until the first non-existent appearance with <code>basename(n).ext</code>. Where n is a positive integer starting from one.
 * //w ww  .  j  a v a2  s .c  o  m
 * @param file
 *            base file
 * @return first non-existent file
 */
public static File getUniqueFile(final File file) {
    if (!file.exists()) {
        return file;
    }

    File tmpFile = new File(file.getAbsolutePath());
    final File parentDir = tmpFile.getParentFile();
    int count = 1;
    final String extension = FilenameUtils.getExtension(tmpFile.getName());
    final String baseName = FilenameUtils.getBaseName(tmpFile.getName());
    do {
        tmpFile = new File(parentDir, baseName + "(" + count++ + ")." + extension);
    } while (tmpFile.exists());
    return tmpFile;
}

From source file:abfab3d.io.input.STSReader.java

/**
 * Load a STS file into a grid./*from ww  w  .  j a v  a2s . co m*/
 *
 * @param is The stream
 * @return
 * @throws java.io.IOException
 */
public TriangleMesh[] loadMeshes(InputStream is) throws IOException {
    ZipArchiveInputStream zis = null;
    TriangleMesh[] ret_val = null;

    try {
        zis = new ZipArchiveInputStream(is);

        ArchiveEntry entry = null;
        int cnt = 0;

        while ((entry = zis.getNextEntry()) != null) {
            // TODO: not sure we can depend on this being first
            if (entry.getName().equals("manifest.xml")) {
                mf = parseManifest(zis);

                ret_val = new TriangleMesh[mf.getParts().size()];
            } else {
                MeshReader reader = new MeshReader(zis, "", FilenameUtils.getExtension(entry.getName()));
                IndexedTriangleSetBuilder its = new IndexedTriangleSetBuilder();
                reader.getTriangles(its);

                // TODO: in this case we could return a less heavy triangle mesh struct?
                WingedEdgeTriangleMesh mesh = new WingedEdgeTriangleMesh(its.getVertices(), its.getFaces());
                ret_val[cnt++] = mesh;
            }
        }
    } finally {
        zis.close();
    }

    return ret_val;
}