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

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

Introduction

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

Prototype

public static String getPath(String filename) 

Source Link

Document

Gets the path from a full filename, which excludes the prefix.

Usage

From source file:com.nagarro.core.util.ws.impl.AddonAwareMessageSource.java

protected boolean validatePath(final String path) {
    if (dirFilter == null) {
        return true;
    }//  w  w  w.  ja  va  2s  .co m
    final String basePath = FilenameUtils.getPath(path);
    return dirFilter.test(basePath);
}

From source file:ca.on.oicr.pde.workflows.GATKGenotypeGVCFsWorkflow.java

@Override
public Map<String, SqwFile> setupFiles() {

    List<String> inputFilesList = Arrays.asList(StringUtils.split(getProperty("input_files"), ","));
    Set<String> inputFilesSet = new HashSet<>(inputFilesList);

    if (inputFilesList.size() != inputFilesSet.size()) {
        throw new RuntimeException("Duplicate files detected in input_files");
    }/*  ww  w  . ja v a  2  s . c om*/

    if ((inputFilesSet.size() % 2) != 0) {
        throw new RuntimeException("Each GVCF should have a corresponding index");
    }

    Map<String, String> gvcfs = new HashMap<>();
    Map<String, String> gvcfIndexes = new HashMap<>();
    for (String f : inputFilesSet) {
        if (f == null || f.isEmpty()) {
        } else if (f.endsWith("g.vcf.gz")) {
            gvcfs.put(StringUtils.removeEnd(f, "g.vcf.gz"), f);
        } else if (f.endsWith("g.vcf.gz.tbi")) {
            gvcfIndexes.put(StringUtils.removeEnd(f, "g.vcf.gz.tbi"), f);
        } else {
            throw new RuntimeException("Unsupported input file: [" + f + "]");
        }
    }

    int id = 0;
    for (Entry<String, String> e : gvcfs.entrySet()) {
        String key = e.getKey();
        String gvcfFilePath = e.getValue();

        String gvcfIndexFilePath = gvcfIndexes.get(key);
        if (gvcfIndexFilePath == null) {
            throw new RuntimeException("Missing index for " + FilenameUtils.getName(gvcfFilePath));
        }

        SqwFile gvcf = this.createFile("file_in_" + id++);
        gvcf.setSourcePath(gvcfFilePath);
        gvcf.setType("application/g-vcf-gz");
        gvcf.setIsInput(true);

        SqwFile gvcfIndex = this.createFile("file_in_" + id++);
        gvcfIndex.setSourcePath(gvcfIndexFilePath);
        gvcfIndex.setType("application/tbi");
        gvcfIndex.setIsInput(true);

        //FIXME: this seems to work for now, it would be better to be able to set the provisionedPath as
        //bai.getProvisionedPath != bai.getOutputPath ...
        //at least with seqware 1.1.0, setting output path changes where the output file will be stored,
        //but the commonly used get provisioned path will return the incorrect path to the file
        gvcfIndex.setOutputPath(FilenameUtils.getPath(gvcf.getProvisionedPath()));

        inputFiles.add(gvcf.getProvisionedPath());
    }

    return this.getFiles();
}

From source file:de.uzk.hki.da.format.DocxConversionStrategy.java

