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:com.liferay.blade.cli.CreateCommand.java

private List<String> getTemplates() throws Exception {
    List<String> templateNames = new ArrayList<>();

    File templatesZip = getGradleTemplatesZip();

    try (Jar jar = new Jar(templatesZip)) {
        Map<String, Map<String, Resource>> directories = jar.getDirectories();

        for (String key : directories.keySet()) {
            Path path = Paths.get(key);

            if (path.getNameCount() == 2 && path.startsWith("standalone")) {
                templateNames.add(path.getName(1).toString());
            }// w  w w.ja v a2  s.com
        }
    }

    return templateNames;
}

From source file:repast.simphony.R.RWizard.java

public String[] getExecutionCommand() {

    List<String> commands = new ArrayList<String>();

    // NOTE: the LOGFILE and DELIMMTER args are processed by our .Rprofile.

    if (SystemUtils.IS_OS_WINDOWS) {
        //commands.add("R_PROFILE_USER=" + prepFileNameForR(getRHome()));
        //commands.add("&");

        envVars.put("R_PROFILE_USER", prepFileNameForR(getRHome()) + ".Rprofile");
        //commands.add("SET R_PROFILE_USER=" + prepFileNameForR(getRHome()));

        //builder.append("& ");
        List<FileDataSink> outputters = fileStep.getChosenOutputters();

        // For each outputter, define the log file and delimitter
        for (int i = 0; i < outputters.size(); i++) {
            Path out = outputters.get(i).getFile().toPath().normalize().toAbsolutePath();
            Path cwd = FileSystems.getDefault().getPath(".").normalize().toAbsolutePath();
            //System.out.println(out);
            //System.out.println(cwd);
            String sout = out.toString();
            if (out.startsWith(cwd)) {
                sout = sout.substring(cwd.toString().length() + 1);
            }/*from www.j  a v  a  2 s  . c  o m*/

            envVars.put("LOG_FILE" + i, sout.replace("\\", "/"));
            Formatter formatter = outputters.get(i).getFormatter();
            if (outputters.get(i).getFormat() != FormatType.TABULAR) {
                LOG.warn("When invoking R, an outputter without a delimited formatter "
                        + "was found. R can only be invoked on output files with using a delimiter.");
                break;
            }
            String delimiter = formatter.getDelimiter();
            envVars.put("DELIMITER" + i, delimiter);
        }
        commands.add(getInstallHome());
    } else if (SystemUtils.IS_OS_MAC) {
        List<FileDataSink> outputters = fileStep.getChosenOutputters();
        List<String> files = new ArrayList<String>();
        List<String> delims = new ArrayList<String>();
        String cwd = new File(".").getAbsolutePath();
        for (int i = 0; i < outputters.size(); i++) {
            Formatter formatter = outputters.get(i).getFormatter();
            if (outputters.get(i).getFormat() != FormatType.TABULAR) {
                LOG.warn("When invoking R, an outputter without a delimited formatter "
                        + "was found. R can only be invoked on output files with using a delimiter.");
                break;
            }
            delims.add(formatter.getDelimiter());
            String fileName = outputters.get(i).getFile().getAbsolutePath();
            File f = new File(fileName);
            if (fileName.startsWith("/")) {
                files.add(fileName);
            } else {
                if (f.exists()) {
                    files.add("./" + fileName);
                } else {
                    // assume its relative to the current working directory
                    files.add(cwd + "/" + fileName);
                }
            }
        }

        for (int i = 0; i < files.size(); i++) {
            envVars.put("LOG_FILE" + i, files.get(i));
            envVars.put("DELIMITER" + i, delims.get(i));
        }

        // this should ceate the .RProfile file
        getRHome();
        envVars.put("R_PROFILE_USER", cwd + "/RHome/.RProfile");
        commands.add("open");
        commands.add("-n");
        commands.add(getInstallHome());
        commands.add(cwd);

    } else {
        // TODO linux command
    }

    return commands.toArray(new String[commands.size()]);
}

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * This is where Nashorn compiles the script, evals it into global scope to get an endpoint, and invokes the setup method of the endpoint.
 * @param rootPath   The root script directory path to assist in building a relative uri type path to discovered scripts.
 * @param f   The javascript file./*w  w w . j av a2 s  . c  om*/
 * @param uriKey   A "pass-back-by-reference" construct to w
 * @return
 */
