List of usage examples for org.apache.commons.io FilenameUtils separatorsToUnix
public static String separatorsToUnix(String path)
From source file:org.apache.rya.shell.RyaCommands.java
@CliCommand(value = LOAD_DATA_CMD, help = "Loads RDF Statement data from a local file to the connected Rya instance.") public String loadData(@CliOption(key = { "file" }, mandatory = true, help = "A local file containing RDF Statements that is to be loaded.") final String file, @CliOption(key = {/*ww w . j a v a 2s.c o m*/ "format" }, mandatory = false, help = "The format of the supplied RDF Statements file. [RDF/XML, N-Triples, Turtle, N3, TriX, TriG, BinaryRDF, N-Quads, JSON-LD, RDF/JSON, RDFa]") final String format) { // Fetch the command that is connected to the store. final ShellState shellState = state.getShellState(); final RyaClient commands = shellState.getConnectedCommands().get(); final Optional<String> ryaInstanceName = shellState.getRyaInstanceName(); try { final long start = System.currentTimeMillis(); // If the provided path is relative, then make it rooted in the user's home. // Make sure the path is formatted with Unix style file // separators('/') before using it as a regex replacement string. // Windows file separators('\') will not work unless escaped. final String userHome = FilenameUtils.separatorsToUnix(System.getProperty("user.home")); final Path rootedFile = Paths.get(file.replaceFirst("^~", userHome)); RDFFormat rdfFormat = null; // If a format was provided, then go with that. if (format != null) { rdfFormat = RdfFormatUtils.getRdfFormatFromName(format); if (rdfFormat == null) { throw new RuntimeException("Unsupported RDF Statement data input format: " + format); } } // Otherwise try to figure it out using the filename. else if (rdfFormat == null) { rdfFormat = Rio.getParserFormatForFileName(rootedFile.getFileName().toString()).get(); if (rdfFormat == null) { throw new RuntimeException( "Unable to detect RDF Statement data input format for file: " + rootedFile); } else { consolePrinter.println("Detected RDF Format: " + rdfFormat); consolePrinter.flush(); } } commands.getLoadStatementsFile().loadStatements(ryaInstanceName.get(), rootedFile, rdfFormat); final String seconds = new DecimalFormat("0.0##").format((System.currentTimeMillis() - start) / 1000.0); return "Loaded the file: '" + file + "' successfully in " + seconds + " seconds."; } catch (final RyaClientException | IOException e) { log.error("Error", e); throw new RuntimeException("Can not load the RDF Statement data. Reason: " + e.getMessage(), e); } }
From source file:org.apache.tika.eval.db.H2Util.java
private static String getConnectionString(Path db, boolean createDBIfItDoesntExist) { String s = "jdbc:h2:" + FilenameUtils.separatorsToUnix(db.toAbsolutePath().toString()); if (!createDBIfItDoesntExist) { s += ";IFEXISTS=TRUE"; }/*from ww w. java 2 s . c o m*/ return s; }
From source file:org.apache.torque.generator.configuration.ClasspathConfigurationProvider.java
protected String getFileName(String name, String directory) { String fileName = getConfigResourceBase() + "/" + directory + "/" + name; // make double dots work for resources in jar files fileName = FilenameUtils.normalizeNoEndSeparator(fileName); fileName = FilenameUtils.separatorsToUnix(fileName); return fileName; }
From source file:org.artifactory.storage.db.spring.DbConfigFactory.java
@Bean(name = "storageProperties") public StorageProperties getDbProperties() throws IOException { ArtifactoryHome artifactoryHome = ContextHelper.get().getArtifactoryHome(); File storagePropsFile = artifactoryHome.getStoragePropertiesFile(); if (!storagePropsFile.exists()) { if (artifactoryHome.isHaConfigured()) { throw new IllegalStateException("Artifactory could not start in HA mode because storage.properties " + "could not be found."); }/*from w w w . j a v a 2 s . com*/ copyDefaultDerbyConfig(storagePropsFile); } log.debug("Loading database properties from: '{}'", storagePropsFile); StorageProperties storageProps = new StorageProperties(storagePropsFile); // configure embedded derby if (isDerbyDbUsed(storageProps.getDbType())) { System.setProperty("derby.stream.error.file", new File(artifactoryHome.getLogDir(), "derby.log").getAbsolutePath()); String url = storageProps.getConnectionUrl(); String dataDir = FilenameUtils.separatorsToUnix(artifactoryHome.getHaAwareDataDir().getAbsolutePath()); url = url.replace("{db.home}", dataDir + "/derby"); storageProps.setConnectionUrl(url); } // first for loading of the driver class. automatic registration doesn't work on some Tomcat installations String driver = storageProps.getDriverClass(); try { Class.forName(driver); } catch (ClassNotFoundException e) { throw new RuntimeException("Failed to load JDBC driver '" + driver + "'", e); } return storageProps; }
From source file:org.artifactory.util.ArchiveUtils.java
/** * Archives the contents of the given directory into the given archive using the apache commons compress tools * * @param sourceDirectory Directory to archive * @param destinationArchive Archive file to create * @param recurse True if should recurse file scan of source directory. False if not * @param archiveType Archive type to create * @throws java.io.IOException Any exceptions that might occur while handling the given files and used streams * @throws IllegalArgumentException Thrown when given invalid destinations *///from w w w .j a v a2s . c o m public static void archive(File sourceDirectory, File destinationArchive, boolean recurse, ArchiveType archiveType) throws IOException { if ((sourceDirectory == null) || (destinationArchive == null)) { throw new IllegalArgumentException("Supplied destinations cannot be null."); } if (!sourceDirectory.isDirectory()) { throw new IllegalArgumentException("Supplied source directory must be an existing directory."); } String sourcePath = sourceDirectory.getAbsolutePath(); String archivePath = destinationArchive.getAbsolutePath(); log.debug("Beginning to archive '{}' into '{}'", sourcePath, archivePath); FileOutputStream destinationOutputStream = new FileOutputStream(destinationArchive); ArchiveOutputStream archiveOutputStream = createArchiveOutputStream( new BufferedOutputStream(destinationOutputStream), archiveType); try { @SuppressWarnings({ "unchecked" }) Collection<File> childrenFiles = org.apache.commons.io.FileUtils.listFiles(sourceDirectory, null, recurse); childrenFiles.remove(destinationArchive); ArchiveEntry archiveEntry; FileInputStream fileInputStream; for (File childFile : childrenFiles) { String childPath = childFile.getAbsolutePath(); String relativePath = childPath.substring((sourcePath.length() + 1), childPath.length()); /** * Need to convert separators to unix format since zipping on windows machines creates windows specific * FS file paths */ relativePath = FilenameUtils.separatorsToUnix(relativePath); archiveEntry = createArchiveEntry(childFile, relativePath, archiveType); fileInputStream = new FileInputStream(childFile); archiveOutputStream.putArchiveEntry(archiveEntry); try { IOUtils.copy(fileInputStream, archiveOutputStream); } finally { IOUtils.closeQuietly(fileInputStream); archiveOutputStream.closeArchiveEntry(); } log.debug("Archive '{}' into '{}'", childPath, archivePath); } } finally { IOUtils.closeQuietly(archiveOutputStream); } log.debug("Completed archiving of '{}' into '{}'", sourcePath, archivePath); }
From source file:org.artifactory.util.ZipUtils.java
/** * Validates the given entry name by removing different slashes that might appear in the begining of the name and * any occurences of relative paths like "../", so we can protect from path traversal attacks * * @param entryName Name of zip entry// ww w. j av a 2 s . c o m */ private static String validateEntryName(String entryName) { entryName = FilenameUtils.separatorsToUnix(entryName); entryName = PathUtils.trimLeadingSlashes(entryName); entryName = removeDotSegments(entryName); return entryName; }
From source file:org.batoo.jpa.parser.impl.acl.ClassloaderAnnotatedClassLocator.java
private Set<Class<?>> findClasses(ClassLoader cl, Set<Class<?>> classes, String root, String path) { final File file = new File(path); if (file.isDirectory()) { ClassloaderAnnotatedClassLocator.LOG.debug("Processing directory {0}", path); for (final String child : file.list()) { this.findClasses(cl, classes, root, path + "/" + child); }/*from w w w .j ava 2 s . c o m*/ } else { if (FilenameUtils.isExtension(path, "class")) { final String normalizedPath = FilenameUtils.separatorsToUnix(FilenameUtils.normalize(path)); final int rootLength = FilenameUtils.normalizeNoEndSeparator(root).length(); String className = normalizedPath.substring(rootLength + 1).replaceAll("/", "."); className = StringUtils.left(className, className.length() - 6); final Class<?> clazz = this.isPersistentClass(cl, className); if (clazz != null) { ClassloaderAnnotatedClassLocator.LOG.debug("Found persistent class {0}", className); classes.add(clazz); } } } return classes; }
From source file:org.batoo.jpa.parser.impl.acl.ClassloaderAnnotatedClassLocator.java
/** * {@inheritDoc}//w w w .java 2s. co m * */ @Override public Set<Class<?>> locateClasses(PersistenceUnitInfo persistenceUnitInfo, URL url) { final String root = FilenameUtils.separatorsToUnix(FilenameUtils.normalize(url.getFile())); ClassloaderAnnotatedClassLocator.LOG.info("Checking persistence root {0} for persistence classes...", root); final HashSet<Class<?>> classes = Sets.newHashSet(); try { return this.findClasses(persistenceUnitInfo.getClassLoader(), classes, root, root); } finally { ClassloaderAnnotatedClassLocator.LOG.info("Found persistent classes {0}", classes.toString()); } }
From source file:org.broad.igv.util.FileUtils.java
/** * Get the relative path from one file to another, specifying the directory separator. * If one of the provided resources does not exist, it is assumed to be a file unless it ends with '/' or * '\'.//from w w w.java2 s . c o m * * @param targetPath targetPath is calculated to this file * @param basePath basePath is calculated from this file * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example) * @return */ public static String getRelativePath(String basePath, String targetPath, String pathSeparator) { // Normalize the paths String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath); String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath); // Undo the changes to the separators made by normalization if (pathSeparator.equals("/")) { normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath); } else if (pathSeparator.equals("\\")) { normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath); } else { throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'"); } String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator)); String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator)); // First get all the common elements. Store them as a string, // and also count how many of them there are. StringBuffer common = new StringBuffer(); int commonIndex = 0; while (commonIndex < target.length && commonIndex < base.length && target[commonIndex].equals(base[commonIndex])) { common.append(target[commonIndex] + pathSeparator); commonIndex++; } if (commonIndex == 0) { // No single common path element. This most // likely indicates differing drive letters, like C: and D:. // These paths cannot be relativized. return targetPath; } // The number of directories we have to backtrack depends on whether the base is a file or a dir // For example, the relative path from // // /foo/bar/baz/gg/ff to /foo/bar/baz // // ".." if ff is a file // "../.." if ff is a directory // // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because // the resource referred to by this path may not actually exist, but it's the best I can do boolean baseIsFile = true; File baseResource = new File(normalizedBasePath); if (baseResource.exists()) { baseIsFile = baseResource.isFile(); } else if (basePath.endsWith(pathSeparator)) { baseIsFile = false; } StringBuffer relative = new StringBuffer(); if (base.length != commonIndex) { int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex; for (int i = 0; i < numDirsUp; i++) { relative.append(".." + pathSeparator); } } relative.append(normalizedTargetPath.substring(common.length())); return relative.toString(); }
From source file:org.broadleafcommerce.common.file.service.BroadleafFileServiceImpl.java
protected ClassPathResource lookupResourceOnClassPath(String name) { if (fileServiceClasspathDirectory != null && !"".equals(fileServiceClasspathDirectory)) { try {/*w ww . ja va2s . co m*/ String resourceName = FilenameUtils .separatorsToUnix(FilenameUtils.normalize(fileServiceClasspathDirectory + '/' + name)); ClassPathResource resource = new ClassPathResource(resourceName); if (resource.exists()) { return resource; } } catch (Exception e) { LOG.error("Error getting resource from classpath", e); } } return null; }