@Override
public List<Event> convertFile(ConversionInstruction ci) throws FileNotFoundException {

    if (ci.getConversion_routine() == null)
        throw new IllegalStateException("conversionRoutine not set");
    if (ci.getConversion_routine().getTarget_suffix().isEmpty())
        throw new IllegalStateException("target suffix in conversionRoutine not set");
    if (ci.getConversion_routine().getParams() == null)
        throw new IllegalStateException("add params not set");
    if (cliConnector == null)
        throw new IllegalStateException("Cli Connector is not set");

    File result = new File(generateTargetFilePath(ci));

    List<Event> results = new ArrayList<Event>();

    getHttpclient().setUrl(ci.getConversion_routine().getParams());
    getHttpclient()/*from   w  w w.j a v a  2 s .  c  o m*/
            .setSourceMimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    getHttpclient().postFileAndReadResponse(ci.getSource_file().toRegularFile(), result);

    if (result.exists()) {
        DAFile daf = new DAFile(pkg, object.getPath("newest").getLastElement(),
                Utilities.slashize(ci.getTarget_folder()) + result.getName());
        logger.debug("new dafile:" + daf);

        // TODO Doing PDF/A Conversion with a temp file, due to recieve PDF 1.5 from MS instead of PDF/A . 
        // This should be the same command for "normal" PDFs
        // read it from Database? 
        File tempFile = new File("/" + FilenameUtils.getPath(daf.toRegularFile().getAbsolutePath()) + "_"
                + daf.toRegularFile().getName());

        String commandAsArray[] = new String[] { "gs", "-q", "-dPDFA", "-dPDFACompatibilityPolicy=1", "-dBATCH",
                "-dNOPAUSE", "-dNOOUTERSAVE", "-dUseCIEColor", "-sProcessColorModel=DeviceCMYK",
                "-sDEVICE=pdfwrite", "-sOutputFile=" + tempFile.getAbsolutePath(), "conf/PDFA_def.ps",
                daf.toRegularFile().getAbsolutePath() };
        if (!cliConnector.execute(commandAsArray)) {
            throw new RuntimeException("GS command not succeeded");
        }

        try {
            if (tempFile.exists()) {
                result.delete();
                FileUtils.moveFile(tempFile, daf.toRegularFile());
            } else
                throw new RuntimeException("temp file " + tempFile.getAbsolutePath() + " was not created!");
        } catch (IOException e1) {
            throw new RuntimeException("MV command not succeeded on temp file " + tempFile.getAbsolutePath(),
                    e1);
        }

        PdfService.validatePdfA(daf.toRegularFile());

        Event e = new Event();
        e.setType("CONVERT");
        e.setDetail("Webservice DOCX2PDF " + ci.getConversion_routine().getParams() + " AND "
                + Utilities.createString(commandAsArray));
        e.setSource_file(daf);
        e.setTarget_file(daf);
        e.setDate(new Date());
        results.add(e);

    } else
        throw new RuntimeException("Target File not found! " + result.getAbsolutePath());
    return results;
}

From source file:ca.on.oicr.pde.workflows.GATKHaplotypeCallerWorkflow.java

@Override
public Map<String, SqwFile> setupFiles() {

    List<String> inputFilesList = Arrays.asList(StringUtils.split(getProperty("input_files"), ","));
    Set<String> inputFilesSet = new HashSet<>(inputFilesList);

    if (inputFilesList.size() != inputFilesSet.size()) {
        throw new RuntimeException("Duplicate files detected in input_files");
    }/*  ww w.j  a v  a 2  s  .  com*/

    if ((inputFilesSet.size() % 2) != 0) {
        throw new RuntimeException("Each bam should have a corresponding index");
    }

    Map<String, String> bams = new HashMap<>();
    Map<String, String> bais = new HashMap<>();
    for (String f : inputFilesSet) {
        String fileExtension = FilenameUtils.getExtension(f);
        String fileKey = FilenameUtils.removeExtension(f);
        if (null != fileExtension) {
            switch (fileExtension) {
            case "bam":
                bams.put(fileKey, f);
                break;
            case "bai":
                if (fileKey.endsWith(".bam")) {
                    fileKey = FilenameUtils.removeExtension(fileKey);
                }
                bais.put(fileKey, f);
                break;
            default:
                throw new RuntimeException("Unsupported input file type");
            }
        }
    }

    int id = 0;
    for (Entry<String, String> e : bams.entrySet()) {
        String key = e.getKey();
        String bamFilePath = e.getValue();

        String baiFilePath = bais.get(key);
        if (baiFilePath == null) {
            throw new RuntimeException("Missing index for " + FilenameUtils.getName(bamFilePath));
        }

        SqwFile bam = this.createFile("file_in_" + id++);
        bam.setSourcePath(bamFilePath);
        bam.setType("application/bam");
        bam.setIsInput(true);

        SqwFile bai = this.createFile("file_in_" + id++);
        bai.setSourcePath(baiFilePath);
        bai.setType("application/bam-index");
        bai.setIsInput(true);

        //FIXME: this seems to work for now, it would be better to be able to set the provisionedPath as
        //bai.getProvisionedPath != bai.getOutputPath ...
        //at least with seqware 1.1.0, setting output path changes where the output file will be stored,
        //but the commonly used get provisioned path will return the incorrect path to the file
        bai.setOutputPath(FilenameUtils.getPath(bam.getProvisionedPath()));

        inputBamFiles.add(bam.getProvisionedPath());
    }

    return this.getFiles();
}

