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

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

Introduction

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

Prototype

public DefaultResourceLoader() 

Source Link

Document

Create a new DefaultResourceLoader.

Usage

From source file:fi.solita.phantomrunner.PhantomRunner.java

private String phantomRunnerInitializerPath() {
    try {//from ww  w  .  j  a  v  a2  s .  c  o  m
        Resource initializer = new DefaultResourceLoader().getResource("classpath:PhantomRunnerInitializer.js");
        return FileUtils.extractResourceToTempDirectory(initializer, "", true).getAbsolutePath();
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:org.jruby.rack.mock.MockServletContext.java

/**
 * Create a new MockServletContext./*from  w  w w  .  jav a  2s.  c  om*/
 * @param resourceBasePath the WAR root directory (should not end with a slash)
 * @param resourceLoader the ResourceLoader to use (or null for the default)
 */
MockServletContext(String resourceBasePath, ResourceLoader resourceLoader) {
    this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
    this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");

    // Use JVM temp dir as ServletContext temp dir.
    String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
    if (tempDir != null) {
        this.attributes.put(TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
    }
}

From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java

@Test
public void testCreateRolePerms() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletContext context = mock(ServletContext.class);
    ApplicationContext appContext = mock(ApplicationContext.class);

    Principal p = mock(Principal.class);

    when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms")).thenReturn(null);
    when(context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE))
            .thenReturn(appContext);//from   w w w.j  a va 2  s . c o m
    when(context.getInitParameter("contextAuthConfigLocation")).thenReturn("somewhere");
    when(appContext.getResource("somewhere")).thenReturn(
            new DefaultResourceLoader().getResource("com/betfair/tornjak/monitor/overlay/auth.properties"));

    when(request.getUserPrincipal()).thenReturn(p);
    when(request.isUserInRole("jmxadmin")).thenReturn(true);

    Auth auth = AuthUtils.checkAuthorised(request, response, context);

    assertThat(auth, notNullValue());
    assertThat("User should be authorised", auth.check(), equalTo(AUTHORISED));
}

From source file:fi.solita.phantomrunner.PhantomRunner.java

private String utilsPath() {
    try {//from  w w  w.  j a v a2  s  .c o  m
        Resource initializer = new DefaultResourceLoader().getResource("classpath:utils.js");
        return FileUtils.extractResourceToTempDirectory(initializer, "", true).getAbsolutePath();
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.mtgi.analytics.aop.config.TemplateBeanDefinitionParser.java

/**
 * <p>Load the template BeanDefinition and call {@link #transform(ConfigurableListableBeanFactory, BeanDefinition, Element, ParserContext)}
 * to apply runtime configuration value to it.  <code>builder</code> will be configured to instantiate the bean
 * in the Spring context that we are parsing.</p>
 * /*from   ww w  .  j  a v a  2  s  .co  m*/
 * <p>During parsing, an instance of {@link TemplateBeanDefinitionParser.TemplateComponentDefinition} is pushed onto <code>ParserContext</code> so
 * that nested tags can access the enclosing template configuration with a call to {@link #findEnclosingTemplateFactory(ParserContext)}.
 * Subclasses can override {@link #newComponentDefinition(String, Object, DefaultListableBeanFactory)} to provide a 
 * subclass of {@link TemplateBeanDefinitionParser.TemplateComponentDefinition} to the parser context if necessary.</p>
 */
@Override
protected final void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {

    //if we have multiple nested bean definitions, we only parse the template factory
    //once.  this allows configuration changes made by enclosing bean parsers to be inherited
    //by contained beans, which is quite useful.
    DefaultListableBeanFactory templateFactory = findEnclosingTemplateFactory(parserContext);
    TemplateComponentDefinition tcd = null;
    if (templateFactory == null) {

        //no nesting -- load the template XML configuration from the classpath.
        final BeanFactory parentFactory = (BeanFactory) parserContext.getRegistry();
        templateFactory = new DefaultListableBeanFactory(parentFactory);

        //load template bean definitions
        DefaultResourceLoader loader = new DefaultResourceLoader();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(templateFactory);
        reader.setResourceLoader(loader);
        reader.setEntityResolver(new ResourceEntityResolver(loader));
        reader.loadBeanDefinitions(templateResource);

        //propagate factory post-processors from the source factory into the template
        //factory.
        BeanDefinition ppChain = new RootBeanDefinition(ChainingBeanFactoryPostProcessor.class);
        ppChain.getPropertyValues().addPropertyValue("targetFactory", templateFactory);
        parserContext.getReaderContext().registerWithGeneratedName(ppChain);

        //push component definition onto the parser stack for the benefit of
        //nested bean definitions.
        tcd = newComponentDefinition(element.getNodeName(), parserContext.extractSource(element),
                templateFactory);
        parserContext.pushContainingComponent(tcd);
    }

    try {
        //allow subclasses to apply overrides to the template bean definition.
        BeanDefinition def = templateFactory.getBeanDefinition(templateId);
        transform(templateFactory, def, element, parserContext);

        //setup our factory bean to instantiate the modified bean definition upon request.
        builder.addPropertyValue("beanFactory", templateFactory);
        builder.addPropertyValue("beanName", templateId);
        builder.getRawBeanDefinition().setAttribute("id", def.getAttribute("id"));

    } finally {
        if (tcd != null)
            parserContext.popContainingComponent();
    }
}

From source file:org.cfr.capsicum.server.ServerRuntimeFactoryBean.java

/**
 * Builds Cayenne configuration object based on configured properties.
 *//*from w w  w . jav a  2s  .  c  o m*/
@Override
public void afterPropertiesSet() throws Exception {
    // check datasource and transaction
    if (transactionManager == null && dataSource == null) {
        throw new IllegalArgumentException("Property 'transactionManager' or 'dataSource' is required");
    }

    // create default resource loader if no attached spring context.
    if (applicationContext == null) {
        this.resourceLoader = new DefaultResourceLoader();
    } else {
        this.resourceLoader = applicationContext;
    }
    SpringServerModule springModule = new SpringServerModule();
    List<String> configurationLocations = ImmutableList.of();
    if (dataDomainDefinitions != null && !dataDomainDefinitions.isEmpty()) {
        configurationLocations = Lists.newArrayListWithCapacity(dataDomainDefinitions.size());
        for (DataDomainDefinition dataDomainDefinition : dataDomainDefinitions) {
            Assert.notNull(dataDomainDefinition.getName(), "the name of DataDomain is required");
            Resource resource = Assert.notNull(dataDomainDefinition.getDomainResource(),
                    "the resource of DataDomain is required");
            URL url = null;
            try {
                url = resource.getURL();
            } catch (IOException ex) {
                throw new CayenneException(ex.getMessage(), ex);
            }
            configurationLocations.add(url.toString());
            // set default update strategy
            if (dataDomainDefinition.getSchemaUpdateStrategy() == null) {
                dataDomainDefinition.setSchemaUpdateStrategy(getDefaultSchemaUpdateStrategy());
            }
        }
    }
    // create specific datasource Factory
    if (dataSourceFactory == null) {
        dataSourceFactory = new SpringDataSourceFactory(this);
    }
    // create cayenne runtime instance with domain definitions
    cayenneRuntime = new ServerRuntime(Iterables.toArray(configurationLocations, String.class), springModule);

    // create default transaction manager
    if (transactionManager == null) {
        transactionManager = new CayenneTransactionManager(dataSource, cayenneRuntime);
    } else {
        this.transactionManager.setCayenneRuntime(cayenneRuntime);
    }

}

From source file:com.haulmont.cuba.core.sys.AbstractWebAppContextLoader.java

protected void initAppProperties(ServletContext sc) {
    // get properties from web.xml
    String appProperties = sc.getInitParameter(APP_PROPS_PARAM);
    if (appProperties != null) {
        StrTokenizer tokenizer = new StrTokenizer(appProperties);
        for (String str : tokenizer.getTokenArray()) {
            int i = str.indexOf("=");
            if (i < 0)
                continue;
            String name = StringUtils.substring(str, 0, i);
            String value = StringUtils.substring(str, i + 1);
            if (!StringUtils.isBlank(name)) {
                AppContext.setProperty(name, value);
            }/*w ww.  jav  a 2  s  .c o m*/
        }
    }

    // get properties from a set of app.properties files defined in web.xml
    String propsConfigName = getAppPropertiesConfig(sc);
    if (propsConfigName == null)
        throw new IllegalStateException(APP_PROPS_CONFIG_PARAM + " servlet context parameter not defined");

    final Properties properties = new Properties();

    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    StrTokenizer tokenizer = new StrTokenizer(propsConfigName);
    tokenizer.setQuoteChar('"');
    for (String str : tokenizer.getTokenArray()) {
        log.trace("Processing properties location: {}", str);
        str = StrSubstitutor.replaceSystemProperties(str);
        InputStream stream = null;
        try {
            if (ResourceUtils.isUrl(str) || str.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) {
                Resource resource = resourceLoader.getResource(str);
                if (resource.exists())
                    stream = resource.getInputStream();
            } else {
                stream = sc.getResourceAsStream(str);
            }

            if (stream != null) {
                log.info("Loading app properties from {}", str);
                try (Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
                    properties.load(reader);
                }
            } else {
                log.trace("Resource {} not found, ignore it", str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    for (Object key : properties.keySet()) {
        AppContext.setProperty((String) key, properties.getProperty((String) key).trim());
    }
}

From source file:org.springmodules.validation.bean.conf.namespace.XmlBasedValidatorBeanDefinitionParser.java

protected Resource createResource(Element resourceDefinition) {
    String path = resourceDefinition.getAttribute(LOCATION_ATTR);
    if (!StringUtils.hasText(path)) {
        throw new ValidationConfigurationException("Resoruce path is required and cannot be empty");
    }//from www . ja v a  2  s  .  c  om
    return new DefaultResourceLoader().getResource(path);
}

From source file:com.thoughtworks.go.http.mocks.MockServletContext.java

/**
 * Create a new {@code MockServletContext} using the supplied resource base
 * path and resource loader./* w  w w  .ja v a2  s . c  o m*/
 * <p>Registers a {@link MockRequestDispatcher} for the Servlet named
 * {@literal 'default'}.
 * @param resourceBasePath the root directory of the WAR (should not end with a slash)
 * @param resourceLoader the ResourceLoader to use (or null for the default)
 * @see #registerNamedDispatcher
 */
public MockServletContext(String resourceBasePath, ResourceLoader resourceLoader) {
    this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
    this.resourceBasePath = resourceBasePath;

    // Use JVM temp dir as ServletContext temp dir.
    String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
    if (tempDir != null) {
        this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
    }

    registerNamedDispatcher(this.defaultServletName, new MockRequestDispatcher(this.defaultServletName));
}

From source file:com.jpoweredcart.common.mock.servlet.MockServletContext.java

/**
 * Create a new MockServletContext.//  w  w  w .j a v  a  2  s  .  com
 * @param resourceBasePath the WAR root directory (should not end with a slash)
 * @param resourceLoader the ResourceLoader to use (or null for the default)
 */
public MockServletContext(String resourceBasePath, ResourceLoader resourceLoader) {
    this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
    this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");

    // Use JVM temp dir as ServletContext temp dir.
    String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
    if (tempDir != null) {
        this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
    }
}