Search in sources :

Example 1 with FileSystemNotFoundException

use of java.nio.file.FileSystemNotFoundException in project ratpack by ratpack.

the class RatpackProperties method resourceToPath.

static Path resourceToPath(URL resource) {
    Objects.requireNonNull(resource, "Resource URL cannot be null");
    URI uri;
    try {
        uri = resource.toURI();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Could not extract URI", e);
    }
    String scheme = uri.getScheme();
    if (scheme.equals("file")) {
        String path = uri.toString().substring("file:".length());
        if (path.contains("//")) {
            path = StringUtils.cleanPath(path.replace("//", ""));
        }
        return Paths.get(new FileSystemResource(path).getFile().toURI());
    }
    if (!scheme.equals("jar")) {
        throw new IllegalArgumentException("Cannot convert to Path: " + uri);
    }
    String s = uri.toString();
    int separator = s.indexOf("!/");
    URI fileURI = URI.create(s.substring(0, separator) + "!/");
    try {
        FileSystems.getFileSystem(fileURI);
    } catch (FileSystemNotFoundException e) {
        try {
            FileSystems.newFileSystem(fileURI, Collections.singletonMap("create", "true"));
        } catch (IOException e1) {
            throw new IllegalArgumentException("Cannot convert to Path: " + uri);
        }
    }
    return Paths.get(fileURI);
}
Also used : FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) URISyntaxException(java.net.URISyntaxException) FileSystemResource(org.springframework.core.io.FileSystemResource) IOException(java.io.IOException) URI(java.net.URI)

Example 2 with FileSystemNotFoundException

use of java.nio.file.FileSystemNotFoundException in project karaf by apache.

the class Builder method loadExternalProfiles.

/**
 * Loads all profiles declared in profile URIs. These will be used in addition to generated
 * <em>startup</em>, <em>boot</em> and <em>installed</em> profiles.
 */
private Map<String, Profile> loadExternalProfiles(List<String> profilesUris) throws IOException, MultiException, InterruptedException {
    Map<String, Profile> profiles = new LinkedHashMap<>();
    Map<String, Profile> filteredProfiles = new LinkedHashMap<>();
    for (String profilesUri : profilesUris) {
        String uri = profilesUri;
        if (uri.startsWith("jar:") && uri.contains("!/")) {
            uri = uri.substring("jar:".length(), uri.indexOf("!/"));
        }
        if (!uri.startsWith("file:")) {
            Downloader downloader = manager.createDownloader();
            downloader.download(uri, null);
            downloader.await();
            StreamProvider provider = manager.getProviders().get(uri);
            profilesUri = profilesUri.replace(uri, provider.getFile().toURI().toString());
        }
        URI profileURI = URI.create(profilesUri);
        Path profilePath;
        try {
            profilePath = Paths.get(profileURI);
        } catch (FileSystemNotFoundException e) {
            // file system does not exist, try to create it
            FileSystem fs = FileSystems.newFileSystem(profileURI, new HashMap<>(), Builder.class.getClassLoader());
            profilePath = fs.provider().getPath(profileURI);
        }
        profiles.putAll(Profiles.loadProfiles(profilePath));
        // Handle blacklisted profiles
        List<ProfileNamePattern> blacklistedProfilePatterns = blacklistedProfileNames.stream().map(ProfileNamePattern::new).collect(Collectors.toList());
        for (String profileName : profiles.keySet()) {
            boolean blacklisted = false;
            for (ProfileNamePattern pattern : blacklistedProfilePatterns) {
                if (pattern.matches(profileName)) {
                    LOGGER.info("   blacklisting profile {} from {}", profileName, profilePath);
                    // TODO review blacklist policy options
                    if (blacklistPolicy == BlacklistPolicy.Discard) {
                        // Override blacklisted profiles with empty one
                        filteredProfiles.put(profileName, ProfileBuilder.Factory.create(profileName).getProfile());
                    } else {
                    // Remove profile completely
                    }
                    // no need to check other patterns
                    blacklisted = true;
                    break;
                }
            }
            if (!blacklisted) {
                filteredProfiles.put(profileName, profiles.get(profileName));
            }
        }
    }
    return filteredProfiles;
}
Also used : Path(java.nio.file.Path) StreamProvider(org.apache.karaf.features.internal.download.StreamProvider) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Downloader(org.apache.karaf.features.internal.download.Downloader) URI(java.net.URI) Profile(org.apache.karaf.profile.Profile) LinkedHashMap(java.util.LinkedHashMap) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) FileSystem(java.nio.file.FileSystem)

Example 3 with FileSystemNotFoundException

use of java.nio.file.FileSystemNotFoundException in project imagingbook-common by imagingbook.

the class ResourceUtils method uriToPath.

/**
 * Converts an URI to a Path for locations that are either
 * in the file system or inside a JAR file.
 *
 * @param uri the specified location
 * @return the associated path
 */
