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:com.jiangnan.es.orm.mybatis.extend.SqlSessionFactoryBean.java

private void autoTypeAliases(Configuration configuration) throws IOException {
    String basePackage = this.basePackage.replaceAll("\\.", "/") + "/";

    List<String> lists = new ArrayList<String>();

    String testPath = "classpath*:" + basePackage + "**/*.class";
    ResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
    Resource[] source = new Resource[0];
    try {//w  ww.ja v  a2  s.  c o m
        source = resourceLoader.getResources(testPath);
    } catch (IOException e) {
        logger.warn("" + basePackage + "DTO");
    }

    for (int i = 0; i < source.length; i++) {
        Resource resource = source[i];

        logger.debug("file:" + resource.getURI().toString());
        int start = resource.getURI().toString().lastIndexOf(basePackage) + basePackage.length();
        int end = resource.getURI().toString().lastIndexOf(resource.getFilename());
        String packageName = resource.getURI().toString().substring(start, end);
        lists.add(basePackage + packageName + resource.getFilename());
        logger.debug("CLASS:" + basePackage + packageName + resource.getFilename());
    }

    for (String className : lists) {
        try {
            className = className.substring(0, className.indexOf(".class")).replaceAll("/", "\\.");
            Class<?> c = Class.forName(className);
            if (Entity.class.isAssignableFrom(c)) {
                configuration.getTypeAliasRegistry().registerAlias(c);
            }
            if (c.getSimpleName().toUpperCase().endsWith("DTO")) {
                configuration.getTypeAliasRegistry().registerAlias(c);
            }
        } catch (java.lang.ExceptionInInitializerError e) {
            logger.warn("" + className);
            continue;
        } catch (ClassNotFoundException e) {
            logger.warn("" + className);
            continue;
        } catch (Exception e) {
            logger.warn("?" + className);
            continue;
        }
    }
}

From source file:org.parancoe.web.util.ReloadableResourceBundleMessageSource.java

/**
 * Load the properties from the given resource.
 *
 * @param resource the resource to load from
 * @param filename the original bundle filename (basename + Locale)
 * @return the populated Properties instance
 * @throws IOException if properties loading failed
 *//* w ww .jav  a 2 s.c  om*/
protected Properties loadProperties(Resource resource, String filename) throws IOException {
    InputStream is = resource.getInputStream();
    Properties props = new Properties();
    try {
        if (resource.getFilename().endsWith(XML_SUFFIX)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Loading properties [" + resource.getFilename() + "]");
            }
            this.propertiesPersister.loadFromXml(props, is);
        } else {
            String encoding = null;
            if (this.fileEncodings != null) {
                encoding = this.fileEncodings.getProperty(filename);
            }
            if (encoding == null) {
                encoding = this.defaultEncoding;
            }
            if (encoding != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Loading properties [" + resource.getFilename() + "] with encoding '"
                            + encoding + "'");
                }
                this.propertiesPersister.load(props, new InputStreamReader(is, encoding));
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Loading properties [" + resource.getFilename() + "]");
                }
                this.propertiesPersister.load(props, is);
            }
        }
        return props;
    } finally {
        is.close();
    }
}

From source file:ua.com.manometer.jasperreports.AbstractJasperReportsView.java

/**
 * Loads a <code>JasperReport</code> from the specified <code>Resource</code>.
 * If the <code>Resource</code> points to an uncompiled report design file then
 * the report file is compiled dynamically and loaded into memory.
 * @param resource the <code>Resource</code> containing the report definition or design
 * @return a <code>JasperReport</code> instance
 *///  w  w w  . j  av a2s .c  om