private static void MakeJavaScriptEndPointDescriptor(Path rootPath, Path f,
        HierarchicalConfiguration scriptConfig, EndpointSetupCompleteCallback cb) {
    CompiledScript compiledScript;
    try (Reader r = Files.newBufferedReader(f, Charset.forName("utf-8"))) {
        compiledScript = ((Compilable) Nashorn).compile(r);
    } catch (Throwable e) {
        cb.setupFailed(f, "Unable to load and compile script at " + f.toAbsolutePath().toString(), e);
        return;
    }
    ScriptObjectMirror obj;
    try {
        obj = (ScriptObjectMirror) compiledScript.eval(Nashorn.getBindings(ScriptContext.GLOBAL_SCOPE));
    } catch (Throwable e) {
        cb.setupFailed(f, "Unable to eval the script at " + f.toAbsolutePath().toString(), e);
        return;
    }
    assert f.startsWith(rootPath);
    String uriKey = FileToUriKey(rootPath, f);
    final JavaScriptEndPoint retVal = new JavaScriptEndPoint(uriKey, obj);

    try {
        if (obj.hasMember("setup")) {
            obj.callMember("setup", uriKey, scriptConfig, ScriptHelper.ScriptLogger,
                    new SetupCompleteCallback() {
                        @Override
                        public void setupComplete() {
                            cb.setupComplete(retVal);
                        }

                        @Override
                        public void setupFailed(String msg) {
                            cb.setupFailed(f, msg, null);
                        }
                    });
        } else {
            cb.setupComplete(retVal);
        }
    } catch (Throwable e) {
        cb.setupFailed(f, "The script at " + f.toAbsolutePath().toString()
                + " did not expose the expected 'setup' method", e);
        return;
    }
}

From source file:org.sonatype.nexus.proxy.storage.local.fs.DefaultFSLocalRepositoryStorage.java

/**
 * Resolve repository file from given request and ensure the file is a child of the repository base directory.
 *///  w  ww.j  a  v a  2s  .  c o  m
private File resolveFile(final Repository repository, final ResourceStoreRequest request) throws IOException {
    // lookup repository base directory
    File baseDir = getBaseDir(repository, request);

    // resolve file relative to base directory
    File file;
    String requestPath = request.getRequestPath();
    if (requestPath == null || RepositoryItemUid.PATH_ROOT.equals(requestPath)) {
        file = baseDir;
    } else if (requestPath.startsWith("/")) {
        file = new File(baseDir, requestPath.substring(1));
    } else {
        file = new File(baseDir, requestPath);
    }

    // FIXME: This check would be more appropriate in FSPeer impl?

    // normalize file path references to remove any relative tokens
    Path basePath = baseDir.toPath().toAbsolutePath().normalize();
    Path filePath = file.toPath().toAbsolutePath().normalize();
    log.trace("Resolve request path '{}' to file: '{}'", requestPath, filePath);

    // ensure file is a child of repository base directory
    if (!filePath.startsWith(basePath)) {
        throw new LocalStorageException(String.format(
                "Attempt to resolve repository '%s' (id='%s') file '%s' which exists outside of repository base directory '%s' is forbidden!",
                repository.getName(), repository.getId(), filePath, basePath));
    }

    return file;
}

From source file:org.opennms.features.newts.converter.NewtsConverter.java

private ResourcePath buildResourcePath(final Path resourceDir) {
    final ResourcePath resourcePath;
    final Path relativeResourceDir = this.rrdDir.relativize(resourceDir);

    // Transform store-by-id path into store-by-foreign-source path
    if (relativeResourceDir.startsWith(Paths.get("snmp"))
            && !relativeResourceDir.startsWith(Paths.get("snmp", "fs"))) {

        // The part after snmp/ is considered the node ID
        final int nodeId = Integer.valueOf(relativeResourceDir.getName(1).toString());

        // Get the foreign source for the node
        final ForeignId foreignId = foreignIds.get(nodeId);
        if (foreignId == null) {
            return null;
        }/*  w  w w .j ava2s  .  c  o m*/

        // Make a store-by-foreign-source compatible path by using the found foreign ID and append the remaining path as-is
        resourcePath = ResourcePath.get(
                ResourcePath.get(ResourcePath.get("snmp", "fs"), foreignId.foreignSource, foreignId.foreignId),
                Iterables.transform(Iterables.skip(relativeResourceDir, 2), Path::toString));

    } else {
        resourcePath = ResourcePath.get(relativeResourceDir);
    }
    return resourcePath;
}

