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:eu.esdihumboldt.hale.ui.util.graph.ExportGraphAction.java

/**
 * @see Action#run()/*from w  w w.j av  a  2 s  .com*/
 */
@Override
public void run() {
    FileDialog dialog = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE);
    // XXX if called from TTreeExporter during transformation, the active
    // shell may be null!

    dialog.setOverwrite(true);
    dialog.setText("Export graph to file");

    String[] imageExtensions = ImageIO.getWriterFileSuffixes();

    StringBuffer extensions = new StringBuffer("*.svg;*.gv;*.dot");
    for (String imageExt : imageExtensions) {
        extensions.append(";*.");
        extensions.append(imageExt);
    }

    dialog.setFilterExtensions(new String[] { extensions.toString() });

    dialog.setFilterNames(new String[] { "Image, SVG or dot file (" + extensions + ")" });

    String fileName = dialog.open();
    if (fileName != null) {
        final File file = new File(fileName);

        //         //XXX use an off-screen graph (testing)
        //         OffscreenGraph graph = new OffscreenGraph(1000, 1000) {
        //            
        //            @Override
        //            protected void configureViewer(GraphViewer viewer) {
        //               viewer.setContentProvider(RenderAction.this.viewer.getContentProvider());
        //               viewer.setLabelProvider(RenderAction.this.viewer.getLabelProvider());
        //               viewer.setInput(RenderAction.this.viewer.getInput());
        //               viewer.setLayoutAlgorithm(new TreeLayoutAlgorithm(TreeLayoutAlgorithm.LEFT_RIGHT), false);
        //            }
        //         };

        // get the graph
        final Graph graph = viewer.getGraphControl();

        final String ext = FilenameUtils.getExtension(file.getAbsolutePath());
        final IFigure root = graph.getRootLayer();

        ProgressMonitorDialog progress = new ProgressMonitorDialog(Display.getCurrent().getActiveShell());
        try {
            progress.run(false, false, new IRunnableWithProgress() {

                @Override
                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    try {
                        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));

                        if (ext.equalsIgnoreCase("gv") || ext.equalsIgnoreCase("dot")) {
                            OffscreenGraph.saveDot(graph, out);
                        }
                        //                     else if (ext.equalsIgnoreCase("svg")) {
                        //                        OffscreenGraph.saveSVG(root, out);
                        //                     }
                        else {
                            OffscreenGraph.saveImage(root, out, ext);
                        }
                    } catch (Throwable e) {
                        log.userError("Error saving graph to file", e);
                    }
                }

            });
        } catch (Throwable e) {
            log.error("Error launching graph export", e);
        }
    }
}

From source file:io.github.mzmine.modules.rawdata.rawdataimport.RawDataImportModule.java

@SuppressWarnings("null")
@Override//  ww w  .  ja  va  2s  .c  o m
public void runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters,
        @Nonnull Collection<Task<?>> tasks) {

    final List<File> fileNames = parameters.getParameter(RawDataImportParameters.fileNames).getValue();
    final String removePrefix = parameters.getParameter(RawDataImportParameters.removePrefix).getValue();
    final String removeSuffix = parameters.getParameter(RawDataImportParameters.removeSuffix).getValue();

    if (fileNames == null) {
        logger.warn("Raw data import module started with no filenames");
        return;
    }
    for (File fileName : fileNames) {

        if ((!fileName.exists()) || (!fileName.canRead())) {
            MZmineGUI.displayMessage("Cannot read file " + fileName);
            logger.warn("Cannot read file " + fileName);
            continue;
        }

        DataPointStore dataStore = DataPointStoreFactory.getTmpFileDataStore();

        RawDataFileImportMethod method = new RawDataFileImportMethod(fileName, dataStore);
        MSDKTask newTask = new MSDKTask("Importing raw data file", fileName.getName(), method);
        newTask.setOnSucceeded(e -> {
            RawDataFile rawDataFile = method.getResult();
            if (rawDataFile == null)
                return;

            // Remove common prefix
            if (!Strings.isNullOrEmpty(removePrefix)) {
                String name = rawDataFile.getName();
                if (name.startsWith(removePrefix))
                    name = name.substring(removePrefix.length());
                rawDataFile.setName(name);
            }

            // Remove common suffix
            if (!Strings.isNullOrEmpty(removeSuffix)) {
                String fileExtension = FilenameUtils.getExtension(fileName.getAbsolutePath());
                String suffix = removeSuffix;
                if (suffix.equals(".*"))
                    suffix = "." + fileExtension;
                String name = rawDataFile.getName();
                if (name.endsWith(suffix))
                    name = name.substring(0, name.length() - suffix.length());
                rawDataFile.setName(name);
            }

            project.addFile(rawDataFile);
        });
        tasks.add(newTask);

    }

}