From source file:de.uzk.hki.da.convert.DocxConversionStrategy.java

@Override
public List<Event> convertFile(WorkArea wa, ConversionInstruction ci) throws FileNotFoundException {

    if (ci.getConversion_routine() == null)
        throw new IllegalStateException("conversionRoutine not set");
    if (ci.getConversion_routine().getTarget_suffix().isEmpty())
        throw new IllegalStateException("target suffix in conversionRoutine not set");
    if (ci.getConversion_routine().getParams() == null)
        throw new IllegalStateException("add params not set");
    if (cliConnector == null)
        throw new IllegalStateException("Cli Connector is not set");

    File result = new File(generateTargetFilePath(wa, ci));

    List<Event> results = new ArrayList<Event>();

    getHttpclient().setUrl(ci.getConversion_routine().getParams());
    getHttpclient()// ww  w  .ja  v  a  2 s. co  m
            .setSourceMimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    getHttpclient().postFileAndReadResponse(wa.toFile(ci.getSource_file()), result);

    if (result.exists()) {
        DAFile daf = new DAFile(object.getNameOfLatestBRep(),
                StringUtilities.slashize(ci.getTarget_folder()) + result.getName());
        logger.debug("new dafile:" + daf);

        // TODO Doing PDF/A Conversion with a temp file, due to recieve PDF 1.5 from MS instead of PDF/A . 
        // This should be the same command for "normal" PDFs
        // read it from Database? 
        File tempFile = new File(
                "/" + FilenameUtils.getPath(wa.toFile(daf).getAbsolutePath()) + "_" + wa.toFile(daf).getName());

        String commandAsArray[] = new String[] { "gs", "-q", "-dPDFA", "-dPDFACompatibilityPolicy=1", "-dBATCH",
                "-dNOPAUSE", "-dNOOUTERSAVE", "-dUseCIEColor", "-sProcessColorModel=DeviceCMYK",
                "-sDEVICE=pdfwrite", "-sOutputFile=" + tempFile.getAbsolutePath(), "conf/PDFA_def.ps",
                wa.toFile(daf).getAbsolutePath() };
        if (!cliConnector.execute(commandAsArray)) {
            throw new RuntimeException("GS command not succeeded");
        }

        try {
            if (tempFile.exists()) {
                result.delete();
                FileUtils.moveFile(tempFile, wa.toFile(daf));
            } else
                throw new RuntimeException("temp file " + tempFile.getAbsolutePath() + " was not created!");
        } catch (IOException e1) {
            throw new RuntimeException("MV command not succeeded on temp file " + tempFile.getAbsolutePath(),
                    e1);
        }

        PdfService.validatePdfA(wa.toFile(daf));

        Event e = new Event();
        e.setType("CONVERT");
        e.setDetail("Webservice DOCX2PDF " + ci.getConversion_routine().getParams() + " AND "
                + StringUtilities.createString(commandAsArray));
        e.setSource_file(daf);
        e.setTarget_file(daf);
        e.setDate(new Date());
        results.add(e);

    } else
        throw new RuntimeException("Target File not found! " + result.getAbsolutePath());
    return results;
}

From source file:com.isomorphic.maven.util.ArchiveUtils.java

