Example usage for java.nio.file Path isAbsolute

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

Introduction

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

Prototype

boolean isAbsolute();

Source Link

Document

Tells whether or not this path is absolute.

Usage

From source file:edu.usc.pgroup.floe.utils.Utils.java

/**
 * Checks if the filename (to be uploaded or downloaded) is valid.
 * It should not contain ".." and should not be an absolute path.
 *
 * @param fileName filename to be uploaded or downloaded relative to the
 *                 coordinator's scratch folder.
 * @return returns true if the filename is valid and can be used in the
 * download or upload functions.//ww w .ja va  2s.c  o  m
 */
public static boolean checkValidFileName(final String fileName) {
    if (fileName.contains("..")) {
        return false;
    }

    Path filePath = FileSystems.getDefault().getPath(fileName);
    if (filePath.isAbsolute()) {
        return true;
    }
    return true;
}

From source file:org.wso2.carbon.logging.service.util.LoggingUtil.java

public static void loadCustomConfiguration() throws Exception {
    // set the appender details

    // we have not provided a facility to add or remove appenders so all the
    // initial appender set should present in the system.
    // and all the initall logger should present in the system
    Set<Appender> appenderSet = new HashSet<Appender>();
    Logger rootLogger = LogManager.getRootLogger();

    // set the root logger level, if the system log level is changed.
    String persistedSystemLoggerLevel = registryManager
            .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_LEVEL);
    boolean systemLogLevelChanged = (persistedSystemLoggerLevel != null);
    if (systemLogLevelChanged) {
        rootLogger.setLevel(Level.toLevel(persistedSystemLoggerLevel));
    }//  w ww  .  j av a2 s  .c o m

    String persistedSystemLogPattern = registryManager
            .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_PATTERN);
    boolean systemLogPatternChanged = (persistedSystemLogPattern != null);
    setSystemLoggingParameters(persistedSystemLoggerLevel,
            (systemLogPatternChanged) ? persistedSystemLogPattern : SYSTEM_LOG_PATTERN);

    addAppendersToSet(rootLogger.getAllAppenders(), appenderSet);

    // System log level has been changed, need to update all the loggers and
    // appenders
    if (systemLogLevelChanged) {
        Logger logger;
        Enumeration loggersEnum = LogManager.getCurrentLoggers();
        Level systemLevel = Level.toLevel(persistedSystemLoggerLevel);
        while (loggersEnum.hasMoreElements()) {
            logger = (Logger) loggersEnum.nextElement();
            // we ignore all class level defined loggers
            addAppendersToSet(logger.getAllAppenders(), appenderSet);
            logger.setLevel(systemLevel);
        }

        for (Appender appender : appenderSet) {
            if (appender instanceof AppenderSkeleton) {
                AppenderSkeleton appenderSkeleton = (AppenderSkeleton) appender;
                appenderSkeleton.setThreshold(systemLevel);
                appenderSkeleton.activateOptions();
            }
        }
    }

    // Update the logger data according to the data stored in the registry.
    Collection loggerCollection = registryManager.getLoggers();
    if (loggerCollection != null) {
        String[] loggerResourcePaths = loggerCollection.getChildren();
        for (String loggerResourcePath : loggerResourcePaths) {
            String loggerName = loggerResourcePath.substring(LoggingConstants.LOGGERS.length());
            Logger logger = LogManager.getLogger(loggerName);
            Resource loggerResource = registryManager.getLogger(loggerName);
            if (loggerResource != null && logger != null) {
                logger.setLevel(
                        Level.toLevel(loggerResource.getProperty(LoggingConstants.LoggerProperties.LOG_LEVEL)));
                logger.setAdditivity(Boolean.parseBoolean(
                        loggerResource.getProperty(LoggingConstants.LoggerProperties.ADDITIVITY)));
            }
        }
    }

    // update the appender data according to data stored in database
    Collection appenderCollection = registryManager.getAppenders();
    if (appenderCollection != null) {
        String[] appenderResourcePaths = appenderCollection.getChildren();
        for (String appenderResourcePath : appenderResourcePaths) {
            String appenderName = appenderResourcePath.substring(LoggingConstants.APPENDERS.length());
            Appender appender = getAppenderFromSet(appenderSet, appenderName);
            Resource appenderResource = registryManager.getAppender(appenderName);
            if (appenderResource != null && appender != null) {
                if ((appender.getLayout() != null) && (appender.getLayout() instanceof PatternLayout)) {
                    ((PatternLayout) appender.getLayout()).setConversionPattern(
                            appenderResource.getProperty(LoggingConstants.AppenderProperties.PATTERN));
                }
                if (appender instanceof FileAppender) {
                    FileAppender fileAppender = ((FileAppender) appender);

                    // resolves the log file path, if not absolute path, calculate with CARBON_HOME as the base
                    Path logFilePath = Paths.get(
                            appenderResource.getProperty(LoggingConstants.AppenderProperties.LOG_FILE_NAME));
                    if (!logFilePath.isAbsolute()) {
                        logFilePath = Paths.get(System.getProperty(ServerConstants.CARBON_HOME))
                                .resolve(logFilePath);
                    }
                    fileAppender.setFile(logFilePath.normalize().toString());
                    fileAppender.activateOptions();
                }

                if (appender instanceof CarbonMemoryAppender) {
                    CarbonMemoryAppender memoryAppender = (CarbonMemoryAppender) appender;
                    memoryAppender.setCircularBuffer(new CircularBuffer(200));
                    memoryAppender.activateOptions();
                }

                if (appender instanceof SyslogAppender) {
                    SyslogAppender syslogAppender = (SyslogAppender) appender;
                    syslogAppender.setSyslogHost(
                            appenderResource.getProperty(LoggingConstants.AppenderProperties.SYS_LOG_HOST));
                    syslogAppender.setFacility(
                            appenderResource.getProperty(LoggingConstants.AppenderProperties.FACILITY));
                }

                if (appender instanceof AppenderSkeleton) {
                    AppenderSkeleton appenderSkeleton = (AppenderSkeleton) appender;
                    appenderSkeleton.setThreshold(Level.toLevel(
                            appenderResource.getProperty(LoggingConstants.AppenderProperties.THRESHOLD)));
                    appenderSkeleton.activateOptions();
                }
            }
        }
    }
}