protected final JasperReport loadReport(Resource resource) {
    try {
        String fileName = resource.getFilename();
        if (fileName.endsWith(".jasper")) {
            // Load pre-compiled report.
            if (logger.isInfoEnabled()) {
                logger.info("Loading pre-compiled Jasper Report from " + resource);
            }
            InputStream is = resource.getInputStream();
            try {
                return (JasperReport) JRLoader.loadObject(is);
            } finally {
                is.close();
            }
        } else if (fileName.endsWith(".jrxml")) {
            // Compile report on-the-fly.
            if (logger.isInfoEnabled()) {
                logger.info("Compiling Jasper Report loaded from " + resource);
            }
            InputStream is = resource.getInputStream();
            try {
                JasperDesign design = JRXmlLoader.load(is);
                return JasperCompileManager.compileReport(design);
            } finally {
                is.close();
            }
        } else {
            throw new IllegalArgumentException(
                    "Report filename [" + fileName + "] must end in either .jasper or .jrxml");
        }
    } catch (IOException ex) {
        throw new ApplicationContextException("Could not load JasperReports report from " + resource, ex);
    } catch (JRException ex) {
        throw new ApplicationContextException("Could not parse JasperReports report from " + resource, ex);
    }
}

From source file:grails.plugins.DefaultGrailsPluginManager.java

private Class<?> loadPluginClass(ClassLoader cl, Resource r) {
    Class<?> pluginClass;//from  w  ww.  ja va2 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(), "UTF-8"));
        } 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:net.sourceforge.vulcan.spring.SpringPluginManager.java

private void importBundledPlugins() {
    if (!importBundledPlugins) {
        return;/*  w w  w.  ja v  a 2s  .co  m*/
    }

    final Resource[] resources;

    try {
        resources = ctx.getResources(bundledPluginResourcesPattern);
    } catch (IOException e) {
        log.error("Failure looking for bundled plugins", e);
        return;
    }

    for (Resource r : resources) {
        try {
            configurationStore.extractPlugin(r.getInputStream());
        } catch (DuplicatePluginIdException ignore) {
            // This happens when plugin is up to date.
        } catch (Exception e) {
            ErrorEvent errorEvent = new ErrorEvent(this, "PluginManager.load.failed",
                    new Object[] { r.getFilename(), e.getMessage() }, e);
            eventHandler.reportEvent(errorEvent);
        }
    }
}

From source file:nl.basjes.parse.useragent.UserAgentAnalyzer.java

