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.qcadoo.view.internal.xml.ViewDefinitionParserImpl.java

@Override
public InternalViewDefinition parseViewXml(final Resource viewXml, final String pluginIdentifier) {
    try {/*from   w w  w .  j  a  v  a  2s.co m*/
        return parse(viewXml.getInputStream(), pluginIdentifier);
    } catch (IOException e) {
        throw ViewDefinitionParserException.forFile(viewXml.getFilename(), "Error while reading view resource",
                e);
    } catch (ViewDefinitionParserNodeException e) {
        throw ViewDefinitionParserException.forFileAndNode(viewXml.getFilename(), e);
    } catch (Exception e) {
        throw ViewDefinitionParserException.forFile(viewXml.getFilename(), e);
    }
}

From source file:com.sfxie.extension.spring4.properties.SwitchPropertiesLoaderSupport.java

/**
 * Load properties into the given instance.
 * @param props the Properties instance to load into
 * @throws IOException in case of I/O errors
 * @see #setLocations//  w  w w .jav  a 2 s. c  o m
 */
protected void loadProperties(Properties props) throws IOException {
    if (this.locations != null) {
        IPropertiesFileFilter propertiesFileFilter = getPropertiesFileFilter();
        InputStream inStream = this.getClass().getClassLoader()
                .getResourceAsStream(propertiesFileFilter.loadPrePropertiesPath());
        if (null != inStream) {
            Properties properties = new Properties();
            properties.load(inStream);
            Context.enviroment = properties.getProperty("enviroment");
            propertiesFileFilter.validate(properties);
            LoggerUtil.system(SystemLogger.class, "?:" + Context.enviroment);
            for (Resource location : this.locations) {
                /*System.out.println(location.getFilename());
                String path = location.getURI().getPath();
                if(null==path || path.equals("")){
                   path = location.getFile().getPath();
                }*/
                //?????????
                if (propertiesFileFilter.filter(properties, location.getFilename())) {
                    if (null != logger && logger.isInfoEnabled()) {
                        logger.info("Loading properties file from " + location);
                    }
                    try {
                        PropertiesLoaderUtils.fillProperties(props,
                                new EncodedResource(location, this.fileEncoding), this.propertiesPersister);
                    } catch (IOException ex) {
                        if (this.ignoreResourceNotFound) {
                            if (null != logger && logger.isWarnEnabled()) {
                                logger.warn(
                                        "Could not load properties from " + location + ": " + ex.getMessage());
                            }
                        } else {
                            throw ex;
                        }
                    }
                }

            }
        } else {
            throw new IOException("classpath:configenviroment.properties.");
        }
    }
}

From source file:com.apdplat.platform.compass.APDPlatLocalCompassBean.java