From source file:org.codice.ddf.configuration.AbsolutePathResolver.java

/**
 * This method will attempt to convert the already given path into an absolute path: first by
 * appending the given {@code rootPath}, then by using {@code Path}'s {@code toAbsolutePath}'s
 * method//from w ww  . ja  v a 2s  .  c om
 *
 * @param rootPath String to append to path
 * @return Absolute path as a String
 */
public String getPath(String rootPath) {
    if (path == null) {
        return null;
    }

    boolean trailingSeparator = path.endsWith(File.separator);

    Path absolutePath = Paths.get(path);

    if (!absolutePath.isAbsolute()) {
        if (StringUtils.isNotBlank(rootPath)) {
            absolutePath = Paths.get(rootPath, path);
        } else {
            LOGGER.debug("Root path is blank. Resolving relative path [{}] to: {}", path,
                    absolutePath.toAbsolutePath());
        }
    }

    String absolutePathStr = absolutePath.toAbsolutePath().toString();
    return trailingSeparator ? absolutePathStr + File.separator : absolutePathStr;
}

From source file:org.sonar.batch.bootstrap.ProjectTempFolderProvider.java

public TempFolder provide(AnalysisProperties props) {
    if (projectTempFolder == null) {
        String workingDirPath = StringUtils.defaultIfBlank(props.property(CoreProperties.WORKING_DIRECTORY),
                CoreProperties.WORKING_DIRECTORY_DEFAULT_VALUE);
        Path workingDir = Paths.get(workingDirPath).normalize();

        if (!workingDir.isAbsolute()) {
            Path base = getBasePath(props);
            workingDir = base.resolve(workingDir);
        }//from  w w  w  .j a va  2s . c  om

        Path tempDir = workingDir.resolve(TMP_NAME);
        try {
            Files.createDirectories(tempDir);
        } catch (IOException e) {
            throw new IllegalStateException("Unable to create root temp directory " + tempDir, e);
        }
        projectTempFolder = new DefaultTempFolder(tempDir.toFile(), true);
        this.instance = projectTempFolder;
    }
    return projectTempFolder;
}