/**
 * Derives a new file path, in whole or in part, from an existing path.  The following use cases are supported explicitly:
 * <ul>   /* w w  w  .ja v  a  2  s. co  m*/
 *    <li>
 *       Rename a file (example: smartgwt-lgpl.jar)
 *       <p/>
 *       <code>
 *          ArchiveUtils.rewritePath("smartgwtee-4.1d/lib/smartgwt.jar", "smartgwt-lgpl.jar");   
 *       </code> 
 *    </li>
 *    <li>
 *       Move to another directory (example: target/smartgwt.jar)
 *      <p/>
 *       <code>
 *          ArchiveUtils.rewritePath("smartgwtee-4.1d/lib/smartgwt.jar", "target");
 *       </code>
 * </li>
 * <li>Move and rename (example: target/smartgwt-lgpl.jar)
 *       <p/>
 *       <code>
 *          ArchiveUtils.rewritePath("smartgwtee-4.1d/lib/smartgwt.jar", "target/smartgwt-lgpl.jar"); 
 *       </code> 
 * </li>
 *  <li>Move to new root directory, preserving some part of the existing path</li>
 *     <ul>
 *        <li>
 *           example: doc/api/com/isomorphic/servlet/IDACall.html
 *           <p/>
 *           <code>
 *              ArchiveUtils.rewritePath("smartgwtee-4.1d/doc/javadoc/com/isomorphic/servlet/IDACall.html","doc/api/#javadoc");
 *           </code>
 *          </li>
 *          <li>
 *           example: doc/api/com/isomorphic/servlet/network/FileAssembly.html
 *           <p/>
 *           <code>
 *                 ArchiveUtils.rewritePath("smartgwtee-4.1d/doc/javadoc/com/isomorphic/servlet/CompressionFilter.html", "doc/api/#javadoc/network");
 *           </code>
 *          </li>
 *     </ul>
        
 * </ul>
 * 
 * @param oldValue the existing path
 * @param newValue the value to use for the new path, including optional tokens
 * @return
 */
public static String rewritePath(String oldValue, String newValue) {

    String path = newValue;
    String filename;

    if ("".equals(FilenameUtils.getExtension(newValue))) {
        filename = FilenameUtils.getName(oldValue);
    } else {
        path = FilenameUtils.getPath(newValue);
        filename = FilenameUtils.getName(newValue);
    }

    Pattern p = Pattern.compile("(.*?)#(.*?)(?:$|(/.*))");
    Matcher m = p.matcher(path);

    if (m.find()) {

        String prefix = m.group(1);
        String dir = m.group(2);
        String suffix = m.group(3);

        int index = oldValue.indexOf(dir);
        int length = dir.length();

        String remainder = FilenameUtils.getPath(oldValue.substring(index + length));

        if (prefix != null && !prefix.equals("")) {
            path = prefix + remainder;
        } else {
            path = remainder;
        }

        if (suffix != null && !suffix.equals("")) {
            path += suffix;
        }
    }

    return FilenameUtils.normalize(path + "/" + filename);
}

From source file:ching.icecreaming.actions.FileLink.java

@Action(value = "file-link", results = { @Result(name = "success", type = "stream", params = { "inputName",
        "imageStream", "contentType", "${contentType}", "contentDisposition", "attachment;filename=${fileName}",
        "allowCaching", "false", "bufferSize", "1024" }), @Result(name = "error", location = "errors.jsp") })
