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.google.api.ads.adwords.awreporting.exporter.reportwriter.GoogleDriveReportWriter.java

@Override
public void write(InputStream inputStream) throws IOException {
    LOGGER.info("Getting AW Reports Drive output folder");
    File outputFolder;/*  w w  w .  jav a 2s.  com*/
    // Get or create an AW Reports folder
    File reportsFolder = googleDriveService.getReportsFolder(mccAccountId);
    outputFolder = reportsFolder;

    if (folderPerAccount) {
        File accountFolder = googleDriveService.getAccountFolder(reportsFolder, String.valueOf(accountId));
        outputFolder = accountFolder;
    }

    // Create a Google Drive PDF file
    File reportFile = new File();
    reportFile.setFileExtension(reportFileType.name());

    String fileNameWithOutExt = FilenameUtils.removeExtension((templateName));
    String reportFileName = fileNameWithOutExt + "_" + accountId + "_" + dateStart + "_" + dateEnd + "."
            + reportFileType.toString().toLowerCase();

    reportFile.setDescription("AdWords Report " + fileNameWithOutExt + " for account " + accountId
            + "for dates between" + dateStart + " and " + dateEnd);

    reportFile.setTitle(reportFileName);

    // Place the file in the correct Drive folder
    reportFile.setParents(Arrays.asList(new ParentReference().setId(outputFolder.getId())));

    // Write the PDF file to Drive.
    if (reportFileType.equals(ReportFileType.PDF)) {
        reportFile.setMimeType(PDF_MIME_TYPE);
        AbstractInputStreamContent aisc = new InputStreamContent(PDF_MIME_TYPE, inputStream);
        googleDriveService.getDriveService().files().insert(reportFile, aisc).execute();
    }

    // Write the HTML file to Drive.
    if (reportFileType.equals(ReportFileType.HTML)) {
        reportFile.setMimeType(HTML_MIME_TYPE);
        AbstractInputStreamContent aisc = new InputStreamContent(HTML_MIME_TYPE, inputStream);
        googleDriveService.getDriveService().files().insert(reportFile, aisc).execute();
    }

    // Convert the HTML file to a Drive Doc and write to Drive.
    if (reportFileType.equals(ReportFileType.DRIVE_DOC)) {
        reportFile.setMimeType(DOC_MIME_TYPE);
        AbstractInputStreamContent aisc = new InputStreamContent(HTML_MIME_TYPE, inputStream);
        googleDriveService.getDriveService().files().insert(reportFile, aisc).setConvert(true).execute();
    }
    inputStream.close();
}

From source file:com.nuvolect.securesuite.webserver.connector.CmdPaste.java

@Override
public InputStream go(@NonNull Map<String, String> params) {
    String url = params.get("url");
    OmniFile dst = new OmniFile(params.get("dst"));

    boolean cut = params.containsKey("cut") && params.get("cut").contentEquals("1");

    String suffix = params.get("suffix");
    JsonArray added = new JsonArray();
    JsonArray removed = new JsonArray();

    /**//from   ww  w  . ja  va  2 s.  c  om
     * Params only has the first element of the targets[] array.
     * This is fine if there is only one target but an issue for multiple file operations.
     * Manually parse the query parameter strings to get all targets.
     */
    String[] qps = params.get("queryParameterStrings").split("&");

    /**
     * Iterate over the source files and copy each to the destination folder.
     * Files can be single files or directories and cut/copy/paste works across
     * different volume types, clear to encrypted, etc.
     * If the cut flag is set also delete each file.
     */
    for (String candidate : qps) {
        if (!candidate.contains("targets")) {
            continue;
        }
        String[] parts = candidate.split("=");

        OmniFile fromFile = new OmniFile(parts[1]);
        String toPath = dst.getPath() + "/" + fromFile.getName();
        OmniFile toFile = null;

        // add no more than 10 tilda
        for (int dupCount = 0; dupCount < 10; dupCount++) {
            toFile = new OmniFile(dst.getVolumeId(), toPath);

            if (!toFile.exists()) {
                break;
            }

            // add ~ to filename, keep extension
            String extension = FilenameUtils.getExtension(toPath);
            if (!extension.isEmpty()) {
                extension = "." + extension;
            }
            toPath = FilenameUtils.removeExtension(toPath) + suffix;
            toPath = toPath + extension;
        }

        boolean success;
        if (fromFile.isDirectory()) {
            success = OmniFiles.copyDirectory(fromFile, toFile);
        } else {
            success = OmniFiles.copyFile(fromFile, toFile);
        }

        if (success) {
            //note: full depth of directory not added
            added.add(FileObj.makeObj(toFile, url));
        }

        if (success && cut) {
            if (fromFile.delete()) {
                removed.add(FileObj.makeObj(fromFile, url));
            } else {
                LogUtil.log(LogUtil.LogType.CMD_PASTE, "File delete failure: " + fromFile.getPath());
            }
        }
    }

    JsonObject wrapper = new JsonObject();

    wrapper.add("added", added);
    wrapper.add("removed", removed);

    return getInputStream(wrapper);
}