From source file:org.niord.core.batch.BatchService.java

/**
 * Computes the absolute path to the given local path within the repository
 *
 * @param localPath the local path withing the batch job repository
 * @return the absolute path to the given local path within the repository
 *//*from w  ww.  ja  v a 2s.c  o  m*/
public Path computeBatchJobPath(Path localPath) {

    Path path = batchJobRoot.normalize().resolve(localPath);

    // Check that it is a valid path within the batch job repository root
    path = path.normalize();
    if (!path.startsWith(batchJobRoot)) {
        throw new RuntimeException("Invalid path " + localPath);
    }

    return path;
}

From source file:org.forgerock.openidm.maintenance.upgrade.UpdateManagerImpl.java

private boolean isReadOnly(Path path) {
    Pattern uiDefaults = Pattern.compile("^ui/*/default");
    return path.startsWith("bin") || uiDefaults.matcher(path.toString()).find();
}

From source file:org.orderofthebee.addons.support.tools.repo.AbstractLogFileWebScript.java

/**
 * Validates a single log file path and resolves it to a file handle.
 *
 * @param filePath//from  ww  w . j  av  a  2s  .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 File validateFilePath(final String filePath) {
    ParameterCheck.mandatoryString("filePath", filePath);

    final Path path = Paths.get(filePath);
    boolean pathAllowed = false;
    final List<Logger> allLoggers = this.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:io.stallion.fileSystem.FileSystemWatcherRunner.java

private void doRun() {
    while (shouldRun) {
        Log.fine("Running the file system watcher.");
        WatchKey key;//  ww w .  j  ava  2s  .c  o m
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            Log.warn("Interuppted the watcher!!!");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Log.info("Exit watcher run method.");
                return;
            }
            continue;
        }
        Log.fine("Watch event key taken. Runner instance is {0}", this.hashCode());

        for (WatchEvent<?> event : key.pollEvents()) {

            WatchEvent.Kind<?> kind = event.kind();
            Log.fine("Event is " + kind);
            // This key is registered only
            // for ENTRY_CREATE events,
            // but an OVERFLOW event can
            // occur regardless if events
            // are lost or discarded.
            if (kind == OVERFLOW) {
                continue;
            }

            // The filename is the
            // context of the event.
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path filename = ev.context();

            // Ignore emacs autosave files
            if (filename.toString().contains(".#")) {
                continue;
            }
            Log.finer("Changed file is {0}", filename);
            Path directory = (Path) key.watchable();
            Log.finer("Changed directory is {0}", directory);
            Path fullPath = directory.resolve(filename);
            Log.fine("Changed path is {0}", fullPath);
            Boolean handlerFound = false;
            for (IWatchEventHandler handler : watchedByPath.values()) {
                Log.finer("Checking matching handler {0} {1}", handler.getInternalHandlerLabel(),
                        handler.getWatchedFolder());
                // Ignore private files
                if (filename.getFileName().startsWith(".")) {
                    continue;
                }
                if ((handler.getWatchedFolder().equals(directory.toAbsolutePath().toString())
                        || (handler.getWatchTree() && directory.startsWith(handler.getWatchedFolder())))
                        && (StringUtils.isEmpty(handler.getExtension())
                                || fullPath.toString().endsWith(handler.getExtension()))) {
                    String relativePath = filename.getFileName().toString();
                    Log.info("Handling {0} with watcher {1} for folder {2}", filename,
                            handler.getClass().getName(), handler.getWatchedFolder());
                    try {
                        handler.handle(relativePath, fullPath.toString(), kind, event);
                        handlerFound = true;
                    } catch (Exception e) {
                        Log.exception(e, "Exception processing path={0} handler={1}", relativePath,
                                handler.getClass().getName());
                    }
                }
            }
            if (!handlerFound) {
                Log.info("No handler found for {0}", fullPath);
            }
        }
        // Reset the key -- this step is critical if you want to
        // receive further watch events.  If the key is no longer valid,
        // the directory is inaccessible so exit the loop.
        boolean valid = key.reset();
        if (!valid) {
            Log.warn("Key invalid! Exit watch.");
            break;
        }
    }
}