Example usage for org.springframework.core.io Resource getFile

List of usage examples for org.springframework.core.io Resource getFile

Introduction

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

Prototype

File getFile() throws IOException;

Source Link

Document

Return a File handle for this resource.

Usage

From source file:annis.administration.DefaultAdministrationDao.java

@SuppressWarnings("unchecked")
private String readSqlFromResource(Resource resource, MapSqlParameterSource args) {
    // XXX: uses raw type, what are the parameters to Map in MapSqlParameterSource?
    Map<String, Object> parameters = args != null ? args.getValues() : new HashMap();
    BufferedReader reader = null;
    try {/*from w ww. jav  a2s  .co  m*/
        StringBuilder sqlBuf = new StringBuilder();
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(resource.getFile()), "UTF-8"));
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            sqlBuf.append(line).append("\n");
        }
        String sql = sqlBuf.toString();
        for (Entry<String, Object> placeHolderEntry : parameters.entrySet()) {
            String key = placeHolderEntry.getKey();
            String value = placeHolderEntry.getValue().toString();
            log.debug("substitution for parameter '" + key + "' in SQL script: " + value);

            sql = sql.replaceAll(key, value);
        }
        return sql;
    } catch (IOException e) {
        log.error("Couldn't read SQL script from resource file.", e);
        throw new FileAccessException("Couldn't read SQL script from resource file.", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(DefaultAdministrationDao.class.getName()).log(Level.SEVERE,
                        null, ex);
            }
        }
    }
}

From source file:org.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean.java