public void afterPropertiesSet() throws Exception {
    CompassConfiguration config = this.config;
    if (config == null) {
        config = newConfiguration();//from  w w  w. j a  v a2s.com
    }

    if (classLoader != null) {
        config.setClassLoader(getClassLoader());
    }

    if (this.configLocation != null) {
        config.configure(this.configLocation.getURL());
    }

    if (this.configLocations != null) {
        for (Resource configLocation1 : configLocations) {
            config.configure(configLocation1.getURL());
        }
    }

    if (this.mappingScan != null) {
        config.addScan(this.mappingScan);
    }

    if (this.compassSettings != null) {
        config.getSettings().addSettings(this.compassSettings);
    }

    if (this.settings != null) {
        config.getSettings().addSettings(this.settings);
    }

    if (resourceLocations != null) {
        for (Resource resourceLocation : resourceLocations) {
            config.addInputStream(resourceLocation.getInputStream(), resourceLocation.getFilename());
        }
    }

    if (resourceJarLocations != null && !"".equals(resourceJarLocations.trim())) {
        log.info("apdplatcompass2");
        log.info("compass resourceJarLocations:" + resourceJarLocations);
        String[] jars = resourceJarLocations.split(",");
        for (String jar : jars) {
            try {
                FileSystemResource resource = new FileSystemResource(FileUtils.getAbsolutePath(jar));
                config.addJar(resource.getFile());
                log.info("compass resourceJarLocations  find:" + jar);
            } catch (Exception e) {
                log.info("compass resourceJarLocations not exists:" + jar);
            }
        }
    }

    if (classMappings != null) {
        for (String classMapping : classMappings) {
            config.addClass(ClassUtils.forName(classMapping, getClassLoader()));
        }
    }

    if (resourceDirectoryLocations != null && !"".equals(resourceDirectoryLocations.trim())) {
        log.info("apdplatcompass3");
        log.info("compass resourceDirectoryLocations:" + resourceDirectoryLocations);
        String[] dirs = resourceDirectoryLocations.split(",");
        for (String dir : dirs) {
            ClassPathResource resource = new ClassPathResource(dir);
            try {
                File file = resource.getFile();
                if (!file.isDirectory()) {
                    log.info("Resource directory location [" + dir + "] does not denote a directory");
                } else {
                    config.addDirectory(file);
                }
                log.info("compass resourceDirectoryLocations find:" + dir);
            } catch (Exception e) {
                log.info("compass resourceDirectoryLocations not exists:" + dir);
            }
        }
    }

    if (mappingResolvers != null) {
        for (InputStreamMappingResolver mappingResolver : mappingResolvers) {
            config.addMappingResover(mappingResolver);
        }
    }

    if (dataSource != null) {
        ExternalDataSourceProvider.setDataSource(dataSource);
        if (config.getSettings().getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS) == null) {
            config.getSettings().setSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS,
                    ExternalDataSourceProvider.class.getName());
        }
    }

    String compassTransactionFactory = config.getSettings().getSetting(CompassEnvironment.Transaction.FACTORY);
    if (compassTransactionFactory == null && transactionManager != null) {
        // if the transaciton manager is set and a transcation factory is not set, default to the SpringSync one.
        config.getSettings().setSetting(CompassEnvironment.Transaction.FACTORY,
                SpringSyncTransactionFactory.class.getName());
    }
    if (compassTransactionFactory != null
            && compassTransactionFactory.equals(SpringSyncTransactionFactory.class.getName())) {
        if (transactionManager == null) {
            throw new IllegalArgumentException(
                    "When using SpringSyncTransactionFactory the transactionManager property must be set");
        }
    }
    SpringSyncTransactionFactory.setTransactionManager(transactionManager);

    if (convertersByName != null) {
        for (Map.Entry<String, Converter> entry : convertersByName.entrySet()) {
            config.registerConverter(entry.getKey(), entry.getValue());
        }
    }
    if (config.getSettings().getSetting(CompassEnvironment.NAME) == null) {
        config.getSettings().setSetting(CompassEnvironment.NAME, beanName);
    }

    if (config.getSettings().getSetting(CompassEnvironment.CONNECTION) == null && connection != null) {
        config.getSettings().setSetting(CompassEnvironment.CONNECTION, connection.getFile().getAbsolutePath());
    }

    if (applicationContext != null) {
        String[] names = applicationContext.getBeanNamesForType(PropertyPlaceholderConfigurer.class);
        for (String name : names) {
            try {
                PropertyPlaceholderConfigurer propConfigurer = (PropertyPlaceholderConfigurer) applicationContext
                        .getBean(name);
                Method method = findMethod(propConfigurer.getClass(), "mergeProperties");
                method.setAccessible(true);
                Properties props = (Properties) method.invoke(propConfigurer);
                method = findMethod(propConfigurer.getClass(), "convertProperties", Properties.class);
                method.setAccessible(true);
                method.invoke(propConfigurer, props);
                method = findMethod(propConfigurer.getClass(), "parseStringValue", String.class,
                        Properties.class, Set.class);
                method.setAccessible(true);
                String nullValue = null;
                try {
                    Field field = propConfigurer.getClass().getDeclaredField("nullValue");
                    field.setAccessible(true);
                    nullValue = (String) field.get(propConfigurer);
                } catch (NoSuchFieldException e) {
                    // no field (old spring version)
                }
                for (Map.Entry entry : config.getSettings().getProperties().entrySet()) {
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    value = (String) method.invoke(propConfigurer, value, props, new HashSet());
                    config.getSettings().setSetting(key, value.equals(nullValue) ? null : value);
                }
            } catch (Exception e) {
                log.debug("Failed to apply property placeholder defined in bean [" + name + "]", e);
            }
        }
    }

    if (postProcessor != null) {
        postProcessor.process(config);
    }
    this.compass = newCompass(config);
    this.compass = (Compass) Proxy.newProxyInstance(SpringCompassInvocationHandler.class.getClassLoader(),
            new Class[] { InternalCompass.class }, new SpringCompassInvocationHandler(this.compass));
}

From source file:org.jnap.core.assets.StaticAssetsHandler.java

