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

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

Introduction

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

Prototype

@Nullable
String getFilename();

Source Link

Document

Determine a filename for this resource, i.e.

Usage

From source file:org.codehaus.groovy.grails.context.support.PluginAwareResourceBundleMessageSource.java

public void afterPropertiesSet() throws Exception {
    if (pluginManager == null || localResourceLoader == null) {
        return;/*w  w w. j a va 2  s  .co m*/
    }

    for (GrailsPlugin plugin : pluginManager.getAllPlugins()) {
        for (Resource pluginBundle : getPluginBundles(plugin)) {
            // If the plugin is an inline plugin, use the abosolute path to the plugin's i18n files.
            // Otherwise, use the relative path to the plugin from the application's perspective.
            String basePath;
            if (isInlinePlugin(plugin)) {
                basePath = getInlinePluginPath(plugin);
            } else {
                basePath = WEB_INF_PLUGINS_PATH.substring(1) + plugin.getFileSystemName();
            }

            final String baseName = StringUtils
                    .substringBefore(FilenameUtils.getBaseName(pluginBundle.getFilename()), "_");
            pluginBaseNames.add(basePath + "/grails-app/i18n/" + baseName);
        }
    }
}

From source file:org.codehaus.groovy.grails.plugins.DefaultGrailsPluginManager.java

private Class<?> loadPluginClass(ClassLoader cl, Resource r) {
    Class<?> pluginClass;//from  w w w  .ja  va 2 s  .  c o  m
    if (cl instanceof GroovyClassLoader) {
        try {
            if (LOG.isInfoEnabled()) {
                LOG.info("Parsing & compiling " + r.getFilename());
            }
            pluginClass = ((GroovyClassLoader) cl).parseClass(IOGroovyMethods.getText(r.getInputStream()));
        } catch (CompilationFailedException e) {
            throw new PluginException("Error compiling plugin [" + r.getFilename() + "] " + e.getMessage(), e);
        } catch (IOException e) {
            throw new PluginException("Error reading plugin [" + r.getFilename() + "] " + e.getMessage(), e);
        }
    } else {
        String className = null;
        try {
            className = GrailsResourceUtils.getClassName(r.getFile().getAbsolutePath());
        } catch (IOException e) {
            throw new PluginException(
                    "Cannot find plugin class [" + className + "] resource: [" + r.getFilename() + "]", e);
        }
        try {
            pluginClass = Class.forName(className, true, cl);
        } catch (ClassNotFoundException e) {
            throw new PluginException(
                    "Cannot find plugin class [" + className + "] resource: [" + r.getFilename() + "]", e);
        }
    }
    return pluginClass;
}

