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.glaf.template.service.MxTemplateServiceImpl.java

@Transactional
public void installAllTemplates() {
    Map<String, Template> templateMap = this.getAllTemplate();
    TemplateReader reader = new TemplateReader();
    try {//from w ww  . j av a 2 s. co  m
        String configPath = SystemProperties.getConfigRootPath() + CONFIG_PATH;
        File file = new File(configPath);
        if (!file.exists() || !file.isDirectory()) {
            return;
        }
        String[] filelist = file.list();
        if (filelist != null) {
            for (int i = 0, len = filelist.length; i < len; i++) {
                String name = filelist[i];
                if (!name.toLowerCase().endsWith(".xml")) {
                    continue;
                }
                String filename = configPath + name;
                Resource resource = new FileSystemResource(filename);
                Map<String, Template> templates = reader.getTemplates(resource.getInputStream());
                Set<Entry<String, Template>> entrySet = templates.entrySet();
                for (Entry<String, Template> entry : entrySet) {
                    Template template = entry.getValue();
                    if (template.getData() == null || template.getFileSize() < 0) {
                        continue;
                    }
                    if (templateMap.get(template.getTemplateId()) != null) {
                        Template model = templateMap.get(template.getTemplateId());
                        if (template.getLastModified() > model.getLastModified()) {
                            logger.debug("reload template config:" + filename);
                            BlobItem blob = new BlobItemEntity();
                            blob.setData(template.getData());
                            blob.setFileId(template.getTemplateId());
                            blob.setBusinessKey(template.getTemplateId());
                            blob.setLastModified(template.getLastModified());
                            blob.setFilename(FileUtils.getFileName(template.getDataFile()));
                            blob.setStatus(1);
                            model.setLastModified(template.getLastModified());
                            model.setFileSize(template.getFileSize());
                            model.setDataFile(template.getDataFile());
                            model.setName(template.getName());
                            model.setTitle(template.getTitle());
                            model.setDescription(template.getDescription());
                            model.setLocked(template.getLocked());

                            templateMapper.updateTemplate(model);
                            blobService.insertBlob(blob);
                            String cacheKey = "x_tpl_" + model.getTemplateId();
                            CacheFactory.remove(cacheKey);
                        }
                    } else {
                        template.setCreateDate(new Date());
                        template.setCreateBy("system");
                        BlobItem blob = new BlobItemEntity();
                        blob.setData(template.getData());
                        blob.setFileId(template.getTemplateId());
                        blob.setBusinessKey(template.getTemplateId());
                        blob.setLastModified(template.getLastModified());
                        blob.setFilename(FileUtils.getFileName(template.getDataFile()));
                        blob.setStatus(1);
                        if (template.getNodeId() == 0 && StringUtils.isNotEmpty(template.getModuleId())) {

                        }
                        if (StringUtils.isEmpty(template.getTemplateId())) {
                            template.setTemplateId(idGenerator.getNextId());
                        }
                        templateMapper.insertTemplate(template);
                        blobService.insertBlob(blob);
                        String cacheKey = "x_tpl_" + template.getTemplateId();
                        CacheFactory.remove(cacheKey);
                    }
                }
            }
        }
    } catch (Exception ex) {
        if (LogUtils.isDebug()) {
            ex.printStackTrace();
            logger.debug(ex);
        }
        throw new RuntimeException(" load templates error:" + ex);
    }
}

From source file:org.springmodules.validation.bean.conf.namespace.XmlBasedValidatorBeanDefinitionParser.java

protected List createResources(Element resourcesDefinition) {
    String dirName = resourcesDefinition.getAttribute(DIR_ATTR);
    final String pattern = resourcesDefinition.getAttribute(PATTERN_ATTR);
    final AntPathMatcher matcher = new AntPathMatcher();
    FileFilter filter = new FileFilter() {
        public boolean accept(File file) {
            return matcher.match(pattern, file.getName());
        }//  www .  j a va  2s.c o m
    };
    List resources = new ArrayList();
    for (Iterator files = new FileIterator(dirName, filter); files.hasNext();) {
        File file = (File) files.next();
        resources.add(new FileSystemResource(file));
    }
    return resources;
}

From source file:com.wavemaker.tools.deployment.cloudfoundry.CloudFoundryDeploymentTarget.java