protected void buildSessionFactory() throws Exception {

    configuration = newConfiguration();/*from w  w w  . j  a v a2  s.  c  o  m*/

    if (configLocations != null) {
        for (Resource resource : configLocations) {
            // Load Hibernate configuration from given location.
            configuration.configure(resource.getURL());
        }
    }

    if (mappingResources != null) {
        // Register given Hibernate mapping definitions, contained in resource files.
        for (String mapping : mappingResources) {
            Resource mr = new ClassPathResource(mapping.trim(), resourcePatternResolver.getClassLoader());
            configuration.addInputStream(mr.getInputStream());
        }
    }

    if (mappingLocations != null) {
        // Register given Hibernate mapping definitions, contained in resource files.
        for (Resource resource : mappingLocations) {
            configuration.addInputStream(resource.getInputStream());
        }
    }

    if (cacheableMappingLocations != null) {
        // Register given cacheable Hibernate mapping definitions, read from the file system.
        for (Resource resource : cacheableMappingLocations) {
            configuration.addCacheableFile(resource.getFile());
        }
    }

    if (mappingJarLocations != null) {
        // Register given Hibernate mapping definitions, contained in jar files.
        for (Resource resource : mappingJarLocations) {
            configuration.addJar(resource.getFile());
        }
    }

    if (mappingDirectoryLocations != null) {
        // Register all Hibernate mapping definitions in the given directories.
        for (Resource resource : mappingDirectoryLocations) {
            File file = resource.getFile();
            if (!file.isDirectory()) {
                throw new IllegalArgumentException(
                        "Mapping directory location [" + resource + "] does not denote a directory");
            }
            configuration.addDirectory(file);
        }
    }

    if (entityInterceptor != null) {
        configuration.setInterceptor(entityInterceptor);
    }

    if (namingStrategy != null) {
        configuration.setNamingStrategy(namingStrategy);
    }

    if (hibernateProperties != null) {
        configuration.addProperties(hibernateProperties);
    }

    if (annotatedClasses != null) {
        configuration.addAnnotatedClasses(annotatedClasses);
    }

    if (annotatedPackages != null) {
        configuration.addPackages(annotatedPackages);
    }

    if (packagesToScan != null) {
        configuration.scanPackages(packagesToScan);
    }

    if (eventListeners != null) {
        configuration.setEventListeners(eventListeners);
    }

    sessionFactory = doBuildSessionFactory();

    buildSessionFactoryProxy();
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

@Override
public synchronized String loadXmlFile(final String xmlFilePath) throws IOException {

    Resource xmlFileResource = resourceLoader.getResource(xmlFilePath);

    return loadXmlFile(xmlFileResource.getFile());
}

From source file:com.baomidou.hibernateplus.HibernateSpringSessionFactoryBean.java

@Override
public void afterPropertiesSet() throws IOException {
    HibernateSpringSessionFactoryBuilder sfb = new HibernateSpringSessionFactoryBuilder(this.dataSource,
            getResourceLoader(), getMetadataSources());

    if (this.configLocations != null) {
        for (Resource resource : this.configLocations) {
            // Load Hibernate configuration from given location.
            sfb.configure(resource.getURL());
        }//from   w  w  w  . ja  v a 2  s .  c  om
    }

    if (this.mappingResources != null) {
        // Register given Hibernate mapping definitions, contained in
        // resource files.
        for (String mapping : this.mappingResources) {
            Resource mr = new ClassPathResource(mapping.trim(), this.resourcePatternResolver.getClassLoader());
            sfb.addInputStream(mr.getInputStream());
        }
    }

    if (this.mappingLocations != null) {
        // Register given Hibernate mapping definitions, contained in
        // resource files.
        for (Resource resource : this.mappingLocations) {
            sfb.addInputStream(resource.getInputStream());
        }
    }

    if (this.cacheableMappingLocations != null) {
        // Register given cacheable Hibernate mapping definitions, read from
        // the file system.
        for (Resource resource : this.cacheableMappingLocations) {
            sfb.addCacheableFile(resource.getFile());
        }
    }

    if (this.mappingJarLocations != null) {
        // Register given Hibernate mapping definitions, contained in jar
        // files.
        for (Resource resource : this.mappingJarLocations) {
            sfb.addJar(resource.getFile());
        }
    }

    if (this.mappingDirectoryLocations != null) {
        // Register all Hibernate mapping definitions in the given
        // directories.
        for (Resource resource : this.mappingDirectoryLocations) {
            File file = resource.getFile();
            if (!file.isDirectory()) {
                throw new IllegalArgumentException(
                        "Mapping directory location [" + resource + "] does not denote a directory");
            }
            sfb.addDirectory(file);
        }
    }

    if (this.entityInterceptor != null) {
        sfb.setInterceptor(this.entityInterceptor);
    }

    if (this.implicitNamingStrategy != null) {
        sfb.setImplicitNamingStrategy(this.implicitNamingStrategy);
    }

    if (this.physicalNamingStrategy != null) {
        sfb.setPhysicalNamingStrategy(this.physicalNamingStrategy);
    }

    if (this.jtaTransactionManager != null) {
        sfb.setJtaTransactionManager(this.jtaTransactionManager);
    }

    if (this.multiTenantConnectionProvider != null) {
        sfb.setMultiTenantConnectionProvider(this.multiTenantConnectionProvider);
    }

    if (this.currentTenantIdentifierResolver != null) {
        sfb.setCurrentTenantIdentifierResolver(this.currentTenantIdentifierResolver);
    }

    if (this.entityTypeFilters != null) {
        sfb.setEntityTypeFilters(this.entityTypeFilters);
    }

    if (this.hibernateProperties != null) {
        sfb.addProperties(this.hibernateProperties);
    }

    if (this.annotatedClasses != null) {
        sfb.addAnnotatedClasses(this.annotatedClasses);
    }

    if (this.annotatedPackages != null) {
        sfb.addPackages(this.annotatedPackages);
    }

    if (this.packagesToScan != null) {
        sfb.scanPackages(this.packagesToScan);
    }

    // Build SessionFactory instance.
    this.configuration = sfb;
    this.sessionFactory = buildSessionFactory(sfb);
    // TODO Caratacus sessionFactory
    EntityInfoUtils.initSession(sessionFactory, setting);
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

/**
 * Set the root folder of this module source
 *
 * @param root/*from w ww  .j  a  v a  2 s. com*/
 */
public void setRootResource(Resource root) {
    try {
        super.setRoot("file://" + root.getFile().getPath());
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.paxml.table.csv.CsvTable.java

public CsvTable(Resource res, CsvOptions opt, ITableRange range) {
    if (opt == null) {
        opt = new CsvOptions();
    }/*  w  ww.  j av  a2  s.c om*/
    this.res = res;
    this.opt = opt;

    CsvPreference pref = opt.toPreference();

    if (res.exists()) {
        try {
            reader = new CsvListReader(
                    new InputStreamReader(new BOMInputStream(res.getInputStream()), opt.getEncoding()), pref);
        } catch (IOException e) {
            throw new PaxmlRuntimeException("Cannot read csv file: " + PaxmlUtils.getResourceFile(res), e);
        }
    } else {
        reader = null;
    }
    List<String> cols = opt.getColumns();
    if (cols == null) {
        // detect headers from file
        headers = new LinkedHashMap<String, IColumn>();
        if (reader != null) {
            String[] h;
            try {
                h = reader.getHeader(true);
            } catch (IOException e) {
                throw new PaxmlRuntimeException(
                        "Cannot read csv file header: " + PaxmlUtils.getResourceFile(res), e);
            }
            if (h != null) {
                for (String s : h) {
                    addColumn(s);
                }
            }
        }
    } else if (cols.isEmpty()) {
        headers = null;
    } else {
        // given header, skip existing header too
        if (reader != null) {
            try {
                reader.getHeader(true);
            } catch (IOException e) {
                throw new PaxmlRuntimeException(
                        "Cannot read csv file header: " + PaxmlUtils.getResourceFile(res), e);
            }
        }
        headers = new LinkedHashMap<String, IColumn>();
        for (String col : cols) {
            addColumn(col);
        }
    }
    CsvListWriter w = null;
    if (!opt.isReadOnly()) {
        writerFile = getWriterFile(res);
        if (writerFile != null) {

            try {
                w = new CsvListWriter(new FileWriter(reader == null ? res.getFile() : writerFile), pref);
                if (headers != null && !headers.isEmpty()) {
                    w.writeHeader(headers.keySet().toArray(new String[headers.size()]));
                }
            } catch (IOException e) {
                // do nothing, because this means writer cannot write to the
                // file.
            }

        }
    } else {
        writerFile = null;
    }
    writer = w;

    if (reader == null && writer == null) {
        throw new PaxmlRuntimeException(
                "Can neither read from nor write to csv file: " + PaxmlUtils.getResourceFile(res));
    }

    setRange(range);
}

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

/**
 * /*  w  w w. ja v a2s.  c  o  m*/
 */
private void _load() {
    Resource sources[] = getSources();
    if (sources == null) {
        return;
    }

    DataFileReader reader = null;
    DataFileWriter successWriter = null, errorWriter = null;

    for (int i = 0; i < sources.length; i++) {
        Resource source = sources[i];
        try {
            String filename = source.getFilename();
            DataFileHandler fileHandler = null;
            for (DataFileHandler fh : dataFileHandlers) {
                if (fh.accept(filename)) {
                    fileHandler = fh;
                    break;
                }
            }
            if (fileHandler == null) {
                throw new DataFileLoaderException("No handler found for filename: " + filename);
            }

            reader = fileHandler.getReader();
            reader.setResource(source);
            successWriter = fileHandler.getSuccessWriter();
            if (successWriter != null) {
                Resource successResource = fileHandler.getSuccessResourceCreator().create(source);
                successWriter.setResource(successResource);
            }
            errorWriter = fileHandler.getErrorWriter();
            if (errorWriter != null) {
                Resource errorResource = fileHandler.getErrorResourceCreator().create(source);
                errorWriter.setResource(errorResource);
            }

            DataContext dataContext = new DataContext(this.attributes);
            dataContext.resource = source;
            dataContext.resourceNum = i;
            dataContext.startTime = new Date();
            if (dataFileProcessor instanceof DataContextAware) {
                ((DataContextAware) dataFileProcessor).setDataContext(dataContext);
            }
            try {
                doReadProcessWrite(dataContext, reader, successWriter, errorWriter);
                dataContext.exitStatus = ExitStatus.COMPLETED;
            } catch (Exception e) {
                dataContext.exitStatus = ExitStatus.FAILED;
                throw e;
            } finally {
                dataContext.finishTime = new Date();
                //may persist dataContext here

                if (reader != null)
                    try {
                        reader.close();
                    } catch (Exception e) {
                    }
                if (successWriter != null)
                    try {
                        successWriter.close();
                    } catch (Exception e) {
                    }
                if (errorWriter != null)
                    try {
                        errorWriter.close();
                    } catch (Exception e) {
                    }
            }

            if (shouldDeleteIfFinish) {
                logger.info("Deleting file " + source);
                source.getFile().delete();
            } else if (destination != null) {
                File destFile = destination.getFile();
                logger.debug("Moving file: " + source.getFile().getCanonicalPath() + " to file: "
                        + destFile.getCanonicalPath());
                if (resource.getFile().isDirectory()) {
                    FileUtils.moveFileToDirectory(source.getFile(), destFile, true);
                } else {
                    FileUtils.moveFile(source.getFile(), destFile);
                }
            }

        } catch (Exception e) {
            if (stopOnError) {
                if (e instanceof DataFileLoaderException) {
                    throw (DataFileLoaderException) e;
                } else {
                    throw new DataFileLoaderException(e.getMessage(), e);
                }
            } else {
                logger.error(e.getMessage(), e);
            }
        }
    } //for each resource
}

From source file:org.ow2.authzforce.pap.dao.flatfile.FlatFileBasedDomainsDAO.java

/**
 * Creates instance//from   w  ww .ja v a 2  s  .  c  o m
 * 
 * @param domainsRoot
 *            root directory of the configuration data of security domains,
 *            one subdirectory per domain
 * @param domainTmpl
 *            domain template directory; directories of new domains are
 *            created from this template
 * @param domainsSyncIntervalSec
 *            how often (in seconds) the synchronization of managed domains
 *            (in memory) with the domain subdirectories in the
 *            <code>domainsRoot</code> directory (on disk) is done. If
 *            <code>domainSyncInterval</code> > 0, every
 *            <code>domainSyncInterval</code>, the managed domains (loaded
 *            in memory) are updated if any change has been detected in the
 *            <code>domainsRoot</code> directory in this interval (since
 *            last sync). To be more specific, <i>any change</i> here means
 *            any creation/deletion/modification of a domain folder
 *            (modification means: any file changed within the folder). If
 *            <code>domainSyncInterval</code> &lt;= 0, synchronization is
 *            disabled.
 * @param pdpModelHandler
 *            PDP configuration model handler
 * @param useRandomAddressBasedUUID
 *            true iff a random multicast address must be used as node field
 *            of generated UUIDs (Version 1), else the MAC address of one of
 *            the network interfaces is used. Setting this to 'true' is NOT
 *            recommended unless the host is disconnected from the network.
 *            These generated UUIDs are used for domain IDs.
 * @param domainDAOClientFactory
 *            domain DAO client factory
 * @throws IOException
 *             I/O error occurred scanning existing domain folders in
 *             {@code domainsRoot} for loading.
 */
@ConstructorProperties({ "domainsRoot", "domainTmpl", "domainsSyncIntervalSec", "pdpModelHandler",
        "useRandomAddressBasedUUID", "domainDAOClientFactory" })
public FlatFileBasedDomainsDAO(final Resource domainsRoot, final Resource domainTmpl,
        final int domainsSyncIntervalSec, final PdpModelHandler pdpModelHandler,
        final boolean useRandomAddressBasedUUID,
        final DomainDAOClient.Factory<VERSION_DAO_CLIENT, POLICY_DAO_CLIENT, FlatFileBasedDomainDAO<VERSION_DAO_CLIENT, POLICY_DAO_CLIENT>, DOMAIN_DAO_CLIENT> domainDAOClientFactory)
        throws IOException {
    if (domainsRoot == null || domainTmpl == null || pdpModelHandler == null
            || domainDAOClientFactory == null) {
        throw ILLEGAL_CONSTRUCTOR_ARGS_EXCEPTION;
    }

    this.domainDAOClientFactory = domainDAOClientFactory;
    this.policyDAOClientFactory = domainDAOClientFactory.getPolicyDAOClientFactory();
    this.policyVersionDAOClientFactory = policyDAOClientFactory.getVersionDAOClientFactory();

    this.uuidGen = initUUIDGenerator(useRandomAddressBasedUUID);
    this.pdpModelHandler = pdpModelHandler;

    // Validate domainsRoot arg
    if (!domainsRoot.exists()) {
        throw new IllegalArgumentException(
                "'domainsRoot' resource does not exist: " + domainsRoot.getDescription());
    }

    final String ioExMsg = "Cannot resolve 'domainsRoot' resource '" + domainsRoot.getDescription()
            + "' as a file on the file system";
    File domainsRootFile = null;
    try {
        domainsRootFile = domainsRoot.getFile();
    } catch (final IOException e) {
        throw new IllegalArgumentException(ioExMsg, e);
    }

    this.domainsRootDir = domainsRootFile.toPath();
    FlatFileDAOUtils.checkFile("File defined by SecurityDomainManager parameter 'domainsRoot'", domainsRootDir,
            true, true);

    // Validate domainTmpl directory arg
    if (!domainTmpl.exists()) {
        throw new IllegalArgumentException(
                "'domainTmpl' resource does not exist: " + domainTmpl.getDescription());
    }

    final String ioExMsg2 = "Cannot resolve 'domainTmpl' resource '" + domainTmpl.getDescription()
            + "' as a file on the file system";
    File domainTmplFile = null;
    try {
        domainTmplFile = domainTmpl.getFile();
    } catch (final IOException e) {
        throw new IllegalArgumentException(ioExMsg2, e);
    }

    this.domainTmplDirPath = domainTmplFile.toPath();
    FlatFileDAOUtils.checkFile("File defined by SecurityDomainManager parameter 'domainTmpl'",
            domainTmplDirPath, true, false);

    LOGGER.debug("Looking for domain sub-directories in directory {}", domainsRootDir);
    try (final DirectoryStream<Path> dirStream = Files.newDirectoryStream(domainsRootDir)) {
        for (final Path domainPath : dirStream) {
            LOGGER.debug("Checking domain in file {}", domainPath);
            if (!Files.isDirectory(domainPath)) {
                LOGGER.warn("Ignoring invalid domain file {} (not a directory)", domainPath);
                continue;
            }

            // domain folder name is the domain ID
            final Path lastPathSegment = domainPath.getFileName();
            if (lastPathSegment == null) {
                throw new RuntimeException("Invalid Domain folder path '" + domainPath + "': no filename");
            }

            final String domainId = lastPathSegment.toString();
            FlatFileBasedDomainDAO<VERSION_DAO_CLIENT, POLICY_DAO_CLIENT> domainDAO = null;
            try {
                domainDAO = new FileBasedDomainDAOImpl(domainPath, null);
            } catch (final IllegalArgumentException e) {
                throw new RuntimeException("Invalid domain data for domain '" + domainId + "'", e);
            }

            final DOMAIN_DAO_CLIENT domain = domainDAOClientFactory.getInstance(domainId, domainDAO);
            domainMap.put(domainId, domain);
        }
    } catch (final IOException e) {
        throw new IOException("Failed to scan files in the domains root directory '" + domainsRootDir
                + "' looking for domain directories", e);
    }

    this.domainDirToMemSyncIntervalSec = Integer.valueOf(domainsSyncIntervalSec).longValue();
}