Example usage for org.springframework.core.io ResourceEditor ResourceEditor

List of usage examples for org.springframework.core.io ResourceEditor ResourceEditor

Introduction

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

Prototype

public ResourceEditor() 

Source Link

Document

Create a new instance of the ResourceEditor class using a DefaultResourceLoader and StandardEnvironment .

Usage

From source file:org.jspringbot.keyword.expression.ELUtils.java

public static String resource(String resourceAsText) throws Exception {
    ResourceEditor editor = new ResourceEditor();
    editor.setAsText(resourceAsText);//  www.j a v a 2  s. c  o  m

    Resource resource = (Resource) editor.getValue();
    String resourceString = IOUtils.toString(resource.getInputStream());

    return replaceVars(resourceString);
}

From source file:org.jspringbot.spring.KeywordUtils.java

/**
 * Retrieves the given keyword's description.
 *
 * @param keyword keyword name/*from  w  w w .  j  a  va  2  s  .  com*/
 * @param context Spring application context
 * @param beanMap keyword name to bean name mapping
 * @return the documentation string of the given keyword, or empty string if unavailable.
 */
public static String getDescription(String keyword, ApplicationContext context, Map<String, String> beanMap) {
    KeywordInfo keywordInfo = getKeywordInfo(keyword, context, beanMap);

    if (keywordInfo == null) {
        return "";
    }

    String desc = keywordInfo.description();

    if (desc.startsWith("classpath:")) {
        try {
            ResourceEditor editor = new ResourceEditor();
            editor.setAsText(desc);
            Resource r = (Resource) editor.getValue();

            return IOUtils.toString(r.getInputStream());
        } catch (Exception ignored) {
        }
    }

    return desc;
}

From source file:com.brienwheeler.lib.db.LocationValidatingPersistenceUnitManager.java

/**
 * Accept a list of locations for persistence XML files.  Before passing this list
 * to our superclass DefaultPersistenceUnitManager, check each location on the list
 * for actual existence.//from  w w w  .  j  a  v a 2  s  . c o m
 */
@Override
public void setPersistenceXmlLocations(String... persistenceXmlLocations) {
    ValidationUtils.assertNotNull(persistenceXmlLocations, "persistenceXmlLocations cannot be null");
    List<String> goodLocations = new ArrayList<String>();

    ResourceEditor editor = new ResourceEditor();
    for (String location : persistenceXmlLocations) {
        if (location == null || location.isEmpty())
            continue;

        editor.setAsText(location);
        Resource resource = (Resource) editor.getValue();
        if (resource != null && resource.exists()) {
            log.debug("using valid persistence XML location: " + location);
            goodLocations.add(location);
        } else {
            log.warn("ignoring invalid persistence XML location: " + location);
        }
    }

    String[] valid = goodLocations.toArray(new String[goodLocations.size()]);
    log.info("using validated persistence locations: [" + ArrayUtils.toString(valid) + "]");
    super.setPersistenceXmlLocations(valid);
}

From source file:org.jspringbot.keyword.db.DbHelper.java

public void init() {
    ResourceEditor editor = new ResourceEditor();
    editor.setAsText("classpath:db-queries/");
    Resource dbDirResource = (Resource) editor.getValue();

    boolean hasDBDirectory = true;
    boolean hasDBProperties = true;

    if (dbDirResource != null) {
        try {// w  w w . j a  v  a2  s . c  o m
            File configDir = dbDirResource.getFile();

            if (configDir.isDirectory()) {
                File[] propertiesFiles = configDir.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File file) {
                        return StringUtils.endsWith(file.getName(), ".properties")
                                || StringUtils.endsWith(file.getName(), ".xml");
                    }
                });

                for (File propFile : propertiesFiles) {
                    addExternalQueries(propFile);
                }
            }
        } catch (IOException ignore) {
            hasDBDirectory = false;
        }
    }

    editor.setAsText("classpath:db-queries.properties");
    Resource dbPropertiesResource = (Resource) editor.getValue();

    if (dbPropertiesResource != null) {
        try {
            if (dbPropertiesResource.getFile().isFile()) {
                addExternalQueries(dbPropertiesResource.getFile());
            }
        } catch (IOException e) {
            hasDBProperties = false;
        }
    }

    editor.setAsText("classpath:db-queries.xml");
    Resource dbXMLResource = (Resource) editor.getValue();

    if (dbXMLResource != null && !hasDBProperties) {
        try {
            if (dbXMLResource.getFile().isFile()) {
                addExternalQueries(dbXMLResource.getFile());
            }
        } catch (IOException e) {
            hasDBProperties = false;
        }
    }

    if (!hasDBDirectory && !hasDBProperties) {
        LOGGER.warn("No query sources found.");
    }

    begin();
}

From source file:org.springmodules.cache.config.AbstractCacheManagerAndProviderFacadeParser.java

/**
 * Parses the given XML element to obtain the value of the property
 * <code>configLocation</code>. This property specifies the location of the
 * configuration file to use to configure the cache manager.
 * //www .  j  a  v a 2  s  . c om
 * @param element
 *          the XML element to parse
 * @return the value of the property <code>configLocation</code>
 */
private PropertyValue parseConfigLocationProperty(Element element) {
    Resource resource = null;

    String configLocation = element.getAttribute("configLocation");
    if (StringUtils.hasText(configLocation)) {
        ResourceEditor resourceEditor = new ResourceEditor();
        resourceEditor.setAsText(configLocation);
        resource = (Resource) resourceEditor.getValue();
    }

    return new PropertyValue("configLocation", resource);
}

From source file:org.springmodules.cache.config.CacheManagerAndProviderFacadeParserTests.java

