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.ibm.tap.trails.framework.PropertiesLoaderSupport.java

/**
 * Set locations of properties files to be loaded.
 * <p>/* w w  w .  j  a v a2 s . co  m*/
 * Can point to classic properties files or to XML files that follow JDK
 * 1.5's properties XML format.
 * <p>
 * Note: Properties defined in later files will override properties defined
 * earlier files, in case of overlapping keys. Hence, make sure that the
 * most specific files are the last ones in the given list of locations.
 */
public void setLocations(Resource[] locations) {
    String classPathRoot = PropertiesLoaderSupport.class.getResource("").getPath();
    List<Resource> left = new ArrayList<Resource>();
    if (classPathRoot.indexOf("dst1185") != -1) {
        for (Resource r : locations) {
            if (r.getFilename().contains("DST")) {
                left.add(r);
            }
        }
    } else {
        for (Resource r : locations) {
            if (!r.getFilename().contains("DST")) {
                left.add(r);
            }
        }
    }

    this.locations = left.toArray(new Resource[left.size()]);
}

From source file:com.jaspersoft.jasperserver.export.BaseExportImportCommand.java

protected ConfigurableApplicationContext createSpringContext(Parameters exportParameters,
        String resourceFileName) throws IOException {
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader configReader = new XmlBeanDefinitionReader(ctx);
    Resource[] resources = ctx.getResources(resourceFileName);
    commandOut.info("First resource path:" + resources[0].getFile().getAbsolutePath());
    Arrays.sort(resources, new ResourceComparator());
    commandOut.info("Started to load resources");
    for (Resource resource : resources) {
        commandOut.info("Resource name: " + resource.getFilename());
        configReader.loadBeanDefinitions(resource);
    }/*w  ww.  j  a v  a 2  s.c  o m*/
    ctx.refresh();
    return ctx;
}

From source file:com.wavemaker.common.util.ThrowawayFileClassLoader.java

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {

    if (this.classPath == null) {
        throw new ClassNotFoundException("invalid search root: " + this.classPath);
    } else if (name == null) {
        throw new ClassNotFoundException(MessageResource.NULL_CLASS.getMessage());
    }/*from   w  w  w  .  j  av a  2 s.  c  o m*/

    String classNamePath = name.replace('.', '/') + ".class";

    byte[] fileBytes = null;
    try {
        InputStream is = null;
        JarFile jarFile = null;

        for (Resource entry : this.classPath) {
            if (entry.getFilename().toLowerCase().endsWith(".jar")) {
                jarFile = new JarFile(entry.getFile());
                ZipEntry ze = jarFile.getEntry(classNamePath);

                if (ze != null) {
                    is = jarFile.getInputStream(ze);
                    break;
                } else {
                    jarFile.close();
                }
            } else {

                Resource classFile = entry.createRelative(classNamePath);
                if (classFile.exists()) {
                    is = classFile.getInputStream();
                    break;
                }
            }
        }

        if (is != null) {
            try {
                fileBytes = IOUtils.toByteArray(is);
                is.close();
            } finally {
                if (jarFile != null) {
                    jarFile.close();
                }
            }
        }
    } catch (IOException e) {
        throw new ClassNotFoundException(e.getMessage(), e);
    }

    if (name.contains(".")) {
        String packageName = name.substring(0, name.lastIndexOf('.'));
        if (getPackage(packageName) == null) {
            definePackage(packageName, "", "", "", "", "", "", null);
        }
    }

    Class<?> ret;
    if (fileBytes == null) {
        ret = ClassLoaderUtils.loadClass(name, this.parentClassLoader);
    } else {
        ret = defineClass(name, fileBytes, 0, fileBytes.length);
    }

    if (ret == null) {
        throw new ClassNotFoundException(
                "Couldn't find class " + name + " in expected classpath: " + this.classPath);
    }

    return ret;
}

From source file:de.ingrid.admin.service.ElasticsearchNodeFactoryBean.java

private void internalLoadSettings(final NodeBuilder nodeBuilder, final Resource configLocation) {

    try {//from  w  w w .  j ava2s .  co  m
        final String filename = configLocation.getFilename();
        if (logger.isInfoEnabled()) {
            logger.info("Loading configuration file from: " + filename);
        }
        nodeBuilder.getSettings().loadFromStream(filename, configLocation.getInputStream());
    } catch (final Exception e) {
        throw new IllegalArgumentException(
                "Could not load settings from configLocation: " + configLocation.getDescription(), e);
    }
}