From source file:eu.edisonproject.training.term.extraction.JtopiaExtractor.java

@Override
public Map<String, Double> termXtraction(String inDir) throws IOException {
    File dir = new File(inDir);
    TermsExtractor termExtractor = new TermsExtractor();
    TermDocument topiaDoc = new TermDocument();
    HashMap<String, Double> keywordsDictionaray = new HashMap();
    int count = 0;

    CharArraySet stopwordsCharArray = new CharArraySet(ConfigHelper.loadStopWords(stopWordsPath), true);
    tokenizer = new StopWord(stopwordsCharArray);
    //        lematizer = new StanfordLemmatizer();

    Set<String> terms = new HashSet<>();

    if (dir.isDirectory()) {
        for (File f : dir.listFiles()) {
            if (FilenameUtils.getExtension(f.getName()).endsWith("txt")) {
                count++;/*from   w  w w  .ja  v  a 2  s.  co m*/
                Logger.getLogger(JtopiaExtractor.class.getName()).log(Level.INFO, "{0}: {1} of {2}",
                        new Object[] { f.getName(), count, dir.list().length });
                terms.addAll(extractFromFile(f, termExtractor, topiaDoc));
            }
        }
    } else if (dir.isFile()) {
        if (FilenameUtils.getExtension(dir.getName()).endsWith("txt")) {
            terms.addAll(extractFromFile(dir, termExtractor, topiaDoc));
        }

    }
    for (String t : terms) {
        Double tf;
        String term = t.toLowerCase().trim().replaceAll(" ", "_");
        while (term.endsWith("_")) {
            term = term.substring(0, term.lastIndexOf("_"));
        }
        while (term.startsWith("_")) {
            term = term.substring(term.indexOf("_") + 1, term.length());
        }
        if (keywordsDictionaray.containsKey(term)) {
            tf = keywordsDictionaray.get(term);
            tf++;
        } else {
            tf = 1.0;
        }
        keywordsDictionaray.put(term, tf);
    }
    return keywordsDictionaray;
}

From source file:net.sf.jvifm.ui.Util.java

public static void editFile(String pwd, String path) {
    Preference preference = Preference.getInstance();
    String EDITOR = preference.getEditorApp();
    File file = new File(path);
    if (file.isFile() && file.canRead()) {
        String ext = FilenameUtils.getExtension(path);
        if (ext.equals("zip") || ext.equals("jar") || ext.equals("war")) { //$NON-NLS-1$

            Util.openFileWithDefaultApp(path);
            //Main.fileManager.zipTabNew(path);
        } else {/*from  w  w  w .j  a v  a 2 s.c  o m*/
            try {
                String param1 = "-p";
                String param2 = "--remote-tab-silent";
                String param3 = "--servername";
                String param4 = "JVIFM";

                String cmd[] = { EDITOR, param3, param4, param1, param2, path };
                // String cmd[]={EDITOR , path};
                Runtime.getRuntime().exec(cmd, null, new File(pwd));
            } catch (Exception e) {
                Util.openFileWithDefaultApp(path);
            }
        }
    }

}

From source file:br.com.pontocontrol.controleponto.controller.impl.ArquivoController.java

@Override
public List<Integer> getAvalableFileMonths(int ano) {
    File dir = new File(getYearPath(ano));
    List<Integer> saida = new ArrayList<Integer>();
    if (dir.exists()) {
        File[] listFiles = dir.listFiles();
        for (File file : listFiles) {
            final String ext = FilenameUtils.getExtension(file.getName());
            final String nomeArquivo = FilenameUtils.getBaseName(file.getName());
            final String[] nomeArquivoSplit = nomeArquivo.split("_");
            if (file.isFile() && EXTENSAO_ARQUIVOS.equalsIgnoreCase(ext)
                    && PREFIXO_ARQUIVOS.equalsIgnoreCase(nomeArquivoSplit[0])) {
                String mesStr = nomeArquivoSplit[1];
                try {
                    Date date = new SimpleDateFormat(SUFIXO_ARQUIVOS_PARSER).parse(mesStr);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    saida.add(calendar.get(Calendar.MONTH));
                } catch (ParseException ex) {
                    LOG.log(Level.SEVERE, format(
                            "Erro ao executar parse de data da entrada \"%s\" atravs do padro \"MMM\" o arquivo ser descartado.",
                            mesStr), ex);
                }/*from   ww  w .jav a2 s  .co m*/
            }
        }
    }
    return saida;
}

