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:MSUmpire.DIA.DIAPack.java

private void RemoveIndexFile() {
    new File(FilenameUtils.removeExtension(Filename) + ".ScanPosFS").delete();
    new File(FilenameUtils.removeExtension(Filename) + ".RTidxFS").delete();
    new File(FilenameUtils.removeExtension(Filename) + ".ScanRTFS").delete();
    new File(FilenameUtils.removeExtension(Filename) + ".ScanidxFS").delete();
    new File(FilenameUtils.removeExtension(Filename) + ".DIAWindowsFS").delete();
}

From source file:com.doplgangr.secrecy.FileSystem.Vault.java

public String addFile(final Context context, final Uri uri) {
    String filename = uri.getLastPathSegment();
    try {/*from   w w w  .  j  ava 2  s.  c o m*/
        String realPath = getPath(context, uri);
        Util.log(realPath, filename);
        filename = new java.io.File(realPath).getName();
        // If we can use real path, better use one.
    } catch (Exception ignored) {
        // Leave it.
    }
    if (!filename.contains("_thumb") && !filename.contains(".nomedia")) {
        ContentResolver cR = context.getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String type = mime.getExtensionFromMimeType(cR.getType(uri));
        if (type != null)
            filename = Base64Coder.encodeString(FilenameUtils.removeExtension(filename)) + "." + type;
    }
    InputStream is = null;
    OutputStream out = null;
    try {
        InputStream stream = context.getContentResolver().openInputStream(uri);
        java.io.File addedFile = new java.io.File(path + "/" + filename);
        addedFile.delete();
        addedFile.createNewFile();
        is = new BufferedInputStream(stream);
        byte buffer[] = new byte[Config.bufferSize];
        int count;
        AES_Encryptor enc = new AES_Encryptor(key);
        out = new CipherOutputStream(new FileOutputStream(addedFile), enc.encryptstream());
        while ((count = is.read(buffer)) != -1)
            out.write(buffer, 0, count);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return filename;
}

From source file:eu.esdihumboldt.hale.io.html.HtmlMappingExporter.java

@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter)
        throws IOProviderConfigurationException, IOException {
    this.reporter = reporter;

    context = new VelocityContext();
    cellIds = new Identifiers<Cell>(Cell.class, false);

    alignment = getAlignment();/*from   w w w  . j  a v  a2 s . c o  m*/

    URL headlinePath = this.getClass().getResource("bg-headline.png"); //$NON-NLS-1$
    URL cssPath = this.getClass().getResource("style.css"); //$NON-NLS-1$
    URL linkPath = this.getClass().getResource("int_link.png"); //$NON-NLS-1$
    URL tooltipIcon = this.getClass().getResource("tooltip.gif"); //$NON-NLS-1$
    final String filesSubDir = FilenameUtils
            .removeExtension(FilenameUtils.getName(getTarget().getLocation().getPath())) + "_files"; //$NON-NLS-1$
    final File filesDir = new File(FilenameUtils.getFullPath(getTarget().getLocation().getPath()), filesSubDir);

    filesDir.mkdirs();
    context.put(FILE_DIRECTORY, filesSubDir);

    try {
        init();
    } catch (Exception e) {
        return reportError(reporter, "Initializing error", e);
    }
    File cssOutputFile = new File(filesDir, "style.css");
    FileUtils.copyFile(getInputFile(cssPath), cssOutputFile);

    // create headline picture
    File headlineOutputFile = new File(filesDir, "bg-headline.png"); //$NON-NLS-1$
    FileUtils.copyFile(getInputFile(headlinePath), headlineOutputFile);

    File linkOutputFile = new File(filesDir, "int_link.png"); //$NON-NLS-1$
    FileUtils.copyFile(getInputFile(linkPath), linkOutputFile);

    File tooltipIconFile = new File(filesDir, "tooltip.png"); //$NON-NLS-1$
    FileUtils.copyFile(getInputFile(tooltipIcon), tooltipIconFile);

    File htmlExportFile = new File(getTarget().getLocation().getPath());
    if (projectInfo != null) {
        Date date = new Date();
        DateFormat dfm = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);

        // associate variables with information data
        String exportDate = dfm.format(date);
        context.put(EXPORT_DATE, exportDate);

        if (projectInfo.getCreated() != null) {
            String created = dfm.format(projectInfo.getCreated());
            context.put(CREATED_DATE, created);
        }

        context.put(PROJECT_INFO, projectInfo);
    }

    if (alignment != null) {
        Collection<TypeCellInfo> typeCellInfos = new ArrayList<TypeCellInfo>();
        Collection<? extends Cell> cells = alignment.getTypeCells();
        Iterator<? extends Cell> it = cells.iterator();
        while (it.hasNext()) {
            final Cell cell = it.next();
            // this is the collection of type cell info
            TypeCellInfo typeCellInfo = new TypeCellInfo(cell, alignment, cellIds, filesSubDir);
            typeCellInfos.add(typeCellInfo);
        }
        // put the full collection of type cell info to the context (for the
        // template)
        context.put(TYPE_CELL_INFOS, typeCellInfos);
        createImages(filesDir);
    }

    context.put(TOOLTIP, getParameter(TOOLTIP).as(boolean.class));

    Template template;
    try {
        template = velocityEngine.getTemplate(templateFile.getName(), "UTF-8");
    } catch (Exception e) {
        return reportError(reporter, "Could not load template", e);
    }

    FileWriter fileWriter = new FileWriter(htmlExportFile);
    template.merge(context, fileWriter);
    fileWriter.close();

    reporter.setSuccess(true);
    return reporter;
}