From source file:com.ppedregal.typescript.maven.TscMojo.java

private void doCompileFiles(boolean checkTimestamp, Collection<File> files) throws MojoExecutionException {
    try {//from  ww w .j a  v  a2s. c o m
        int compiledFiles = 0;
        if (!watching) {
            getLog().info("Searching directory " + sourceDirectory.getCanonicalPath());
        }
        for (File file : files) {
            try {
                String path = file.getPath().substring(sourceDirectory.getPath().length());
                String sourcePath = path;
                String targetPath = FilenameUtils.removeExtension(path) + ".js";
                File sourceFile = new File(sourceDirectory, sourcePath).getAbsoluteFile();
                File targetFile = new File(targetDirectory, targetPath).getAbsoluteFile();
                if (!targetFile.exists() || !checkTimestamp
                        || sourceFile.lastModified() > targetFile.lastModified()) {
                    String sourceFilePath = sourceFile.getPath();
                    getLog().info(String.format("Compiling: %s", sourceFilePath));
                    String generatePath = targetFile.getPath();
                    tsc("--out", generatePath, sourceFilePath);
                    getLog().info(String.format("Generated: %s", generatePath));
                    compiledFiles++;
                }
            } catch (TscInvocationException e) {
                getLog().error(e.getMessage());
                if (getLog().isDebugEnabled()) {
                    getLog().debug(e);
                }
            }
        }
        if (compiledFiles == 0) {
            getLog().info("Nothing to compile");
        } else {
            getLog().info(String.format("Compiled %s file(s)", compiledFiles));
        }
    } catch (IOException e) {
        throw createMojoExecutionException(e);
    }
}

From source file:neembuu.uploader.zip.generator.NUZipFileGenerator.java

private void visitClassFile(Path file, BasicFileAttributes attrs, Path uploadersDirectory) throws IOException {
    Class c;/*from   w  ww.ja  v  a 2s .c  o  m*/
    try {
        c = load(file, uploadersDirectory);
    } catch (Throwable a) {
        System.err.println("skipping " + file);
        a.printStackTrace();
        return;
    }

    SmallModule moduleDescription = (SmallModule) c.getAnnotation(SmallModule.class);
    if (moduleDescription == null) {
        System.out.println("not a small module" + file);
        return;
    }
    if (moduleDescription.ignore()) {
        Logger.getLogger(NUZipFileGenerator.class.getName()).log(Level.INFO, "Ignoring : {0}",
                FilenameUtils.removeExtension(c.getName()));
        return;
    }
    handleSmallModule(moduleDescription, c, uploadersDirectory);
}

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

/**
 * Checking for new files in the staging area.   
 *///from  ww  w.  j  a  va 2s. co  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 ingestNoBagit 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:com.jadarstudios.rankcapes.forge.cape.CapePack.java

