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

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

Introduction

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

Prototype

public FileSystemResource(Path filePath) 

Source Link

Document

Create a new FileSystemResource from a Path handle, performing all file system interactions via NIO.2 instead of File .

Usage

From source file:org.globus.security.provider.TestPEMFileBasedKeyStore.java

@Test
public void testUserCerts() throws Exception {
    PEMKeyStore store = new PEMKeyStore();
    // Parameters in properties file
    Properties properties = new Properties();
    properties.setProperty(PEMKeyStore.CERTIFICATE_FILENAME,
            new FileSystemResource(this.certFile.getTempFile()).getURL().toExternalForm());
    properties.setProperty(PEMKeyStore.KEY_FILENAME,
            new FileSystemResource(this.keyFile.getTempFile()).getURL().toExternalForm());
    InputStream ins = null;/*  ww  w  .  jav  a  2  s .  c o  m*/
    try {
        ins = getProperties(properties);
        store.engineLoad(ins, null);
    } finally {
        if (ins != null) {
            ins.close();
        }
    }
    Enumeration aliases = store.engineAliases();
    assertTrue(aliases.hasMoreElements());
    String alias = (String) aliases.nextElement();
    Key key = store.engineGetKey(alias, null);
    assertNotNull(key);
    assertTrue(key instanceof PrivateKey);

    Certificate[] chain = store.engineGetCertificateChain(alias);
    assertNotNull(chain);

    Certificate certificate = store.engineGetCertificate(alias);
    assertNull(certificate);

    X509Credential x509Credential = new X509Credential(new FileInputStream(this.certFile.getAbsoluteFilename()),
            new FileInputStream(this.keyFile.getAbsoluteFilename()));

    assertEquals(key, x509Credential.getPrivateKey());
    Certificate[] x509CredentialChain = x509Credential.getCertificateChain();
    assertEquals(chain.length, x509CredentialChain.length);
    for (int i = 0; i < chain.length; i++) {
        assert (chain[i].equals(x509CredentialChain[i]));
    }

    store = new PEMKeyStore();
    properties.setProperty(PEMKeyStore.CERTIFICATE_FILENAME,
            new FileSystemResource(this.certFile.getTempFile()).getURL().toExternalForm());
    properties.setProperty(PEMKeyStore.KEY_FILENAME,
            new FileSystemResource(this.keyEncFile.getTempFile()).getURL().toExternalForm());
    try {
        ins = getProperties(properties);
        store.engineLoad(ins, null);
    } finally {
        if (ins != null) {
            ins.close();
        }
    }
    aliases = store.engineAliases();
    assert (aliases.hasMoreElements());
    alias = (String) aliases.nextElement();

    try {
        store.engineGetKey(alias, null);
        fail();
    } catch (UnrecoverableKeyException e) {
        //this had better fail
    }
    key = store.engineGetKey(alias, "test".toCharArray());
    assertNotNull(key);
    assertTrue(key instanceof PrivateKey);
    chain = store.engineGetCertificateChain(alias);
    assertNotNull(chain);
}

From source file:org.opennms.ng.dao.support.PropertiesGraphDao.java

/**
 * Create a PrefabGraphTypeDao from the properties file in sourceResource
 * If reloadable is true, add the type's reload call back to each graph,
 * otherwise don't If sourceResource is not a file-based resource, then
 * reloadable should be false NB: I didn't want to get into checking for
 * what the implementation class of Resource is, because that could break
 * in future with new classes and types that do have a File underneath
 * them. This way, it's up to the caller, who *should* be able to make a
 * sensible choice as to whether the resource is reloadable or not.
 *
 * @param type// w ww  .  j av  a  2 s .  com
 * @param sourceResource
 * @param reloadable
 * @return
 */