public static Path uriToPath(URI uri) {
    Path path = null;
    String scheme = uri.getScheme();
    switch(scheme) {
        case "jar":
            {
                // resource inside JAR file
                FileSystem fs = null;
                try {
                    // check if this FileSystem already exists
                    fs = FileSystems.getFileSystem(uri);
                } catch (FileSystemNotFoundException e) {
                // that's OK to happen, the file system is not created automatically
                }
                if (fs == null) {
                    // must not create the file system twice
                    try {
                        fs = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap());
                    } catch (IOException e) {
                        throw new RuntimeException("uriToPath: " + e.toString());
                    }
                }
                String ssp = uri.getSchemeSpecificPart();
                int startIdx = ssp.lastIndexOf('!');
                // in-Jar path (after the last '!')
                String inJarPath = ssp.substring(startIdx + 1);
                path = fs.getPath(inJarPath);
                break;
            }
        case "file":
            {
                // resource in ordinary file system
                path = Paths.get(uri);
                break;
            }
        default:
            throw new IllegalArgumentException("Cannot handle this URI type: " + scheme);
    }
    return path;
}
Also used : Path(java.nio.file.Path) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) FileSystem(java.nio.file.FileSystem) IOException(java.io.IOException)

Example 4 with FileSystemNotFoundException

use of java.nio.file.FileSystemNotFoundException in project java-common-lib by sosy-lab.

the class ConfigurationBuilder method loadFromResource.

/**
 * Load options from a class-loader resource with a "key = value" format.
 *
 * <p>There must not be any #include directives in the resource.
 *
 * @param contextClass The class to use for looking up the resource.
 * @param resourceName The name of the resource relative to {@code contextClass}.
 * @throws IllegalArgumentException If the resource cannot be found or read, or contains invalid
 *     syntax or #include directives.
 */
public ConfigurationBuilder loadFromResource(Class<?> contextClass, String resourceName) {
    URL url = Resources.getResource(contextClass, resourceName);
    CharSource source = Resources.asCharSource(url, StandardCharsets.UTF_8);
    setupProperties();
    // Get the path to the source, used for error messages and resolving relative path names.
    @Var Path sourcePath;
    @Var String sourceString;
    try {
        sourcePath = Paths.get(url.toURI());
        sourceString = sourcePath.toString();
    } catch (URISyntaxException | FileSystemNotFoundException | IllegalArgumentException e) {
        // If this fails, e.g., because url is a HTTP URL, we can also use the raw string.
        // This will not allow resolving relative path names, but everything else works.
        sourcePath = null;
        sourceString = url.toString();
    }
    try {
        Parser parser = Parser.parse(source, Optional.ofNullable(sourcePath), sourceString);
        properties.putAll(parser.getOptions());
        sources.putAll(parser.getSources());
    } catch (InvalidConfigurationException | IOException e) {
        throw new IllegalArgumentException("Error in resource " + resourceName + " relative to " + contextClass.getName(), e);
    }
    return this;
}
Also used : Path(java.nio.file.Path) CharSource(com.google.common.io.CharSource) Var(com.google.errorprone.annotations.Var) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URL(java.net.URL) FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException)

Example 5 with FileSystemNotFoundException

use of java.nio.file.FileSystemNotFoundException in project fabric8 by fabric8io.

the class FabricProfileFileSystemProvider method uriToPath.

protected Path uriToPath(URI uri) {
    String scheme = uri.getScheme();
    if ((scheme == null) || (!scheme.equalsIgnoreCase(getScheme()))) {
        throw new IllegalArgumentException("URI scheme is not '" + getScheme() + "'");
    }
    try {
        String root = uri.getRawSchemeSpecificPart();
        int i = root.lastIndexOf("!/");
        if (i != -1) {
            root = root.substring(0, i);
        }
        URI rootUri = new URI(root);
        try {
            return Paths.get(rootUri).toAbsolutePath();
        } catch (FileSystemNotFoundException e) {
            try {
                FileSystem fs = FileSystems.newFileSystem(rootUri, new HashMap<String, Object>(), FabricProfileFileSystemProvider.class.getClassLoader());
                return fs.provider().getPath(rootUri).toAbsolutePath();
            } catch (IOException e2) {
                e.addSuppressed(e2);
                throw e;
            }
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}
Also used : FileSystemNotFoundException(java.nio.file.FileSystemNotFoundException) HashMap(java.util.HashMap) FileSystem(java.nio.file.FileSystem) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Aggregations

FileSystemNotFoundException (java.nio.file.FileSystemNotFoundException)20 IOException (java.io.IOException)11 Path (java.nio.file.Path)11 URI (java.net.URI)9 URISyntaxException (java.net.URISyntaxException)9 FileSystem (java.nio.file.FileSystem)5 File (java.io.File)4 URL (java.net.URL)4 HashMap (java.util.HashMap)3 FileInputStream (java.io.FileInputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 FileOutputStream (java.io.FileOutputStream)2 MalformedURLException (java.net.MalformedURLException)2 Test (org.junit.Test)2 Vulnerability (com.blackducksoftware.integration.fortify.batch.model.Vulnerability)1 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 CsvMapper (com.fasterxml.jackson.dataformat.csv.CsvMapper)1 CsvSchema (com.fasterxml.jackson.dataformat.csv.CsvSchema)1 CharSource (com.google.common.io.CharSource)1 Var (com.google.errorprone.annotations.Var)1