/**
 * Parses a static cape JSON node.//from w ww.  j  ava2  s  .com
 *
 * @param name     the name of the cape.
 * @param capeFile the filename of the cape
 */
private void parseStaticCapeNode(String name, String capeFile) {
    String fileName = FilenameUtils.removeExtension(capeFile);
    if (this.unprocessedCapes.containsKey(fileName)) {
        StaticCape cape = this.unprocessedCapes.get(fileName).setName(name);
        this.processedCapes.put(name, cape);
    }
}

From source file:com.uwsoft.editor.data.manager.TextureManager.java

public void loadCurrentProjectSpriteAnimations(String path, String curResolution) {
    spriteAnimAtlases.clear();//  ww w .  ja  v a2s. c  om
    FileHandle sourceDir = new FileHandle(path + curResolution + "/sprite-animations");
    for (FileHandle entry : sourceDir.list()) {
        if (entry.file().isDirectory()) {
            String animName = FilenameUtils.removeExtension(entry.file().getName());
            TextureAtlas atlas = new TextureAtlas(
                    Gdx.files.internal(entry.file().getAbsolutePath() + File.separator + animName + ".atlas"));
            spriteAnimAtlases.put(animName, atlas);
        }
    }
}

From source file:edu.ur.ir.repository.service.DefaultRepositoryService.java

/**
 * Create a versioned file in the repository.
 * //from w w  w  . j  a  v  a 2  s .c  o m
 * @param repositoryId - id of the repository to create the versioned file in.
 * @param f - file to add
 * @param fileName - name user wishes to give the file.
 * @param descrption - description of the file.
 * @param original file name - original file name used to upload this file
 * and the user wishes to give the file a name that is different than the one on the file system
 * 
 * @return - the created versioned file.
 * @throws edu.ur.file.IllegalFileSystemNameException 
 */
public VersionedFile createVersionedFile(IrUser user, Repository repository, File f, String fileName,
        String description) throws IllegalFileSystemNameException {

    FileInfo info = createFileInfo(repository, f, fileName, description);

    VersionedFile versionedFile = new VersionedFile(user, info, FilenameUtils.removeExtension(fileName));
    versionedFile.setDescription(description);
    versionedFileDAO.makePersistent(versionedFile);

    return versionedFile;
}

From source file:io.stallion.dataAccess.file.TextFilePersister.java