private PrefabGraphTypeDao createPrefabGraphType(String type, Resource sourceResource, boolean reloadable) {
    InputStream in = null;
    try {
        in = sourceResource.getInputStream();
        Properties properties = new Properties();
        properties.load(in);
        PrefabGraphTypeDao t = new PrefabGraphTypeDao();
        t.setName(type);

        t.setCommandPrefix(getProperty(properties, "command.prefix"));
        t.setOutputMimeType(getProperty(properties, "output.mime"));

        t.setDefaultReport(properties.getProperty("default.report", "none"));

        String includeDirectoryString = properties.getProperty("include.directory");
        t.setIncludeDirectory(includeDirectoryString);

        if (includeDirectoryString != null) {
            Resource includeDirectoryResource;

            File includeDirectoryFile = new File(includeDirectoryString);
            if (includeDirectoryFile.isAbsolute()) {
                includeDirectoryResource = new FileSystemResource(includeDirectoryString);
            } else {
                includeDirectoryResource = sourceResource.createRelative(includeDirectoryString);
            }

            File includeDirectory = includeDirectoryResource.getFile();

            if (includeDirectory.isDirectory()) {
                t.setIncludeDirectoryResource(includeDirectoryResource);
            } else {
                // Just warn; no need to throw a hissy fit or otherwise fail to load
                LOG.warn("includeDirectory '{}' specified in '{}' is not a directory",
                        includeDirectoryFile.getAbsolutePath(), sourceResource.getFilename());
            }
        }

        // Default to 5 minutes; it's up to users to specify a shorter
        // time if they don't mind OpenNMS spamming on that directory
        int interval;
        try {
            interval = Integer.parseInt(properties.getProperty("include.directory.rescan", "300000"));
        } catch (NumberFormatException e) {
            // Default value if one was specified but it wasn't an integer
            interval = 300000;
            LOG.warn(
                    "The property 'include.directory.rescan' in {} was not able to be parsed as an integer.  Defaulting to {}ms",
                    sourceResource, interval, e);
        }

        t.setIncludeDirectoryRescanInterval(interval);

        List<PrefabGraph> graphs = loadPrefabGraphDefinitions(t, properties);

        for (PrefabGraph graph : graphs) {
            //The graphs list may contain nulls; see loadPrefabGraphDefinitions for reasons
            if (graph != null) {
                FileReloadContainer<PrefabGraph> container;
                if (reloadable) {
                    container = new FileReloadContainer<PrefabGraph>(graph, sourceResource, t.getCallback());
                } else {
                    container = new FileReloadContainer<PrefabGraph>(graph);
                }

                t.addPrefabGraph(container);
            }
        }

        //This *must* come after loading the main graph file, to ensure overrides are correct
        this.scanIncludeDirectory(t);
        return t;

    } catch (IOException e) {
        LOG.error("Failed to load prefab graph configuration of type {} from {}", type, sourceResource, e);
        return null;
    } finally {
        IOUtils.closeQuietly(in);
    }

}

From source file:org.codehaus.groovy.grails.scaffolding.AbstractGrailsTemplateGenerator.java

protected Set<String> getTemplateNames() throws IOException {

    if (resourceLoader != null && grailsApplication.isWarDeployed()) {
        try {//from  w  w w . j  ava 2  s .c  o  m
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
                    resourceLoader);
            return extractNames(resolver.getResources("/WEB-INF/templates/scaffolding/*.gsp"));
        } catch (Exception e) {
            return Collections.emptySet();
        }
    }

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Set<String> resources = new HashSet<String>();

    String templatesDirPath = basedir + "/src/templates/scaffolding";
    Resource templatesDir = new FileSystemResource(templatesDirPath);
    if (templatesDir.exists()) {
        try {
            resources.addAll(extractNames(resolver.getResources("file:" + templatesDirPath + "/*.gsp")));
        } catch (Exception e) {
            log.error("Error while loading views from " + basedir, e);
        }
    }

    File pluginDir = getPluginDir();
    try {
        resources.addAll(
                extractNames(resolver.getResources("file:" + pluginDir + "/src/templates/scaffolding/*.gsp")));
    } catch (Exception e) {
        // ignore
        log.error("Error locating templates from " + pluginDir + ": " + e.getMessage(), e);
    }

    return resources;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.QCLiveTestDataGeneratorSlowTest.java

/**
 * Tests the {@link QCLiveTestDataGenerator#executeSQLScriptFile(SchemaType, org.springframework.core.io.Resource)} method with
 * a non-existent SQL script file resource.
 *///from  ww  w  . j a  v  a 2  s  .c om