From source file:com.itemanalysis.jmetrik.manager.ExportDataCommand.java

/**
 * If output file not specified then use the same name as the original file but change the suffix.
 * @return//  ww w.j  a  va2s . c  om
 */
@Override
public File getOutputFile() {
    File f = getOutputFile();
    if (null == f) {
        String s = getDataFile().getAbsolutePath();
        s = FilenameUtils.removeExtension(s);
        s += ".csv";
        return new File(s);
    } else {
        return f;
    }
}

From source file:eu.edisonproject.classification.tfidf.mapreduce.TFIDFDriverImpl.java

/**
 *
 * @param inputPath/*from w w  w .  j  a  v  a  2  s  . com*/
 */
public void executeTFIDF(String inputPath) {
    try {
        File items = new File(INPUT_ITEMSET);
        if (!items.exists()) {
            throw new IOException(items.getAbsoluteFile() + " not found");
        }

        String OUTPUT_PATH1 = System.currentTimeMillis() + "_" + UUID.randomUUID()
                + "-TFIDFDriverImpl-1-word-freq";

        if (items.length() < 200000000) {
            String AVRO_FILE = System.currentTimeMillis() + "_" + UUID.randomUUID() + "-TFIDFDriverImpl-avro";
            Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.INFO, "Starting text2Avro");
            text2Avro(inputPath, AVRO_FILE);

            Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.INFO,
                    "Starting WordFrequencyInDocDriver: {0},{1},{2},{3},{4}",
                    new Object[] { AVRO_FILE, OUTPUT_PATH1, INPUT_ITEMSET, NUM_OF_LINES, STOPWORDS_PATH });
            String[] args1 = { AVRO_FILE, OUTPUT_PATH1, INPUT_ITEMSET, STOPWORDS_PATH };
            ToolRunner.run(new WordFrequencyInDocDriver(), args1);
        } else {
            Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.INFO, "Starting TermWordFrequency");
            String[] args1 = { INPUT_ITEMSET, OUTPUT_PATH1, inputPath, STOPWORDS_PATH, NUM_OF_LINES };
            ToolRunner.run(new TermWordFrequency(), args1);
        }
        String OUTPUT_PATH2 = System.currentTimeMillis() + "_" + UUID.randomUUID()
                + "-TFIDFDriverImpl-2-word-counts";
        ;
        String[] args2 = { OUTPUT_PATH1, OUTPUT_PATH2 };
        ToolRunner.run(new WordCountsForDocsDriver(), args2);

        File docs = new File(inputPath);
        File[] files = docs.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".txt");
            }
        });
        Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.INFO, "docs:{0}", docs.getAbsolutePath());
        int numberOfDocuments = files.length;
        String OUTPUT_PATH3 = System.currentTimeMillis() + "_" + UUID.randomUUID()
                + "-TFIDFDriverImpl-3-tf-idf";
        String[] args3 = { OUTPUT_PATH2, OUTPUT_PATH3, String.valueOf(numberOfDocuments) };
        ToolRunner.run(new WordsInCorpusTFIDFDriver(), args3);

        StringBuilder fileNames = new StringBuilder();
        String prefix = "";
        for (File name : files) {
            if (name.isFile() && FilenameUtils.getExtension(name.getName()).endsWith("txt")) {
                fileNames.append(prefix);
                prefix = ",";
                fileNames.append(FilenameUtils.removeExtension(name.getName()).replaceAll("_", ""));
            }
        }
        String OUTPUT_PATH4 = System.currentTimeMillis() + "_" + UUID.randomUUID()
                + "-TFIDFDriverImpl-4-distances";
        String[] args4 = { OUTPUT_PATH3, OUTPUT_PATH4, COMPETENCES_PATH, fileNames.toString() };
        Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.INFO, "args4:{0}", Arrays.toString(args4));
        ToolRunner.run(new CompetencesDistanceDriver(), args4);

        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(conf);
        Path hdfsRes = new Path(OUTPUT_PATH4);
        FileStatus[] results = fs.listStatus(hdfsRes);
        for (FileStatus s : results) {
            Path dest = new Path(OUT + "/" + s.getPath().getName());
            Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.INFO, "Copy: {0} to: {1}",
                    new Object[] { s.getPath(), dest });
            fs.copyToLocalFile(s.getPath(), dest);
        }
        fs.delete(hdfsRes, true);

    } catch (Exception ex) {
        Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:androidassetsgenerator.AssetGenerator.java

private File path(String fileName, String outputDir, String outputSize) {
    String name = FilenameUtils.removeExtension(fileName);
    String extension = FilenameUtils.getExtension(fileName);
    Path path = Paths.get(
            outputDir + Constants.SLASH + Constants.PREFIX + name.toUpperCase() + Constants.SLASH + outputSize);

    if (!Files.exists(path)) {
        try {//from   w w  w. j a  va 2 s. co  m
            Files.createDirectories(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    File file = new File(path.toString() + Constants.SLASH + Constants.PREFIX + name.toUpperCase()
            + Constants.DOT + extension);

    return file;
}

From source file:dk.dma.msiproxy.common.repo.ThumbnailService.java

/**
 * Returns or creates the a thumbnail for the given file if it is an image.
 * Otherwise, null is returned//from w w  w .  j av  a2 s .  com
 *
 * @param file the file to create a thumbnail for
 * @param type the type of image
 * @param size the size of the thumbnail
 * @return the thumbnail file or null if none was found or created
 */
public Path createThumbnail(Path file, String type, IconSize size) {

    try {
        // Construct the thumbnail name by appending "_thumb_size" to the file name
        String thumbName = String.format("%s_thumb_%d.%s",
                FilenameUtils.removeExtension(file.getFileName().toString()), size.getSize(),
                FilenameUtils.getExtension(file.getFileName().toString()));

        // Check if the thumbnail already exists
        Path thumbFile = file.getParent().resolve(thumbName);
        if (Files.isRegularFile(thumbFile) && Files.getLastModifiedTime(thumbFile).toMillis() >= Files
                .getLastModifiedTime(file).toMillis()) {
            return thumbFile;
        }

        // Check whether to use VIPS or java
        if (StringUtils.isNotBlank(vipsCmd) && vipsFileTypes.contains(type.toLowerCase())) {
            // Use VIPS
            createThumbnailUsingVips(file, thumbFile, size);

        } else {
            // Use java APIs
            createThumbnailUsingJava(file, thumbFile, size);
        }

        return thumbFile;

    } catch (Throwable e) {
        // Alas, no thumbnail
        return null;
    }
}

From source file:com.fileOperations.ImageToPDF.java

/**
 * create PDF from image and scales it accordingly to fit in a single page
 *
 * @param folderPath String//from  www .  jav  a 2 s  .  c o m
 * @param imageFileName String
 * @return String new filename
 */
public static String createPDFFromImageNoDelete(String folderPath, String imageFileName) {
    String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf";
    String image = folderPath + imageFileName;
    PDImageXObject pdImage = null;
    File imageFile = null;
    FileInputStream fileStream = null;
    BufferedImage bim = null;

    File attachmentLocation = new File(folderPath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    // the document
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    try {
        doc = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        float margin = 72;
        float pageWidth = page.getMediaBox().getWidth() - 2 * margin;
        float pageHeight = page.getMediaBox().getHeight() - 2 * margin;

        if (image.toLowerCase().endsWith(".jpg")) {
            imageFile = new File(image);
            fileStream = new FileInputStream(image);
            pdImage = JPEGFactory.createFromStream(doc, fileStream);
            //            } else if ((image.toLowerCase().endsWith(".tif")
            //                    || image.toLowerCase().endsWith(".tiff"))
            //                    && TIFFCompression(image) == COMPRESSION_GROUP4) {
            //                imageFile = new File(image);
            //                pdImage = CCITTFactory.createFromFile(doc, imageFile);
        } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp")
                || image.toLowerCase().endsWith(".png")) {
            imageFile = new File(image);
            bim = ImageIO.read(imageFile);
            pdImage = LosslessFactory.createFromImage(doc, bim);
        }

        if (pdImage != null) {
            if (pdImage.getWidth() > pdImage.getHeight()) {
                page.setRotation(270);
                PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(),
                        page.getMediaBox().getWidth());
                page.setMediaBox(rotatedPage);
                pageWidth = page.getMediaBox().getWidth() - 2 * margin;
                pageHeight = page.getMediaBox().getHeight() - 2 * margin;
            }
            Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight);
            Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight());
            Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize);
            float startX = page.getMediaBox().getLowerLeftX() + margin;
            float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height;

            doc.addPage(page);
            contentStream = new PDPageContentStream(doc, page);
            contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height);
            contentStream.close();
            doc.save(folderPath + pdfFile);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
        return "";
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
                return "";
            }
        }
    }
    if (fileStream != null) {
        try {
            fileStream.close();
        } catch (IOException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    if (bim != null) {
        bim.flush();
    }
    return pdfFile;
}

From source file:com.itemanalysis.jmetrik.manager.ImportDataCommand.java

/**
 * If output file not specified then use the same name as the original file but change the suffix.
 * @return/*from  www .ja  va2s.c  o m*/
 */
@Override
public File getOutputFile() {
    if (null == outputFile) {
        String s = getDataFile().getAbsolutePath();
        s = FilenameUtils.removeExtension(s);
        s += ".jmetrik";
        return new File(s);
    } else {
        return outputFile;
    }
}

From source file:com.springsense.nutch.indexer.SpringSenseIndexingFilter.java

protected String preprocessUrlOrPath(String urlOrPath) {
    if (StringUtils.isBlank(urlOrPath)) {
        return null;
    }//  w  w  w  .j  ava 2  s  . co  m

    String path = null;

    URL url;
    try {
        url = new URL(urlOrPath);

        path = url.getPath();
    } catch (MalformedURLException e) {
        // Assume we got a file path... We'll attempt to treat it so.
        path = urlOrPath;
    }

    String decodedUrlOrPath = null;
    try {
        decodedUrlOrPath = URLDecoder.decode(path, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        LOG.error(String.format("Couldn't decode URL or path: '%s' due to an error", urlOrPath), e);
        return null;
    }

    String fileBaseNameWithoutExtension = FilenameUtils
            .removeExtension(FilenameUtils.getBaseName(decodedUrlOrPath));

    return splitCamelCase(fileBaseNameWithoutExtension);
}