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:io.spring.initializr.test.generator.ProjectAssert.java

private Properties properties(String localPath) {
    File f = file(localPath);//  ww  w .  j av a  2  s .co  m
    try {
        return PropertiesLoaderUtils.loadProperties(new FileSystemResource(f));
    } catch (Exception e) {
        throw new IllegalStateException("Cannot load Properties", e);
    }
}

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

private void loadIncludedFile(PrefabGraphTypeDao type, File file) throws FileNotFoundException, IOException {
    Properties props = new Properties();
    InputStream fileIn = new FileInputStream(file);
    try {/*from   ww w  .j  a v  a  2s .c  o  m*/
        props.load(fileIn);
    } finally {
        IOUtils.closeQuietly(fileIn);
    }
    //Clear any malformed setting; if everything goes ok, it'll remain cleared
    // If there's problems, it'll be re-added.
    type.removeMalformedFile(file);
    try {
        List<PrefabGraph> subGraphs = loadPrefabGraphDefinitions(type, props);
        for (PrefabGraph graph : subGraphs) {
            if (graph == null) {
                //Indicates a multi-graph file that had a munted graph definition
                type.addMalformedFile(file); //Record that the file was partly broken
            } else {
                type.addPrefabGraph(new FileReloadContainer<PrefabGraph>(graph, new FileSystemResource(file),
                        type.getCallback()));
            }
        }

    } catch (DataAccessResourceFailureException e) {
        LOG.error("Problem while attempting to load {}", file, e);
        type.addMalformedFile(file); //Record that the file was completely broken
    }
}

From source file:org.eclipse.gemini.blueprint.test.provisioning.internal.LocalFileSystemMavenRepository.java

/**
 * Return the resource of the indicated bundle in the local Maven repository
 * //from   ww w . j  a v a  2s.  com
 * @param groupId - the groupId of the organization supplying the bundle
 * @param artifact - the artifact id of the bundle
 * @param version - the version of the bundle
 * @return
 */
protected Resource localMavenBundle(String groupId, String artifact, String version, String type) {
    StringBuilder location = new StringBuilder(groupId.replace('.', SLASH_CHAR));
    location.append(SLASH_CHAR);
    location.append(artifact);
    location.append(SLASH_CHAR);
    location.append(version);
    location.append(SLASH_CHAR);
    location.append(artifact);
    location.append('-');
    location.append(version);
    location.append(".");
    location.append(type);

    return new FileSystemResource(new File(repositoryHome, location.toString()));
}

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

@Test
public void testIgnoreEmptyFile() throws Exception {
    File aTmpFile = File.createTempFile("input-copy-", ".csv", new File("target/"));
    FileCopyTasklet aTasklet = new FileCopyTasklet();
    aTasklet.setIgnoreEmptyFile(true);/*ww w .j a  v a  2 s.  c  o m*/
    aTasklet.setOrigin(new FileSystemResource(aTmpFile));
    aTasklet.setDestination(new FileSystemResource("target/input-copyEmpty.csv"));
    StepContribution aStepContribution = mock(StepContribution.class);
    aTasklet.execute(aStepContribution, null);
    verify(aStepContribution, times(0)).incrementReadCount();
    verify(aStepContribution, times(0)).incrementWriteCount(1);

    assertFalse(aTasklet.getDestination().getFile().exists());
    assertTrue(aTasklet.getOrigin().getFile().exists());
    assertEquals(0, aTasklet.getOrigin().getFile().length());
}

From source file:org.biopax.validator.api.ValidatorUtils.java

/**
 * Gets the validator's home directory path.
 * /*from w ww .  java  2  s  .c  o  m*/
 * @return
 * @throws IOException 
 */
public static String getHomeDir() throws IOException {
    Resource r = new FileSystemResource(ResourceUtils.getFile("classpath:"));
    return r.createRelative("..").getFile().getCanonicalPath();
}

From source file:edu.dfci.cccb.mev.dataset.rest.google.GoogleWorkspace.java

@Override
@SneakyThrows({ IOException.class, DatasetComposingException.class })
public void put(Dataset dataset) {
    workspaceDelegate.put(dataset);//from w ww .  jav  a 2  s.  com
    try (TemporaryFile ds = new TemporaryFile()) {
        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(ds))) {
            composer.compose(dataset).write(out);
        }
        String id = google.driveOperations().upload(new FileSystemResource(ds),
                DriveFile.builder().setTitle(dataset.name()).build(), new UploadParameters()).getId();
        session.put(id, new HashMap<String, Class<? extends Analysis>>());
    }
}