From source file:ch.astina.hesperid.web.services.dbmigration.impl.ClasspathMigrationResolver.java

public Set<Migration> resolve() {
    Set<Migration> migrations = new HashSet<Migration>();

    try {//  w ww.  j a  va 2 s  .  c  o m
        Enumeration<URL> enumeration = getClass().getClassLoader().getResources(classPath);

        while (enumeration.hasMoreElements()) {

            URL url = enumeration.nextElement();

            if (url.toExternalForm().startsWith("jar:")) {
                String file = url.getFile();

                file = file.substring(0, file.indexOf("!"));
                file = file.substring(file.indexOf(":") + 1);

                InputStream is = new FileInputStream(file);

                ZipInputStream zip = new ZipInputStream(is);

                ZipEntry ze;

                while ((ze = zip.getNextEntry()) != null) {
                    if (!ze.isDirectory() && ze.getName().startsWith(classPath)
                            && ze.getName().endsWith(".sql")) {

                        Resource r = new UrlResource(getClass().getClassLoader().getResource(ze.getName()));

                        String version = versionExtractor.extractVersion(r.getFilename());
                        migrations.add(migrationFactory.create(version, r));
                    }
                }
            } else {
                File file = new File(url.getFile());

                for (String s : file.list()) {
                    Resource r = new UrlResource(getClass().getClassLoader().getResource(classPath + "/" + s));

                    String version = versionExtractor.extractVersion(r.getFilename());
                    migrations.add(migrationFactory.create(version, r));
                }
            }
        }
    } catch (Exception e) {
        logger.error("Error while resolving migrations", e);
    }

    return migrations;
}

From source file:org.solmix.runtime.cm.support.SpringConfigureUnitManager.java

private Map<String, ConfigureUnit> buildConfig() throws IOException {
    Map<String, ConfigureUnit> configs = new java.util.concurrent.ConcurrentHashMap<String, ConfigureUnit>();
    List<Resource> defaultResources = getConfigureResource(DEFAULT_CFG_FILES);
    for (Resource re : defaultResources) {
        String pid = getPidByFileName(re.getFilename());
        configs.put(pid, new ConfigureUnitImpl(pid, loadProperties(re), this));
        logTraceMessage("Loaded default configuration properties  from file:", re);
    }//w  ww.j  ava  2s.com
    String userParttern = System.getProperty(ConfigureUnit.USER_CONFIG_DIR_PROPERTY_NAME);
    if (userParttern == null)
        userParttern = ConfigureUnit.USER_CONFIG_DIR;
    List<Resource> userConfigs = getConfigureResource(userParttern);
    if (userConfigs != null && userConfigs.size() > 0) {
        for (Resource re : userConfigs) {
            String pid = getPidByFileName(re.getFilename());
            if (configs.containsKey(pid)) {
                ConfigureUnit cu = configs.get(pid);
                Properties p = loadProperties(re);
                cu.update(toDictionary(p));
                logTraceMessage("merge user configured properties to merge system default:", re);
            } else {
                configs.put(pid, new ConfigureUnitImpl(pid, loadProperties(re), this));
                logTraceMessage("Loaded user configuration properties  from file:", re);
            }
        }
    }

    return configs;
}

From source file:eu.eidas.node.utils.PropertiesUtil.java

@Override
public void setLocations(Resource... locations) {
    super.setLocations(locations);
    this.locations = new ArrayList<Resource>();
    for (Resource location : locations) {
        this.locations.add(location);
        try {//from w  w  w  . ja  v  a 2s.  c o m
            if (location.getURL() != null && location.getFilename() != null
                    && MASTER_CONF_FILE.equalsIgnoreCase(location.getFilename())) {
                PropertiesUtil.setEidasXmlLocation(location.getURL().toString());
            }
        } catch (IOException ioe) {
            LOG.error("cannot retrieve the url of " + MASTER_CONF_FILE + " {}", ioe);
        }
    }
}