From source file:ai.grakn.migration.base.io.MigrationOptions.java

private String resolvePath(String path) {
    Path givenPath = Paths.get(path);
    if (givenPath.isAbsolute()) {
        return givenPath.toAbsolutePath().toString();
    }/*from w  ww .j a v  a2 s.  co  m*/

    return Paths.get("").toAbsolutePath().resolve(givenPath).toString();
}

From source file:org.apache.geode.management.internal.cli.commands.StartMemberUtilsTest.java

@Test
public void testWorkingDirWithRelativePath() throws Exception {
    Path relativePath = Paths.get("some").resolve("relative").resolve("path");
    assertThat(relativePath.isAbsolute()).isFalse();
    String resolvedWorkingDir = StartMemberUtils.resolveWorkingDir(relativePath.toString(), "server1");
    assertThat(resolvedWorkingDir).isEqualTo(relativePath.toAbsolutePath().toString());
}

From source file:com.textocat.textokit.commons.consumer.AnnotationPerLineWriter.java

@Override
public void process(CAS cas) throws AnalysisEngineProcessException {
    String docUriStr = DocumentUtils.getDocumentUri(cas);
    if (docUriStr == null) {
        throw new IllegalStateException("Can't extract document URI");
    }/*  www. java2 s.  c o  m*/
    Path docUriPath = IoUtils.extractPathFromURI(docUriStr);
    if (docUriPath.isAbsolute()) {
        docUriPath = Paths.get("/").relativize(docUriPath);
    }
    Path outputPath = outputDir.resolve(docUriPath);
    outputPath = IoUtils.addExtension(outputPath, outputFileSuffix);
    try (PrintWriter out = IoUtils.openPrintWriter(outputPath.toFile())) {
        for (AnnotationFS anno : CasUtil.select(cas, targetType)) {
            String text = anno.getCoveredText();
            text = StringUtils.replaceChars(text, "\r\n", "  ");
            out.println(text);
        }
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }
}

From source file:fr.duminy.jbackup.core.archive.FileCollector.java

private void collectFilesImpl(List<SourceWithPath> collectedFiles, Collection<ArchiveParameters.Source> sources,
        MutableLong totalSize, Cancellable cancellable) throws IOException {
    totalSize.setValue(0L);// ww  w  .j a v a2s. c o  m

    for (ArchiveParameters.Source source : sources) {
        Path sourcePath = source.getSource();
        if (!sourcePath.isAbsolute()) {
            throw new IllegalArgumentException(String.format("The file '%s' is relative.", sourcePath));
        }

        long size;

        if (Files.isDirectory(sourcePath)) {
            size = collect(collectedFiles, sourcePath, source.getDirFilter(), source.getFileFilter(),
                    cancellable);
        } else {
            collectedFiles.add(new SourceWithPath(sourcePath, sourcePath));
            size = Files.size(sourcePath);
        }

        totalSize.add(size);
    }
}

From source file:de.ncoder.studipsync.storage.StandardPathResolver.java

@Override
public Path resolve(Path root, Download download, Path srcFile) {
    if (srcFile.isAbsolute()) {
        srcFile = srcFile.getRoot().relativize(srcFile);
    }//from ww  w. j  a v a 2  s .  c  o  m
    Path dstRoot = resolve(root, download).getParent(); //only dir in root of src == dir of download ("Hauptordner")
    Path dstPath = dstRoot.resolve(srcFile.toString());
    log.debug(dstPath + " = " + dstRoot + " <~ " + srcFile);
    return dstPath;
}

From source file:org.apache.archiva.configuration.StubConfiguration.java

@Override
public Path getDataDirectory() {
    if (configuration != null
            && StringUtils.isNotEmpty(configuration.getArchivaRuntimeConfiguration().getDataDirectory())) {
        Path dataDir = Paths.get(configuration.getArchivaRuntimeConfiguration().getDataDirectory());
        if (dataDir.isAbsolute()) {
            return dataDir;
        } else {//from  w w  w . ja  v  a  2 s  .  com
            return getAppServerBaseDir().resolve(dataDir);
        }
    } else {
        return getAppServerBaseDir().resolve("data");
    }

}