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:de.codecentric.boot.admin.controller.LogfileController.java

@RequestMapping("/logfile")
@ResponseBody/*from   w w w  . j ava2 s.co m*/
public String getLogfile(HttpServletResponse response) {
    String path = env.getProperty("logging.file");
    if (path == null) {
        LOGGER.error("Logfile download failed for missing property 'logging.file'");
        return "Logfile download failed for missing property 'logging.file'";
    }
    Resource file = new FileSystemResource(path);
    if (!file.exists()) {
        LOGGER.error("Logfile download failed for missing file at path=" + path);
        return "Logfile download failed for missing file at path=" + path;
    }
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getFilename() + "\"");
    try {
        FileCopyUtils.copy(file.getInputStream(), response.getOutputStream());
    } catch (IOException e) {
        LOGGER.error("Logfile download failed for path=" + path);
        return "Logfile download failed for path=" + path;
    }
    return null;
}

From source file:org.kew.rmf.reconciliation.service.ReconciliationService.java

/**
 * Lists the available configuration files from the classpath.
 *///w w  w  .  ja v  a2  s .  c om
public List<String> listAvailableConfigurationFiles() throws ReconciliationServiceException {
    List<String> availableConfigurations = new ArrayList<>();
    ResourcePatternResolver pmrpr = new PathMatchingResourcePatternResolver();
    try {
        Resource[] configurationResources = pmrpr.getResources("classpath*:" + CONFIG_BASE + "*Match.xml");
        logger.debug("Found {} configuration file resources", configurationResources.length);

        for (Resource resource : configurationResources) {
            availableConfigurations.add(resource.getFilename());
        }
    } catch (IOException e) {
        throw new ReconciliationServiceException("Unable to list available configurations", e);
    }

    return availableConfigurations;
}

From source file:com.flipkart.aesop.runtime.spring.RuntimeComponentContainer.java

/**
 * Interface method implementation. Loads/Reloads runtime(s) defined in the specified {@link FileSystemResource} 
 * @see org.trpr.platform.runtime.spi.component.ComponentContainer#loadComponent(org.springframework.core.io.Resource)
 *//*from www. j a  va  2 s.  c  o  m*/
public void loadComponent(Resource resource) {
    if (!FileSystemResource.class.isAssignableFrom(resource.getClass())
            || !resource.getFilename().equalsIgnoreCase(this.getRuntimeConfigFileName())) {
        throw new UnsupportedOperationException("Runtimes can be loaded only from files by name : "
                + this.getRuntimeConfigFileName() + ". Specified resource is : " + resource.toString());
    }
    loadRuntimeContext(new ServerContainerConfigInfo(((FileSystemResource) resource).getFile()));
}

From source file:com.sinnerschrader.s2b.accounttool.logic.component.licences.LicenseSummary.java

@Override
public void afterPropertiesSet() throws Exception {
    for (String licenseFile : licenseFiles) {
        Resource res = resourceLoader.getResource(licenseFile);
        if (res != null && res.exists()) {
            try {
                log.info("Loading License Summary file {} of Project ", licenseFile);
                String fileName = StringUtils.lowerCase(res.getFilename());
                if (StringUtils.endsWith(fileName, ".json")) {
                    storeForType(DependencyType.NPM, loadFromJSON(res));
                } else if (StringUtils.endsWith(fileName, ".xml")) {
                    storeForType(DependencyType.MAVEN, loadFromXML(res));
                } else {
                    log.warn("Could not identify file ");
                }/*from  ww  w  .java2 s  . c  o m*/
            } catch (Exception e) {
                log.warn("Could not load license file {}", licenseFile);
                if (log.isDebugEnabled()) {
                    log.error("Exception on loading license file", e);
                }
            }
        }
    }
    freeze();
}

From source file:org.jahia.modules.bootstrap.rules.BootstrapCompiler.java

