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

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

Introduction

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

Prototype

public static String getFullPath(String filename) 

Source Link

Document

Gets the full path from a full filename, which is the prefix + path.

Usage

From source file:org.javabeanstack.io.IOUtil.java

/**
 * Devuelve el path de un archivo ejemplo c:/carpeta1/subcarpeta1/archivo.txt
 * retorna c:/carpeta1/subcarpeta1//*  ww w  . j  a v a 2s.  com*/
 * @param file nombre y path del archivo
 * @return el path del archivo
 */
public static String getFullPath(String file) {
    return FilenameUtils.getFullPath(file);
}

From source file:org.jboss.windup.util.RPMToZipTransformer.java

public static File convertRpmToZip(File file) throws Exception {
    LOG.info("File: " + file.getAbsolutePath());

    FileInputStream fis = new FileInputStream(file);
    ReadableChannelWrapper in = new ReadableChannelWrapper(Channels.newChannel(fis));

    InputStream uncompressed = new GZIPInputStream(fis);
    in = new ReadableChannelWrapper(Channels.newChannel(uncompressed));

    String rpmZipName = file.getName();
    rpmZipName = StringUtils.replace(rpmZipName, ".", "-");
    rpmZipName = rpmZipName + ".zip";
    String rpmZipPath = FilenameUtils.getFullPath(file.getAbsolutePath());

    File rpmZipOutput = new File(rpmZipPath + File.separator + rpmZipName);
    LOG.info("Converting RPM: " + file.getName() + " to ZIP: " + rpmZipOutput.getName());
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(rpmZipOutput));

    String rpmName = file.getName();
    rpmName = StringUtils.replace(rpmName, ".", "-");

    CpioHeader header;/* ww w. j ava2 s . c  o  m*/
    int total = 0;
    do {
        header = new CpioHeader();
        total = header.read(in, total);

        if (header.getFileSize() > 0) {
            BoundedInputStream bis = new BoundedInputStream(uncompressed, header.getFileSize());

            String relPath = FilenameUtils.separatorsToSystem(header.getName());
            relPath = StringUtils.removeStart(relPath, ".");
            relPath = StringUtils.removeStart(relPath, "/");
            relPath = rpmName + File.separator + relPath;
            relPath = StringUtils.replace(relPath, "\\", "/");

            ZipEntry zipEntry = new ZipEntry(relPath);
            zos.putNextEntry(zipEntry);
            IOUtils.copy(bis, zos);
        } else {
            final int skip = header.getFileSize();
            if (uncompressed.skip(skip) != skip)
                throw new RuntimeException("Skip failed.");
        }

        total += header.getFileSize();
    } while (!header.isLast());

    zos.flush();
    zos.close();

    return rpmZipOutput;
}

From source file:org.jodconverter.cli.CliConverter.java

/**
 * Converts the specified files. The output format are generate from the output filenames.
 *
 * @param inputFilenames An array containing the filenames of the files to convert.
 * @param outputFilenames An array containing the output filenames to convert into.
 * @param outputDirPath The directory where to create a converted file if not specified in the
 *     output filename. If null and the directory is not specified in the output filename, a
 *     converted file will be created into the same directory as the input files.
 * @param overwrite Indicates whether an output file that already exists must be overwritten.
 * @throws OfficeException If an error occurs while converting the files.
 *///from  ww w.ja v a2  s  .  c o m