public void handle() {
    try {//  w w w  .  j  ava  2  s  .com
        Resource[] resources = this.resourceResolver.getResources(source);
        if (destination != null) {
            Resource destRes = new ServletContextResource(servletContext, destination);
            resetResource(destRes);
            BufferedWriter writer = new BufferedWriter(
                    new FileWriterWithEncoding(destRes.getFile(), this.encoding, true));
            for (Resource resource : resources) {
                IOUtils.copy(resource.getInputStream(), writer);
            }
            IOUtils.closeQuietly(writer);
            resources = new Resource[1];
            resources[0] = destRes;
        }

        for (Resource resource : resources) {
            //            doHandle(resource);
            //            File file = resource.getFile();
            String digest = DigestUtils.shaHex(resource.getInputStream());
            availableStaticAssets.put(resource.getFilename(), digest);
            if (compress) {
                Resource compressedResource = doCompression(resource);
                digest = DigestUtils.shaHex(compressedResource.getInputStream());
                availableStaticAssets.put(compressedResource.getFilename(), digest);
            }
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:it.geosolutions.httpproxy.service.impl.ProxyConfigImpl.java

/**
 * Save last modification of the file to track it and override this bean
 * properties if the file has been changed
 * /*from w  w w .ja v a 2s .c  o  m*/
 * @param location
 *            Resource location of the file
 * 
 * @throws IOException
 */
private void trackLocation(Resource location) throws IOException {
    String fileName = location.getFilename();
    Long lastModified = location.lastModified();
    if (!(timeModificationByLocation.containsKey(fileName))) {
        // Save last modification timestamp
        timeModificationByLocation.put(fileName, lastModified);
    } else if (isModified(fileName, lastModified)) {
        // Override proxy configuration
        LOGGER.log(Level.INFO, "Proxy configuration has changed at runtime in file '" + fileName + "'");
        overrideProperties(location);
    }
}

From source file:org.activiti.spring.SpringProcessEngineConfiguration.java

protected void autoDeployResources(ProcessEngine processEngine) {
    if (deploymentResources != null && deploymentResources.length > 0) {
        RepositoryService repositoryService = processEngine.getRepositoryService();

        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering()
                .name(deploymentName);//  w ww  .jav  a 2 s .  co m

        for (Resource resource : deploymentResources) {
            String resourceName = null;

            if (resource instanceof ContextResource) {
                resourceName = ((ContextResource) resource).getPathWithinContext();

            } else if (resource instanceof ByteArrayResource) {
                resourceName = resource.getDescription();

            } else {
                try {
                    resourceName = resource.getFile().getAbsolutePath();
                } catch (IOException e) {
                    resourceName = resource.getFilename();
                }
            }

            try {
                if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip")
                        || resourceName.endsWith(".jar")) {
                    deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
                } else {
                    deploymentBuilder.addInputStream(resourceName, resource.getInputStream());
                }
            } catch (IOException e) {
                throw new ActivitiException(
                        "couldn't auto deploy resource '" + resource + "': " + e.getMessage(), e);
            }
        }

        deploymentBuilder.deploy();
    }
}

From source file:eu.trentorise.game.test.GameTest.java

private String relativeRulePath(Resource resource, String classpathFolder) throws IOException {
    String path = null;//from   w  w  w.ja v  a2s. com
    if (resource != null) {
        path = classpathFolder;
        String uri = resource.getURI().getPath();
        String pattern = String.format(".*/%s(.*)%s", classpathFolder, resource.getFilename());
        Pattern subfolderPattern = Pattern.compile(pattern);
        Matcher m = subfolderPattern.matcher(uri);
        if (m.matches() && m.group(1) != null) {
            path += m.group(1);
        }
        path += resource.getFilename();
    }
    return path;
}

From source file:net.sourceforge.vulcan.metrics.XmlMetricsPlugin.java

private void loadTransformers() throws IOException {
    LOG.info("Reloading XSL transformers because they have changed.");

    transformers.clear();// www . j  a v  a2s  . c om
    for (Resource r : resourceResolver.getResources(transformSourcePath)) {
        try {
            final long lastModified = r.getFile().lastModified();
            if (lastModified > newestTransformDate) {
                newestTransformDate = lastModified;
            }

            final SAXSource source = new SAXSource(XMLReaderFactory.createXMLReader(),
                    new InputSource(r.getInputStream()));

            transformers.put(r.getFilename(), transformerFactory.newTransformer(source));
        } catch (Exception e) {
            eventHandler.reportEvent(
                    new ErrorEvent(this, "metrics.errors.load.transform", new Object[] { e.getMessage() }, e));
        }
    }
}

From source file:com.diaimm.april.db.jpa.hibernate.multidbsupport.PersistenceUnitReader.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 java.io.IOException if the checking failed
 *///from   ww  w.ja v a2  s . co m
protected URL determinePersistenceUnitRootUrl(Resource resource) throws IOException {
    URL originalURL = resource.getURL();

    // 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);
    }

    // check META-INF folder
    String urlToString = originalURL.toExternalForm();
    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));
    if (persistenceUnitRoot.endsWith("/")) {
        persistenceUnitRoot = persistenceUnitRoot.substring(0, persistenceUnitRoot.length() - 1);
    }
    return new URL(persistenceUnitRoot);
}