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

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

Introduction

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

Prototype

public static String getFullPathNoEndSeparator(String filename) 

Source Link

Document

Gets the full path from a full filename, which is the prefix + path, and also excluding the final directory separator.

Usage

From source file:org.pentaho.platform.repository.RepositoryFilenameUtils.java

/**
 * Gets the full path from a full filename, which is the prefix + path, and also excluding the final directory
 * separator.//from ww  w  .j  a  v a 2  s.  c om
 * <p/>
 * This method will handle a file in either Unix or Windows format. The method is entirely text based, and
 * returns the text before the last forward or backslash.
 * 
 * <pre>
 * a.txt        --> ""
 * a/b/c        --> a/b
 * a/b/c/       --> a/b/c
 * /a.txt       --> /
 * /a/b/c       --> /a/b
 * /a/b/c/      --> /a/b/c
 * </pre>
 * <p/>
 * The output will be the same irrespective of the machine that the code is running on.
 * 
 * @param filename
 *          the filename to query, null returns null
 * @return the path of the file, an empty string if none exists, null if invalid
 */
public static String getFullPathNoEndSeparator(final String filename) {
    return FilenameUtils.getFullPathNoEndSeparator(filename);
}

From source file:org.pentaho.platform.repository2.mt.RepositoryTenantManager.java

@Override
public ITenant createTenant(final ITenant parentTenant, final String tenantName,
        final String tenantAdminRoleName, final String authenticatedRoleName, final String anonymousRoleName) {
    Tenant newTenant;/* w w w  . j a  va2s  . c om*/
    String parentTenantFolder;
    if (parentTenant == null) {
        if (repositoryFileDao.getFileByAbsolutePath("/" + tenantName) != null) {
            return null;
        }
    } else {
        if (repositoryFileDao
                .getFileByAbsolutePath(parentTenant.getRootFolderAbsolutePath() + "/" + tenantName) != null) {
            return null;
        }
    }
    if (parentTenant == null) {
        newTenant = new Tenant(RepositoryFile.SEPARATOR + tenantName, true);
        parentTenantFolder = "/";
    } else {
        newTenant = new Tenant(parentTenant.getRootFolderAbsolutePath() + RepositoryFile.SEPARATOR + tenantName,
                true);
        parentTenantFolder = parentTenant.getRootFolderAbsolutePath();
    }

    String tenantCreatorId = PentahoSessionHolder.getSession().getName();
    RepositoryFile tenantRootFolder = createTenantFolder(parentTenant, tenantName, tenantCreatorId);

    userRoleDao.createRole(newTenant, tenantAdminRoleName, "", new String[0]);
    userRoleDao.createRole(newTenant, authenticatedRoleName, "", new String[0]);
    userRoleDao.createRole(newTenant, anonymousRoleName, "", new String[0]);
    roleBindingDao.setRoleBindings(newTenant, authenticatedRoleName,
            singleTenantAuthenticatedAuthorityRoleBindingList);

    String tenantAdminRoleId = tenantedRoleNameResolver.getPrincipleId(newTenant, tenantAdminRoleName);
    RepositoryFileSid tenantAdminRoleSid = new RepositoryFileSid(tenantAdminRoleId, Type.ROLE);

    this.jcrTemplate.save();
    // If parent tenant is null then we assume we're creating the system tenant. In which case we'll give the
    // system
    // tenant admin permissions on the root folder.
    if (parentTenant == null) {
        repositoryFileAclDao.addAce(tenantRootFolder.getId(), tenantAdminRoleSid,
                EnumSet.of(RepositoryFilePermission.ALL));
    } else {

        RepositoryFileAcl acl = repositoryFileAclDao.getAcl(tenantRootFolder.getId());
        Builder aclBuilder = new RepositoryFileAcl.Builder(acl).ace(tenantAdminRoleSid,
                EnumSet.of(RepositoryFilePermission.ALL));

        IPentahoSession origPentahoSession = PentahoSessionHolder.getSession();
        Authentication origAuthentication = SecurityContextHolder.getContext().getAuthentication();
        login(repositoryAdminUsername, tenantAdminRoleId);
        try {
            // Give all to Tenant Admin of all ancestors
            while (!parentTenantFolder.equals("/")) {
                ITenant tenant = new Tenant(parentTenantFolder, true);
                String parentTenantAdminRoleId = tenantedRoleNameResolver.getPrincipleId(tenant,
                        tenantAdminRoleName);
                RepositoryFileSid parentTenantAdminSid = new RepositoryFileSid(parentTenantAdminRoleId,
                        Type.ROLE);
                aclBuilder.ace(parentTenantAdminSid, EnumSet.of(RepositoryFilePermission.ALL));
                parentTenantFolder = FilenameUtils.getFullPathNoEndSeparator(parentTenantFolder);
            }
            repositoryFileAclDao.updateAcl(aclBuilder.build());
        } catch (Throwable th) {
            th.printStackTrace();
        } finally {
            PentahoSessionHolder.setSession(origPentahoSession);
            SecurityContextHolder.getContext().setAuthentication(origAuthentication);
        }
    }

    try {
        RepositoryFileSid fileOwnerSid = new RepositoryFileSid(tenantCreatorId);
        createInitialTenantFolders(newTenant, tenantRootFolder, fileOwnerSid);
    } catch (Exception ex) {
        throw new RuntimeException("Error creating initial tenant folders", ex);
    }
    return newTenant;
}