From source file:org.codehaus.groovy.grails.web.mapping.DefaultUrlMappingEvaluator.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public List evaluateMappings(Resource resource) {
    InputStream inputStream = null;
    try {/* ww w.  j  a va  2  s.c o  m*/
        inputStream = resource.getInputStream();
        return evaluateMappings(classLoader.parseClass(IOGroovyMethods.getText(inputStream)));
    } catch (IOException e) {
        throw new UrlMappingException(
                "Unable to read mapping file [" + resource.getFilename() + "]: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.codehaus.mojo.gwt.webxml.ServletAnnotationFinder.java

/**
 * @param packageName/*w  w w  .  ja v  a 2 s.co  m*/
 * @return cannot return <code>null</null>
 * @throws IOException
 */
public Set<ServletDescriptor> findServlets(String packageName, String startPath, ClassLoader classLoader)
        throws IOException {
    Set<ServletDescriptor> servlets = new LinkedHashSet<ServletDescriptor>();
    PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver(
            classLoader);
    String patternFinder = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
            + ClassUtils.convertClassNameToResourcePath(packageName) + "/**/*.class";

    Resource[] resources = pathMatchingResourcePatternResolver.getResources(patternFinder);
    SimpleMetadataReaderFactory simpleMetadataReaderFactory = new SimpleMetadataReaderFactory();
    getLogger().debug("springresource " + resources.length + " for pattern " + patternFinder);
    for (Resource resource : resources) {
        getLogger().debug("springresource " + resource.getFilename());
        MetadataReader metadataReader = simpleMetadataReaderFactory.getMetadataReader(resource);

        if (metadataReader.getAnnotationMetadata().hasAnnotation(RemoteServiceRelativePath.class.getName())) {
            Map<String, Object> annotationAttributes = metadataReader.getAnnotationMetadata()
                    .getAnnotationAttributes(RemoteServiceRelativePath.class.getName());
            getLogger().debug("found RemoteServiceRelativePath annotation for class "
                    + metadataReader.getClassMetadata().getClassName());
            if (StringUtils.isNotBlank(startPath)) {
                StringBuilder path = new StringBuilder();
                if (!startPath.startsWith("/")) {
                    path.append('/');
                }
                path.append(startPath);
                String annotationPathValue = (String) annotationAttributes.get("value");
                if (!annotationPathValue.startsWith("/")) {
                    path.append('/');
                }
                path.append(annotationPathValue);
                ServletDescriptor servletDescriptor = new ServletDescriptor(path.toString(),
                        metadataReader.getClassMetadata().getClassName());
                servlets.add(servletDescriptor);
            } else {
                StringBuilder path = new StringBuilder();
                String annotationPathValue = (String) annotationAttributes.get("value");
                if (!annotationPathValue.startsWith("/")) {
                    path.append('/');
                }
                path.append(annotationPathValue);
                ServletDescriptor servletDescriptor = new ServletDescriptor(path.toString(),
                        metadataReader.getClassMetadata().getClassName());
                servlets.add(servletDescriptor);
            }
        }
    }
    return servlets;
}

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

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

    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.dataconservancy.dcs.integration.bootstrap.MetadataFormatRegistryBootstrap.java

public void bootstrapFormats() throws InterruptedException, IOException {

    if (isDisabled) {
        log.info("MetadataFormatRegistryBootstrap is disabled; not executing bootstrapping process.");
        return;//from  w w  w  .j  a  v  a2 s .co m
    }

    long bootStart = System.currentTimeMillis();
    log.info("Bootstrapping the DCS... ");
    MetadataSchemeMapper schemeMapper = new MetadataSchemeMapper();

    MetadataFormatMapper mapper = new MetadataFormatMapper(schemeMapper);

    Iterator<RegistryEntry<DcsMetadataFormat>> iter = memoryRegistry.iterator();

    List<DepositInfo> depositStatus = new ArrayList<DepositInfo>();

    while (iter.hasNext()) {
        RegistryEntry<DcsMetadataFormat> registryEntry = iter.next();

        try {
            if (queryService.lookup(registryEntry.getId()) != null) {
                // The archive already has the entry
                log.debug("Not bootstrapping registry entry {}: it is already in the archive.",
                        registryEntry.getId());
                continue;
            }
        } catch (QueryServiceException e) {
            log.warn("Error depositing DCP (skipping it): " + e.getMessage(), e);
            continue;
        }

        final Dcp entryDcp = mapper.to(registryEntry, null);

        for (DcsFile dcsFile : entryDcp.getFiles()) {
            final Resource r;
            if (dcsFile.getSource().startsWith(FILE_PREFIX)) {
                r = new FileSystemResource(new URL(dcsFile.getSource()).getPath());
            } else if (dcsFile.getSource().startsWith(CLASSPATH_PREFIX)) {
                r = new ClassPathResource(dcsFile.getSource().substring(CLASSPATH_PREFIX.length()));
            } else {
                throw new RuntimeException(
                        "Unknown file source " + dcsFile.getSource() + " for file name " + dcsFile.getName());
            }

            if (!r.exists()) {
                throw new RuntimeException("Resource " + r.getFilename() + " doesn't exist.");
            }

            Map<String, String> metadata = new HashMap<String, String>();
            HttpHeaderUtil.addDigest("SHA-1", calculateChecksum("SHA-1", r), metadata);
            metadata.put(HttpHeaderUtil.CONTENT_TYPE, APPLICATION_XML);
            metadata.put(HttpHeaderUtil.CONTENT_DISPOSITION, "filename=" + r.getFilename());
            metadata.put(HttpHeaderUtil.CONTENT_LENGTH, Long.toString(r.contentLength()));
            DepositInfo info = fileManager.deposit(r.getInputStream(), APPLICATION_XML, null, metadata);
            dcsFile.setSource(info.getMetadata().get(SRC_HEADER));
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        modelBuilder.buildSip(entryDcp, baos);
        try {
            Map<String, String> metadata = new HashMap<String, String>();
            metadata.put(HttpHeaderUtil.CONTENT_TYPE, APPLICATION_XML);
            metadata.put(HttpHeaderUtil.CONTENT_LENGTH, Integer.toString(baos.size()));
            final ByteArrayInputStream byteIn = new ByteArrayInputStream(baos.toByteArray());
            depositStatus.add(manager.deposit(byteIn, APPLICATION_XML, DCP_PACKAGING, metadata));
        } catch (PackageException e) {
            log.warn("Error depositing DCP: " + e.getMessage(), e);
            continue;
        }
    }

    Iterator<DepositInfo> statusItr = depositStatus.iterator();

    while (statusItr.hasNext()) {
        DepositInfo info = statusItr.next();
        try {
            if (!checkStatusUntilTimeout(info, 600000)) {
                File f;
                FileOutputStream fos = null;
                try {
                    f = File.createTempFile("bootstrap-", ".xml");
                    fos = new FileOutputStream(f);
                    IOUtils.copy(info.getDepositStatus().getInputStream(), fos);
                } finally {
                    if (fos != null) {
                        fos.close();
                    }
                }
                log.warn(
                        "Error bootstrapping the DCS; error depositing package {}: see {} for more information.",
                        info.getDepositID(), f.getAbsolutePath());
            }
        } catch (Exception e) {
            log.warn("Error bootstrapping the DCS; error depositing package {}: {}",
                    new Object[] { info.getDepositID(), e.getMessage(), e });
        }
    }

    log.info("Bootstrap complete in {} ms", System.currentTimeMillis() - bootStart);
}

From source file:org.dataconservancy.dcs.integration.bootstrap.MetadataFormatRegistryBootstrap.java

/**
 * Calculates a checksum for the supplied resource, using the supplied algorithm.
 *
 * @param algo the algorithm/*  w  w w . j ava 2s  .  c om*/
 * @param r the resource
 * @return the byte representation of the checksum
 * @throws RuntimeException if the checksum cannot be calculated for whatever reason
 */
private byte[] calculateChecksum(String algo, Resource r) {
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance(algo);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    InputStream in = null;
    try {
        in = r.getInputStream();
    } catch (Exception e) {
        throw new RuntimeException(
                "Unable to obtain inputstream for Resource " + r.getFilename() + ": " + e.getMessage(), e);
    }
    int read = 0;
    int size = 1024;
    byte[] buf = new byte[size];
    try {
        while ((read = in.read(buf, 0, size)) != -1) {
            md.update(buf, 0, read);
        }
    } catch (IOException e) {
        throw new RuntimeException(
                "Unable to calculate checksum for Resource " + r.getFilename() + ": " + e.getMessage(), e);
    }

    return md.digest();
}

From source file:org.dspace.servicemanager.config.DSpaceDynamicConfigurationService.java

private void loadConfiguration() {
    // now we load the settings from properties files
    String homePath = System.getProperty(DSPACE_HOME);

    // now we load from the provided parameter if its not null
    if (this.home != null && homePath == null) {
        homePath = this.home;
    }//  ww  w  . j a va2s. c  o m

    if (homePath == null) {
        String catalina = System.getProperty("catalina.base");
        if (catalina == null)
            catalina = System.getProperty("catalina.home");
        if (catalina != null) {
            homePath = catalina + File.separatorChar + DSPACE + File.separatorChar;
        }
    }
    if (homePath == null) {
        homePath = System.getProperty("user.home");
    }
    if (homePath == null) {
        homePath = "/";
    }

    try {
        config = new DSpacePropertiesConfiguration(homePath + File.separatorChar + DSPACE_CONFIG_PATH);
        File modulesDirectory = new File(
                homePath + File.separator + DSPACE_MODULES_CONFIG_PATH + File.separator);
        modulesConfig = new TreeMap<String, DSpacePropertiesConfiguration>();
        if (modulesDirectory.exists()) {
            try {
                Resource[] resources = new PathMatchingResourcePatternResolver()
                        .getResources(modulesDirectory.toURI().toURL().toString() + "*" + DOT_CONFIG);
                if (resources != null) {
                    for (Resource resource : resources) {
                        String prefix = resource.getFilename().substring(0,
                                resource.getFilename().lastIndexOf("."));
                        modulesConfig.put(prefix, new DSpacePropertiesConfiguration(resource.getFile()));
                    }
                }
            } catch (Exception e) {
                log.error("Error while loading the modules properties from:"
                        + modulesDirectory.getAbsolutePath());
            }
        } else {
            log.info("Failed to load the modules properties since (" + homePath + File.separator
                    + DSPACE_MODULES_CONFIG_PATH + "): Does not exist");
        }

    } catch (IllegalArgumentException e) {
        //This happens if we don't have a modules directory
        log.error("Error while loading the module properties since (" + homePath + File.separator
                + DSPACE_MODULES_CONFIG_PATH + "): is not a valid directory", e);
    } catch (ConfigurationException e) {
        // This happens if an error occurs on parsing files
        log.error(
                "Error while loading properties from " + homePath + File.separator + DSPACE_MODULES_CONFIG_PATH,
                e);
    }

    try {
        File addonsDirectory = new File(homePath + File.separator + DSPACE_ADDONS_CONFIG_PATH + File.separator);
        addonsConfig = new TreeMap<String, DSpacePropertiesConfiguration>();
        if (addonsDirectory.exists()) {
            try {
                Resource[] resources = new PathMatchingResourcePatternResolver()
                        .getResources(addonsDirectory.toURI().toURL().toString() + "*" + DOT_CONFIG);
                if (resources != null) {
                    for (Resource resource : resources) {
                        String prefix = resource.getFilename().substring(0,
                                resource.getFilename().lastIndexOf("."));
                        addonsConfig.put(prefix, new DSpacePropertiesConfiguration(resource.getFile()));
                    }
                }
            } catch (Exception e) {
                log.error(
                        "Error while loading the addons properties from:" + addonsDirectory.getAbsolutePath());
            }
        } else {
            log.info("Failed to load the addons properties since (" + homePath + File.separator
                    + DSPACE_ADDONS_CONFIG_PATH + "): Does not exist");
        }

    } catch (IllegalArgumentException e) {
        //This happens if we don't have a modules directory
        log.error("Error while loading the module properties since (" + homePath + File.separator
                + DSPACE_ADDONS_CONFIG_PATH + "): is not a valid directory", e);
    }
}

From source file:org.easycloud.las.core.util.Resources.java

/**
 * Load the given <tt>Resource</tt> and return
 * the contents as a String//ww w . ja  v  a  2s  . c  o m
 *
 * @param resource the <tt>Resource</tt>
 * @return the contents of the resource or null if it's an invalid resource
 */
public static String loadResource(Resource resource) {
    if (resource != null) {
        try {
            return loadResource(resource.getInputStream());
        } catch (Exception ex) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(ex.getMessage(), ex);
            }
            throw new FileOperationsException("Failed to load resource " + resource.getFilename(), ex);
        }
    }
    return null;
}

From source file:org.grails.spring.context.support.PluginAwareResourceBundleMessageSource.java

public void afterPropertiesSet() throws Exception {
    if (pluginCacheMillis == Long.MIN_VALUE) {
        pluginCacheMillis = cacheMillis;
    }//  w  ww.  j  a v  a  2 s.c o  m

    if (localResourceLoader == null) {
        return;
    }

    Resource[] resources;
    if (Environment.isDevelopmentMode()) {
        File[] propertiesFiles = new File(BuildSettings.BASE_DIR, GRAILS_APP_I18N_PATH_COMPONENT)
                .listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                        return name.endsWith(".properties");
                    }
                });
        if (propertiesFiles != null && propertiesFiles.length > 0) {
            List<Resource> resourceList = new ArrayList<Resource>(propertiesFiles.length);
            for (File propertiesFile : propertiesFiles) {
                resourceList.add(new FileSystemResource(propertiesFile));
            }
            resources = resourceList.toArray(new Resource[resourceList.size()]);
        } else {
            resources = new Resource[0];
        }
    } else {
        resources = resourceResolver.getResources("classpath*:**/*.properties");
    }

    List<String> basenames = new ArrayList<String>();
    for (Resource resource : resources) {
        String filename = resource.getFilename();
        String baseName = GrailsStringUtils.getFileBasename(filename);
        int i = baseName.indexOf('_');
        if (i > -1) {
            baseName = baseName.substring(0, i);
        }
        if (!basenames.contains(baseName) && !baseName.equals(""))
            basenames.add(baseName);
    }

    setBasenames(basenames.toArray(new String[basenames.size()]));

}