/**
 * Verifies that the method//from w  ww.j  a v  a  2  s.  com
 * <code>{@link AbstractCacheManagerAndProviderFacadeParser#doParse(String, Element, BeanDefinitionRegistry)}</code>
 * creates a <code>{@link Resource}</code> from the path specified in the
 * XML attribute "configLocation" and sets such resource as the value of the
 * property "configLocation" of the cache manager factory definition.
 * 
 * @throws Exception
 *           any exception thrown when reading the contents of the specified
 *           configuration file
 */
public void testDoParseWithExistingConfigLocation() throws Exception {
    configElementBuilder.configLocation = ("classpath:" + PathUtils.getPackageNameAsPath(getClass())
            + "/fakeConfigLocation.xml");
    Element element = configElementBuilder.toXml();

    expectGetCacheManagerClass();
    parserControl.replay();

    parser.doParse(BeanName.CACHE_PROVIDER_FACADE, element, registry);
    Resource configLocation = getConfigLocationFromCacheManager();

    ResourceEditor editor = new ResourceEditor();
    editor.setAsText(configElementBuilder.configLocation);
    String expectedContent = getResourceContent((Resource) editor.getValue());
    String actualContent = getResourceContent(configLocation);
    assertEquals("<Config resource content>", expectedContent, actualContent);

    assertCacheProviderFacadeHasCacheManagerAsProperty();
}

From source file:org.jspringbot.keyword.expression.ELUtils.java

private static Properties getInProperties(String location) throws IOException {
    if (inCache.containsKey(location)) {
        return inCache.get(location);
    }/*from   w w w .ja va2s . com*/

    ResourceEditor editor = new ResourceEditor();

    editor.setAsText(location);

    Resource resource = (Resource) editor.getValue();
    File inFile = resource.getFile();

    Properties properties = new Properties();
    properties.load(new FileReader(inFile));

    inCache.put(location, properties);

    return properties;
}

From source file:com.brienwheeler.lib.spring.beans.PropertyPlaceholderConfigurer.java

/**
 * Programatically process a single property file location, using System
 * properties in preference to included definitions for placeholder
 * resolution, and setting any resolved properties as System properties, if
 * no property by that name already exists.
 * /*w  w w . j a v  a  2 s  . co m*/
 * @param locationName String-encoded resource location for the properties file to process
 * @param placeholderPrefix the placeholder prefix String
 * @param placeholderSuffix the placeholder suffix String
 */
public static void processLocation(String locationName, String placeholderPrefix, String placeholderSuffix) {
    ResourceEditor resourceEditor = new ResourceEditor();
    resourceEditor.setAsText(locationName);

    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    configurer.setLocation((Resource) resourceEditor.getValue());
    if (placeholderPrefix != null)
        configurer.setPlaceholderPrefix(placeholderPrefix);
    if (placeholderSuffix != null)
        configurer.setPlaceholderSuffix(placeholderSuffix);
    configurer.quiet = true;

    GenericApplicationContext context = new GenericApplicationContext();
    context.getBeanFactory().registerSingleton("propertyPlaceholderConfigurer", configurer);
    context.refresh();
    context.close();
}

From source file:org.jspringbot.keyword.config.ConfigHelper.java

public void init() throws IOException {
    ResourceEditor editor = new ResourceEditor();
    editor.setAsText("classpath:config/");
    Resource configDirResource = (Resource) editor.getValue();

    boolean hasConfigDirectory = true;
    boolean hasConfigProperties = true;

    if (configDirResource != null) {
        try {//from  ww  w  .j  a va2s  .  com
            File configDir = configDirResource.getFile();

            if (configDir.isDirectory()) {
                File[] propertiesFiles = configDir.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File file) {
                        return StringUtils.endsWith(file.getName(), ".properties")
                                || StringUtils.endsWith(file.getName(), ".xml");
                    }
                });

                for (File propFile : propertiesFiles) {
                    String filename = propFile.getName();
                    String name = StringUtils.substring(filename, 0, StringUtils.indexOf(filename, "."));

                    addProperties(name, propFile);
                }
            }
        } catch (IOException e) {
            hasConfigDirectory = false;
        }
    }

    editor.setAsText("classpath:config.properties");
    Resource configPropertiesResource = (Resource) editor.getValue();

    if (configPropertiesResource != null) {
        try {
            File configPropertiesFile = configPropertiesResource.getFile();

            if (configPropertiesFile.isFile()) {
                Properties configs = new Properties();

                configs.load(new FileReader(configPropertiesFile));

                for (Map.Entry entry : configs.entrySet()) {
                    String name = (String) entry.getKey();
                    editor.setAsText(String.valueOf(entry.getValue()));

                    try {
                        Resource resource = (Resource) editor.getValue();
                        addProperties(name, resource.getFile());
                    } catch (Exception e) {
                        throw new IOException(String.format("Unable to load config '%s'.", name), e);
                    }
                }
            }
        } catch (IOException e) {
            hasConfigProperties = false;
        }
    }

    if (!hasConfigDirectory && !hasConfigProperties) {
        LOGGER.warn("No configuration found.");
    }
}

From source file:org.jspringbot.keyword.csv.CSVState.java

public void parseCSVResource(String resource) throws IOException {
    ResourceEditor editor = new ResourceEditor();
    editor.setAsText(resource);/*from  w  w  w.  j a va 2s.  c  o  m*/

    Resource r = (Resource) editor.getValue();

    readAll(new InputStreamReader(r.getInputStream()));

    LOG.createAppender().appendBold("Parse CSV Resource:").append(" (count=%d)", CollectionUtils.size(lines))
            .appendText(toCSV(lines)).log();
}