From source file:de.zib.gndms.gndmc.AbstractClient.java

/**
 * Upload (POST) a file on a url.//w ww  .  j  a va2 s  . com
 *
 * The request header contains a given user name, the body of the request contains
 * a given object of type P.
 *
 * @param <T> The body type of the response.
 * @param clazz The type of the return value.
 * @param fileName Remote filename.
 * @param originalFileName Path to local file.
 * @param url The url of the request.
 * @param dn The user name.
 * @return The response as entity.
 */
protected final <T> ResponseEntity<T> postFile(final Class<T> clazz, final String fileName,
        final String originalFileName, final String url, final String dn) {

    GNDMSResponseHeader requestHeaders = new GNDMSResponseHeader();
    MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
    final HttpEntity requestEntity;

    if (dn != null) {
        requestHeaders.setDN(dn);
    }

    form.add("file", new FileSystemResource(originalFileName));
    requestEntity = new HttpEntity(form, requestHeaders);

    if (null == restTemplate)
        throw new NullPointerException("Please set RestTemplate in Client!");

    return restTemplate.postForEntity(url, requestEntity, clazz);
}

From source file:org.eclipse.gemini.blueprint.test.provisioning.internal.LocalFileSystemMavenRepository.java

/**
 * Find a local maven artifact in the current build tree. This searches for
 * resources produced by the package phase of a maven build.
 * /*from w  w w  .  j  a  v a 2 s . c  o m*/
 * @param artifactId
 * @param version
 * @param type
 * @return
 */
protected Resource localMavenBuildArtifact(String groupId, String artifactId, String version, String type) {
    try {
        File found = new MavenPackagedArtifactFinder(groupId, artifactId, version, type)
                .findPackagedArtifact(new File("."));
        Resource res = new FileSystemResource(found);
        if (log.isDebugEnabled()) {
            log.debug("[" + artifactId + "|" + version + "] resolved to " + res.getDescription()
                    + " as a local maven artifact");
        }
        return res;
    } catch (IOException ioEx) {
        throw (RuntimeException) new IllegalStateException(
                "Artifact " + artifactId + "-" + version + "." + type + " could not be found").initCause(ioEx);
    }
}

From source file:info.jtrac.config.JtracConfigurer.java