public void testExecSQLScriptFileWithInvalidFile() throws SQLException {

    String actualMessage = null;
    try {
        new QCLiveTestDataGenerator().executeSQLScriptFile(SchemaType.LOCAL_COMMON,
                new FileSystemResource("invalidSQLScriptFile"));
    } catch (IOException ioe) {
        actualMessage = ioe.getMessage();
    }

    // Assert that the correct exception message is thrown
    assertEquals("SQL script file resource 'class path resource [invalidSQLScriptFile]' is not readable.",
            actualMessage);
}

From source file:com.acmemotors.batch.LoaderJobConfiguration.java

@Bean
@StepScope//from w  w w  . ja v  a2s  .  com
public FlatFileItemReader<Map<String, Object>> reader(@Value("#{jobParameters['inputFile']}") String fileName)
        throws Exception {

    DefaultLineMapper<Map<String, Object>> mapper = new DefaultLineMapper<>();
    mapper.setLineTokenizer(jsonLineTokenzier());
    mapper.setFieldSetMapper(new FieldSetMapper<Map<String, Object>>() {

        private UUID journeyId = UUID.randomUUID();

        private Double readDouble(String value) {
            if (StringUtils.hasText(value)) {
                return Double.valueOf(value);
            } else {
                return null;
            }
        }

        private Integer readInteger(String value) {
            if (StringUtils.hasText(value)) {
                return Integer.valueOf(value);
            } else {
                return null;
            }
        }

        @Override
        public Map<String, Object> mapFieldSet(FieldSet fieldSet) throws BindException {

            Map<String, Object> map = new HashMap<>();

            map.put(VIN.getHerbieField(), fieldSet.readString(VIN.getHerbieField()));
            map.put(LONGITUDE.getHerbieField(), readDouble(fieldSet.readString(LONGITUDE.getHerbieField())));
            map.put(LATITUDE.getHerbieField(), readDouble(fieldSet.readString(LATITUDE.getHerbieField())));
            map.put(RPM.getHerbieField(), readDouble(fieldSet.readString(RPM.getHerbieField())));
            map.put(VEHICLE_SPEED.getHerbieField(),
                    readInteger(fieldSet.readString(VEHICLE_SPEED.getHerbieField())));
            String statuses = fieldSet.readString(FUEL_SYSTEM_STATUS.getHerbieField());
            String[] statusPieces = statuses.substring(1, statuses.length() - 1).split(",");
            Integer[] integerStatuses = { readInteger(statusPieces[0].trim()),
                    readInteger(statusPieces[1].trim()) };
            map.put(FUEL_SYSTEM_STATUS.getHerbieField(), integerStatuses);
            map.put(ENGINE_LOAD.getHerbieField(),
                    readDouble(fieldSet.readString(ENGINE_LOAD.getHerbieField())));
            map.put(COOLANT_TEMP.getHerbieField(),
                    readInteger(fieldSet.readString(COOLANT_TEMP.getHerbieField())));
            map.put(SHORT_TERM_FUEL.getHerbieField(),
                    readDouble(fieldSet.readString(SHORT_TERM_FUEL.getHerbieField())));
            map.put(LONG_TERM_FUEL.getHerbieField(),
                    readDouble(fieldSet.readString(LONG_TERM_FUEL.getHerbieField())));
            map.put(INTAKE_MANIFOLD_PRESSURE.getHerbieField(),
                    readInteger(fieldSet.readString(INTAKE_MANIFOLD_PRESSURE.getHerbieField())));
            map.put(INTAKE_AIR_TEMP.getHerbieField(),
                    readInteger(fieldSet.readString(INTAKE_AIR_TEMP.getHerbieField())));
            map.put(MAF_AIRFLOW.getHerbieField(),
                    readDouble(fieldSet.readString(MAF_AIRFLOW.getHerbieField())));
            map.put(THROTTLE_POSITION.getHerbieField(),
                    readInteger(fieldSet.readString(THROTTLE_POSITION.getHerbieField())));
            map.put(OBD_STANDARDS.getHerbieField(), fieldSet.readString(OBD_STANDARDS.getHerbieField()));
            map.put(TIME_SINCE_ENGINE_START.getHerbieField(),
                    readInteger(fieldSet.readString(TIME_SINCE_ENGINE_START.getHerbieField())));
            map.put(FUEL_LEVEL_INPUT.getHerbieField(),
                    readInteger(fieldSet.readString(FUEL_LEVEL_INPUT.getHerbieField())));
            map.put(RELATIVE_THROTTLE_POS.getHerbieField(),
                    readDouble(fieldSet.readString(RELATIVE_THROTTLE_POS.getHerbieField())));
            map.put(ABSOLUTE_THROTTLE_POS_B.getHerbieField(),
                    readDouble(fieldSet.readString(ABSOLUTE_THROTTLE_POS_B.getHerbieField())));
            map.put(ACCELERATOR_THROTTLE_POS_D.getHerbieField(),
                    readDouble(fieldSet.readString(ACCELERATOR_THROTTLE_POS_D.getHerbieField())));
            map.put(ACCELERATOR_THROTTLE_POS_E.getHerbieField(),
                    readDouble(fieldSet.readString(ACCELERATOR_THROTTLE_POS_E.getHerbieField())));
            map.put(DISTANCE_WITH_MIL_ON.getHerbieField(),
                    readInteger(fieldSet.readString(DISTANCE_WITH_MIL_ON.getHerbieField())));
            map.put(CATALYST_TEMP.getHerbieField(),
                    readDouble(fieldSet.readString(CATALYST_TEMP.getHerbieField())));
            map.put(BAROMETRIC_PRESSURE.getHerbieField(),
                    readInteger(fieldSet.readString(BAROMETRIC_PRESSURE.getHerbieField())));
            map.put(CONTROL_MODULE_VOLTAGE.getHerbieField(),
                    readDouble(fieldSet.readString(CONTROL_MODULE_VOLTAGE.getHerbieField())));
            map.put(ACCELERATION.getHerbieField(),
                    readDouble(fieldSet.readString(ACCELERATION.getHerbieField())));
            map.put(BEARING.getHerbieField(), readDouble(fieldSet.readString(BEARING.getHerbieField())));
            map.put(JOURNEY_ID.getHerbieField(), journeyId.toString());

            return map;
        }
    });

    mapper.afterPropertiesSet();

    FlatFileItemReader<Map<String, Object>> reader = new FlatFileItemReader<>();
    reader.setLineMapper(mapper);
    reader.setResource(new FileSystemResource(fileName));
    reader.afterPropertiesSet();

    return reader;
}