public void loadResources(String resourceString, boolean showMatcherStats) {
    LOG.info("Loading from: \"{}\"", resourceString);

    flattener = new UserAgentTreeFlattener(this);
    yaml = new Yaml();

    Map<String, Resource> resources = new TreeMap<>();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {//from   w  ww.  j  a v a2s  .  co  m
        Resource[] resourceArray = resolver.getResources(resourceString);
        for (Resource resource : resourceArray) {
            resources.put(resource.getFilename(), resource);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    doingOnlyASingleTest = false;
    int maxFilenameLength = 0;

    if (resources.isEmpty()) {
        throw new InvalidParserConfigurationException("Unable to find ANY config files");
    }

    for (Map.Entry<String, Resource> resourceEntry : resources.entrySet()) {
        try {
            Resource resource = resourceEntry.getValue();
            String filename = resource.getFilename();
            maxFilenameLength = Math.max(maxFilenameLength, filename.length());
            loadResource(resource.getInputStream(), filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    LOG.info("Loaded {} files", resources.size());

    if (lookups != null && !lookups.isEmpty()) {
        // All compares are done in a case insensitive way. So we lowercase ALL keys of the lookups beforehand.
        Map<String, Map<String, String>> cleanedLookups = new HashMap<>(lookups.size());
        for (Map.Entry<String, Map<String, String>> lookupsEntry : lookups.entrySet()) {
            Map<String, String> cleanedLookup = new HashMap<>(lookupsEntry.getValue().size());
            for (Map.Entry<String, String> entry : lookupsEntry.getValue().entrySet()) {
                cleanedLookup.put(entry.getKey().toLowerCase(), entry.getValue());
            }
            cleanedLookups.put(lookupsEntry.getKey(), cleanedLookup);
        }
        lookups = cleanedLookups;
    }

    LOG.info("Building all matchers");
    int totalNumberOfMatchers = 0;
    int skippedMatchers = 0;
    if (matcherConfigs != null) {
        long fullStart = System.nanoTime();
        for (Map.Entry<String, Resource> resourceEntry : resources.entrySet()) {
            Resource resource = resourceEntry.getValue();
            String configFilename = resource.getFilename();
            List<Map<String, List<String>>> matcherConfig = matcherConfigs.get(configFilename);
            if (matcherConfig == null) {
                continue; // No matchers in this file (probably only lookups and/or tests)
            }

            long start = System.nanoTime();
            int startSize = informMatcherActions.size();
            for (Map<String, List<String>> map : matcherConfig) {
                try {
                    allMatchers.add(new Matcher(this, lookups, wantedFieldNames, map));
                    totalNumberOfMatchers++;
                } catch (UselessMatcherException ume) {
                    skippedMatchers++;
                }
            }
            long stop = System.nanoTime();
            int stopSize = informMatcherActions.size();

            if (showMatcherStats) {
                Formatter msg = new Formatter(Locale.ENGLISH);
                msg.format(
                        "Building %4d matchers from %-" + maxFilenameLength
                                + "s took %5d msec resulted in %8d extra hashmap entries",
                        matcherConfig.size(), configFilename, (stop - start) / 1000000, stopSize - startSize);
                LOG.info(msg.toString());
            }
        }
        long fullStop = System.nanoTime();

        Formatter msg = new Formatter(Locale.ENGLISH);
        msg.format(
                "Building %4d (dropped %4d) matchers from %4d files took %5d msec resulted in %8d hashmap entries",
                totalNumberOfMatchers, skippedMatchers, matcherConfigs.size(), (fullStop - fullStart) / 1000000,
                informMatcherActions.size());
        LOG.info(msg.toString());

    }
    LOG.info("Analyzer stats");
    LOG.info("Lookups      : {}", (lookups == null) ? 0 : lookups.size());
    LOG.info("Matchers     : {} (total:{} ; dropped: {})", allMatchers.size(), totalNumberOfMatchers,
            skippedMatchers);
    LOG.info("Hashmap size : {}", informMatcherActions.size());
    LOG.info("Testcases    : {}", testCases.size());
    //        LOG.info("All possible field names:");
    //        int count = 1;
    //        for (String fieldName : getAllPossibleFieldNames()) {
    //            LOG.info("- {}: {}", count++, fieldName);
    //        }
}

From source file:com.gst.infrastructure.core.boot.EmbeddedTomcatWithSSLConfiguration.java

public File getFile(Resource resource) throws IOException {
    try {/*w  ww . j av a2 s.  c o m*/
        return resource.getFile();
    } catch (IOException e) {
        // Uops.. OK, try again (below)
    }

    try {
        URL url = resource.getURL();
        /**
         * // If this creates filenames that are too long on Win, // then
         * could just use resource.getFilename(), // even though not unique,
         * real risk prob. min.bon String tempDir =
         * System.getProperty("java.io.tmpdir"); tempDir = tempDir + "/" +
         * getClass().getSimpleName() + "/"; String path = url.getPath();
         * String uniqName = path.replace("file:/", "").replace('!', '_');
         * String tempFullPath = tempDir + uniqName;
         **/
        // instead of File.createTempFile(prefix?, suffix?);
        File targetFile = new File(resource.getFilename());
        long len = resource.contentLength();
        if (!targetFile.exists() || targetFile.length() != len) { // Only
                                                                  // copy
                                                                  // new
                                                                  // files
            FileUtils.copyURLToFile(url, targetFile);
        }
        return targetFile;
    } catch (IOException e) {
        // Uops.. erm, give up:
        throw new IOException("Cannot obtain a File for Resource: " + resource.toString(), e);
    }

}

From source file:grails.spring.BeanBuilder.java

/**
 * Imports Spring bean definitions from either XML or Groovy sources into the current bean builder instance
 *
 * @param resourcePattern The resource pattern
 *///from w w  w.j av a  2  s  . c o m
public void importBeans(String resourcePattern) {
    try {
        Resource[] resources = resourcePatternResolver.getResources(resourcePattern);
        for (Resource resource : resources) {
            if (resource.getFilename().endsWith(".groovy")) {
                loadBeans(resource);
            } else if (resource.getFilename().endsWith(".xml")) {
                SimpleBeanDefinitionRegistry beanRegistry = new SimpleBeanDefinitionRegistry();
                XmlBeanDefinitionReader beanReader = new XmlBeanDefinitionReader(beanRegistry);
                beanReader.loadBeanDefinitions(resource);
                String[] beanNames = beanRegistry.getBeanDefinitionNames();
                for (String beanName : beanNames) {
                    springConfig.addBeanDefinition(beanName, beanRegistry.getBeanDefinition(beanName));
                }
            }
        }
    } catch (IOException e) {
        LOG.error("Error loading beans for resource pattern: " + resourcePattern, e);
    }
}

From source file:com.apdplat.platform.spring.APDPlatPersistenceUnitReader.java

/**
 * Determine the persistence unit root URL based on the given resource
 * (which points to the <code>persistence.xml</code> file we're reading).
 * @param resource the resource to check
 * @return the corresponding persistence unit root URL
 * @throws IOException if the checking failed
 *///from  w  w w  .  j  av a2 s .  co  m
protected URL determinePersistenceUnitRootUrl(Resource resource) throws IOException {
    URL originalURL = resource.getURL();
    String urlToString = originalURL.toExternalForm();

    // If we get an archive, simply return the jar URL (section 6.2 from the JPA spec)
    if (ResourceUtils.isJarURL(originalURL)) {
        return ResourceUtils.extractJarFileURL(originalURL);
    }

    else {
        // check META-INF folder
        if (!urlToString.contains(META_INF)) {
            if (logger.isInfoEnabled()) {
                logger.info(resource.getFilename()
                        + " should be located inside META-INF directory; cannot determine persistence unit root URL for "
                        + resource);
            }
            return null;
        }
        if (urlToString.lastIndexOf(META_INF) == urlToString.lastIndexOf('/') - (1 + META_INF.length())) {
            if (logger.isInfoEnabled()) {
                logger.info(resource.getFilename()
                        + " is not located in the root of META-INF directory; cannot determine persistence unit root URL for "
                        + resource);
            }
            return null;
        }

        String persistenceUnitRoot = urlToString.substring(0, urlToString.lastIndexOf(META_INF));
        return new URL(persistenceUnitRoot);
    }
}

From source file:com.formkiq.web.AbstractIntegrationTest.java

/**
 * Get DB Migration Scripts.//  www . j  a va2 s  . c o  m
 * @return {@link String}
 * @throws IOException IOException
 */
protected List<String> getDBSystemPropertiesMigrationScripts() throws IOException {

    List<String> list = new ArrayList<>();
    ClassLoader cl = this.getClass().getClassLoader();
    ResourcePatternResolver r = new PathMatchingResourcePatternResolver(cl);
    Resource[] resources = r.getResources("classpath:db/migration/*.sql");
    for (Resource resource : resources) {
        list.add("/db/migration/" + resource.getFilename());
    }

    Collections.sort(list);

    List<String> sqls = new ArrayList<>();
    for (String s : list) {

        String txt = Resources.getResourceAsString(s);
        String[] lines = Strings.splitByNewLine(txt);
        for (String l : lines) {
            if (l.contains("system_properties") && l.contains("update")) {
                sqls.add(l);
            } else if (l.contains("system_properties") && l.contains("key.public")) {
                sqls.add(l);
            }
        }
    }

    return sqls;
}