private void configureJtrac() throws Exception {

    String jtracHome = null;//from   www  .j ava2  s  .co  m
    ClassPathResource jtracInitResource = new ClassPathResource("jtrac-init.properties");
    // jtrac-init.properties assumed to exist
    Properties props = loadProps(jtracInitResource.getFile());
    logger.info("found 'jtrac-init.properties' on classpath, processing...");
    jtracHome = props.getProperty("jtrac.home");
    if (jtracHome != null) {
        logger.info("'jtrac.home' property initialized from 'jtrac-init.properties' as '" + jtracHome + "'");
    }
    //======================================================================
    FilenameFilter ff = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.startsWith("messages_") && name.endsWith(".properties");
        }
    };
    File[] messagePropsFiles = jtracInitResource.getFile().getParentFile().listFiles(ff);
    String locales = "en";
    for (File f : messagePropsFiles) {
        int endIndex = f.getName().indexOf('.');
        String localeCode = f.getName().substring(9, endIndex);
        locales += "," + localeCode;
    }
    logger.info("locales available configured are '" + locales + "'");
    props.setProperty("jtrac.locales", locales);
    //======================================================================
    if (jtracHome == null) {
        logger.info(
                "valid 'jtrac.home' property not available in 'jtrac-init.properties', trying system properties.");
        jtracHome = System.getProperty("jtrac.home");
        if (jtracHome != null) {
            logger.info("'jtrac.home' property initialized from system properties as '" + jtracHome + "'");
        }
    }
    if (jtracHome == null) {
        logger.info(
                "valid 'jtrac.home' property not available in system properties, trying servlet init paramters.");
        jtracHome = servletContext.getInitParameter("jtrac.home");
        if (jtracHome != null) {
            logger.info("Servlet init parameter 'jtrac.home' exists: '" + jtracHome + "'");
        }
    }
    if (jtracHome == null) {
        jtracHome = System.getProperty("user.home") + "/.jtrac";
        logger.warn("Servlet init paramter  'jtrac.home' does not exist.  Will use 'user.home' directory '"
                + jtracHome + "'");
    }
    //======================================================================
    File homeFile = new File(jtracHome);
    if (!homeFile.exists()) {
        homeFile.mkdir();
        logger.info("directory does not exist, created '" + homeFile.getPath() + "'");
        if (!homeFile.exists()) {
            String message = "invalid path '" + homeFile.getAbsolutePath()
                    + "', try creating this directory first.  Aborting.";
            logger.error(message);
            throw new Exception(message);
        }
    } else {
        logger.info("directory already exists: '" + homeFile.getPath() + "'");
    }
    props.setProperty("jtrac.home", homeFile.getAbsolutePath());
    //======================================================================
    File attachmentsFile = new File(jtracHome + "/attachments");
    if (!attachmentsFile.exists()) {
        attachmentsFile.mkdir();
        logger.info("directory does not exist, created '" + attachmentsFile.getPath() + "'");
    } else {
        logger.info("directory already exists: '" + attachmentsFile.getPath() + "'");
    }
    File indexesFile = new File(jtracHome + "/indexes");
    if (!indexesFile.exists()) {
        indexesFile.mkdir();
        logger.info("directory does not exist, created '" + indexesFile.getPath() + "'");
    } else {
        logger.info("directory already exists: '" + indexesFile.getPath() + "'");
    }
    //======================================================================
    File propsFile = new File(homeFile.getPath() + "/jtrac.properties");
    if (!propsFile.exists()) {
        propsFile.createNewFile();
        logger.info("properties file does not exist, created '" + propsFile.getPath() + "'");
        OutputStream os = new FileOutputStream(propsFile);
        Writer out = new PrintWriter(os);
        try {
            out.write("database.driver=org.hsqldb.jdbcDriver\n");
            out.write("database.url=jdbc:hsqldb:file:${jtrac.home}/db/jtrac\n");
            out.write("database.username=sa\n");
            out.write("database.password=\n");
            out.write("hibernate.dialect=org.hibernate.dialect.HSQLDialect\n");
            out.write("hibernate.show_sql=false\n");
        } finally {
            out.close();
            os.close();
        }
        logger.info("HSQLDB will be used.  Finished creating '" + propsFile.getPath() + "'");
    } else {
        logger.info("'jtrac.properties' file exists: '" + propsFile.getPath() + "'");
    }
    //======================================================================
    String version = "0.0.0";
    String timestamp = "0000";
    ClassPathResource versionResource = new ClassPathResource("jtrac-version.properties");
    if (versionResource.exists()) {
        logger.info("found 'jtrac-version.properties' on classpath, processing...");
        Properties versionProps = loadProps(versionResource.getFile());
        version = versionProps.getProperty("version");
        timestamp = versionProps.getProperty("timestamp");
    } else {
        logger.info("did not find 'jtrac-version.properties' on classpath");
    }
    logger.info("jtrac.version = '" + version + "'");
    logger.info("jtrac.timestamp = '" + timestamp + "'");
    props.setProperty("jtrac.version", version);
    props.setProperty("jtrac.timestamp", timestamp);
    props.setProperty("database.validationQuery", "SELECT 1");
    props.setProperty("ldap.url", "");
    props.setProperty("ldap.activeDirectoryDomain", "");
    props.setProperty("ldap.searchBase", "");
    props.setProperty("database.datasource.jndiname", "");
    // set default properties that can be overridden by user if required
    setProperties(props);
    // finally set the property that spring is expecting, manually
    FileSystemResource fsr = new FileSystemResource(propsFile);
    setLocation(fsr);
}

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

@Test
public void testEmptyFile() throws Exception {
    File aTmpFile = File.createTempFile("input-copy-", ".csv", new File("target/"));
    FileCopyTasklet aTasklet = new FileCopyTasklet();
    aTasklet.setIgnoreEmptyFile(false);//  ww w.  j  ava 2s.  com
    aTasklet.setOrigin(new FileSystemResource(aTmpFile));
    aTasklet.setDestination(new FileSystemResource("target/input-copyEmpty2.csv"));
    StepContribution aStepContribution = mock(StepContribution.class);
    aTasklet.execute(aStepContribution, null);
    verify(aStepContribution, times(1)).incrementReadCount();
    verify(aStepContribution, times(1)).incrementWriteCount(1);

    assertTrue(aTasklet.getDestination().getFile().exists());
    assertTrue(aTasklet.getOrigin().getFile().exists());
    assertEquals(0, aTasklet.getOrigin().getFile().length());
    assertEquals(0, aTasklet.getDestination().getFile().length());
}