private void compileBootstrap(JCRNodeWrapper siteOrModuleVersion, List<Resource> lessResources,
        String variables) throws IOException, LessException, RepositoryException {
    if (lessResources != null && !lessResources.isEmpty()) {
        File tmpLessFolder = new File(FileUtils.getTempDirectory(), "less-" + System.currentTimeMillis());
        tmpLessFolder.mkdir();/* w  w w  . jav  a  2 s.c om*/
        try {
            List<String> allContent = new ArrayList<String>();
            for (Resource lessResource : lessResources) {
                File lessFile = new File(tmpLessFolder, lessResource.getFilename());
                if (!lessFile.exists()) {
                    InputStream inputStream;
                    if (variables != null && VARIABLES_LESS.equals(lessResource.getFilename())) {
                        inputStream = new SequenceInputStream(lessResource.getInputStream(),
                                new ByteArrayInputStream(variables.getBytes()));
                    } else {
                        inputStream = lessResource.getInputStream();
                    }
                    final FileOutputStream output = new FileOutputStream(lessFile);
                    IOUtils.copy(inputStream, output);
                    IOUtils.closeQuietly(inputStream);
                    IOUtils.closeQuietly(output);
                }
                final FileInputStream input = new FileInputStream(lessFile);
                allContent.addAll(IOUtils.readLines(input));
                IOUtils.closeQuietly(input);
            }
            String md5 = DigestUtils.md5Hex(StringUtils.join(allContent, '\n'));

            JCRNodeWrapper node = siteOrModuleVersion;
            for (String pathPart : StringUtils.split(CSS_FOLDER_PATH, '/')) {
                if (node.hasNode(pathPart)) {
                    node = node.getNode(pathPart);
                } else {
                    node = node.addNode(pathPart, "jnt:folder");
                }
            }

            boolean compileCss = true;
            JCRNodeWrapper bootstrapCssNode;

            if (node.hasNode(BOOTSTRAP_CSS)) {
                bootstrapCssNode = node.getNode(BOOTSTRAP_CSS);
                String content = bootstrapCssNode.getFileContent().getText();
                String timestamp = StringUtils.substringBetween(content, "/* sources hash ", " */");
                if (timestamp != null && md5.equals(timestamp)) {
                    compileCss = false;
                }
            } else {
                bootstrapCssNode = node.addNode(BOOTSTRAP_CSS, "jnt:file");
            }
            if (compileCss) {
                File bootstrapCss = new File(tmpLessFolder, BOOTSTRAP_CSS);
                lessCompiler.compile(new File(tmpLessFolder, "bootstrap.less"), bootstrapCss);
                FileOutputStream f = new FileOutputStream(bootstrapCss, true);
                IOUtils.write("\n/* sources hash " + md5 + " */\n", f);
                IOUtils.closeQuietly(f);
                FileInputStream inputStream = new FileInputStream(bootstrapCss);
                bootstrapCssNode.getFileContent().uploadFile(inputStream, "text/css");
                bootstrapCssNode.getSession().save();
                IOUtils.closeQuietly(inputStream);
            }
        } catch (IOException e) {
            throw new RepositoryException(e);
        } catch (LessException e) {
            throw new RepositoryException(e);
        } finally {
            FileUtils.deleteQuietly(tmpLessFolder);
        }
    }
}

From source file:com.siberhus.tdfl.DefaultResourceCreator.java

@Override
public Resource create(Resource example) throws IOException {

    String parent = example.getFile().getParent();
    String targetDirPath = parent + File.separator + subdirectory;
    File targetDir = new File(targetDirPath);
    if (!targetDir.exists()) {
        if (createDirectory) {
            targetDir.mkdir();/*from ww  w  .j  av a2s .com*/
        }
    }
    String filename = example.getFilename();
    if (extension == null)
        extension = FilenameUtils.getExtension(filename);
    filename = FilenameUtils.getBaseName(filename);
    if (prefix != null) {
        filename = prefix + filename;
    }
    if (suffix != null) {
        filename = filename + suffix;
    }
    filename = filename + "." + extension;
    return new FileSystemResource(targetDirPath + File.separator + filename);
}

From source file:org.carewebframework.api.spring.LocalPropertySource.java

private void loadProperties() {
    if (sources != null && properties == null) {
        properties = new Properties();

        for (String source : sources) {
            try {
                for (Resource resource : appContext.getResources(source)) {
                    InputStream is = null;
                    try {
                        is = resource.getInputStream();
                        properties.load(is);
                    } catch (IOException e) {
                        IOUtils.closeQuietly(is);
                        log.error("Error loading properties from " + resource.getFilename(), e);
                    }//from   w ww  .  j ava  2  s  .  co m
                }
            } catch (IOException e) {
                log.error("Error load property resources.", e);
            }
        }
    }
}

From source file:com.flipkart.phantom.runtime.impl.spring.ServiceProxyComponentContainer.java