From source file:annis.administration.DefaultAdministrationDao.java

/**
* Reads tab seperated files from the filesystem, but it takes only files into
* account with the {@link DefaultAdministrationDao#REL_ANNIS_FILE_SUFFIX}
* suffix. Further it is straight forward except for the
* {@link DefaultAdministrationDao#FILE_RESOLVER_VIS_MAP} and the
* {@link DefaultAdministrationDao#EXAMPLE_QUERIES}. This is done by this
* method automatically./*from  www.  j a v a  2  s  .co m*/
*
* <ul>
*
* <li>{@link DefaultAdministrationDao#FILE_RESOLVER_VIS_MAP}: For backwards
* compatibility, the columns must be counted, since there exists one
* additional column for visibility behaviour of visualizers.</li>
*
* <li>{@link DefaultAdministrationDao#EXAMPLE_QUERIES}: If this file does not
* exists, the example query table is empty</li>
*
* </ul>
*
* @param path The path to the relANNIS. The files have to have this suffix
* {@link DefaultAdministrationDao#REL_ANNIS_FILE_SUFFIX}
*/
void bulkImport(String path) {
    log.info("bulk-loading data");

    for (String table : importedTables) {
        if (table.equalsIgnoreCase(FILE_RESOLVER_VIS_MAP)) {
            importResolverVisMapTable(path, table);
        }
        // check if example query exists. If not copy it from the resource folder.
        else if (table.equalsIgnoreCase(EXAMPLE_QUERIES)) {
            File f = new File(path, table + REL_ANNIS_FILE_SUFFIX);
            if (f.exists()) {
                log.info(table + REL_ANNIS_FILE_SUFFIX + " file exists");
                bulkloadTableFromResource(tableInStagingArea(table), new FileSystemResource(f));

                // turn off auto generating example queries.
                generateExampleQueries = false;
            } else {
                log.info(table + REL_ANNIS_FILE_SUFFIX + " file not found");
            }
        } else if (table.equalsIgnoreCase("node")) {
            bulkImportNode(path);
        } else {
            bulkloadTableFromResource(tableInStagingArea(table),
                    new FileSystemResource(new File(path, table + REL_ANNIS_FILE_SUFFIX)));
        }
    }
}

From source file:com.apdplat.platform.spring.APDPlatPersistenceUnitReader.java

/**
 * Parse the <code>jar-file</code> XML elements.
 */// w  w w.j  av a  2s .com
@SuppressWarnings("unchecked")
protected void parseJarFiles(Element persistenceUnit, SpringPersistenceUnitInfo unitInfo) throws IOException {
    List<Element> jars = DomUtils.getChildElementsByTagName(persistenceUnit, JAR_FILE_URL);
    for (Element element : jars) {
        logger.info(
                "apdplatspring jpa2(2. Start to execute custom modifications  of APDPlat for Spring JPA )");
        String jarHolder = DomUtils.getTextValue(element).trim();
        if (jarHolder == null || "".equals(jarHolder.trim())) {
            continue;
        }
        logger.info("??(Content of placeholder is): " + jarHolder);
        //${}??
        String realJars = PropertyHolder.getProperty(jarHolder.substring(2, jarHolder.length() - 1));
        logger.info(
                "???(Content of config file related to placeholder is): "
                        + realJars);
        String[] jarArray = realJars.split(",");
        for (String jar : jarArray) {
            if (StringUtils.hasText(jar)) {
                FileSystemResource resource = new FileSystemResource(FileUtils.getAbsolutePath(jar));
                unitInfo.addJarFileUrl(resource.getURL());
            }
        }
    }
}

From source file:fr.acxio.tools.agia.tasks.ZipFilesTaskletTest.java

@Test
public void testExistingZipFile() throws Exception {
    File aTargetFile = File.createTempFile("target/Z8-input", ".zip");
    String aTargetFilename = aTargetFile.getAbsolutePath();

    ZipFilesTasklet aTasklet = new ZipFilesTasklet();
    aTasklet.setSourceBaseDirectory(new FileSystemResource("src/test/resources/testFiles/"));
    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();
    aSourceFactory.setPattern("file:src/test/resources/testFiles/input.csv");
    aTasklet.setSourceFactory(aSourceFactory);
    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();
    aDestinationFactory.setExpression(aTargetFilename);
    aTasklet.setDestinationFactory(aDestinationFactory);

    assertTrue(new File(aTargetFilename).exists());

    StepContribution aStepContribution = mock(StepContribution.class);
    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));
    verify(aStepContribution, times(1)).incrementReadCount();
    verify(aStepContribution, times(1)).incrementWriteCount(1);

    assertTrue(new File(aTargetFilename).exists());
    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));
    Enumeration<ZipArchiveEntry> aEntries = aZipFile.getEntries();
    assertTrue(aEntries.hasMoreElements());
    assertEquals("input.csv", aEntries.nextElement().getName());
    assertFalse(aEntries.hasMoreElements());
    aZipFile.close();/*from   ww  w.  j a va  2s. c om*/
}