public void convert(final String[] inputFilenames, final String[] outputFilenames, final String outputDirPath,
        final boolean overwrite) throws OfficeException {

    Validate.notEmpty(inputFilenames, "The validated input filenames array is empty");
    Validate.notEmpty(outputFilenames, "The validated output filenames array is empty");

    final int inputLength = inputFilenames.length;
    final int outputLength = outputFilenames.length;

    // Make sure lengths are ok, these need to be equal
    Validate.isTrue(inputLength == outputLength,
            "input filenames array length [%d]and output filenames array length[%d] don't match",
            inputLength, outputLength);

    // Prepare the output directory
    final File outputDir = outputDirPath == null ? null : new File(outputDirPath);
    prepareOutputDir(outputDir);

    // For all the input/output filename pairs...
    for (int i = 0; i < inputFilenames.length; i++) {

        // Get the input and output files
        final String inputFilename = inputFilenames[i];
        final String inputFullPath = FilenameUtils.getFullPath(inputFilename);
        final String outputFilename = outputFilenames[i];
        final String outputFullPath = FilenameUtils.getFullPath(outputFilename);
        final File outputDirectory = StringUtils.isBlank(outputFullPath) ? outputDir == null // NOSONAR
                ? StringUtils.isBlank(inputFullPath) // NOSONAR
                        ? new File(".")
                        : new File(inputFullPath)
                : outputDir : new File(outputFullPath);

        // Convert the file
        convertFile(new File(inputFilename), outputDirectory, FilenameUtils.getName(outputFilename), overwrite);
    }
}

From source file:org.jwebsocket.plugins.filesystem.FileSystemPlugIn.java

/**
 * Saves or appends a file, depends of the aToken.append (Boolean) arg.
 *
 * @param aConnector/* w  w  w.jav  a  2 s .  c o m*/
 * @param aToken
 */
private void mWrite(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();
    String lMsg;

    boolean lAppend = aToken.getBoolean("append");
    if (mLog.isDebugEnabled()) {
        mLog.debug("Processing '" + (lAppend ? "append" : "save") + "'...");
    }

    // check if user is allowed to run 'save' or 'append' command
    if (!hasAuthority(aConnector, NS_FILESYSTEM + "." + (lAppend ? "append" : "save"))) {
        if (mLog.isDebugEnabled()) {
            mLog.debug("Returning 'Access denied'...");
        }
        lServer.sendToken(aConnector, lServer.createAccessDenied(aToken));
        return;
    }
    String lAlias = aToken.getString("alias", PUBLIC_ALIAS_DIR_KEY);

    // instantiate response token
    Token lResponse = lServer.createResponse(aToken);

    // obtain required parameters for file load operation
    String lFilename = aToken.getString("filename");
    String lScope = aToken.getString("scope", JWebSocketCommonConstants.SCOPE_PRIVATE);

    // scope may be "private" or "public"
    String lBaseDir;
    if (JWebSocketCommonConstants.SCOPE_PRIVATE.equals(lScope)) {
        if (SESSION_ALIAS_DIR_KEY.equals(lAlias)) {
            lBaseDir = getAliasPath(aConnector, lAlias);
        } else if (UUID_ALIAS_DIR_KEY.equals(lAlias)) {
            lBaseDir = getAliasPath(aConnector, lAlias);
        } else {
            lBaseDir = getAliasPath(aConnector, PRIVATE_ALIAS_DIR_KEY);
        }
    } else if (JWebSocketCommonConstants.SCOPE_PUBLIC.equals(lScope)) {
        lBaseDir = getAliasPath(aConnector, lAlias);
    } else {
        lMsg = "invalid scope";
        if (mLog.isDebugEnabled()) {
            mLog.debug(lMsg);
        }
        lServer.sendErrorToken(aConnector, aToken, -1, lMsg);
        return;
    }

    Boolean lNotify = aToken.getBoolean("notify", false);
    String lData = aToken.getString("data", null);
    if (null == lData) {
        sendErrorToken(aConnector, aToken, -1, "Argument 'data' contains null value!");
        return;
    }

    String lEncoding = aToken.getString("encoding", "base64");
    Boolean lEncode = aToken.getBoolean("encode", false);
    byte[] lBA;
    if (!lEncode && "base64".equals(lEncoding)) {
        // supporting HTML5 readAsDataURL method
        int lIdx = lData.indexOf(',');
        if (lIdx >= 0) {
            lData = lData.substring(lIdx + 1);
        }
        lBA = Tools.base64Decode(lData);
        lData = null;
    } else {
        lBA = lData.getBytes();
    }

    String lFullPath = lBaseDir + lFilename;
    File lFile = new File(lFullPath);
    try {
        if (!isPathInFS(lFile, lBaseDir)) {
            sendErrorToken(aConnector, aToken, -1,
                    "The file '" + lFilename + "' is out of the file-system location!");
            return;
        }

        checkForSave(aConnector, lFile, lBA);
        // prevent two threads at a time writing to the same file
        synchronized (this) {
            // force create folder if not yet exists
            File lDir = new File(FilenameUtils.getFullPath(lFullPath));
            FileUtils.forceMkdir(lDir);
            if (lData == null) {
                FileUtils.writeByteArrayToFile(lFile, lBA, lAppend);
            } else {
                FileUtils.writeStringToFile(lFile, lData, "UTF-8", lAppend);
            }
        }
    } catch (Exception lEx) {
        lResponse.setInteger("code", -1);
        lMsg = lEx.getClass().getSimpleName() + " while saving file: " + lFilename + ". " + lEx.getMessage();
        lResponse.setString("msg", lMsg);
        mLog.error(lMsg);
    }
    // send response to requester
    lServer.sendToken(aConnector, lResponse);

    // send notification event to other affected clients
    // to allow to update their content (if desired)
    Token lEvent;
    // create token of type "event"
    lEvent = TokenFactory.createToken(BaseToken.TT_EVENT);
    lEvent.setNS(NS_FILESYSTEM);
    lEvent.setString("name", lAppend ? "fileappended" : "filesaved");
    lEvent.setString("filename", lFilename);
    lEvent.setString("sourceId", aConnector.getId());

    if (lNotify) {
        if (lScope.equals(JWebSocketCommonConstants.SCOPE_PUBLIC)) {
            lServer.broadcastToken(lEvent);
        } else {
            // notify requester if desired
            lServer.sendToken(aConnector, lEvent);
        }
    }
}

