Example usage for org.springframework.core.io Resource getURL

List of usage examples for org.springframework.core.io Resource getURL

Introduction

In this page you can find the example usage for org.springframework.core.io Resource getURL.

Prototype

URL getURL() throws IOException;

Source Link

Document

Return a URL handle for this resource.

Usage

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageMetaInfo.java

/**
 * Attempts to establish what the last modified date of the given resource is. If the last modified date cannot
 * be etablished -1 is returned// w  w  w.  j av a 2  s.  c om
 *
 * @param resource The Resource to evaluate
 * @return The last modified date or -1
 */
private long establishLastModified(Resource resource) {
    if (resource == null)
        return -1;

    if (resource instanceof FileSystemResource) {
        return ((FileSystemResource) resource).getFile().lastModified();
    }

    long last;
    URLConnection urlc = null;

    try {
        URL url = resource.getURL();
        if ("file".equals(url.getProtocol())) {
            File file = new File(url.getFile());
            if (file.exists()) {
                return file.lastModified();
            }
        }
        urlc = url.openConnection();
        urlc.setDoInput(false);
        urlc.setDoOutput(false);
        last = urlc.getLastModified();
    } catch (FileNotFoundException fnfe) {
        last = -1;
    } catch (IOException e) {
        last = -1;
    } finally {
        if (urlc != null) {
            try {
                InputStream is = urlc.getInputStream();
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return last;
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine.java

/**
 * Establishes the name to use for the given resource
 *
 * @param res The Resource to calculate the name for
 * @param pageName The name of the page, can be null, in which case method responsible for calculation
 *
 * @return  The name as a String//w w  w .ja  va  2 s.  c  om
 */
protected String establishPageName(Resource res, String pageName) {
    if (res == null) {
        return generateTemplateName();
    }

    try {
        String name = pageName != null ? pageName : res.getURL().getPath();
        // As the name take the first / off and then replace all characters that aren't
        // a word character or a digit with an underscore
        if (name.startsWith("/"))
            name = name.substring(1);
        return name.replaceAll("[^\\w\\d]", "_");
    } catch (IllegalStateException e) {
        return generateTemplateName();
    } catch (IOException ioex) {
        return generateTemplateName();
    }
}

From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsLayoutDecoratorMapper.java

private String searchPluginViewsForWarDeployed(String name, ResourceLoader resourceLoader) {
    String pluginViewLocation = null;
    ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(resourceLoader);
    try {//w  ww .j av  a  2 s .co m
        Resource[] resources = resourceResolver.getResources(GrailsResourceUtils.WEB_INF + "/plugins/*/"
                + GrailsResourceUtils.GRAILS_APP_DIR + "/views/layouts/" + name);
        if (resources.length > 0 && resources[0].exists()) {
            Resource r = resources[0];
            String url = r.getURL().toString();
            pluginViewLocation = GrailsResourceUtils.WEB_INF + url.substring(url.indexOf("/plugins"));
        }
    } catch (Exception e) {
        // ignore
    }
    return pluginViewLocation;
}

From source file:org.compass.spring.LocalCompassBean.java

public void afterPropertiesSet() throws Exception {
    CompassConfiguration config = this.config;
    if (config == null) {
        config = newConfiguration();// ww w. j a  v  a 2s .c  o m
    }

    if (classLoader != null) {
        config.setClassLoader(getClassLoader());
    }

    if (this.configLocation != null) {
        config.configure(this.configLocation.getURL());
    }

    if (this.configLocations != null) {
        for (Resource configLocation1 : configLocations) {
            config.configure(configLocation1.getURL());
        }
    }

    if (this.mappingScan != null) {
        config.addScan(this.mappingScan);
    }

    if (this.compassSettings != null) {
        config.getSettings().addSettings(this.compassSettings);
    }

    if (this.settings != null) {
        config.getSettings().addSettings(this.settings);
    }

    if (resourceLocations != null) {
        for (Resource resourceLocation : resourceLocations) {
            config.addInputStream(resourceLocation.getInputStream(), resourceLocation.getFilename());
        }
    }

    if (resourceJarLocations != null) {
        for (Resource resourceJarLocation : resourceJarLocations) {
            config.addJar(resourceJarLocation.getFile());
        }
    }

    if (classMappings != null) {
        for (String classMapping : classMappings) {
            config.addClass(ClassUtils.forName(classMapping, getClassLoader()));
        }
    }

    if (resourceDirectoryLocations != null) {
        for (Resource resourceDirectoryLocation : resourceDirectoryLocations) {
            File file = resourceDirectoryLocation.getFile();
            if (!file.isDirectory()) {
                throw new IllegalArgumentException("Resource directory location [" + resourceDirectoryLocation
                        + "] does not denote a directory");
            }
            config.addDirectory(file);
        }
    }

    if (mappingResolvers != null) {
        for (InputStreamMappingResolver mappingResolver : mappingResolvers) {
            config.addMappingResolver(mappingResolver);
        }
    }

    if (convertersByName != null) {
        for (Map.Entry<String, Converter> entry : convertersByName.entrySet()) {
            config.registerConverter(entry.getKey(), entry.getValue());
        }
    }
    if (config.getSettings().getSetting(CompassEnvironment.NAME) == null) {
        config.getSettings().setSetting(CompassEnvironment.NAME, beanName);
    }

    if (config.getSettings().getSetting(CompassEnvironment.CONNECTION) == null && connection != null) {
        config.getSettings().setSetting(CompassEnvironment.CONNECTION, connection.getFile().getAbsolutePath());
    }

    if (applicationContext != null) {
        String[] names = applicationContext.getBeanNamesForType(PropertyPlaceholderConfigurer.class);
        for (String name : names) {
            try {
                PropertyPlaceholderConfigurer propConfigurer = (PropertyPlaceholderConfigurer) applicationContext
                        .getBean(name);
                Method method = findMethod(propConfigurer.getClass(), "mergeProperties");
                method.setAccessible(true);
                Properties props = (Properties) method.invoke(propConfigurer);
                method = findMethod(propConfigurer.getClass(), "convertProperties", Properties.class);
                method.setAccessible(true);
                method.invoke(propConfigurer, props);
                method = findMethod(propConfigurer.getClass(), "parseStringValue", String.class,
                        Properties.class, Set.class);
                method.setAccessible(true);
                String nullValue = null;
                try {
                    Field field = propConfigurer.getClass().getDeclaredField("nullValue");
                    field.setAccessible(true);
                    nullValue = (String) field.get(propConfigurer);
                } catch (NoSuchFieldException e) {
                    // no field (old spring version)
                }
                for (Map.Entry entry : config.getSettings().getProperties().entrySet()) {
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    value = (String) method.invoke(propConfigurer, value, props, new HashSet());
                    config.getSettings().setSetting(key, value.equals(nullValue) ? null : value);
                }
            } catch (Exception e) {
                log.debug("Failed to apply property placeholder defined in bean [" + name + "]", e);
            }
        }
    }

    // we do this after the proeprties placeholder hack, so if other Compass beans are created beacuse
    // of it, we still maintain the correct thread local setting of the data source and transaction manager
    if (dataSource != null) {
        ExternalDataSourceProvider.setDataSource(dataSource);
        if (config.getSettings().getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS) == null) {
            config.getSettings().setSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS,
                    ExternalDataSourceProvider.class.getName());
        }
    }

    String compassTransactionFactory = config.getSettings().getSetting(CompassEnvironment.Transaction.FACTORY);
    if (compassTransactionFactory == null && transactionManager != null) {
        // if the transaciton manager is set and a transcation factory is not set, default to the SpringSync one.
        config.getSettings().setSetting(CompassEnvironment.Transaction.FACTORY,
                SpringSyncTransactionFactory.class.getName());
    }
    if (compassTransactionFactory != null
            && compassTransactionFactory.equals(SpringSyncTransactionFactory.class.getName())) {
        if (transactionManager == null) {
            throw new IllegalArgumentException(
                    "When using SpringSyncTransactionFactory the transactionManager property must be set");
        }
    }
    SpringSyncTransactionFactory.setTransactionManager(transactionManager);

    if (postProcessor != null) {
        postProcessor.process(config);
    }
    this.compass = newCompass(config);
    this.compass = (Compass) Proxy.newProxyInstance(SpringCompassInvocationHandler.class.getClassLoader(),
            new Class[] { InternalCompass.class }, new SpringCompassInvocationHandler(this.compass));
}

From source file:org.craftercms.engine.util.ConfigUtils.java

public static XMLConfiguration readXmlConfiguration(Resource resource, char listDelimiter,
        Map<String, Lookup> prefixLookups) throws ConfigurationException {
    Parameters params = new Parameters();
    FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<>(
            XMLConfiguration.class);

    try {//  w ww . j a  v a 2s. co  m
        XMLBuilderParameters xmlParams = params.xml().setURL(resource.getURL())
                .setListDelimiterHandler(new DefaultListDelimiterHandler(listDelimiter));

        if (MapUtils.isNotEmpty(prefixLookups)) {
            xmlParams = xmlParams.setPrefixLookups(prefixLookups);
        }

        builder.configure(xmlParams);
    } catch (IOException e) {
        throw new ConfigurationException("Unable to get URL of resource " + resource, e);
    }

    return builder.getConfiguration();
}

From source file:org.dataconservancy.cos.osf.client.model.AbstractMockServerTest.java

/**
 * Starts mock HTTP servers on the port specified by the OSF client configuration and the Waterbutler client
 * configuration// w w  w . j  a  v  a  2  s  . c  om
 */
@Before
public void startMockServer() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();

    final JacksonConfigurer<OsfClientConfiguration> osfConfigurer = new DefaultOsfJacksonConfigurer<>();
    final JacksonConfigurer<WbClientConfiguration> wbConfigurer = new DefaultWbJacksonConfigurer<>();

    final ResourceLoader loader = new DefaultResourceLoader();

    final Resource configuration = loader.getResource(getOsfServiceConfigurationResource());
    assertTrue("Unable to resolve configuration resource: '" + getOsfServiceConfigurationResource() + "'",
            configuration.exists());

    mockServer = ClientAndServer.startClientAndServer(
            osfConfigurer.configure(mapper.readTree(IOUtils.toString(configuration.getURL(), "UTF-8")), mapper,
                    OsfClientConfiguration.class).getPort());

    wbMockServer = ClientAndServer.startClientAndServer(
            wbConfigurer.configure(mapper.readTree(IOUtils.toString(configuration.getURL(), "UTF-8")), mapper,
                    WbClientConfiguration.class).getPort());

    /* Sets up the expectations of the mock http server.
     *
     * Invokes the NodeResponseCallback when the HTTP header "X-Response-Resource" is present.
     * The header value is a classpath resource to the JSON document to be serialized for the
     * response.
     */
    mockServer.when(request().withHeader(X_RESPONSE_RESOURCE))
            .callback(callback().withCallbackClass(NodeResponseCallback.class.getName()));
    wbMockServer.when(request().withHeader(X_RESPONSE_RESOURCE))
            .callback(callback().withCallbackClass(NodeResponseCallback.class.getName()));
}

From source file:org.devproof.portal.core.module.theme.service.ThemeServiceImpl.java

private String getZipPath(Resource roots[], Resource current) throws IOException {
    String currentPath = current.getURL().getPath();
    for (Resource root : roots) {
        String rootPath = root.getURL().getPath();
        if (currentPath.startsWith(rootPath)) {
            return StringUtils.removeStart(currentPath, rootPath);
        }//w w w.j  a  v a  2s .  c  o m
    }
    return null;
}

From source file:org.eclipse.gemini.blueprint.extender.internal.blueprint.activator.support.BlueprintConfigurationScanner.java

/**
 * Checks if the given bundle contains existing configurations. The absolute paths are returned without performing
 * any checks.//from w w w.  j  a v a 2 s  .  c o m
 * 
 * @return
 */
private String[] findValidBlueprintConfigs(Bundle bundle, String[] locations) {
    List<String> configs = new ArrayList<String>(locations.length);
    ResourcePatternResolver loader = new OsgiBundleResourcePatternResolver(bundle);

    boolean debug = log.isDebugEnabled();
    for (String location : locations) {
        if (isAbsolute(location)) {
            configs.add(location);
        }
        // resolve the location to check if it's present
        else {
            try {
                String loc = location;
                if (loc.endsWith("/")) {
                    loc = loc + "*.xml";
                }
                Resource[] resources = loader.getResources(loc);
                if (!ObjectUtils.isEmpty(resources)) {
                    for (Resource resource : resources) {
                        if (resource.exists()) {
                            String value = resource.getURL().toString();
                            if (debug)
                                log.debug("Found location " + value);
                            configs.add(value);
                        }
                    }
                }
            } catch (IOException ex) {
                if (debug)
                    log.debug("Cannot resolve location " + location, ex);
            }
        }
    }
    return (String[]) configs.toArray(new String[configs.size()]);
}

From source file:org.eclipse.gemini.blueprint.io.OsgiBundleResourcePatternResolver.java

/**
 * Based on the search type, uses the appropriate searching method.
 * /*from w  w w.  ja va2s  .c  o m*/
 * @see OsgiBundleResource#BUNDLE_URL_PREFIX
 * @see org.springframework.core.io.support.PathMatchingResourcePatternResolver#getResources(java.lang.String)
 */
private Set<Resource> doFindPathMatchingFileResources(Resource rootDirResource, String subPattern,
        int searchType) throws IOException {

    String rootPath = null;

    if (rootDirResource instanceof OsgiBundleResource) {
        OsgiBundleResource bundleResource = (OsgiBundleResource) rootDirResource;
        rootPath = bundleResource.getPath();
        searchType = bundleResource.getSearchType();
    } else if (rootDirResource instanceof UrlResource) {
        rootPath = rootDirResource.getURL().getPath();
    }

    if (rootPath != null) {
        String cleanPath = OsgiResourceUtils.stripPrefix(rootPath);
        // sanitize the root folder (since it's possible to not specify the root which fails any further matches)
        if (!cleanPath.endsWith(FOLDER_SEPARATOR)) {
            cleanPath = cleanPath + FOLDER_SEPARATOR;
        }
        String fullPattern = cleanPath + subPattern;
        Set<Resource> result = new LinkedHashSet<Resource>();
        doRetrieveMatchingBundleEntries(bundle, fullPattern, cleanPath, result, searchType);
        return result;
    } else {
        return super.doFindPathMatchingFileResources(rootDirResource, subPattern);
    }
}

From source file:org.grails.web.servlet.context.support.GrailsRuntimeConfigurator.java

protected void doPostResourceConfiguration(GrailsApplication app, RuntimeSpringConfiguration springConfig) {
    ClassLoader classLoader = app.getClassLoader();
    String resourceName = null;//from  ww  w .j a  va 2s .  co  m
    try {
        Resource springResources;
        if (app.isWarDeployed()) {
            resourceName = GrailsRuntimeConfigurator.SPRING_RESOURCES_XML;
            springResources = parent.getResource(resourceName);
        } else {
            resourceName = DEVELOPMENT_SPRING_RESOURCES_XML;
            ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
            springResources = patternResolver.getResource(resourceName);
        }

        if (springResources != null && springResources.exists()) {
            if (LOG.isDebugEnabled())
                LOG.debug(
                        "[RuntimeConfiguration] Configuring additional beans from " + springResources.getURL());
            DefaultListableBeanFactory xmlBf = new OptimizedAutowireCapableBeanFactory();
            new XmlBeanDefinitionReader(xmlBf).loadBeanDefinitions(springResources);
            xmlBf.setBeanClassLoader(classLoader);
            String[] beanNames = xmlBf.getBeanDefinitionNames();
            if (LOG.isDebugEnabled())
                LOG.debug("[RuntimeConfiguration] Found [" + beanNames.length + "] beans to configure");
            for (String beanName : beanNames) {
                BeanDefinition bd = xmlBf.getBeanDefinition(beanName);
                final String beanClassName = bd.getBeanClassName();
                Class<?> beanClass = beanClassName == null ? null
                        : ClassUtils.forName(beanClassName, classLoader);

                springConfig.addBeanDefinition(beanName, bd);
                String[] aliases = xmlBf.getAliases(beanName);
                for (String alias : aliases) {
                    springConfig.addAlias(alias, beanName);
                }
                if (beanClass != null) {
                    if (BeanFactoryPostProcessor.class.isAssignableFrom(beanClass)) {
                        ((ConfigurableApplicationContext) springConfig.getUnrefreshedApplicationContext())
                                .addBeanFactoryPostProcessor(
                                        (BeanFactoryPostProcessor) xmlBf.getBean(beanName));
                    }
                }
            }
        } else if (LOG.isDebugEnabled()) {
            LOG.debug("[RuntimeConfiguration] " + resourceName + " not found. Skipping configuration.");
        }
    } catch (Exception ex) {
        LOG.error("[RuntimeConfiguration] Unable to perform post initialization config: " + resourceName, ex);
    }

    GrailsRuntimeConfigurator.loadSpringGroovyResources(springConfig, app);
}