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:com.siberhus.tdfl.DflSimpleTest.java

@Test
public void testOverrideLoader() {
    DataFileLoader<Employee> dfl = new DataFileLoader<Employee>() {
        @Override/*  ww  w  .  j  av a  2 s  . c om*/
        protected void doReadProcessWrite(DataContext dataContext, DataFileReader reader,
                DataFileWriter successWriter, DataFileWriter errorWriter) throws Exception {
            super.doReadProcessWrite(dataContext, reader, successWriter, errorWriter);
        }
    };
    dfl.setDataFileHandlers(handlers);
    dfl.setDataFileProcessor(employeeDfp);
    dfl.setResource(new FileSystemResource(XLS_FILE_IN_NAME));
    dfl.load();

}

From source file:org.cbio.portal.pipelines.foundation.MetaDataTasklet.java

/**
 * Create and Write meta data file.//from ww w.j a  v  a  2 s.c om
 * @param executionContext
 * @throws Exception 
 */
private void writeMetaStagingFile(ExecutionContext executionContext, String metaFilename, List<String> metaData)
        throws Exception {
    FlatFileItemWriter<String> flatFileItemWriter = new FlatFileItemWriter<>();
    PassThroughLineAggregator aggr = new PassThroughLineAggregator();

    try {
        flatFileItemWriter.setLineAggregator(aggr);
        flatFileItemWriter.setResource(new FileSystemResource(metaFilename));
        flatFileItemWriter.open(executionContext);
        flatFileItemWriter.write(metaData);
        flatFileItemWriter.close();
    } catch (Exception ex) {
        LOG.error("Error writing meta data file: " + metaFilename);
        ex.printStackTrace();
    }

}

From source file:org.globus.security.stores.ResourceSecurityWrapperStore.java

private Set<V> addCredentials(File directory) throws ResourceStoreException {
    FilenameFilter filter = getDefaultFilenameFilter();
    String[] children = directory.list(filter);
    Set<V> roots = new HashSet<V>();
    try {/*from   w  w w  .  ja v a2 s  .  c o  m*/
        for (String child : children) {
            File childFile = new File(directory, child);
            if (childFile.isDirectory()) {
                roots.addAll(addCredentials(childFile));
            } else {
                Resource resource = new FileSystemResource(childFile);
                String resourceUri = resource.getURI().toASCIIString();
                T fbo = this.wrapperMap.get(resourceUri);
                if (fbo == null) {
                    fbo = create(new FileSystemResource(childFile));
                }
                V target = fbo.create(resource);
                this.wrapperMap.put(resourceUri, fbo);
                roots.add(target);
            }
        }
        return roots;
    } catch (IOException e) {
        throw new ResourceStoreException(e);
    }
}

From source file:com.lm.lic.manager.controller.PocketGearWithdrawLicHandler.java

@SuppressWarnings("unchecked")
public boolean verifyPocketGearRequest(HttpServletRequest request) {
    boolean valid = false;
    com.hhc.client.CertificateReader reader = new com.hhc.client.CertificateReader();
    java.security.PublicKey publicKey = null;
    try {//from  w w w.j  a  v  a2 s  . c om
        String pathToClassesDir = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        int index = pathToClassesDir.indexOf("/WEB-INF/");
        String fullPath = pathToClassesDir.substring(0, index + "/WEB-INF/".length())
                + "certificates/Handango.cert";

        FileSystemResource fr = new FileSystemResource(fullPath);
        publicKey = reader.getPublicKey(fr.getInputStream());
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
        return false;
    }

    com.hhc.client.Authenticator authenticator = new com.hhc.client.Authenticator(publicKey);
    try {
        if (authenticator.verify(request.getParameterMap())) {
            valid = true;
        } else {
            valid = false;
        }
    } catch (AuthenticatorException e) {
        e.printStackTrace();
        return false;
    }

    valid = true;
    return valid;
}

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

private File findInDirectoryTree(String fileName, File root) {
    boolean trace = log.isTraceEnabled();

    File targetDir = new File(root, TARGET);
    if (targetDir.exists()) {
        File artifact = new File(targetDir, fileName);
        // found artifact
        if (artifact.exists()) {
            if (trace)
                log.trace("Found artifact at " + artifact.getAbsolutePath()
                        + "; checking the pom.xml groupId...");
            // check the groupId inside the parent pom
            // (happens late to allow filtering to occur)
            File pomXml = new File(root, POM_XML);
            String groupId = getGroupIdFromPom(new FileSystemResource(pomXml));
            if (trace)
                log.trace("Pom [" + pomXml.getAbsolutePath() + "] has groupId [" + groupId + "]");
            if (this.groupId.equals(groupId))
                return artifact;
        }//from  ww  w .  j a va2  s. c  om
    }
    File[] children = root.listFiles(new FileFilter() {

        public boolean accept(File pathname) {
            if (!isMavenProjectDirectory(pathname)) {
                return false;
            }
            if (pathname.getName().equals(TARGET)) {
                return false;
            }
            if (pathname.getName().equals("src")) {
                return false;
            }
            if (pathname.getName().equals(".svn")) {
                return false;
            }
            return true;
        }
    });

    for (int i = 0; i < children.length; i++) {
        File found = findInDirectoryTree(fileName, children[i]);
        if (found != null) {
            return found;
        }
    }

    return null;
}

From source file:com.alliander.osgp.adapter.ws.smartmetering.infra.ws.WebServiceTemplateFactory.java

/**
 * @throws WebServiceSecurityException/*from   w  w w . ja v  a  2 s  .c  o  m*/
 *             if an error occurs while attempting to create a secured
 *             connection.
 */