From source file:org.jwebsocket.plugins.mail.MailPlugInService.java

/**
 *
 * @param aConnector// ww w .j  av a  2  s  .  c o  m
 * @param aToken
 * @param aResponse
 * @param aServer
 * @param aPlugInNS
 */
public void addAttachment(WebSocketConnector aConnector, Token aToken, Token aResponse, TokenServer aServer,
        String aPlugInNS) {
    String lId = aToken.getString("id");
    String lFilename = aToken.getString("filename");
    String lData = aToken.getString("data");
    String lEncoding = aToken.getString("encoding", "base64");
    String lMsg;

    Token lMailStoreToken = mMailStore.getMail(lId);
    if (null == lMailStoreToken) {
        lMsg = "No mail with id '" + lId + "' found.";
        if (mLog.isDebugEnabled()) {
            mLog.debug(lMsg);
        }
        aResponse.setInteger("code", -1);
        aResponse.setString("msg", lMsg);
        // send error response to requester
        aServer.sendToken(aConnector, aResponse);
        return;
    }

    byte[] lBA = null;
    try {
        if ("base64".equals(lEncoding)) {
            int lIdx = lData.indexOf(',');
            if (lIdx >= 0) {
                lData = lData.substring(lIdx + 1);
            }
            lBA = Base64.decodeBase64(lData);
        } else {
            lBA = lData.getBytes("UTF-8");
        }
    } catch (UnsupportedEncodingException lEx) {
        mLog.error(lEx.getClass().getSimpleName() + " on save: " + lEx.getMessage());
    }

    String lBaseDir;
    String lUsername = aServer.getUsername(aConnector);
    lBaseDir = mSettings.getMailRoot();
    if (lUsername != null) {
        lBaseDir = FilenameUtils
                .getFullPath(JWebSocketConfig.expandEnvVarsAndProps(lBaseDir).replace("{username}", lUsername));
    }

    // complete the response token
    String lFullPath = lBaseDir + lFilename;
    File lFile = new File(lFullPath);
    try {
        // prevent two threads at a time writing to the same file
        synchronized (this) {
            // force create folder if not yet exists
            File lDir = new File(FilenameUtils.getFullPath(lFullPath));
            FileUtils.forceMkdir(lDir);
            if (lBA != null) {
                FileUtils.writeByteArrayToFile(lFile, lBA);
            } else {
                FileUtils.writeStringToFile(lFile, lData, "UTF-8");
            }
        }
        List<Object> lAttachments = lMailStoreToken.getList("attachments");
        if (null == lAttachments) {
            lAttachments = new FastList<Object>();
            lMailStoreToken.setList("attachments", lAttachments);
        }
        lAttachments.add(lFile.getAbsolutePath());

        mMailStore.storeMail(lMailStoreToken);

        Token lSplitToken = archiveAttachments(aConnector, aToken, lMailStoreToken, lBaseDir, aServer,
                aPlugInNS);

    } catch (IOException lEx) {
        aResponse.setInteger("code", -1);
        lMsg = lEx.getClass().getSimpleName() + " on save: " + lEx.getMessage();
        aResponse.setString("msg", lMsg);
        mLog.error(lMsg);
    }
}

