Search in sources :

Example 1 with ResourceLoader

use of io.micronaut.core.io.ResourceLoader in project micronaut-core by micronaut-projects.

the class HttpConverterRegistrar method register.

@Override
public void register(ConversionService<?> conversionService) {
    conversionService.addConverter(String.class, HttpVersion.class, s -> {
        try {
            return HttpVersion.valueOf(Double.parseDouble(s));
        } catch (NumberFormatException e) {
            return HttpVersion.valueOf(s);
        }
    });
    conversionService.addConverter(Number.class, HttpVersion.class, s -> HttpVersion.valueOf(s.doubleValue()));
    conversionService.addConverter(CharSequence.class, Readable.class, (object, targetType, context) -> {
        String pathStr = object.toString();
        Optional<ResourceLoader> supportingLoader = resourceResolver.getSupportingLoader(pathStr);
        if (!supportingLoader.isPresent()) {
            context.reject(pathStr, new ConfigurationException("No supported resource loader for path [" + pathStr + "]. Prefix the path with a supported prefix such as 'classpath:' or 'file:'"));
            return Optional.empty();
        } else {
            final Optional<URL> resource = resourceResolver.getResource(pathStr);
            if (resource.isPresent()) {
                return Optional.of(Readable.of(resource.get()));
            } else {
                context.reject(object, new ConfigurationException("No resource exists for value: " + object));
                return Optional.empty();
            }
        }
    });
    conversionService.addConverter(CharSequence.class, MediaType.class, (object, targetType, context) -> {
        try {
            return Optional.of(MediaType.of(object));
        } catch (IllegalArgumentException e) {
            context.reject(e);
            return Optional.empty();
        }
    });
    conversionService.addConverter(Number.class, HttpStatus.class, (object, targetType, context) -> {
        try {
            HttpStatus status = HttpStatus.valueOf(object.shortValue());
            return Optional.of(status);
        } catch (IllegalArgumentException e) {
            context.reject(object, e);
            return Optional.empty();
        }
    });
    conversionService.addConverter(CharSequence.class, SocketAddress.class, (object, targetType, context) -> {
        String address = object.toString();
        try {
            URL url = new URL(address);
            int port = url.getPort();
            if (port == -1) {
                port = url.getDefaultPort();
            }
            if (port == -1) {
                context.reject(object, new ConfigurationException("Failed to find a port in the given value"));
                return Optional.empty();
            }
            return Optional.of(InetSocketAddress.createUnresolved(url.getHost(), port));
        } catch (MalformedURLException malformedURLException) {
            String[] parts = object.toString().split(":");
            if (parts.length == 2) {
                try {
                    int port = Integer.parseInt(parts[1]);
                    return Optional.of(InetSocketAddress.createUnresolved(parts[0], port));
                } catch (IllegalArgumentException illegalArgumentException) {
                    context.reject(object, illegalArgumentException);
                    return Optional.empty();
                }
            } else {
                context.reject(object, new ConfigurationException("The address is not in a proper format of IP:PORT or a standard URL"));
                return Optional.empty();
            }
        }
    });
    conversionService.addConverter(CharSequence.class, ProxySelector.class, (object, targetType, context) -> {
        if (object.toString().equals("default")) {
            return Optional.of(ProxySelector.getDefault());
        } else {
            return Optional.empty();
        }
    });
}
Also used : ResourceLoader(io.micronaut.core.io.ResourceLoader) MalformedURLException(java.net.MalformedURLException) ConfigurationException(io.micronaut.context.exceptions.ConfigurationException) HttpStatus(io.micronaut.http.HttpStatus) URL(java.net.URL)

Example 2 with ResourceLoader

use of io.micronaut.core.io.ResourceLoader in project micronaut-core by micronaut-projects.

the class DefaultEnvironment method readPropertySourceList.

/**
 * @param name The name to resolver property sources
 * @return The list of property sources
 */
protected List<PropertySource> readPropertySourceList(String name) {
    List<PropertySource> propertySources = new ArrayList<>();
    for (String configLocation : configLocations) {
        ResourceLoader resourceLoader;
        if (configLocation.equals("classpath:/")) {
            resourceLoader = this;
        } else if (configLocation.startsWith("classpath:")) {
            resourceLoader = this.forBase(configLocation);
        } else if (configLocation.startsWith("file:")) {
            configLocation = configLocation.substring(5);
            Path configLocationPath = Paths.get(configLocation);
            if (Files.exists(configLocationPath) && Files.isDirectory(configLocationPath) && Files.isReadable(configLocationPath)) {
                resourceLoader = new DefaultFileSystemResourceLoader(configLocationPath);
            } else {
                // Skip not existing config location
                continue;
            }
        } else {
            throw new ConfigurationException("Unsupported config location format: " + configLocation);
        }
        readPropertySourceList(name, resourceLoader, propertySources);
    }
    return propertySources;
}
Also used : Path(java.nio.file.Path) DefaultFileSystemResourceLoader(io.micronaut.core.io.file.DefaultFileSystemResourceLoader) ResourceLoader(io.micronaut.core.io.ResourceLoader) FileSystemResourceLoader(io.micronaut.core.io.file.FileSystemResourceLoader) ClassPathResourceLoader(io.micronaut.core.io.scan.ClassPathResourceLoader) ConfigurationException(io.micronaut.context.exceptions.ConfigurationException) ArrayList(java.util.ArrayList) DefaultFileSystemResourceLoader(io.micronaut.core.io.file.DefaultFileSystemResourceLoader)

Example 3 with ResourceLoader

use of io.micronaut.core.io.ResourceLoader in project micronaut-core by micronaut-projects.

the class PropertiesInfoSource method retrievePropertiesPropertySource.