/**
 * Interface method implementation. Loads/Reloads proxy handler(s) defined in the specified {@link FileSystemResource}
 * @see org.trpr.platform.runtime.spi.component.ComponentContainer#loadComponent(org.springframework.core.io.Resource)
 *//*from  www.  j a va 2  s  . c o m*/
public void loadComponent(Resource resource) {
    if (!FileSystemResource.class.isAssignableFrom(resource.getClass()) || !resource.getFilename()
            .equalsIgnoreCase(ServiceProxyFrameworkConstants.SPRING_PROXY_HANDLER_CONFIG)) {
        throw new UnsupportedOperationException("Proxy handers can be loaded only from files by name : "
                + ServiceProxyFrameworkConstants.SPRING_PROXY_HANDLER_CONFIG + ". Specified resource is : "
                + resource.toString());
    }
    loadProxyHandlerContext(new HandlerConfigInfo(((FileSystemResource) resource).getFile()));
}

From source file:com.clican.pluto.dataprocess.engine.impl.ProcessorContainerImpl.java

/**
 * Springinit-method???//from w  ww  .j  a va 2 s.  co m
 */
@SuppressWarnings("unchecked")
public void start() {
    if (log.isInfoEnabled()) {
        log.info("Begin to start Process Data Container");
    }
    for (String scan : scanList) {
        scan = scan.trim();
        try {
            String pattern1;
            String pattern2;
            if (scan.startsWith("file")) {
                pattern1 = scan + "/**/*.xml";
                pattern2 = scan + "/**/*.properties";
            } else {
                pattern1 = ClassUtils.convertClassNameToResourcePath(scan) + "/**/*.xml";
                pattern2 = ClassUtils.convertClassNameToResourcePath(scan) + "/**/*.properties";
            }
            Resource[] resources1 = resourcePatternResolver.getResources(pattern1);
            Resource[] resources2 = resourcePatternResolver.getResources(pattern2);
            Map<String, Resource> map1 = new HashMap<String, Resource>();
            Map<String, Resource> map2 = new HashMap<String, Resource>();
            Set<String> usingPropertyResource = new HashSet<String>();
            for (Resource resource : resources1) {
                map1.put(resource.getFilename().split("\\.")[0], resource);
            }
            for (Resource resource : resources2) {
                String fileName = resource.getFilename().split("\\.")[0];
                String[] fn = fileName.split("\\_");
                if (fn.length == 2 && map1.containsKey(fn[0])) {
                    usingPropertyResource.add(fn[0]);
                } else {
                    throw new RuntimeException("properties[" + fileName + "]???");
                }
                map2.put(resource.getFilename().split("\\.")[0], resource);
            }
            for (Resource resource1 : resources1) {
                final Resource xmlRes = resource1;

                String fileName1 = resource1.getFilename().split("\\.")[0];
                if (usingPropertyResource.contains(fileName1)) {
                    for (Resource resource2 : resources2) {
                        AbstractXmlApplicationContext subContext = new AbstractXmlApplicationContext(
                                this.applicationContext) {
                            protected Resource[] getConfigResources() {
                                return new Resource[] { xmlRes };
                            }
                        };
                        String fileName2 = resource2.getFilename().split("\\.")[0];
                        String[] fn = fileName2.split("\\_");
                        if (fn[0].equals(fileName1)) {
                            com.clican.pluto.common.support.spring.PropertyPlaceholderConfigurer parentConf = (com.clican.pluto.common.support.spring.PropertyPlaceholderConfigurer) applicationContext
                                    .getBean("propertyConfigurer");
                            Resource[] resources = new Resource[1 + parentConf.getLocations().length];
                            for (int i = 0; i < parentConf.getLocations().length; i++) {
                                resources[i] = parentConf.getLocations()[i];
                            }
                            resources[resources.length - 1] = resource2;
                            com.clican.pluto.common.support.spring.PropertyPlaceholderConfigurer subContainerConf = new com.clican.pluto.common.support.spring.PropertyPlaceholderConfigurer();
                            subContainerConf.setFileEncoding("utf-8");
                            subContainerConf.setLocations(resources);
                            subContext.addBeanFactoryPostProcessor(subContainerConf);
                            subContext.refresh();
                            processorGroupSpringMap.put(fn[1], subContext);
                            Collection<String> coll = (Collection<String>) subContext
                                    .getBeansOfType(BaseDataProcessor.class).keySet();
                            for (String beanName : coll) {
                                BaseDataProcessor bean = (BaseDataProcessor) subContext.getBean(beanName);
                                if (bean.isStartProcessor()) {
                                    startProcessorNameMap.put(fn[1], beanName);
                                    break;
                                }
                            }
                            if (!startProcessorNameMap.containsKey(fn[1])) {
                                throw new RuntimeException(
                                        "?Process Container," + fn[1] + "?");
                            }
                        }
                    }
                } else {
                    AbstractXmlApplicationContext subContext = new AbstractXmlApplicationContext(
                            this.applicationContext) {
                        protected Resource[] getConfigResources() {
                            return new Resource[] { xmlRes };
                        }
                    };
                    subContext.addBeanFactoryPostProcessor(
                            (BeanFactoryPostProcessor) applicationContext.getBean("propertyConfigurer"));
                    subContext.refresh();
                    processorGroupSpringMap.put(fileName1, subContext);
                    Collection<String> coll = (Collection<String>) subContext
                            .getBeansOfType(BaseDataProcessor.class).keySet();
                    for (String beanName : coll) {
                        BaseDataProcessor bean = (BaseDataProcessor) subContext.getBean(beanName);
                        if (bean.isStartProcessor()) {
                            startProcessorNameMap.put(fileName1, beanName);
                            break;
                        }
                    }
                    if (!startProcessorNameMap.containsKey(fileName1)) {
                        throw new RuntimeException(
                                "?Process Container," + fileName1 + "?");
                    }
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    for (Deploy deploy : deployList) {
        try {
            ClassPathXmlApplicationContext subContext = new ClassPathXmlApplicationContext(
                    new String[] { deploy.getUrl() }, this.applicationContext);
            if (StringUtils.isNotEmpty(deploy.getPropertyResources())) {
                com.clican.pluto.common.support.spring.PropertyPlaceholderConfigurer parentConf = (com.clican.pluto.common.support.spring.PropertyPlaceholderConfigurer) applicationContext
                        .getBean("propertyConfigurer");

                String[] propertyResources = deploy.getPropertyResources().split(",");
                Resource[] resources = new Resource[propertyResources.length
                        + parentConf.getLocations().length];
                for (int i = 0; i < parentConf.getLocations().length; i++) {
                    resources[i] = parentConf.getLocations()[i];
                }
                for (int i = parentConf.getLocations().length; i < resources.length; i++) {
                    String propertyResource = propertyResources[i - parentConf.getLocations().length];
                    if (propertyResource.startsWith("classpath")) {
                        resources[i] = new ClassPathResource(
                                propertyResource.substring(propertyResource.indexOf(":") + 1));
                    } else {
                        resources[i] = new FileSystemResource(
                                propertyResource.substring(propertyResource.indexOf(":") + 1));
                    }

                }

                com.clican.pluto.common.support.spring.PropertyPlaceholderConfigurer subContainerConf = new com.clican.pluto.common.support.spring.PropertyPlaceholderConfigurer();
                subContainerConf.setFileEncoding("utf-8");
                subContainerConf.setLocations(resources);
                subContext.addBeanFactoryPostProcessor(subContainerConf);
            } else {
                subContext.addBeanFactoryPostProcessor(
                        (BeanFactoryPostProcessor) applicationContext.getBean("propertyConfigurer"));
            }
            subContext.refresh();
            processorGroupSpringMap.put(deploy.getName(), subContext);
            Collection<String> coll = (Collection<String>) subContext.getBeansOfType(BaseDataProcessor.class)
                    .keySet();
            for (String beanName : coll) {
                BaseDataProcessor bean = (BaseDataProcessor) subContext.getBean(beanName);
                if (bean.isStartProcessor()) {
                    startProcessorNameMap.put(deploy.getName(), beanName);
                    break;
                }
            }
            if (!startProcessorNameMap.containsKey(deploy.getName())) {
                throw new RuntimeException(
                        "?Process Container," + deploy.getName() + "?");
            }
        } catch (Exception e) {
            log.error("Depoly [" + deploy.getName() + "] failure", e);
            throw new RuntimeException(e);
        }
    }

    log.info("The Process Data Container has been started successfully.");
}

From source file:org.codehaus.griffon.plugins.DefaultGriffonPluginManager.java

private Class loadPluginClass(GroovyClassLoader gcl, Resource r) {
    Class pluginClass;/*from ww  w .  ja  v  a 2s  .  co m*/
    try {
        pluginClass = gcl.parseClass(r.getFile());
    } 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);
    }
    return pluginClass;
}