From source file:com.google.api.ads.adwords.jaxws.extensions.AwReporting.java

/**
 * Initialize the application context, adding the properties configuration file depending on the
 * specified path./*ww w.j  a  v a 2 s.co  m*/
 *
 * @param propertiesPath the path to the file.
 * @return the resource loaded from the properties file.
 * @throws IOException error opening the properties file.
 */
private static Properties initApplicationContextAndProperties(String propertiesPath) throws IOException {

    Resource resource = new ClassPathResource(propertiesPath);
    if (!resource.exists()) {
        resource = new FileSystemResource(propertiesPath);
    }
    LOGGER.trace("Innitializing Spring application context.");
    DynamicPropertyPlaceholderConfigurer.setDynamicResource(resource);

    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
    String dbType = (String) properties.get(AW_REPORT_MODEL_DB_TYPE);
    if (dbType != null && dbType.equals(DataBaseType.MONGODB.name())) {

        LOGGER.debug("Using MONGO DB configuration properties.");
        appCtx = new ClassPathXmlApplicationContext("classpath:aw-reporting-mongodb-beans.xml");
    } else {

        LOGGER.debug("Using SQL DB configuration properties.");
        appCtx = new ClassPathXmlApplicationContext("classpath:aw-reporting-sql-beans.xml");
    }

    return properties;
}