private HttpComponentsMessageSender webServiceMessageSender(final String keystore)
        throws WebServiceSecurityException {

    try {
        // Open keystore, assuming same identity
        final KeyStoreFactoryBean keyStoreFactory = new KeyStoreFactoryBean();
        keyStoreFactory.setType(this.keyStoreType);
        keyStoreFactory.setLocation(new FileSystemResource(this.keyStoreLocation + "/" + keystore + ".pfx"));
        keyStoreFactory.setPassword(this.keyStorePassword);
        keyStoreFactory.afterPropertiesSet();

        final KeyStore keyStore = keyStoreFactory.getObject();
        if (keyStore == null || keyStore.size() == 0) {
            throw new KeyStoreException("Key store is empty");
        }

        // Create HTTP sender and associate keystore to it
        final HttpComponentsMessageSender sender = new HttpComponentsMessageSender();
        final HttpClient client = sender.getHttpClient();
        final SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore, this.keyStorePassword,
                this.trustStoreFactory.getObject());

        final Scheme scheme = new Scheme("https", 443, socketFactory);
        client.getConnectionManager().getSchemeRegistry().register(scheme);

        return sender;

    } catch (IOException | GeneralSecurityException e) {
        throw new WebServiceSecurityException("An exception occured while creating a secured connection.", e);
    }

}

From source file:com.gzj.tulip.load.ResourceRef.java

public Resource getInnerResource(String subPath) throws IOException {
    Assert.isTrue(!subPath.startsWith("/"));
    String rootPath = resource.getURI().getPath();
    if (getProtocol().equals("jar")) {
        return new UrlResource("jar:file:" + rootPath + "!/" + subPath);
    } else {/* ww w  .jav a  2  s.c  om*/
        return new FileSystemResource(rootPath + subPath); // FileSystemResource?file:
    }
}

From source file:de.langmi.spring.batch.examples.readers.file.archive.ArchiveMultiResourceItemReaderTest.java

/**
 * Test with tar file which contains 2 text files, with 20 lines each.
 * /*from  w  w  w  .  j  a  v a 2s . c  om*/
 * @throws Exception 
 */
@Test
public void testOneTarFile() throws Exception {
    LOG.debug("testOneTarFile");
    ArchiveMultiResourceItemReader<String> mReader = new ArchiveMultiResourceItemReader<String>();
    // setup multResourceReader
    mReader.setArchives(
            new Resource[] { new FileSystemResource("src/test/resources/input/file/archive/input.tar") });

    // call general setup last
    generalMultiResourceReaderSetup(mReader);

    // open with mock context
    mReader.open(MetaDataInstanceFactory.createStepExecution().getExecutionContext());

    // read
    try {
        String item = null;
        int count = 0;
        do {
            item = mReader.read();
            if (item != null) {
                count++;
            }
        } while (item != null);
        assertEquals(40, count);
    } catch (Exception e) {
        throw e;
    } finally {
        mReader.close();
    }
}

From source file:org.mitre.jose.TestJWKSetKeyStore.java

@Test
public void ksEmptyConstructorkLoc() {

    JWKSetKeyStore ks = new JWKSetKeyStore();

    File file = new File(ks_file);

    Resource loc = new FileSystemResource(file);
    assertTrue(loc.exists());//from   www .  ja  v  a  2 s. c  o  m
    assertTrue(loc.isReadable());

    ks.setLocation(loc);

    assertEquals(loc.getFilename(), ks.getLocation().getFilename());
}

From source file:com.glaf.core.entity.mybatis.MyBatisSessionFactory.java

protected static void reloadSessionFactory() {
    long start = System.currentTimeMillis();
    Set<String> mappers = new HashSet<String>();
    Configuration configuration = new Configuration();
    String path = SystemProperties.getConfigRootPath() + "/conf/mapper";
    try {/*from  w  ww .  j a  v  a  2s.  c  o m*/
        Map<String, byte[]> dataMap = getLibMappers();
        for (int i = 0; i < dataMap.size(); i++) {
            Set<Entry<String, byte[]>> entrySet = dataMap.entrySet();
            for (Entry<String, byte[]> entry : entrySet) {
                String key = entry.getKey();
                if (key.indexOf("/") != -1) {
                    key = key.substring(key.lastIndexOf("/"), key.length());
                }
                byte[] bytes = entry.getValue();
                String filename = path + "/" + key;
                try {
                    FileUtils.save(filename, bytes);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        List<String> list = getClassPathMappers();
        for (int i = 0; i < list.size(); i++) {
            Resource mapperLocation = new FileSystemResource(list.get(i));
            try {
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
                        configuration, mapperLocation.toString(), configuration.getSqlFragments());
                xmlMapperBuilder.parse();
                mappers.add(mapperLocation.getFilename());
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", ex);
            } finally {
                ErrorContext.instance().reset();
            }
        }

        File dir = new File(path);
        if (dir.exists() && dir.isDirectory()) {
            File contents[] = dir.listFiles();
            if (contents != null) {
                for (int i = 0; i < contents.length; i++) {
                    if (contents[i].isFile() && contents[i].getName().endsWith("Mapper.xml")) {
                        if (mappers.contains(contents[i].getName())) {
                            continue;
                        }
                        Resource mapperLocation = new FileSystemResource(contents[i]);
                        try {
                            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(
                                    mapperLocation.getInputStream(), configuration, mapperLocation.toString(),
                                    configuration.getSqlFragments());
                            xmlMapperBuilder.parse();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            throw new NestedIOException(
                                    "Failed to parse mapping resource: '" + mapperLocation + "'", ex);
                        } finally {
                            ErrorContext.instance().reset();
                        }
                    }
                }
            }
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    long time = System.currentTimeMillis() - start;
    System.out.println("SessionFactory" + (time));
}