public T fromString(String fileContent, Path fullPath) {
    if (fullPath.toString().endsWith(".html") || fullPath.toString().endsWith(".htm")) {
        return fromHtml(fileContent, fullPath);
    }//from   w  ww .  j  a  v a2  s. c om
    String relativePath = fullPath.toString().replace(getBucketFolderPath(), "");
    Path path = fullPath;

    T item = null;
    try {
        item = getModelClass().newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    item.setTags(new ArrayList<String>()).setElementById(new HashMap<>()).setElements(new ArrayList<>())
            .setPublishDate(ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("UTC"))).setTitle("")
            .setDraft(false).setTemplate("").setContent("").setSlug("");

    /* Get the id and slug */

    item.setSlug(FilenameUtils.removeExtension(relativePath));
    if (!item.getSlug().startsWith("/")) {
        item.setSlug("/" + item.getSlug());
    }
    if (item.getSlug().endsWith("/index")) {
        item.setSlug(item.getSlug().substring(item.getSlug().length() - 6));
    }

    if (empty(fileContent.trim())) {
        return item;
    }

    /* Parse out toml properties, if found */
    String tomlContent;
    Matcher tomlMatcher = tomlPattern.matcher(fileContent);
    if (tomlMatcher.find()) {
        tomlContent = tomlMatcher.group(1).trim();
        fileContent = tomlMatcher.replaceAll("\n");
        Map tomlMap = new Toml().read(tomlContent).to(HashMap.class);
        for (Object key : tomlMap.keySet()) {
            Object value = tomlMap.get(key);
            setProperty(item, key.toString(), value);
        }
    }

    List<String> allLines = Arrays.asList(fileContent.split("\n"));

    if (allLines.size() == 0) {
        return item;
    }

    if (empty(item.getTitle())) {
        item.setTitle(allLines.get(0));
    }

    String titleLine = "";
    List<String> propertiesSection = list();
    String rawContent = "";
    int propertiesStartAt = 0;
    if (allLines.size() > 1) {
        if (allLines.get(1).startsWith("----") || allLines.get(1).startsWith("====")) {
            titleLine = allLines.get(0);
            propertiesStartAt = 2;
            item.setTitle(titleLine);
        }
    }

    int propertiesEndAt = propertiesStartAt;
    for (; propertiesEndAt < allLines.size(); propertiesEndAt++) {
        String line = allLines.get(propertiesEndAt);
        if (line.trim().equals("---")) {
            continue;
        }
        int colon = line.indexOf(':');
        if (colon == -1) {
            break;
        }
        String key = line.substring(0, colon).trim();
        String value = line.substring(colon + 1, line.length()).trim();
        if ("oldUrls".equals(key)) {
            setProperty(item, key, apply(list(StringUtils.split(value, ";")), (aUrl) -> aUrl.trim()));
        } else {
            setProperty(item, key, value);
        }
    }
    if (propertiesEndAt < allLines.size()) {
        rawContent = StringUtils.join(allLines.subList(propertiesEndAt, allLines.size()), "\n").trim();
    }

    Boolean isMarkdown = false;
    if (path.toString().toLowerCase().endsWith(".txt") || path.toString().toLowerCase().endsWith(".md")) {
        isMarkdown = true;
    }
    item.setElements(StElementParser.parseElements(rawContent, isMarkdown));
    List<StElement> items = item.getElements();
    for (StElement ele : items) {
        item.getElementById().put(ele.getId(), ele);
    }

    String itemContent = StElementParser.removeTags(rawContent).trim();
    item.setOriginalContent(itemContent);

    if (isMarkdown) {
        Log.fine("Parse for page {0} {1} {2}", item.getId(), item.getSlug(), item.getTitle());
        String cacheKey = DigestUtils.md5Hex("markdown-to-html" + Literals.GSEP + itemContent);
        String cached = null;
        if (!"test".equals(Settings.instance().getEnv())) {
            cached = PermaCache.get(cacheKey);
        }
        if (cached == null) {
            itemContent = Markdown.instance().process(itemContent);
            PermaCache.set(cacheKey, itemContent);
        } else {
            itemContent = cached;
        }

        item.setContent(itemContent);
    }

    if (empty(item.getId())) {
        item.setId(makeIdFromFilePath(relativePath));
    }

    Log.fine("Loaded text item: id:{0} slug:{1} title:{2} draft:{3}", item.getId(), item.getSlug(),
            item.getTitle(), item.getDraft());
    return item;
}

From source file:es.ehu.si.ixa.pipe.parse.Annotate.java

public void parseForTesting(File inputText) throws IOException {
    StringBuffer parsingDoc = new StringBuffer();
    if (inputText.isFile()) {
        List<String> inputTrees = FileUtils.readLines(inputText, "UTF-8");
        for (String sentence : inputTrees) {
            Parse parsedSentence = parser.parse(sentence, 1)[0];
            parsedSentence.show(parsingDoc);
            parsingDoc.append("\n");
        }//from   w ww. j  av  a  2s  . c om
        File outfile = new File(FilenameUtils.removeExtension(inputText.getPath()) + ".test");
        System.err.println("Writing test parse file to " + outfile);
        FileUtils.writeStringToFile(outfile, parsingDoc.toString(), "UTF-8");
    } else {
        System.out.println("Choose a correct file!");
        System.exit(1);
    }
}