From source file:org.kalypso.utils.shape.ShapeUtilities.java

/**
 * This function copies the files of a shape to the destination folder.
 *
 * @param shapeFile/*  ww w  .j a  v a  2s .  co m*/
 *          One of the shape files. The others will be determined by removing the file extension and listing the files
 *          of the parent with the same basename.
 * @param destinationDirectory
 *          To this directory the shape will be copied.
 * @param destinationBasename
 *          The basename for the destination files of the shape.
 * @return The copied files (only their filenames).
 */
public static String[] copyShape(final File shapeFile, final File destinationDirectory,
        final String destinationBasename) throws IOException {
    /* The shape parameter is not allowed to be a directory. */
    if (shapeFile.isDirectory())
        throw new IllegalArgumentException(Messages.getString("ShapeUtilities_0")); //$NON-NLS-1$

    /* The destination parameter must be a directory. */
    if (!destinationDirectory.isDirectory())
        throw new IllegalArgumentException(Messages.getString("ShapeUtilities_1")); //$NON-NLS-1$

    /* Source. */
    final File shapeDirectory = new File(FilenameUtils.getFullPath(shapeFile.getAbsolutePath()));

    /* Get all filenames of the files from shape (e.g. get all filenames with the same basename specified). */
    final String[] filenames = shapeDirectory
            .list(new BasenameFilenameFilter(FilenameUtils.getBaseName(shapeFile.getName())));

    /* Copy all found files. */
    final List<String> files = new ArrayList<>();
    for (final String filename : filenames) {
        /* The filenames. */
        final String sourceFilename = filename;
        String destinationFilename = filename;

        /* If a destination basename is given, use it. */
        if (destinationBasename != null && destinationBasename.length() > 0) {
            final String extension = FilenameUtils.getExtension(filename);
            destinationFilename = destinationBasename + "." + extension; //$NON-NLS-1$
        }

        /* The files. */
        final File source = new File(shapeDirectory, sourceFilename);
        final File destination = new File(destinationDirectory, destinationFilename);

        /* Copy. */
        FileUtils.copyFile(source, destination);

        /* This one was copied. */
        files.add(destinationFilename);
    }

    return files.toArray(new String[] {});
}

From source file:org.kalypso.utils.shape.ShapeUtilities.java

/**
 * This function deletes the files of a shape.
 *
 * @param shapeFile//from  w w w .ja  v a2 s . co m
 *          One of the shape files. The others will be determined by removing the file extension and listing the files
 *          of the parent with the same basename.
 */
public static void deleteShape(final File shapeFile) {
    /* The shape parameter is not allowed to be a directory. */
    if (shapeFile.isDirectory())
        throw new IllegalArgumentException(Messages.getString("ShapeUtilities_3")); //$NON-NLS-1$

    /* The shape directory. */
    final File shapeDirectory = new File(FilenameUtils.getFullPath(shapeFile.getAbsolutePath()));

    /* Get all filenames of the files from shape (e.g. get all filenames with the same basename specified). */
    final String[] filenames = shapeDirectory
            .list(new BasenameFilenameFilter(FilenameUtils.getBaseName(shapeFile.getName())));

    /* Delete all found files. */
    for (final String filename : filenames) {
        /* The files. */
        final File file = new File(shapeDirectory, filename);

        /* Delete. */
        file.delete();
    }
}