@Override
public String deploy(Project project, DeploymentInfo deploymentInfo, java.io.File tempWebAppRoot)
        throws DeploymentStatusException {
    ApplicationArchive applicationArchive;
    if (tempWebAppRoot == null) {
        applicationArchive = this.webAppAssembler.assemble(project);
        applicationArchive = modifyApplicationArchive(applicationArchive);
    } else {/* w  w w .  j av a 2s. c o m*/
        //try {
        //    this.webAppAssembler.prepareForAssemble(new LocalFolder(tempWebAppRoot));
        //} catch (IOException ex) {
        //    throw new DeploymentStatusException(ex.getMessage());
        //}
        applicationArchive = this.webAppAssembler.assemble(project.getProjectName(),
                new FileSystemResource(tempWebAppRoot));
    }
    return doDeploy(applicationArchive, deploymentInfo);
}

From source file:org.beanio.spring.SpringTest.java

/**
 * Test BeanIO flat file writer for XML.
 *///from   w w w  .  java 2s  .co  m
@Test
@SuppressWarnings("unchecked")
public void testRestarbleXmlItemWriter() throws Exception {
    ExecutionContext ec = new ExecutionContext();

    File tempFile = File.createTempFile("beanio-", "xml");
    tempFile.deleteOnExit();

    BeanIOFlatFileItemWriter<Human> writer = (BeanIOFlatFileItemWriter<Human>) context
            .getBean("itemWriter-xml");
    writer.setResource(new FileSystemResource(tempFile));
    writer.open(ec);

    List<Human> list = new ArrayList<Human>();
    list.add(new Human(Human.FRIEND, "John", 'M'));
    writer.write(list);
    writer.update(ec);

    long position = ec.getLong("BeanIOFlatFileItemWriter.current.count");
    assertTrue(position > 0);

    list.clear();
    list.add(new Human(Human.COWORKER, "Mike", 'M'));
    list.add(new Human(Human.NEIGHBOR, "Steve", 'M'));
    writer.write(list);
    writer.close();
    assertFileMatches("xout1.xml", tempFile);

    // open for restart
    writer = (BeanIOFlatFileItemWriter<Human>) context.getBean("itemWriter-xml");
    writer.setResource(new FileSystemResource(tempFile));
    writer.open(ec);

    list.clear();
    list.add(new Human(Human.FRIEND, "Jen", 'F'));
    writer.write(list);

    writer.update(ec);
    writer.close();
    assertFileMatches("xout2.xml", tempFile);
}

From source file:com.silverpeas.jcrutil.BetterRepositoryFactoryBean.java

/**
 * @throws Exception/*from  ww w.  j a  v a  2s.co m*/
 * @see org.springmodules.jcr.RepositoryFactoryBean#resolveConfigurationResource()
 */
@Override
protected void resolveConfigurationResource() throws Exception {
    // read the configuration object
    if (repositoryConfig != null) {
        return;
    }

    if (this.configuration == null) {
        log.debug("no configuration resource specified, using the default one:" + DEFAULT_CONF_FILE);
        configuration = new ClassPathResource(DEFAULT_CONF_FILE);
    }

    if (homeDir == null) {
        if (log.isDebugEnabled()) {
            log.debug("no repository home dir specified, using the default one:" + DEFAULT_REP_DIR);
        }
        homeDir = new FileSystemResource(DEFAULT_REP_DIR);
    }
    if (getConfigurationProperties() != null) {
        String goodConfig = replaceVariables(loadConfigurationKeys(), getConfiguration(configuration), true);
        repositoryConfig = RepositoryConfig.create(new InputSource(new StringReader(goodConfig)),
                homeDir.getFile().getAbsolutePath());
    } else {
        repositoryConfig = RepositoryConfig.create(new InputSource(configuration.getInputStream()),
                homeDir.getFile().getAbsolutePath());
    }
}

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 www  .ja  va 2s.  co  m
 * @throws Exception 
 */
@Test
public void testOneGzippedTarFile() throws Exception {
    LOG.debug("testOneGzippedTarFile");
    ArchiveMultiResourceItemReader<String> mReader = new ArchiveMultiResourceItemReader<String>();
    // setup multResourceReader
    mReader.setArchives(new Resource[] {
            new FileSystemResource("src/test/resources/input/file/archive/input_nested_dir.tar.gz") });

    // 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(80, count);
    } catch (Exception e) {
        throw e;
    } finally {
        mReader.close();
    }
}