From source file:logic.Export.java

public boolean convertXls()
        throws IOException, FileNotFoundException, IllegalArgumentException, ParseException {
    FileInputStream tamplateFile = new FileInputStream(templatePath);
    XSSFWorkbook workbook = new XSSFWorkbook(tamplateFile);

    CellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setDataFormat(workbook.getCreationHelper().createDataFormat().getFormat("#,##"));
    double hours = 0.0;
    NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
    Number number;// w  w  w . j  av a  2s  .  c o  m
    XSSFSheet sheet;
    XSSFSheet sheet2;
    Cell cell = null;
    ConvertData cd = new ConvertData();
    for (int i = 0; i < cd.getSheetnames().size(); i++) {
        sheet2 = workbook.cloneSheet(0, cd.sheetnames.get(i));
        sheet = workbook.getSheetAt(i + 1);
        //formate sheets
        sheet.getPrintSetup().setLandscape(true);
        sheet.getPrintSetup().setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);

        cell = sheet.getRow(0).getCell(1);
        cell.setCellValue(cd.sheetnames.get(i));
        ArrayList<String[]> convert = cd.convert(cd.sheetnames.get(i));
        //setPrintArea 
        workbook.setPrintArea(i + 1, //sheet index
                0, //start column Spalte
                6, //end column
                0, //start row zeile
                convert.size() + 8 //end row
        );
        for (int Row = 0; Row < convert.size(); Row++) {
            for (int Cell = 0; Cell < convert.get(Row).length; Cell++) {
                cell = sheet.getRow(9 + Row).getCell(Cell);
                if (Cell == 3) {
                    if ("true".equals(convert.get(Row)[Cell])) {
                        XSSFCellStyle style1 = workbook.createCellStyle();
                        style1 = (XSSFCellStyle) cell.getCellStyle();
                        style1 = (XSSFCellStyle) style1.clone();
                        style1.setFillBackgroundColor(HSSFColor.RED.index);
                        style1.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
                        XSSFColor myColor = new XSSFColor(Color.RED);
                        style1.setFillForegroundColor(myColor);
                        sheet.getRow(9 + Row).getCell(6).setCellStyle(style1);
                    }
                } else {
                    cell.setCellValue(convert.get(Row)[Cell]);
                }
            }
        }
    }

    workbook.removeSheetAt(0);
    tamplateFile.close();
    File exportFile = newPath.getSelectedFile();
    if (FilenameUtils.getExtension(exportFile.getName()).equalsIgnoreCase("xlsx")) {

    } else {
        exportFile = new File(exportFile.getParentFile(),
                FilenameUtils.getBaseName(exportFile.getName()) + ".xlsx");
    }

    FileOutputStream outFile = new FileOutputStream(exportFile);
    workbook.write(outFile);
    outFile.close();
    tamplateFile.close();
    return true;

}

From source file:com.github.riccardove.easyjasub.EasyJaSubInputFromCommand.java

private static String getExtension(File file) {
    String ext = FilenameUtils.getExtension(file.getName());
    return ext != null ? ext.toUpperCase() : null;
}

From source file:com.limegroup.gnutella.gui.search.SearchResultDataLine.java

/**
 * Returns the icon./*from   w w w .j  a  v a2 s.co m*/
 */
Icon getIcon() {

    //gubs: seems like this didn't fly
    //maybe the icon isn't refreshed.
    //see MetadataModel.addProperties()
    if (isDownloading()) {
        return GUIMediator.getThemeImage("downloading");
    }

    String ext = FilenameUtils.getExtension(getFilename());

    return IconManager.instance().getIconForExtension(ext);
}

From source file:bjerne.gallery.service.impl.ImageResizeServiceImpl.java