From source file:org.kitodo.production.services.file.FileService.java

private void removePrefixFromRelatedMetsAnchorFilesFor(URI temporaryMetadataFilename) throws IOException {
    File temporaryFile = new File(temporaryMetadataFilename);
    File directoryPath = new File(temporaryFile.getParentFile().getPath());
    for (File temporaryAnchorFile : listFiles(directoryPath)) {
        String temporaryAnchorFileName = temporaryAnchorFile.toString();
        if (temporaryAnchorFile.isFile()
                && FilenameUtils.getBaseName(temporaryAnchorFileName).startsWith(TEMPORARY_FILENAME_PREFIX)) {
            String anchorFileName = FilenameUtils.concat(FilenameUtils.getFullPath(temporaryAnchorFileName),
                    temporaryAnchorFileName.replace(TEMPORARY_FILENAME_PREFIX, ""));
            temporaryAnchorFileName = FilenameUtils.concat(FilenameUtils.getFullPath(temporaryAnchorFileName),
                    temporaryAnchorFileName);
            renameFile(Paths.get(temporaryAnchorFileName).toUri(),
                    new File(anchorFileName).toURI().getRawPath());
        }/*from  w w  w.j a  v  a2 s  .c  o m*/
    }
}

From source file:org.kitodo.services.file.FileService.java

private void removePrefixFromRelatedMetsAnchorFilesFor(URI temporaryMetadataFilename) throws IOException {
    File temporaryFile = new File(temporaryMetadataFilename);
    File directoryPath = new File(temporaryFile.getParentFile().getPath());
    for (File temporaryAnchorFile : listFiles(directoryPath)) {
        String temporaryAnchorFileName = temporaryAnchorFile.toString();
        if (temporaryAnchorFile.isFile()
                && FilenameUtils.getBaseName(temporaryAnchorFileName).startsWith(TEMPORARY_FILENAME_PREFIX)) {
            String anchorFileName = FilenameUtils.concat(FilenameUtils.getFullPath(temporaryAnchorFileName),
                    temporaryAnchorFileName.replace(TEMPORARY_FILENAME_PREFIX, ""));
            temporaryAnchorFileName = FilenameUtils.concat(FilenameUtils.getFullPath(temporaryAnchorFileName),
                    temporaryAnchorFileName);
            renameFile(URI.create(anchorFileName), temporaryAnchorFileName);
        }//w  ww. j ava2 s.c om
    }
}

From source file:org.kitodo.services.ProcessService.java

private void removePrefixFromRelatedMetsAnchorFilesFor(String temporaryMetadataFilename) throws IOException {
    SafeFile temporaryFile = new SafeFile(temporaryMetadataFilename);
    SafeFile directoryPath = new SafeFile(temporaryFile.getParentFile().getPath());
    for (SafeFile temporaryAnchorFile : directoryPath.listFiles()) {
        String temporaryAnchorFileName = temporaryAnchorFile.toString();
        if (temporaryAnchorFile.isFile()
                && FilenameUtils.getBaseName(temporaryAnchorFileName).startsWith(TEMPORARY_FILENAME_PREFIX)) {
            String anchorFileName = FilenameUtils.concat(FilenameUtils.getFullPath(temporaryAnchorFileName),
                    temporaryAnchorFileName.replace(TEMPORARY_FILENAME_PREFIX, ""));
            temporaryAnchorFileName = FilenameUtils.concat(FilenameUtils.getFullPath(temporaryAnchorFileName),
                    temporaryAnchorFileName);
            FilesystemHelper.renameFile(temporaryAnchorFileName, anchorFileName);
        }/*from w  w  w  .j  a v  a2  s.c  o  m*/
    }
}