From source file:fr.acxio.tools.agia.alfresco.AlfrescoNodeContentWriter.java

@Override
public void write(List<? extends NodeList> sData)
        throws RemoteException, NodePathException, VersionOperationException, FileNotFoundException {
    if (!sData.isEmpty()) {
        init();// w  w w.  j a  v a  2  s.  c om
        RepositoryServiceSoapBindingStub aRepositoryService = getAlfrescoService().getRepositoryService();

        for (NodeList aNodeList : sData) {
            for (Node aNode : aNodeList) {
                if (aNode instanceof Document) {
                    Document aDocument = (Document) aNode;
                    if ((aDocument.getContentPath() != null) && (aDocument.getContentPath().length() > 0)) {
                        // If the document has a content path, the file must
                        // exist
                        File aFile = new File(aDocument.getContentPath());
                        if (aFile.exists() && aFile.isFile()) {
                            String aCurrentNodePath = aNode.getPath();
                            String aScheme = null;
                            String aAddress = null;
                            String aUUID = null;

                            if ((aNode.getUuid() != null) && !aNode.getUuid().isEmpty()) {
                                aScheme = aNode.getScheme();
                                aAddress = aNode.getAddress();
                                aUUID = aNode.getUuid();
                            }
                            if (aUUID == null) {
                                org.alfresco.webservice.types.Node[] aMatchingNodes = getRepositoryMatchingNodes(
                                        aRepositoryService, aCurrentNodePath);
                                if ((aMatchingNodes != null) && (aMatchingNodes.length > 0)) {
                                    if (aMatchingNodes.length > 1) {
                                        throw new VersionOperationException("Too many matching nodes");
                                    }
                                    org.alfresco.webservice.types.Node aRepositoryNode = aMatchingNodes[0];
                                    aScheme = aRepositoryNode.getReference().getStore().getScheme();
                                    aAddress = aRepositoryNode.getReference().getStore().getAddress();
                                    aUUID = aRepositoryNode.getReference().getUuid();
                                }
                            }

                            if (aUUID != null) {
                                if (LOGGER.isDebugEnabled()) {
                                    LOGGER.debug("Will upload content");
                                }

                                StringBuilder aURL = new StringBuilder(getAlfrescoService().getWebappAddress());
                                aURL.append(URL_TEMPLATE_UPLOAD);

                                Map<String, String> aURLVariables = new HashMap<String, String>();
                                aURLVariables.put(PARAM_SCHEME, aScheme);
                                aURLVariables.put(PARAM_ADDRESS, aAddress);
                                aURLVariables.put(PARAM_UUID, aUUID);
                                aURLVariables.put(PARAM_NAME, aFile.getName());
                                aURLVariables.put(PARAM_TICKET, getAlfrescoService().getTicket());
                                aURLVariables.put(PARAM_ENCODING, aDocument.getEncoding());
                                aURLVariables.put(PARAM_MIMETYPE, aDocument.getMimeType());

                                HttpHeaders aHeaders = new HttpHeaders();
                                aHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                                aHeaders.setContentLength(aFile.length());
                                HttpEntity<FileSystemResource> aEntity = new HttpEntity<FileSystemResource>(
                                        new FileSystemResource(aFile), aHeaders);
                                getRestTemplate().put(aURL.toString(), aEntity, aURLVariables);

                                if (LOGGER.isDebugEnabled()) {
                                    LOGGER.debug("Content uploaded");
                                }

                            } else {
                                throw new NodePathException("Cannot find the node: " + aNode.getPath());
                            }
                        } else if (failIfFileNotFound) {
                            throw new FileNotFoundException(aDocument.getContentPath());
                        }
                    }
                }
            }
        }

        cleanup();
    }
}

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

@Test
public void testCannotEmptyOrigin() throws Exception {
    FileCopyTasklet aTasklet = new FileCopyTasklet();
    aTasklet.setOrigin(new FileSystemResource("src/test/resources/testFiles/input.csv"));
    aTasklet.setDestination(new FileSystemResource("target/input-copy8.csv"));
    aTasklet.execute(null, null);/*from w ww  . ja va2s .c  o m*/

    File aOrigin = aTasklet.getDestination().getFile();
    assertTrue(aOrigin.exists());
    FileInputStream aInputStream = new FileInputStream(aOrigin);
    FileLock aLock = aInputStream.getChannel().lock(0L, Long.MAX_VALUE, true); // shared lock

    aTasklet.setEmptyOrigin(true);
    aTasklet.setOrigin(new FileSystemResource("target/input-copy8.csv"));
    aTasklet.setDestination(new FileSystemResource("target/input-copy9.csv"));
    try {
        aTasklet.execute(null, null);
        fail("Must throw a FileCopyException");
    } catch (FileCopyException e) {
        // Fallthrough
    } finally {
        aLock.release();
        aInputStream.close();
    }
}

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

