Example usage for java.nio.file Path startsWith

List of usage examples for java.nio.file Path startsWith

Introduction

In this page you can find the example usage for java.nio.file Path startsWith.

Prototype

default boolean startsWith(String other) 

Source Link

Document

Tests if this path starts with a Path , constructed by converting the given path string, in exactly the manner specified by the #startsWith(Path) startsWith(Path) method.

Usage

From source file:org.tinymediamanager.core.ImageCache.java

/**
 * Gets the cached file, if ImageCache is activated<br>
 * If not found, cache original first/*from ww w.j a  v a2  s.c  o m*/
 * 
 * @param path
 *          the path
 * @return the cached file
 */
public static Path getCachedFile(Path path) {
    if (path == null) {
        return null;
    }
    path = path.toAbsolutePath();

    Path cachedFile = ImageCache.getCacheDir()
            .resolve(getMD5(path.toString()) + "." + Utils.getExtension(path));
    if (Files.exists(cachedFile)) {
        LOGGER.trace("found cached file :) " + path);
        return cachedFile;
    }

    // TODO: when does this happen?!?!
    // is the path already inside the cache dir? serve direct
    if (path.startsWith(CACHE_DIR.toAbsolutePath())) {
        return path;
    }

    // is the image cache activated?
    if (!Globals.settings.isImageCache()) {
        LOGGER.trace("ImageCache not activated - return original file 1:1");
        return path;
    }

    try {
        Path p = ImageCache.cacheImage(path);
        LOGGER.trace("cached file successfully :) " + p);
        return p;
    } catch (EmptyFileException e) {
        LOGGER.warn("failed to cache file (file is empty): " + path);
    } catch (FileNotFoundException e) {
        LOGGER.trace(e.getMessage());
    } catch (Exception e) {
        LOGGER.warn("problem caching file: " + e.getMessage());
    }

    // fallback
    return path;
}

From source file:org.orderofthebee.addons.support.tools.share.LogFileHandler.java

/**
 * Validates a single log file path and resolves it to a file handle.
 *
 * @param filePath//from   w w  w .  ja  v  a 2  s  .c o  m
 *            the file path to validate
 * @return the resolved file handle if the file path is valid and allowed to be accessed
 *
 * @throws WebScriptException
 *             if access to the log file is prohibited
 */
protected static File validateFilePath(final String filePath) {
    ParameterCheck.mandatoryString("filePath", filePath);

    final Path path = Paths.get(filePath);
    boolean pathAllowed = false;
    final List<Logger> allLoggers = LogFileHandler.getAllLoggers();

    for (final Logger logger : allLoggers) {
        @SuppressWarnings("unchecked")
        final Enumeration<Appender> allAppenders = logger.getAllAppenders();
        while (allAppenders.hasMoreElements() && !pathAllowed) {
            final Appender appender = allAppenders.nextElement();
            if (appender instanceof FileAppender) {
                final String appenderFile = ((FileAppender) appender).getFile();
                final File configuredFile = new File(appenderFile);
                final Path configuredFilePath = configuredFile.toPath().toAbsolutePath().getParent();
                pathAllowed = pathAllowed || (path.startsWith(configuredFilePath)
                        && path.getFileName().toString().startsWith(configuredFile.getName()));
            }
        }
    }

    if (!pathAllowed) {
        throw new WebScriptException(Status.STATUS_FORBIDDEN, "The log file path " + filePath
                + " could not be resolved to a valid log file - access to any other file system contents is forbidden via this web script");
    }

    final File file = path.toFile();

    if (!file.exists()) {
        throw new WebScriptException(Status.STATUS_NOT_FOUND,
                "The log file path " + filePath + " could not be resolved to an existing log file");
    }

    return file;
}

From source file:org.apache.storm.daemon.logviewer.utils.LogFileDownloader.java

/**
 * Checks authorization for the log file and download.
 *
 * @param fileName file to download/* www .  j a v  a2  s . c  o  m*/
 * @param user username
 * @param isDaemon true if the file is a daemon log, false if the file is an worker log
 * @return a Response which lets browsers download that file.
 */
public Response downloadFile(String fileName, String user, boolean isDaemon) throws IOException {
    Path rootDir = isDaemon ? daemonLogRoot : logRoot;
    Path rawFile = rootDir.resolve(fileName);
    Path file = rawFile.toAbsolutePath().normalize();
    if (!file.startsWith(rootDir) || !rawFile.normalize().toString().equals(rawFile.toString())) {
        //Ensure filename doesn't contain ../ parts 
        return LogviewerResponseBuilder.buildResponsePageNotFound();
    }
    if (isDaemon && Paths.get(fileName).getNameCount() != 1) {
        //Prevent daemon log reads from pathing into worker logs
        return LogviewerResponseBuilder.buildResponsePageNotFound();
    }

    if (file.toFile().exists()) {
        if (isDaemon || resourceAuthorizer.isUserAllowedToAccessFile(user, fileName)) {
            fileDownloadSizeDistMb.update(Math.round((double) file.toFile().length() / FileUtils.ONE_MB));
            return LogviewerResponseBuilder.buildDownloadFile(file.toFile(), numFileDownloadExceptions);
        } else {
            return LogviewerResponseBuilder.buildResponseUnauthorizedUser(user);
        }
    } else {
        return LogviewerResponseBuilder.buildResponsePageNotFound();
    }
}