/**
 * <p>Extends {@link io.micronaut.management.endpoint.info.InfoEndpoint} to add a helper method for retrieving a
 * {@link PropertySource} from a properties file. </p>
 *
 * @param path             The path to the properties file
 * @param prefix           prefix for resolving the file (used if not included in {@code path})
 * @param extension        file extension (used if not included in {@code path})
 * @param resourceResolver Instance of {@link ResourceResolver} to resolve the file location
 * @return An {@link Optional} of {@link PropertySource} containing the values from the properties file
 */
default Optional<PropertySource> retrievePropertiesPropertySource(String path, String prefix, String extension, ResourceResolver resourceResolver) {
    StringBuilder pathBuilder = new StringBuilder();
    if ((prefix != null) && !path.startsWith(prefix)) {
        pathBuilder.append(prefix);
    }
    if ((extension != null) && path.endsWith(extension)) {
        int index = path.indexOf(extension);
        pathBuilder.append(path, 0, index);
    } else {
        pathBuilder.append(path);
    }
    String propertiesPath = pathBuilder.toString();
    Optional<ResourceLoader> resourceLoader = resourceResolver.getSupportingLoader(propertiesPath);
    if (resourceLoader.isPresent()) {
        PropertiesPropertySourceLoader propertySourceLoader = new PropertiesPropertySourceLoader();
        return propertySourceLoader.load(propertiesPath, resourceLoader.get());
    }
    return Optional.empty();
}
Also used : ResourceLoader(io.micronaut.core.io.ResourceLoader) PropertiesPropertySourceLoader(io.micronaut.context.env.PropertiesPropertySourceLoader)

Example 4 with ResourceLoader

use of io.micronaut.core.io.ResourceLoader in project micronaut-core by micronaut-projects.

the class StaticResourceResolver method resolve.

/**
 * Resolves a path to a URL.
 *
 * @param resourcePath The path to the resource
 * @return The optional URL
 */
public Optional<URL> resolve(String resourcePath) {
    for (Map.Entry<String, List<ResourceLoader>> entry : resourceMappings.entrySet()) {
        List<ResourceLoader> loaders = entry.getValue();
        String mapping = entry.getKey();
        if (!loaders.isEmpty() && pathMatcher.matches(mapping, resourcePath)) {
            String path = pathMatcher.extractPathWithinPattern(mapping, resourcePath);
            // A request to the root of the mapping
            if (StringUtils.isEmpty(path)) {
                path = INDEX_PAGE;
            }
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            for (ResourceLoader loader : loaders) {
                Optional<URL> resource = loader.getResource(path);
                if (resource.isPresent()) {
                    return resource;
                } else {
                    if (path.indexOf('.') == -1) {
                        if (!path.endsWith("/")) {
                            path = path + "/";
                        }
                        path += INDEX_PAGE;
                        resource = loader.getResource(path);
                        if (resource.isPresent()) {
                            return resource;
                        }
                    }
                }
            }
        }
    }
    return Optional.empty();
}
Also used : ResourceLoader(io.micronaut.core.io.ResourceLoader) List(java.util.List) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) URL(java.net.URL)

Example 5 with ResourceLoader

use of io.micronaut.core.io.ResourceLoader in project micronaut-cache by micronaut-projects.

the class HazelcastConfigResourceCondition method resourceExists.

/**
 * Checks whether any path given exists.
 *
 * @param context the condition context
 * @param paths the paths to check
 * @return true if any of the given paths exists. False otherwise.
 */
protected boolean resourceExists(ConditionContext<?> context, String[] paths) {
    final BeanContext beanContext = context.getBeanContext();
    ResourceResolver resolver;
    final List<ResourceLoader> resourceLoaders;
    if (beanContext instanceof ApplicationContext) {
        ResourceLoader resourceLoader = ((ApplicationContext) beanContext).getEnvironment();
        resourceLoaders = Arrays.asList(resourceLoader, FileSystemResourceLoader.defaultLoader());
    } else {
        resourceLoaders = Arrays.asList(ClassPathResourceLoader.defaultLoader(beanContext.getClassLoader()), FileSystemResourceLoader.defaultLoader());
    }
    resolver = new ResourceResolver(resourceLoaders);
    for (String resourcePath : paths) {
        if (resolver.getResource(resourcePath).isPresent()) {
            return true;
        }
    }
    return false;
}
Also used : BeanContext(io.micronaut.context.BeanContext) ClassPathResourceLoader(io.micronaut.core.io.scan.ClassPathResourceLoader) FileSystemResourceLoader(io.micronaut.core.io.file.FileSystemResourceLoader) ResourceLoader(io.micronaut.core.io.ResourceLoader) ApplicationContext(io.micronaut.context.ApplicationContext) ResourceResolver(io.micronaut.core.io.ResourceResolver)

Aggregations

ResourceLoader (io.micronaut.core.io.ResourceLoader)6 FileSystemResourceLoader (io.micronaut.core.io.file.FileSystemResourceLoader)3 ClassPathResourceLoader (io.micronaut.core.io.scan.ClassPathResourceLoader)3 ConfigurationException (io.micronaut.context.exceptions.ConfigurationException)2 ResourceResolver (io.micronaut.core.io.ResourceResolver)2 URL (java.net.URL)2 ApplicationContext (io.micronaut.context.ApplicationContext)1 BeanContext (io.micronaut.context.BeanContext)1 PropertiesPropertySourceLoader (io.micronaut.context.env.PropertiesPropertySourceLoader)1 DefaultFileSystemResourceLoader (io.micronaut.core.io.file.DefaultFileSystemResourceLoader)1 HttpStatus (io.micronaut.http.HttpStatus)1 MalformedURLException (java.net.MalformedURLException)1 Path (java.nio.file.Path)1 ArrayList (java.util.ArrayList)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1 Map (java.util.Map)1