public String execute() throws Exception {
    Configuration propertiesConfiguration1 = new PropertiesConfiguration("mimeTypes.properties");
    File file1 = null, file2 = null;
    String string1 = null, fileExtension = null;
    fileExtension = FilenameUtils.getExtension(fileName);
    contentType = "application/octet-stream";
    if (!StringUtils.isBlank(fileExtension)) {
        if (propertiesConfiguration1.containsKey(fileExtension))
            contentType = propertiesConfiguration1.getString(fileExtension);
    } else {/*  w ww.j a v  a  2  s .co m*/
        contentType = "image/png";
    }
    try {
        if (StringUtils.isBlank(sessionId)) {
            sessionId = httpServletRequest.getSession().getId();
        }
        string1 = System.getProperty("java.io.tmpdir") + File.separator + sessionId;
        if (StringUtils.isBlank(fileExtension))
            string1 += File.separator + FilenameUtils.getPath(fileName);
        fileName = FilenameUtils.getName(fileName);
        if (StringUtils.equalsIgnoreCase(fileExtension, "html")) {
            file2 = new File(string1, FilenameUtils.getBaseName(fileName) + ".zip");
            if (file2.exists()) {
                file1 = file2;
                contentType = "application/zip";
                fileName = file2.getName();
            } else {
                file1 = new File(string1, fileName);
            }
        } else {
            file1 = new File(string1, fileName);
        }
        if (file1.exists()) {
            imageStream = new BufferedInputStream(FileUtils.openInputStream(file1));
        }
    } catch (IOException exception1) {
        addActionError(exception1.getMessage());
        return ERROR;
    }
    return SUCCESS;
}

From source file:ca.on.oicr.pde.workflows.GATK3Workflow.java

@Override
public Map<String, SqwFile> setupFiles() {

    List<String> inputFilesList = Arrays.asList(StringUtils.split(getProperty("input_files"), ","));
    Set<String> inputFilesSet = new HashSet<>(inputFilesList);

    if (inputFilesList.size() != inputFilesSet.size()) {
        throw new RuntimeException("Duplicate files detected in input_files");
    }/*from   ww  w. jav a  2s .c o m*/

    if ((inputFilesSet.size() % 2) != 0) {
        throw new RuntimeException("Each bam should have a corresponding index");
    }

    Map<String, String> bams = new HashMap<>();
    Map<String, String> bais = new HashMap<>();
    for (String f : inputFilesSet) {
        String fileExtension = FilenameUtils.getExtension(f);
        String fileKey = FilenameUtils.removeExtension(f);
        if (null != fileExtension) {
            switch (fileExtension) {
            case "bam":
                bams.put(fileKey, f);
                break;
            case "bai":
                bais.put(fileKey, f);
                break;
            default:
                throw new RuntimeException("Unsupported input file type");
            }
        }
    }

    int id = 0;
    for (Entry<String, String> e : bams.entrySet()) {
        String key = e.getKey();
        String bamFilePath = e.getValue();

        String baiFilePath = bais.get(key);
        if (baiFilePath == null) {
            throw new RuntimeException("Missing index for " + FilenameUtils.getName(bamFilePath));
        }

        SqwFile bam = this.createFile("file_in_" + id++);
        bam.setSourcePath(bamFilePath);
        bam.setType("application/bam");
        bam.setIsInput(true);

        SqwFile bai = this.createFile("file_in_" + id++);
        bai.setSourcePath(baiFilePath);
        bai.setType("application/bam-index");
        bai.setIsInput(true);

        //FIXME: this seems to work for now, it would be better to be able to set the provisionedPath as
        //bai.getProvisionedPath != bai.getOutputPath ...
        //at least with seqware 1.1.0, setting output path changes where the output file will be stored,
        //but the commonly used get provisioned path will return the incorrect path to the file
        bai.setOutputPath(FilenameUtils.getPath(bam.getProvisionedPath()));

        inputBamFiles.add(bam.getProvisionedPath());
    }

    return this.getFiles();
}

From source file:net.mitnet.tools.pdf.book.io.FileHelper.java

/**
 * Returns the path between a file and a parent directory/folder.
 * /*from ww  w  .ja v a  2s. co m*/
 * NOTE: The file must be a child of the parent.
 * 
 * For example,
 * if parentDir is "/home/users/nobody/spool/docs/input"
 * and file is "/home/users/nobody/spool/docs/input/a/b/c/test.odt"
 * the path to parent will be "a/b/c"
 * 
 * @param parentDir parent dir
 * @param file file relative to parent dir
 */