@Override
public void resizeImage(File origImage, File newImage, int width, int height) throws IOException {
    LOG.debug("Entering resizeImage(origImage={}, width={}, height={})", origImage, width, height);
    long startTime = System.currentTimeMillis();
    InputStream is = new BufferedInputStream(new FileInputStream(origImage));
    BufferedImage i = ImageIO.read(is);
    IOUtils.closeQuietly(is);//from   w  w  w  . j a v a  2s .  com
    BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    int origWidth = i.getWidth();
    int origHeight = i.getHeight();
    LOG.debug("Original size of image - width: {}, height={}", origWidth, height);
    float widthFactor = ((float) origWidth) / ((float) width);
    float heightFactor = ((float) origHeight) / ((float) height);
    float maxFactor = Math.max(widthFactor, heightFactor);
    int newHeight, newWidth;
    if (maxFactor > 1) {
        newHeight = (int) (((float) origHeight) / maxFactor);
        newWidth = (int) (((float) origWidth) / maxFactor);
    } else {
        newHeight = origHeight;
        newWidth = origWidth;
    }
    LOG.debug("Size of scaled image will be: width={}, height={}", newWidth, newHeight);
    int startX = Math.max((width - newWidth) / 2, 0);
    int startY = Math.max((height - newHeight) / 2, 0);
    Graphics2D scaledGraphics = scaledImage.createGraphics();
    scaledGraphics.setColor(backgroundColor);
    scaledGraphics.fillRect(0, 0, width, height);
    scaledGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    scaledGraphics.drawImage(i, startX, startY, newWidth, newHeight, null);
    OutputStream resultImageOutputStream = new BufferedOutputStream(FileUtils.openOutputStream(newImage));
    String extension = FilenameUtils.getExtension(origImage.getName());
    ImageIO.write(scaledImage, extension, resultImageOutputStream);
    IOUtils.closeQuietly(resultImageOutputStream);
    long duration = System.currentTimeMillis() - startTime;
    LOG.debug("Time in milliseconds to scale {}: {}", newImage.toString(), duration);
}

From source file:com.github.technosf.posterer.models.impl.KeyStoreBean.java

/**
 * Instantiates a {@code KeyStoreBean} wrapping the given keystore
 * <p>/*from w  ww.  jav  a 2 s  .c  om*/
 * Loads the Key Store file into a {@code KeyStore} and checks the password.
 * If the Key Store
 * can be accessed successfully, validation is successful..
 * 
 * @param file
 *            the KeyStore file
 * @param password
 *            the Key Store password
 * @throws KeyStoreBeanException
 *             Thrown when a {@code KeyStoreBean} cannot be created.
 */
@SuppressWarnings("null")
public KeyStoreBean(final File keyStoreFile, final String keyStorePassword) throws KeyStoreBeanException {
    file = keyStoreFile;
    password = keyStorePassword;

    InputStream inputStream = null;

    /*
     * Check file existence
     */
    if (keyStoreFile == null || !keyStoreFile.exists() || !keyStoreFile.canRead())
    // Key Store File cannot be read
    {
        throw new KeyStoreBeanException("Cannot read Key Store file");
    }

    try
    // to get the file input stream
    {
        inputStream = Files.newInputStream(keyStoreFile.toPath(), StandardOpenOption.READ);
    } catch (IOException e) {
        throw new KeyStoreBeanException("Error reading Key Store file", e);
    }

    // Get the file name and extension
    fileName = FilenameUtils.getName(keyStoreFile.getName());
    String fileExtension = FilenameUtils.getExtension(keyStoreFile.getName().toLowerCase());

    /*
     * Identify keystore type, and create an instance
     */
    try {
        switch (fileExtension) {
        case "p12":
            keyStore = KeyStore.getInstance("PKCS12");
            break;
        case "jks":
            keyStore = KeyStore.getInstance("JKS");
            break;
        default:
            throw new KeyStoreBeanException(String.format("Unknown keystore extention: [%1$s]", fileExtension));
        }
    } catch (KeyStoreException e) {
        throw new KeyStoreBeanException("Cannot get keystore instance");
    }

    /*
     * Load the keystore data into the keystore instance
     */
    try {
        keyStore.load(inputStream, password.toCharArray());
        valid = true;
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new KeyStoreBeanException("Cannot load the KeyStore", e);
    }

    /*
     * Key store loaded, so config the bean
     */
    try {
        type = keyStore.getType();
        size = keyStore.size();

        Enumeration<String> aliasIterator = keyStore.aliases();
        while (aliasIterator.hasMoreElements()) {
            String alias = aliasIterator.nextElement();
            certificates.put(alias, keyStore.getCertificate(alias));
        }
    } catch (KeyStoreException e) {
        throw new KeyStoreBeanException("Cannot process the KeyStore", e);
    }
}