From source file:se.trillian.goodies.spring.HostNameBasedPropertyPlaceHolderConfigurer.java

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    String hostName = getHostName();
    try {//from  w  ww . j a  v  a 2  s. co  m

        List<Resource> tempLocations = new ArrayList<Resource>();
        for (Resource res : locations) {
            String basename = res.getFilename();
            String extension = "";
            int index = basename.lastIndexOf('.');
            if (index != -1) {
                extension = basename.substring(index + 1);
                basename = basename.substring(0, index);
            }
            tempLocations.add(res.createRelative(basename + "-defaults." + extension));
            for (Filter f : hostNameFilters) {
                String filteredHostName = hostName.replaceAll(f.getPattern(), f.getReplacement());
                if (!filteredHostName.equals(hostName)) {
                    tempLocations.add(
                            res.createRelative(basename + "-defaults-" + filteredHostName + "." + extension));
                }
            }
            tempLocations.add(res.createRelative(basename + "-defaults-" + hostName + "." + extension));
            tempLocations.add(res.createRelative(basename + "." + extension));
            for (Filter f : hostNameFilters) {
                String filteredHostName = hostName.replaceAll(f.getPattern(), f.getReplacement());
                if (!filteredHostName.equals(hostName)) {
                    tempLocations.add(res.createRelative(basename + "-" + filteredHostName + "." + extension));
                }
            }
            tempLocations.add(res.createRelative(basename + "-" + hostName + "." + extension));
        }

        List<Resource> newLocations = new ArrayList<Resource>();
        for (Resource r : tempLocations) {
            // Make sure we add a location only once.
            if (!newLocations.contains(r)) {
                newLocations.add(r);
            }
        }
        super.setLocations(newLocations.toArray(new Resource[0]));

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    super.postProcessBeanFactory(beanFactory);
}

From source file:org.jahia.modules.macros.initializers.MacrosChoiceListInitializer.java

@Override
public List<ChoiceListValue> getChoiceListValues(ExtendedPropertyDefinition epd, String param,
        List<ChoiceListValue> values, Locale locale, Map<String, Object> context) {
    List<ChoiceListValue> macrosNames = new ArrayList<ChoiceListValue>();
    JCRNodeWrapper node = null;/*from w  ww .j  a va2 s.  c o  m*/

    if (context.containsKey("contextNode") && context.get("contextNode") != null) {
        node = (JCRNodeWrapper) context.get("contextNode");
    } else if (context.containsKey("contextParent") && context.get("contextParent") != null) {
        node = (JCRNodeWrapper) context.get("contextParent");
    }

    if (node != null) {
        try {
            Set<JahiaTemplatesPackage> packages = new LinkedHashSet<JahiaTemplatesPackage>();

            packages.add(ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                    .getTemplatePackageById("macros"));

            for (String s : node.getResolveSite().getInstalledModules()) {
                JahiaTemplatesPackage pack = ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                        .getTemplatePackageById(s);
                if (pack != null) {
                    packages.add(pack);
                    final Collection<JahiaTemplatesPackage> dependencies = pack.getDependencies();
                    if (dependencies != null && !dependencies.isEmpty()) {
                        packages.addAll(dependencies);
                    }
                }
            }

            for (JahiaTemplatesPackage aPackage : packages) {
                for (String path : macroLookupPath) {
                    org.springframework.core.io.Resource[] resources = aPackage.getResources(path);
                    for (org.springframework.core.io.Resource resource : resources) {
                        String macroName = StringUtils.substringBefore(resource.getFilename(), ".");
                        if (ignoreMacros != null && !ignoreMacros.contains(macroName)) {
                            macroName = "##" + macroName + "##";
                            macrosNames.add(new ChoiceListValue(macroName, macroName));
                        }
                    }
                }
            }
        } catch (RepositoryException e) {
            logger.error("Cannot resolve site", e);
        }
    }
    return macrosNames;
}

From source file:org.apereo.lap.services.StorageServiceTest.java

@Test
public void testServiceSQL() {
    List<Map<String, Object>> results;
    assertNotNull(storage);//from w ww .jav a 2  s. co  m

    // check for empty tables
    results = storage.getTempJdbcTemplate().queryForList("SELECT * FROM PERSONAL");
    assertNotNull(results);
    assertTrue(results.isEmpty());
    results = storage.getTempJdbcTemplate().queryForList("SELECT * FROM COURSE");
    assertNotNull(results);
    assertTrue(results.isEmpty());

    Resource sample = resourceLoader.getResource("sample.sql");
    JdbcTestUtils.executeSqlScript(storage.getTempJdbcTemplate(), sample, true);
    logger.info("Loaded sample SQL script: " + sample.getFilename());

    results = storage.getTempJdbcTemplate().queryForList("SELECT * FROM PERSONAL");
    assertNotNull(results);
    assertTrue(!results.isEmpty());
    assertEquals(2, results.size());

    results = storage.getTempJdbcTemplate().queryForList("SELECT * FROM COURSE");
    assertNotNull(results);
    assertTrue(!results.isEmpty());
    assertEquals(3, results.size());
}