protected void zipResource(Resource sSourceResource, ZipArchiveOutputStream sZipArchiveOutputStream,
        StepContribution sContribution, ChunkContext sChunkContext) throws IOException, ZipFilesException {
    // TODO : use a queue to reduce the callstack overhead
    if (sSourceResource.exists()) {
        File aSourceFile = sSourceResource.getFile();
        String aSourcePath = aSourceFile.getCanonicalPath();

        if (!aSourcePath.startsWith(sourceBaseDirectoryPath)) {
            throw new ZipFilesException(
                    "Source file " + aSourcePath + " does not match base directory " + sourceBaseDirectoryPath);
        }//from w w w. j  a va 2  s.  com

        if (sContribution != null) {
            sContribution.incrementReadCount();
        }
        String aZipEntryName = aSourcePath.substring(sourceBaseDirectoryPath.length() + 1);
        sZipArchiveOutputStream.putArchiveEntry(new ZipArchiveEntry(aZipEntryName));
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Zipping {} to {}", sSourceResource.getFile().getCanonicalPath(), aZipEntryName);
        }
        if (aSourceFile.isFile()) {
            InputStream aInputStream = sSourceResource.getInputStream();
            IOUtils.copy(aInputStream, sZipArchiveOutputStream);
            aInputStream.close();
            sZipArchiveOutputStream.closeArchiveEntry();
        } else {
            sZipArchiveOutputStream.closeArchiveEntry();
            for (File aFile : aSourceFile
                    .listFiles((FileFilter) (recursive ? TrueFileFilter.TRUE : FileFileFilter.FILE))) {
                zipResource(new FileSystemResource(aFile), sZipArchiveOutputStream, sContribution,
                        sChunkContext);
            }
        }
        if (sContribution != null) {
            sContribution.incrementWriteCount(1);
        }
    } else if (LOGGER.isInfoEnabled()) {
        LOGGER.info("{} does not exist", sSourceResource.getFilename());
    }
}

From source file:architecture.ee.component.core.lifecycle.RepositoryImpl.java

public void setServletContext(ServletContext servletContext) {

    // 1.  ?? ? ? ?  : ARCHITECTURE_INSTALL_ROOT
    String value = servletContext.getInitParameter(ApplicationConstants.ARCHITECTURE_PROFILE_ROOT_ENV_KEY);
    if (!StringUtils.isEmpty(value)) {
        try {/* w  w  w  .  j  a  va2  s .c  o m*/
            ServletContextResourceLoader servletResoruceLoader = new ServletContextResourceLoader(
                    servletContext);
            Resource resource = servletResoruceLoader.getResource(value);
            if (resource.exists()) {
                log.debug(L10NUtils.format("003003", ApplicationConstants.ARCHITECTURE_PROFILE_ROOT_ENV_KEY,
                        resource.getURI()));
                this.rootResource = resource;
                setState(State.INITIALIZED);
                initailized = true;
            }
        } catch (Throwable e) {
            this.rootResource = null;
        }
    }

    if (!initailized && !StringUtils.isEmpty(value)) {
        Resource obj;
        try {
            obj = resoruceLoader.getResource(value);
            if (obj.exists()) {
                log.debug(L10NUtils.format("003003", ApplicationConstants.ARCHITECTURE_PROFILE_ROOT_ENV_KEY,
                        obj.getURI()));
                this.rootResource = obj;
                setState(State.INITIALIZED);
                initailized = true;

            }
        } catch (Throwable e) {
            log.error(e);
        }
    }

    if (!initailized) {
        try {
            ServletContextResource resource = new ServletContextResource(servletContext, "/WEB-INF");
            File file = resource.getFile();
            if (file.exists()) {
                this.rootResource = new FileSystemResource(file);
                setState(State.INITIALIZED);
                initailized = true;
            }
        } catch (Throwable e) {
            log.error(e);
        }
    }
}