From source file:org.pentaho.platform.repository2.unified.fileio.RepositoryContentOutputHandler.java

public IContentItem getFileOutputContentItem() {
    String filePath = getSolutionPath();
    if (StringUtils.isEmpty(filePath)) {
        filePath = getContentRef();/*from w  ww .  ja  v a2 s .  co  m*/
    }
    if (filePath.startsWith("~/") || filePath.startsWith("~\\") || filePath.equals("~")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        filePath = ClientRepositoryPaths.getUserHomeFolderPath(getSession().getName()) + "/"; //$NON-NLS-1$
        filePath = filePath + (getSolutionPath().length() > 1 ? getSolutionPath().substring(2)
                : getSolutionPath().substring(1));
    }

    filePath = replaceIllegalChars(filePath);

    IContentItem contentItem = null;
    String requestedFileExtension = MimeHelper.getExtension(getMimeType());
    if (requestedFileExtension == null) {
        contentItem = new RepositoryFileContentItem(filePath);
    } else {
        String tempFilePath = FilenameUtils.getFullPathNoEndSeparator(filePath) + "/"
                + FilenameUtils.getBaseName(filePath) + requestedFileExtension;
        contentItem = new RepositoryFileContentItem(tempFilePath);
    }
    return contentItem;
}

From source file:org.pentaho.platform.repository2.unified.fileio.RepositoryFileOutputHandler.java

public IContentItem getOutputContentItem(final String outputName, final String contentName,
        final String instanceId, final String localMimeType) {
    IContentItem outputContentItem = null;
    if (outputName.equals(IOutputHandler.RESPONSE) && contentName.equals(IOutputHandler.CONTENT)) {
        String requestedFileExtension = MimeHelper.getExtension(localMimeType);
        String currentExtension = FilenameUtils.getExtension(outputStream.getFilePath());
        if (requestedFileExtension == null) {
            if (currentExtension != null) {
                String tempFilePath = FilenameUtils.getFullPathNoEndSeparator(outputStream.getFilePath()) + "/"
                        + FilenameUtils.getBaseName(outputStream.getFilePath());
                outputStream.setFilePath(tempFilePath);
                outputContentItem = new RepositoryFileContentItem(outputStream);
            } else {
                outputContentItem = new RepositoryFileContentItem(outputStream);
            }/*from w w  w .  ja  va2s  .c om*/
        } else if (!requestedFileExtension.substring(1).equals(currentExtension.toLowerCase())) {
            String tempFilePath = FilenameUtils.getFullPathNoEndSeparator(outputStream.getFilePath()) + "/"
                    + FilenameUtils.getBaseName(outputStream.getFilePath()) + requestedFileExtension;
            outputStream.setFilePath(tempFilePath);
            outputContentItem = new RepositoryFileContentItem(outputStream);
        } else {
            outputContentItem = new RepositoryFileContentItem(outputStream);
        }
        responseExpected = true;
    } else {
        IContentOutputHandler output = PentahoSystem.getOutputDestinationFromContentRef(contentName, session);
        // If the output handler wasn't found with just the content name. Try to look it up with the output name as
        // well.
        // (This mirrors HttpOutputHandler's lookup logic)
        if (output == null) {
            output = PentahoSystem.getOutputDestinationFromContentRef(outputName + ":" + contentName, session); //$NON-NLS-1$
        }
        if (output != null) {
            output.setSession(PentahoSessionHolder.getSession());
            output.setInstanceId(instanceId);
            String filePath = "~/workspace/" + contentName; //$NON-NLS-1$
            if (contentName.startsWith("/")) {
                filePath = contentName;
            }
            output.setSolutionPath(filePath);
            output.setMimeType(localMimeType);
            outputContentItem = output.getFileOutputContentItem();
        }
    }
    return outputContentItem;
}