public static String getPathToParent(File parentDir, File file) {

    String pathToParent = null;

    if (parentDir != null && file != null) {
        // String fileName = file.getName();
        // int fileNameLength = fileName.length();
        String parentDirAbsolutePath = parentDir.getAbsolutePath();
        String fileAbsolutePath = file.getAbsolutePath();
        int parentDirAbsolutePathLength = parentDirAbsolutePath.length();
        // int fileAbsolutePathLength = fileAbsolutePath.length();
        String relativeFilePath = fileAbsolutePath.substring(parentDirAbsolutePathLength);
        // String relativePath = FilenameUtils.getPathNoEndSeparator(relativeFilePath);
        String relativePath = FilenameUtils.getPath(relativeFilePath);
        if (!StringUtils.isEmpty(relativePath)) {
            pathToParent = relativePath;
        }
    }

    return pathToParent;
}

From source file:eu.esdihumboldt.hale.common.core.io.PathUpdate.java

/**
 * Tries to find an existing readable URI.<br>
 * <ul>/* w  w  w.j  av  a  2  s  . c  om*/
 * <li>if the URI isn't absolute:
 * <ul>
 * <li>if a new location is available it is resolved against that</li>
 * <li>if an old location is available it is resolved against that</li>
 * </ul>
 * </li>
 * <li>if the URI is absolute:
 * <ul>
 * <li>if an old and a new location is available it is transformed in the
 * same way</li>
 * <li>the URI is used as is</li>
 * </ul>
 * </li>
 * </ul>
 * If none of the applicable cases results in a valid, existing URI and
 * tryFallback is true {@link #updatePathFallback(URI)} is returned,
 * otherwise <code>null</code> is returned.
 * 
 * @param uri the URI in question
 * @param tryFallback whether to use {@link #updatePathFallback(URI)} in the
 *            end or not
 * @param allowResource whether to allow resolving through {@link Resources}
 * @param keepRelative If the URI is relative to the new location and
 *            keepRelative is set, the URI is returned as is.<br>
 *            Also, if the URI is relative to the old location and it is
 *            possible to construct a relative path to the new location,
 *            that is returned
 * @return a valid, existing URI or <code>null</code>
 */
public URI findLocation(URI uri, boolean tryFallback, boolean allowResource, boolean keepRelative) {
    if ("jdbc".equals(uri.getScheme())) {
        // not possible to update JDBC URLs or test the stream
        return uri;
    }

    if (!uri.isAbsolute()) {
        if (newLocation != null) {
            URI newAbsolute = newLocation.resolve(uri);
            if (HaleIO.testStream(newAbsolute, allowResource)) {
                if (keepRelative) {
                    return uri;
                } else {
                    return newAbsolute;
                }
            } else {
                // Check if the resource file name needs
                // to be URL-encoded first (for project archives
                // that were created w/ hale studio 3.2.0 and before)
                String resourcePath = FilenameUtils.getPath(uri.toString());
                String resourceFileName = FilenameUtils.getName(uri.toString());
                try {
                    String encodedPath = resourcePath + URLEncoder.encode(resourceFileName, "UTF-8");
                    URI encodedUri = URI.create(encodedPath);
                    newAbsolute = newLocation.resolve(encodedUri);
                    if (HaleIO.testStream(newAbsolute, allowResource)) {
                        if (keepRelative) {
                            return encodedUri;
                        } else {
                            return newAbsolute;
                        }
                    }
                } catch (UnsupportedEncodingException e) {
                    log.debug(MessageFormat.format("Could not URL-encode \"{0}\"", resourceFileName), e);
                }
            }
        }
        if (oldLocation != null) {
            URI oldAbsolute = oldLocation.resolve(uri);
            if (HaleIO.testStream(oldAbsolute, allowResource)) {
                if (keepRelative)
                    return IOUtils.getRelativePath(oldAbsolute, newLocation);
                else
                    return oldAbsolute;
            }
        }
    } else {
        if (oldLocation != null && newLocation != null) {
            URI changed = changePath(uri);
            if (HaleIO.testStream(changed, allowResource))
                return changed;
        }
        if (HaleIO.testStream(uri, allowResource))
            return uri;
    }
    if (tryFallback)
        return updatePathFallback(uri);
    else
        return null;
}