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:jease.cms.service.Imports.java

private static Document newDocument(String filename, InputStream inputStream) throws IOException {
    Document document = new Document();
    document.setId(Filenames.asId(filename));
    document.setTitle(FilenameUtils.removeExtension(filename));
    document.setLastModified(new Date());
    document.setContentType(MimeTypes.guessContentTypeFromName(filename));
    copyStreamToFile(inputStream, document.getFile());
    // Trigger conversion to plain text
    document.getText();/* w  w  w . j ava  2s  .co  m*/
    return document;
}

From source file:avantssar.aslanpp.testing.Tester.java

public static void doTest(TranslationReport rep, ITestTask task, File sourceBaseDir, File targetBaseDir,
        ASLanPPConnectorImpl translator, TesterCommandLineOptions options, PrintStream err) {
    String relativePath = FilenameUtils.normalize(task.getASLanPP().getAbsolutePath())
            .substring(FilenameUtils.normalizeNoEndSeparator(sourceBaseDir.getAbsolutePath()).length() + 1);
    File aslanPPinput = new File(
            FilenameUtils.concat(FilenameUtils.normalize(targetBaseDir.getAbsolutePath()), relativePath));

    try {/*from ww w  .  java2 s.c  o  m*/
        FileUtils.copyFile(task.getASLanPP(), aslanPPinput, true);
        File aslanPPcheck1 = new File(
                FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.aslan++");
        File aslanPPcheck1det = new File(
                FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.detailed.aslan++");
        File aslanPPcheck1err = new File(
                FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.errors.aslan++");
        File aslanPPcheck1warn = new File(
                FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.warnings.aslan++");
        File aslanPPcheck2 = null;
        File aslanPPcheck2det = null;
        File aslanPPcheck2err = null;
        File aslanPPcheck2warn = null;
        File aslanFile = new File(FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".aslan");
        File errorsFile = new File(
                FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".errors.txt");
        File warningsFile = new File(
                FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".warnings.txt");

        // Load the file and write it back to another file.
        // Then again load it back and write it to another file.
        // The files should have the same content.
        String fileName = aslanPPinput.getAbsolutePath();
        String aslanppSpec = FileUtils.readFileToString(task.getASLanPP());
        TranslatorOptions optPP = new TranslatorOptions();
        optPP.setPrettyPrint(true);
        TranslatorOptions optPPdet = new TranslatorOptions();
        optPPdet.setPreprocess(true);
        // EntityManager.getInstance().purge();
        TranslatorOutput firstLoad = translator.translate(optPP, fileName, aslanppSpec);
        FileUtils.writeStringToFile(aslanPPcheck1, firstLoad.getSpecification());
        FileUtils.writeLines(aslanPPcheck1err, firstLoad.getErrors());
        aslanPPcheck1err = deleteIfZero(aslanPPcheck1err);
        FileUtils.writeLines(aslanPPcheck1warn, firstLoad.getWarnings());
        aslanPPcheck1warn = deleteIfZero(aslanPPcheck1warn);
        // EntityManager.getInstance().purge();
        TranslatorOutput firstLoadDet = translator.translate(optPPdet, fileName, aslanppSpec);
        // TODO should use translate_main, since result will be empty
        FileUtils.writeStringToFile(aslanPPcheck1det, firstLoadDet.getSpecification());
        if (firstLoad.getSpecification() != null) {
            aslanPPcheck2 = new File(
                    FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.aslan++");
            aslanPPcheck2det = new File(
                    FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.detailed.aslan++");
            aslanPPcheck2err = new File(
                    FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.errors.aslan++");
            aslanPPcheck2warn = new File(
                    FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.warnings.aslan++");
            // EntityManager.getInstance().purge();
            TranslatorOutput secondLoad = translator.translate(optPP, null, firstLoad.getSpecification());
            FileUtils.writeStringToFile(aslanPPcheck2, secondLoad.getSpecification());
            FileUtils.writeLines(aslanPPcheck2err, secondLoad.getErrors());
            aslanPPcheck2err = deleteIfZero(aslanPPcheck2err);
            FileUtils.writeLines(aslanPPcheck2warn, secondLoad.getWarnings());
            aslanPPcheck2warn = deleteIfZero(aslanPPcheck2warn);
            // EntityManager.getInstance().purge();
            TranslatorOutput secondLoadDet = translator.translate(optPPdet, null, firstLoad.getSpecification());
            FileUtils.writeStringToFile(aslanPPcheck2det, secondLoadDet.getSpecification());
        }

        // EntityManager.getInstance().purge();
        TranslatorOutput result = translator.translate(options, fileName, aslanppSpec);
        FileUtils.writeStringToFile(aslanFile, result.getSpecification());
        FileUtils.writeLines(errorsFile, result.getErrors());
        FileUtils.writeLines(warningsFile, result.getWarnings());

        File expASLan = null;
        if (task.getExpectedASLan() != null) {
            expASLan = new File(
                    FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".expected.aslan");
            FileUtils.copyFile(task.getExpectedASLan(), expASLan, true);
        }

        TranslationInstance ti = rep.newInstance(aslanPPinput, deleteIfZero(aslanPPcheck1),
                deleteIfZero(aslanPPcheck1det), deleteIfZero(aslanPPcheck2), deleteIfZero(aslanPPcheck2det),
                result.getErrors().size(), deleteIfZero(errorsFile), result.getWarnings().size(),
                deleteIfZero(warningsFile), deleteIfZero(expASLan), deleteIfZero(aslanFile),
                task.getExpectedVerdict());
        if (ti.hasTranslation()) {
            if (bm != null && bm.getBackendRunners().size() > 0) {
                for (final IBackendRunner runner : bm.getBackendRunners()) {
                    try {
                        List<String> pars = task.getBackendParameters(runner.getName());
                        pool.execute(new BackendTask(runner.spawn(), pars, aslanFile, ti));
                    } catch (BackendRunnerInstantiationException bex) {
                        Debug.logger.error("Failed to spawn backend " + runner.getName() + ".", bex);
                    }
                }
            }
        }
    } catch (Exception e) {
        System.out.println("Exception while testing file '" + task.getASLanPP().getAbsolutePath() + "': "
                + e.getMessage());
        Debug.logger.error("Failed to test file '" + aslanPPinput + "'.", e);
    }
}

From source file:com.kotcrab.vis.editor.module.project.TextureCacheModule.java

private void reloadCache() {
    if (cacheFile.exists()) {
        TextureAtlas oldCache = null;// w  w  w.ja v a  2  s  . com

        if (cache != null)
            oldCache = cache;

        cache = new TextureAtlas(cacheFile);

        for (Entry<String, TextureRegion> e : regions.entries()) {
            String path = e.key;
            String regionName = FilenameUtils.removeExtension(path);
            TextureRegion region = e.value;
            TextureRegion newRegion = cache.findRegion(regionName);
            if (newRegion == null) {
                Texture texture = textures.get(path);
                if (texture == null) {
                    Log.warn(TAG, "Missing texture for region: " + path);
                    region.setRegion(missingRegion);
                } else {
                    if (DEBUG_LOG)
                        Log.debug(TAG, "Update region using texture: " + path);
                    region.setRegion(new TextureRegion(texture));
                }
            } else {
                if (textures.containsKey(path)) {
                    if (DEBUG_LOG)
                        Log.debug(TAG, "Dispose texture " + path);
                    textures.get(path).dispose();
                    textures.remove(path);
                }
                if (DEBUG_LOG)
                    Log.debug(TAG, "Update region using cache " + path);
                region.setRegion(newRegion);
            }
        }

        if (DEBUG_LOG)
            Log.debug(TAG, "Post update regions array size " + regions.size);

        disposeCacheLater(oldCache);

        App.eventBus.post(new ResourceReloadedEvent(EnumSet.of(ResourceType.TEXTURES)));
    } else
        Log.error(TAG,
                "Texture cache not ready, probably they aren't any textures in project or packer failed");
}

From source file:nc.noumea.mairie.distiller.DistillerTest.java

@Test
public void fTestPdfNotCorrupted() {
    // get the stream of the smb file
    try {/*from  w  w w  .j a va 2  s.  c  o  m*/
        String pdfFileName = FilenameUtils.removeExtension(testFileName) + ".pdf";
        SmbFile sFile = new SmbFile(pdfDirectory + pdfFileName, auth);
        SmbFileInputStream stream = new SmbFileInputStream(sFile);

        PdfReader reader = new PdfReader(stream);
        Assert.assertNotNull(reader);
        int nbPages = reader.getNumberOfPages();
        Assert.assertTrue("A not corrupted pdf has at least one page", nbPages > 0);
        reader.close();
        stream.close();

    } 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.//from  w  w w.  j a  v  a  2  s .com
 * 
 * @param inFile
 *            a list of terms
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@Test(dataProviderClass = TestFileProvider.class, dataProvider = "childTestFiles", groups = { "functest" })
public void children(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);
        OntClass clazz = index.getModel().getOntClass(term);
        w.println(index.getChildren(clazz));
    }
    w.flush();
    w.close();

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

From source file:de.pixida.logtest.designer.Editor.java

private void updateDocumentName() {
    final String nameForUnassingedDocument = String.format("New %s [%d]", this.type.getName(),
            newDocumentRunningIndex++);//from  w w w .j  a v  a  2 s .  c  o m
    this.setDocumentName(this.file != null ? this.file.getPath() : nameForUnassingedDocument,
            this.file != null ? FilenameUtils.removeExtension(FilenameUtils.getName(this.file.getName()))
                    : nameForUnassingedDocument);
}

From source file:algorithm.QRCodeWatermarking.java

/**
 * Creates a PNG image that contains the QR-code with the information from
 * the payload file. The image has the same name as the payload file.
 * //  w w w .ja va 2 s.c o  m
 * @param payload
 * @return qr code as png image file
 * @throws IOException
 */
private File createBarcodeFile(File payload, String imageFormat, String usedMethod) throws IOException {
    // Create restoration metadata only for the payload file to spare space.
    PayloadSegment metadata = new PayloadSegment(payload);
    metadata.addOptionalProperty("usedMethod", usedMethod);
    byte[] payloadSegment = metadata.getPayloadSegmentBytes();
    String barcodeInformation = new String(payloadSegment);
    int size = getQRCodeSize();
    String outputFileName = FilenameUtils.removeExtension(getOutputFileName(payload)) + "." + imageFormat;
    File outputFile = new File(outputFileName);
    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
    BitMatrix byteMatrix = encodeWithQRCode(barcodeInformation, hintMap, size);
    if (byteMatrix == null) {
        return null;
    }
    BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
    image.createGraphics();
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setColor(Color.WHITE);
    graphics.fillRect(0, 0, size, size);
    graphics.setColor(Color.BLACK);
    for (int x = 0; x < size; x++) {
        for (int y = 0; y < size; y++) {
            if (byteMatrix.get(x, y)) {
                graphics.fillRect(x, y, 1, 1);
            }
        }
    }
    ImageIO.write(image, imageFormat, outputFile);
    return outputFile;
}

From source file:de.uzk.hki.da.core.IngestAreaScannerWorker.java

/**
 * Checking for new files in the staging area.   
 *///from w  ww. j av a 2  s.c  o  m
@Override
public void scheduleTaskImplementation() {

    try {

        long currentTimeStamp = System.currentTimeMillis();

        for (User contractor : contractors) {

            for (String child : scanContractorFolderForReadySips(contractor.getShort_name(),
                    currentTimeStamp)) {

                logger.info("Found file \"" + child + "\" in ingest Area. Creating job for \""
                        + contractor.getShort_name() + "\"");

                Object object = null;
                try {
                    object = registerObjectService.registerObject(child, contractor);
                } catch (UserException e) {
                    logger.error("cannot register object " + child + " for contractor " + contractor
                            + ". Skip creating job for object.", e);
                    continue;
                }

                Job job = insertJobIntoQueueAndSetWorkFlowState(contractor,
                        convertMaskedSlashes(FilenameUtils.removeExtension(child)), localNodeId, object);
                logger.debug("Created new Object " + object + ":::: Created job: " + job);
            }
        }
    } catch (Exception e) { // Should catch everything in scheduleTask. Otherwise thread dies without notice.
        logger.error("Caught: " + e, e);
    }
}

From source file:net.rptools.tokentool.AppActions.java

public static void saveToken(File rptok_file, boolean overwrite) {
    if (rptok_file != null) {
        if (!rptok_file.getName().toUpperCase().endsWith(".RPTOK")) {
            rptok_file = new File(rptok_file.getAbsolutePath() + ".rptok");
        }//from  www.j a va 2  s .c o m

        if (rptok_file.exists() && !overwrite) {
            if (!TokenTool.confirm("File exists.  Overwrite?")) {
                return;
            } else {
                rptok_file.delete();
            }
        }

        String tokenName = FilenameUtils.removeExtension(rptok_file.getName());

        try {
            // Write out the token image first or aka POG image.
            File tokenImageFile = File.createTempFile("tokenImage", ".png");

            // PW: This code addes the pHYs chunk to the
            // output png file with X & Y dpi set.
            BufferedImage tokenImg = TokenTool.getFrame().getComposedToken();
            BufferedImage portraitImg = TokenTool.getFrame().getTokenCompositionPanel().getBaseImage();

            ImageWriter writer = getImageWriterBySuffix("png");
            // Created object for outputStream so we can properly close it! No longer locks .png files until app closes!
            ImageOutputStream ios = ImageIO.createImageOutputStream(tokenImageFile);
            writer.setOutput(ios);
            ImageWriteParam param = writer.getDefaultWriteParam();

            PNGMetadata png = new PNGMetadata();
            // 39.375 inches per meter
            // I'm using the image width for the DPI under
            // the assumption that the token fits within
            // one cell.
            int resX = (int) (tokenImg.getWidth() * 39.375f);
            png.pHYs_pixelsPerUnitXAxis = resX;
            png.pHYs_pixelsPerUnitYAxis = resX;
            png.pHYs_unitSpecifier = 1; // Meters - alternative is "unknown"
            png.pHYs_present = true;

            writer.write(null, new IIOImage(tokenImg, null, png), param);
            ios.close();

            // Now write out the Portrait image, here we'll use JPEG to save space
            File portraitImageFile = File.createTempFile("portraitImage", ".jpg");
            writer.reset();
            writer = getImageWriterBySuffix("jpg");
            ios = ImageIO.createImageOutputStream(portraitImageFile);
            writer.setOutput(ios);
            param = writer.getDefaultWriteParam();

            writer.write(null, new IIOImage(portraitImg, null, null), param);
            writer.dispose();
            ios.close();

            // Lets create the token!
            Token _token = new Token();
            Asset tokenImage = null;
            tokenImage = AssetManager.createAsset(tokenImageFile);
            AssetManager.putAsset(tokenImage);
            _token = new Token(tokenName, tokenImage.getId());
            _token.setGMName(tokenName);

            // Jamz: Below calls not needed, creates extra entries in XML preventing token image from changing inside MapTool
            //_token.setImageAsset(tokenImage.getName());
            //_token.setImageAsset(tokenImage.getName(), tokenImage.getId());

            // set the image shape
            Image image = ImageIO.read(tokenImageFile);
            _token.setShape(TokenUtil.guessTokenType(image));

            // set the height/width, fixes dragging to stamp layer issue
            _token.setHeight(tokenImg.getHeight());
            _token.setWidth(tokenImg.getWidth());

            // set the portrait image asset
            Asset portrait = AssetManager.createAsset(portraitImageFile); // Change for portrait
            AssetManager.putAsset(portrait);
            _token.setPortraitImage(portrait.getId());

            // Time to write out the .rptok token file...
            PackedFile pakFile = null;
            try {
                pakFile = new PackedFile(rptok_file);
                saveAssets(_token.getAllImageAssets(), pakFile);
                pakFile.setContent(_token);
                BufferedImage thumb = ImageUtil.createCompatibleImage(image, THUMB_SIZE, THUMB_SIZE, null);
                pakFile.putFile(FILE_THUMBNAIL, ImageUtil.imageToBytes(thumb, "png"));
                pakFile.setProperty(PROP_VERSION, TokenToolFrame.VERSION);
                pakFile.save();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (pakFile != null)
                    pakFile.close();
                tokenImageFile.delete();
                portraitImageFile.delete();
            }

        } catch (IOException ioe) {
            ioe.printStackTrace();
            TokenTool.showError("Unable to write image: " + ioe);
        }
    }
}

From source file:Model.MultiPlatformLDA.java

public void readData() {
    Scanner sc = null;//from w ww .  jav a  2  s  .  c  om
    BufferedReader br = null;
    String line = null;
    HashMap<String, Integer> userId2Index = null;
    HashMap<Integer, String> userIndex2Id = null;

    try {
        String folderName = dataPath + "/users";
        File postFolder = new File(folderName);

        // Read number of users
        int nUser = postFolder.listFiles().length;
        users = new User[nUser];
        userId2Index = new HashMap<String, Integer>(nUser);
        userIndex2Id = new HashMap<Integer, String>(nUser);
        int u = -1;

        // Read the posts from each user file
        for (File postFile : postFolder.listFiles()) {
            u++;
            users[u] = new User();

            // Read index of the user
            String userId = FilenameUtils.removeExtension(postFile.getName());
            userId2Index.put(userId, u);
            userIndex2Id.put(u, userId);
            users[u].userID = userId;

            // Read the number of posts from user
            int nPost = 0;
            br = new BufferedReader(new FileReader(postFile.getAbsolutePath()));
            while (br.readLine() != null) {
                nPost++;
            }
            br.close();

            // Declare the number of posts from user
            users[u].posts = new Post[nPost];

            // Read each of the post
            br = new BufferedReader(new FileReader(postFile.getAbsolutePath()));
            int j = -1;
            while ((line = br.readLine()) != null) {
                j++;
                users[u].posts[j] = new Post();

                sc = new Scanner(line.toString());
                sc.useDelimiter(",");
                while (sc.hasNext()) {
                    users[u].posts[j].postID = sc.next();
                    users[u].posts[j].platform = sc.nextInt();
                    users[u].posts[j].batch = sc.nextInt();

                    // Read the words in each post
                    String[] tokens = sc.next().toString().split(" ");
                    users[u].posts[j].words = new int[tokens.length];
                    for (int i = 0; i < tokens.length; i++) {
                        users[u].posts[j].words[i] = Integer.parseInt(tokens[i]);
                    }
                }
            }
            br.close();
        }

        // Read post vocabulary
        String vocabularyFileName = dataPath + "/vocabulary.csv";

        br = new BufferedReader(new FileReader(vocabularyFileName));
        int nPostWord = 0;
        while (br.readLine() != null) {
            nPostWord++;
        }
        br.close();
        vocabulary = new String[nPostWord];

        br = new BufferedReader(new FileReader(vocabularyFileName));
        while ((line = br.readLine()) != null) {
            String[] tokens = line.split(",");
            int index = Integer.parseInt(tokens[0]);
            vocabulary[index] = tokens[1];
        }
        br.close();

    } catch (Exception e) {
        System.out.println("Error in reading post from file!");
        e.printStackTrace();
        System.exit(0);
    }
}