From source file:org.pentaho.platform.repository2.unified.fs.FileSystemRepositoryFileDao.java

public Map<String, Serializable> getFileMetadata(final Serializable fileId) {
    final String metadataFilename = FilenameUtils.concat(
            FilenameUtils.concat(FilenameUtils.getFullPathNoEndSeparator(fileId.toString()), ".metadata"),
            FilenameUtils.getName(fileId.toString()));
    final Map<String, Serializable> metadata = new HashMap<String, Serializable>();
    BufferedReader reader = null;
    try {/* www.j  a  v a2s  . c om*/
        reader = new BufferedReader(new FileReader(metadataFilename));
        String data = reader.readLine();
        while (data != null) {
            final int pos = data.indexOf('=');
            if (pos > 0) {
                final String key = data.substring(0, pos);
                final String value = (data.length() > pos ? data.substring(pos + 1) : null);
                metadata.put(key, value);
            }
            data = reader.readLine();
        }
    } catch (FileNotFoundException e) {
        // Do nothing ... metadata empty
    } catch (IOException e) {
        throw new UnifiedRepositoryException("Error reading metadata [" + fileId + "]", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }
    return metadata;
}

From source file:org.pepstock.jem.node.security.SecurityUtils.java

/**
 * Checks if the file name must be checked, ignored or rejected 
 * //from www .  j  a  v  a2 s .  c o  m
 * @param fileName to check!
 * @return if authorized or must be checked
 */
public int checkWriteFileName(String fileName) {
    // to write a "root.properties" file is not allowed
    // because that file is use for GDG to maintain the catalog
    // and the risk is to create an inconsistent situation on GDG
    if (fileName.endsWith(Root.ROOT_FILE_NAME)) {
        return TO_BE_REJECTED;
    }

    // checks if filename is located on a data paths
    String dataPath = DataPathsContainer.getInstance().getAbsoluteDataPath(fileName);
    // if yes (not null!) the permission must be checked
    if (dataPath != null) {
        return TO_BE_CHECKED;
    }

    // gets if you are going on toher GFS file systems
    boolean gfsFolder = fileName.startsWith(LIBRARY_PATH) || fileName.startsWith(BINARY_PATH)
            || fileName.startsWith(CLASS_PATH) || fileName.startsWith(SOURCE_PATH);

    // if yes, ad additional permission check must be performed (the user must have
    // the GFS file system permission)
    if (gfsFolder) {
        return TO_BE_GFS_CHECKED;
    }

    // if you're using the temporary folder, GO! No check
    if (fileName.startsWith(temp)) {
        return TO_BE_IGNORED;
    }

    // if you're trying to access to the output path
    if (fileName.startsWith(OUTPUT_PATH)) {
        // checks if you're access to the OUTPUT path, not to the sub folder
        // because subfolder are ALWAYS accessible in write because used to write
        // user data as SYSOUT
        if (FilenameUtils.getFullPathNoEndSeparator(fileName).equalsIgnoreCase(OUTPUT_PATH)) {
            String file = FilenameUtils.getName(fileName);
            // checks you are trying to write on the system files,
            // files managed by JEM node. This is NOT allowed.
            // throws a SECURITY exception
            if (OutputSystem.JCL_FILE.equalsIgnoreCase(file) || OutputSystem.JOB_FILE.equalsIgnoreCase(file)
                    || OutputSystem.JOBLOG_FILE.equalsIgnoreCase(file)
                    || OutputSystem.MESSAGESLOG_FILE.equalsIgnoreCase(file)) {
                return TO_BE_REJECTED;
            }
        }
        // if here, you can write on OUTPUT path
        return TO_BE_IGNORED;
    }

    // if you are trying to write on JEM home.
    // This is NOT allowed.
    // throws a SECURITY exception
    if (fileName.startsWith(HOME)) {
        return TO_BE_REJECTED;
    }

    // if you are trying to write on persistent path.
    // This is NOT allowed.
    // throws a SECURITY exception
    if (fileName.startsWith(PERSISTENCE_PATH)) {
        return TO_BE_REJECTED;
    }

    // if arrives here, means is local file system
    return TO_BE_LOCAL_FS_CHECKED;
}

From source file:org.pgptool.gui.encryptionparams.impl.EncryptionParamsStorageImpl.java

@Override
public void persistDialogParametersForCurrentInputs(EncryptionDialogParameters dialogParameters,
        boolean updateFolderSettings) {
    encryptionParams.put(dialogParameters.getSourceFile(), dialogParameters);
    if (updateFolderSettings) {
        encryptionParams.put(FilenameUtils.getFullPathNoEndSeparator(dialogParameters.getSourceFile()),
                dialogParameters);//from  ww  w .  j av  a2s  .  c om
    }
}

From source file:org.pgptool.gui.encryptionparams.impl.EncryptionParamsStorageImpl.java

@Override
public EncryptionDialogParameters findParamsBasedOnSourceFile(String sourceFile,
        boolean fallBackToFolderSettingsIfAny) {
    EncryptionDialogParameters params = encryptionParams.find(sourceFile, null);
    if (fallBackToFolderSettingsIfAny && params == null) {
        params = encryptionParams.find(FilenameUtils.getFullPathNoEndSeparator(sourceFile), null);
    }//from   w ww. j  a v a 2 s .  com
    return params;
}

From source file:org.pgptool.gui.tools.fileswatcher.MultipleFilesWatcher.java

public void watchForFileChanges(String filePathName) {
    try {//from ww  w .j av a  2s.c  o  m
        String baseFolderStr = FilenameUtils.getFullPathNoEndSeparator(filePathName);
        String relativeFilename = FilenameUtils.getName(filePathName);

        synchronized (watcherName) {
            BaseFolder baseFolder = baseFolders.get(baseFolderStr);
            if (baseFolder != null) {
                log.debug("Parent directory is already being watched " + baseFolderStr
                        + ", will just add file to watch " + relativeFilename);
                baseFolder.interestedFiles.add(relativeFilename);
                return;
            }

            Path path = Paths.get(baseFolderStr);
            WatchKey key = path.register(watcher, ENTRY_DELETE, ENTRY_MODIFY, ENTRY_CREATE);
            baseFolder = new BaseFolder(baseFolderStr, key, path, relativeFilename);

            keys.put(key, baseFolder);
            baseFolders.put(baseFolderStr, baseFolder);

            log.debug("New watch key created for folder " + baseFolderStr + ", add first file "
                    + relativeFilename);
        }
    } catch (Throwable t) {
        log.error("Failed to watch file " + filePathName, t);
        // not goinf to ruin app workflow
    }
}

From source file:org.pgptool.gui.tools.fileswatcher.MultipleFilesWatcher.java

public void stopWatchingFile(String filePathName) {
    try {//from  w  ww  .j  a v a2  s .co  m
        String baseFolderStr = FilenameUtils.getFullPathNoEndSeparator(filePathName);
        String relativeFilename = FilenameUtils.getName(filePathName);

        synchronized (watcherName) {
            BaseFolder baseFolder = baseFolders.get(baseFolderStr);
            if (baseFolder == null) {
                log.debug("No associated watchers found for " + baseFolderStr);
                return;
            }

            baseFolder.interestedFiles.remove(relativeFilename);
            log.debug("File is no longer watched in folder " + baseFolderStr + " file " + relativeFilename);
            if (baseFolder.interestedFiles.size() > 0) {
                return;
            }

            // NOTE: Decided to turn this off, because file might re-appear in case it's app
            // re-created it. See #91, #75
            // keys.remove(baseFolder.key);
            // baseFolders.remove(baseFolder.folder);
            // baseFolder.key.cancel();
            // log.debug("Folder watch key is canceled " + baseFolderStr);
        }
    } catch (Throwable t) {
        log.error("Failed to watch file " + filePathName, t);
        // not goinf to ruin app workflow
    }
}