From source file:org.xenmaster.web.TemplateHook.java

@Override
public void handle(RequestBundle rb) throws IOException {
    if (rb.getPathParts().length < 1) {
        return;/*  ww w .j a va2s . co  m*/
    }
    String path = "";
    try {
        String concat = StringUtils.join(rb.getPathParts(), '/');
        URI uri = new URI(concat);
        uri = uri.normalize();
        path = uri.getPath();
    } catch (URISyntaxException ex) {
        Logger.getLogger(getClass()).error(ex);
    }
    if (path.isEmpty()) {
        return;
    }

    path = Settings.getInstance().getString("WebContentPath") + "/" + this.getSelector() + "/" + path;
    File f = new File(path);
    if (f.exists() && f.isDirectory()) {
        Path p = f.toPath();
        JsonObject contentTree = new JsonObject();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(p)) {
            for (Path file : stream) {
                if (file.toFile().isFile() && !file.startsWith(".")) {
                    contentTree.addProperty(FilenameUtils.getBaseName(file.toString()),
                            IOUtils.toString(new FileInputStream(file.toFile())));
                }
            }
        }
        Gson gson = new Gson();
        rb.replyWithString(gson.toJson(contentTree));
    }
}

From source file:com.dancorder.Archiverify.SynchingVisitor.java

private boolean isNotInErrorPath(Path relativeFilePath) {
    return errorPath == null || !relativeFilePath.startsWith(errorPath);
}

From source file:ezbake.deployer.publishers.artifact.ArtifactContentsPublisher.java

protected boolean doesResourceAlreadyExistInArtifact(java.nio.file.Path artifactPath,
        java.nio.file.Path artifactBasePath, byte[] artifact) throws DeploymentException {

    try (org.apache.commons.compress.archivers.tar.TarArchiveInputStream tais = new org.apache.commons.compress.archivers.tar.TarArchiveInputStream(
            new org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream(
                    new java.io.ByteArrayInputStream(artifact)))) {

        org.apache.commons.compress.archivers.ArchiveEntry nextEntry;
        while ((nextEntry = tais.getNextEntry()) != null) {

            if (nextEntry.isDirectory())
                continue;

            java.nio.file.Path entryPath = java.nio.file.Paths.get(nextEntry.getName());
            if (!entryPath.startsWith(artifactBasePath))
                continue;

            if (entryPath.compareTo(artifactPath) == 0) {
                return true;
            }// w  ww  . j  a v  a 2  s .c  o m
        }
    } catch (java.io.IOException e) {
        throw new DeploymentException(e.getMessage());
    }
    return false;
}

From source file:com.blackducksoftware.integration.hub.detect.workflow.diagnostic.RelevantFileTracker.java

private boolean isChildOfTrackedFolder(final File file) {
    final Path filePath = file.toPath();
    return Stream.of(relevantDirectory).anyMatch(trackedFile -> filePath.startsWith(trackedFile.toPath()));
}

From source file:net.larry1123.elec.util.logger.LoggerDirectoryHandler.java

/**
 * Checks if the path is not null and is in the right directory
 *
 * @param path What path to check/*  w  w w  .ja va2 s .  co  m*/
 *
 * @return {@code true} if path is right; {@code false} if path is not current
 */
public boolean isPathCurrent(Path path) {
    return path != null && path.startsWith(getMainLoggerPath().resolve(mainLogger.getName()));
}

From source file:org.codice.ddf.configuration.migration.PathUtils.java

/**
 * Checks if the specified path is located under ${ddf.home}.
 *
 * @param path the path to check if it is relative from ${ddf.home}
 * @return <code>true</code> if the path it located under ${ddf.home}; <code>false</code>
 *     otherwise//www.ja v  a2s. c o m
 */
public boolean isRelativeToDDFHome(Path path) {
    return path.startsWith(ddfHome);
}

From source file:com.xpn.xwiki.internal.skin.EnvironmentSkin.java

private String getResourcePath(String resource, boolean testExist) {
    String skinFolder = getSkinFolder();
    String resourcePath = skinFolder + resource;

    // Prevent inclusion of templates from other directories
    Path normalizedResource = Paths.get(resourcePath).normalize();
    if (!normalizedResource.startsWith(skinFolder)) {
        LOGGER.warn("Direct access to template file [{}] refused. Possible break-in attempt!",
                normalizedResource);/*from   w w w  .  java 2s.  co  m*/

        return null;
    }

    if (testExist) {
        // Check if the resource exist
        if (this.environment.getResource(resourcePath) == null) {
            return null;
        }
    }

    return resourcePath;
}