List of usage examples for java.nio.file Path normalize
Path normalize();
From source file:io.cloudslang.content.database.services.databases.MSSqlDatabase.java
private static void validateLibraryPath(String sqlJdbcAuthLibraryPath) { final List<String> exceptions = new ArrayList<>(); if (StringUtils.isEmpty(sqlJdbcAuthLibraryPath)) { throw new RuntimeException(EMPTY_DRIVER_PATH_EXCEPTION); }//w ww.j a v a 2s . c o m final Path libraryPath = Paths.get(sqlJdbcAuthLibraryPath); try { if (!libraryPath.equals(libraryPath.toRealPath())) { exceptions.add(SYMBOLIC_PATH_EXCEPTION); } if (!Files.isDirectory(libraryPath)) { exceptions.add(INVALID_DIRECTORY_PATH_EXCEPTION); } if (!libraryPath.isAbsolute()) { exceptions.add(DRIVER_PATH_NOT_ABSOLUTE_EXCEPTION); } if (!libraryPath.equals(libraryPath.normalize())) { exceptions.add(NOT_THE_SHORTEST_PATH_EXCEPTION); } } catch (IOException e) { exceptions.add(INVALID_PATH); } finally { if (exceptions.size() != 0) { throw new RuntimeException(join(exceptions, NEW_LINE)); } } }
From source file:org.sakuli.starter.helper.SakuliFolderHelper.java
/** * Validates the path to the sakuli main folder and set the path to {@link SakuliPropertyPlaceholderConfigurer} * * @param sakuliMainFolderPath path to the sakuli main folder * @param tempLogCache temporary string for later logging * @return the updated tempLogCache String. * @throws FileNotFoundException if the folder doesn't exist *///from w w w .ja v a 2s. co m public static String checkSakuliHomeFolderAndSetContextVariables(String sakuliMainFolderPath, String tempLogCache) throws FileNotFoundException { Path normalizedPath = normalizePath(sakuliMainFolderPath); Path mainFolderPath = normalizedPath != null ? normalizedPath : getAlternativeSakuliMainFolder(); if (!Files.exists(mainFolderPath)) { throw new FileNotFoundException("SAKULI HOME folder \"" + mainFolderPath + "\" does not exist!"); } if (!checkSubMainFolder(mainFolderPath)) { throw new FileNotFoundException("the assigned SAKULI HOME folder \"" + mainFolderPath + "\" does not have a valid file structure! Please use the correct folder!"); } SakuliPropertyPlaceholderConfigurer.SAKULI_HOME_FOLDER_VALUE = mainFolderPath.normalize().toAbsolutePath() .toString(); return tempLogCache + "\nset property '" + SakuliProperties.SAKULI_HOME_FOLDER + "' to \"" + SakuliPropertyPlaceholderConfigurer.SAKULI_HOME_FOLDER_VALUE + "\""; }
From source file:org.dataconservancy.dcs.util.UriUtility.java
/** * Resolves the supplied {@code bag://} URI against a platform-specific base directory. This method is used to * resolve resources in a bag to a platform-specific {@code Path} used by the caller to access the content of the * resource.//ww w . j a v a 2s . c o m * <p> * Example usage: * Given a bag that contains a resource identified by the URI {@code bag://my-bag/data/bar}, and the bag has been * exploded into the directory {@code /tmp/foo/my-bag} (where the bag payload directory is located at * {@code /tmp/foo/my-bag/data}) then the base directory of the bag is {@code /tmp/foo}. If the caller wishes to * resolve the URI {@code bag://my-bag/data/bar}, they would invoke this method: * </p> * <pre> * Path result = UriUtility.resolveBagUri(Paths.get("/tmp/foo"), new URI("bag://my-bag/data/bar")); * assert Paths.get("/tmp/foo/my-bag/data/bar").equals(result); * </pre> * <p> * The base directory does not need to exist. This implementation will {@link Path#normalize() normalize} the * supplied directory. * </p> * <p> * The {@code bag://} URI is converted to a path by concatenating the authority portion of the URI with the path * portion. * </p> * <p> * If the supplied {@code bagUri} is <em>not</em> a URI with the {@code bag} scheme, an * {@code IllegalArgumentException} is thrown. * </p> * * @param baseDir the base directory that contains the bag * @param bagUri a URI identifying a resource in a bag * @return a platform-specific {@code Path}, used to access the contents of the resource identified by {@code bagUri} * @throws IllegalArgumentException if the supplied bagUri is null or empty, if {@code baseDir} is null, if * {@code bagUri} does not have scheme {@code bag} * @throws RuntimeException if the supplied base directory cannot be normalized */ public static Path resolveBagUri(Path baseDir, URI bagUri) { if (bagUri == null) { throw new IllegalArgumentException( String.format(ERR_RESOLVE_BAGURI + "bag uri was null.", "null", baseDir)); } if (!bagUri.getScheme().equals(BAG_URI_SCHEME)) { throw new IllegalArgumentException( String.format(ERR_RESOLVE_BAGURI + "bag uri had incorrect scheme.", bagUri, baseDir)); } if (baseDir == null) { throw new IllegalArgumentException( String.format(ERR_RESOLVE_BAGURI + "base directory was null", bagUri, "null")); } // normalize the base directory path Path originalDir = baseDir; baseDir = baseDir.normalize(); if (baseDir == null) { throw new RuntimeException(String.format(ERR_RESOLVE_BAGURI + "failed to normalize the base directory.", bagUri, originalDir)); } Path bagPath = Paths.get(bagUri.getAuthority(), bagUri.getPath()); return baseDir.resolve(bagPath); }
From source file:org.forgerock.openidm.maintenance.upgrade.UpdateManagerImpl.java
/** * Execute a {@link Function} on an input stream for the given {@link Path}. * * @param path the {@link Path} on which to open an {@link InputStream} * @param function the {@link Function} to be applied to that {@link InputStream} * @param <R> The return type of the function * @param <E> The exception type thrown by the function * @return The result of the function// w w w.j a v a 2s.co m * @throws E on exception from the function * @throws IOException on failure to create an input stream from the path given */ static <R, E extends Exception> R withInputStreamForPath(Path path, Function<InputStream, R, E> function) throws E, IOException { try (final InputStream is = Files.newInputStream(path.normalize())) { return function.apply(is); } }
From source file:org.mycore.common.MCRUtils.java
/** * Extracts files in a tar archive. Currently works only on uncompressed tar files. * /*from w ww . ja va 2 s .co m*/ * @param source * the uncompressed tar to extract * @param expandToDirectory * the directory to extract the tar file to * @throws IOException * if the source file does not exists */ public static void untar(Path source, Path expandToDirectory) throws IOException { try (TarArchiveInputStream tain = new TarArchiveInputStream(Files.newInputStream(source))) { TarArchiveEntry tarEntry; FileSystem targetFS = expandToDirectory.getFileSystem(); HashMap<Path, FileTime> directoryTimes = new HashMap<>(); while ((tarEntry = tain.getNextTarEntry()) != null) { Path target = MCRPathUtils.getPath(targetFS, tarEntry.getName()); Path absoluteTarget = expandToDirectory.resolve(target).normalize().toAbsolutePath(); if (tarEntry.isDirectory()) { Files.createDirectories(expandToDirectory.resolve(absoluteTarget)); directoryTimes.put(absoluteTarget, FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime())); } else { if (Files.notExists(absoluteTarget.getParent())) { Files.createDirectories(absoluteTarget.getParent()); } Files.copy(tain, absoluteTarget, StandardCopyOption.REPLACE_EXISTING); Files.setLastModifiedTime(absoluteTarget, FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime())); } } //restore directory dates Files.walkFileTree(expandToDirectory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Path absolutePath = dir.normalize().toAbsolutePath(); Files.setLastModifiedTime(absolutePath, directoryTimes.get(absolutePath)); return super.postVisitDirectory(dir, exc); } }); } }
From source file:org.dataconservancy.packaging.impl.UriUtility.java
/** * Resolves the supplied {@code bag://} URI against a platform-specific base directory. This method is used to * resolve resources in a bag to a platform-specific {@code Path} used by the caller to access the content of the * resource./* w w w. jav a 2 s . c om*/ * <p> * Example usage: Given a bag that contains a resource identified by the URI {@code bag://my-bag/data/bar}, and * the bag has been exploded into the directory {@code /tmp/foo/my-bag} (where the bag payload directory is * located at {@code /tmp/foo/my-bag/data}) then the base directory of the bag is {@code /tmp/foo}. If the caller * wishes to resolve the URI {@code bag://my-bag/data/bar}, they would invoke this method: * </p> * <pre> * Path result = UriUtility.resolveBagUri(Paths.get("/tmp/foo"), new URI("bag://my-bag/data/bar")); * assert Paths.get("/tmp/foo/my-bag/data/bar").equals(result); * </pre> * <p> * The base directory does not need to exist. This implementation will {@link Path#normalize() normalize} the * supplied directory. * </p> * <p> * The {@code bag://} URI is converted to a path by concatenating the authority portion of the URI with the path * portion. * </p> * <p> * If the supplied {@code bagUri} is <em>not</em> a URI with the {@code bag} scheme, an * {@code IllegalArgumentException} is thrown. * </p> * * @param baseDir the base directory that contains the bag * @param bagUri a URI identifying a resource in a bag * @return a platform-specific {@code Path}, used to access the contents of the resource identified by * {@code bagUri} * @throws IllegalArgumentException if the supplied bagUri is null or empty, if {@code baseDir} is null, if * {@code bagUri} does not have scheme {@code bag} * @throws RuntimeException if the supplied base directory cannot be normalized */ public static Path resolveBagUri(final Path baseDir, final URI bagUri) { if (bagUri == null) { throw new IllegalArgumentException( String.format(ERR_RESOLVE_BAGURI + "bag uri was null.", "null", baseDir)); } if (!bagUri.getScheme().equals(BAG_URI_SCHEME)) { throw new IllegalArgumentException( String.format(ERR_RESOLVE_BAGURI + "bag uri had incorrect scheme.", bagUri, baseDir)); } if (baseDir == null) { throw new IllegalArgumentException( String.format(ERR_RESOLVE_BAGURI + "base directory was null", bagUri, "null")); } // normalize the base directory path final Path originalDir = baseDir; final Path normalizedDir = baseDir.normalize(); if (normalizedDir == null) { throw new RuntimeException(String.format(ERR_RESOLVE_BAGURI + "failed to normalize the base directory.", bagUri, originalDir)); } final Path bagPath = Paths.get(bagUri.getAuthority(), bagUri.getPath()); return normalizedDir.resolve(bagPath); }
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 ava 2s . com*/ 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:misc.FileHandler.java
/** * Normalizes the given folder name, so that it can be stored in the * database.//from ww w.j a v a 2 s. c om * * @param folderName * the folder name to normalize. May be <code>null</code>. * @return the normalized folder name. */ public static Path normalizeFolder(Path folderName) { if (folderName != null) { Path normalized = folderName.normalize(); return ("".equals(normalized.toString().trim())) ? ROOT_PATH : normalized; } else { return ROOT_PATH; } }
From source file:misc.FileHandler.java
/** * Returns a canonical representation of the given path as a string. * /*from www . ja v a 2 s .c om*/ * @param path * the path to convert * @return a canonical representation of the given path as a String. */ public static String toCanonicalPath(Path path) { if (path == null) { return null; } URI pathUri = path.normalize().toUri(); return Paths.get("").toUri().relativize(pathUri).toASCIIString(); }
From source file:misc.FileHandler.java
/** * Returns a temporary file path that is on the same file store as the given * file. The temporary file is created without content, if the given file's * file store is identical to the system's default temporary directory file * store./*w ww . ja v a 2 s. c om*/ * * @param target * the file which determines the file store. * @return the path of the temporary file or <code>null</code>, if an error * occurred. */ public static Path getTempFile(Path target) { Path tempFile = null; boolean success = false; target = target.normalize(); try { Path targetDirectory = target.toAbsolutePath().getParent(); tempFile = Files.createTempFile(target.getFileName().toString(), TEMP_FILE_SUFFIX); if (!Files.getFileStore(tempFile).equals(Files.getFileStore(targetDirectory))) { // the temporary file should be in the target directory. Files.delete(tempFile); tempFile = Paths.get(targetDirectory.toString(), tempFile.getFileName().toString()); success = true; } else { success = true; } } catch (IOException e) { Logger.logError(e); } finally { if (!success && (tempFile != null)) { try { Files.deleteIfExists(tempFile); } catch (IOException innerE) { Logger.logError(innerE); } } } return success ? tempFile : null; }