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

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

Introduction

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

Prototype

@Override
public File getFile() 

Source Link

Document

This implementation returns the underlying File reference.

Usage

From source file:org.dd4t.core.util.IOUtils.java

public static String convertFileToString(String filePath) {
    FileSystemResource resource = new FileSystemResource(filePath);
    File file = resource.getFile();
    byte[] buffer = new byte[(int) file.length()];
    try {//from  w ww .  j a  v  a  2s  . com
        resource.getInputStream().read(buffer);
        resource.getInputStream().close();
        return new String(buffer);
    } catch (IOException e) {
        return null;
    }
}

From source file:com.wavemaker.tools.project.LauncherHelper.java

public static String getNewDefaultWMHome() throws IOException {
    FileSystemResource oldDefault = (FileSystemResource) LocalStudioConfiguration.getDefaultWaveMakerHome();
    return oldDefault.getFile().getAbsolutePath() + " " + getCurrentVersionString();
}

From source file:com.glaf.activiti.util.ProcessUtils.java

public static byte[] getImage(String processDefinitionId) {
    byte[] bytes = null;
    ProcessDefinition processDefinition = cache.get(processDefinitionId);
    if (processDefinition == null) {
        ActivitiProcessQueryService activitiProcessQueryService = ContextFactory
                .getBean("activitiProcessQueryService");
        processDefinition = activitiProcessQueryService.getProcessDefinition(processDefinitionId);
    }/*from  w  w w  . j  a  va2  s  .c om*/

    if (processDefinition != null) {
        String resourceName = processDefinition.getDiagramResourceName();
        if (resourceName != null) {
            String filename = ApplicationContext.getAppPath() + "/deploy/bpmn/"
                    + getImagePath(processDefinition);
            FileSystemResource fs = new FileSystemResource(filename);
            if (!fs.exists()) {
                try {
                    ActivitiDeployQueryService activitiDeployQueryService = ContextFactory
                            .getBean("activitiDeployQueryService");
                    InputStream inputStream = activitiDeployQueryService
                            .getResourceAsStream(processDefinition.getDeploymentId(), resourceName);
                    logger.debug("save:" + filename);
                    FileUtils.save(filename, inputStream);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            return FileUtils.getBytes(fs.getFile());
        }
    }

    return bytes;
}

From source file:ca.airspeed.demo.testingemail.EmailService.java

public void sendWithAttachments(InternetAddress to, String subject, String textBody,
        List<FileSystemResource> fileList) throws MessagingException {
    notNull(mailSender, String.format("Check your configuration, I need an instance of %s.",
            JavaMailSender.class.getCanonicalName()));
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(to);//from www .j a  va  2 s . c  om
    helper.setFrom(senderAddress);
    helper.setSubject(subject);
    helper.setText(textBody);
    for (FileSystemResource resource : fileList) {
        helper.addAttachment(resource.getFilename(), resource.getFile());
    }
    mailSender.send(message);
}

From source file:cz.zcu.kiv.eeg.mobile.base.ui.scenario.ScenarioAddActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    //obtaining file selected in FileChooserActivity
    case (Values.SELECT_FILE_FLAG): {
        if (resultCode == Activity.RESULT_OK) {
            selectedFile = data.getExtras().getString(Values.FILE_PATH);
            selectedFileLength = data.getExtras().getLong(Values.FILE_LENGTH);
            TextView selectedFileView = (TextView) findViewById(R.id.fchooserSelectedFile);
            EditText mimeView = (EditText) findViewById(R.id.scenario_mime_value);
            TextView fileSizeView = (TextView) findViewById(R.id.scenario_file_size_value);

            FileSystemResource file = new FileSystemResource(selectedFile);
            selectedFileView.setText(file.getFilename());
            mimeView.setText(FileUtils.getMimeType(selectedFile));

            String fileSize = FileUtils.getFileSize(file.getFile().length());
            fileSizeView.setText(fileSize);
            Toast.makeText(this, selectedFile, Toast.LENGTH_SHORT).show();
        }//from ww  w  .jav  a2 s. co m
        break;
    }
    }
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public boolean deleteFile(Resource resource) {
    Assert.isInstanceOf(FileSystemResource.class, resource, "Expected a FileSystemResource");
    FileSystemResource fileResource = (FileSystemResource) resource;
    if (fileResource.getFile().isDirectory()) {
        try {/*from   ww w  . ja  v a  2s .c  o m*/
            FileUtils.forceDelete(fileResource.getFile());
            return true;
        } catch (IOException ex) {
            throw new WMRuntimeException(ex);
        }
    } else {
        return fileResource.getFile().delete();
    }

}

From source file:org.broadleafcommerce.admin.util.controllers.FileUploadController.java

private void backupExistingFile(FileSystemResource fileResource, String basepath) {
    if (fileResource.exists()) {
        String originalFilename = fileResource.getFilename();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        int dotIndex = originalFilename.lastIndexOf(".");
        String extension = originalFilename.substring(dotIndex, originalFilename.length());
        String filename = originalFilename.substring(0, dotIndex);
        String dateString = dateFormat.format(new Date());
        String backupFilename = filename + dateString + extension;
        fileResource.getFile().renameTo(new File(basepath + File.separator + backupFilename));
    }//ww w  .  j  a v a  2s. co  m
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public Resource createPath(Resource resource, String path) {
    Assert.isInstanceOf(FileSystemResource.class, resource, "Expected a FileSystemResource");
    try {/*from  w w  w  .  j  av  a2  s .  c  o m*/
        if (!resource.exists()) {
            File rootFile = resource.getFile();
            while (rootFile.getAbsolutePath().length() > 1 && !rootFile.exists()) {
                rootFile = rootFile.getParentFile();
            }
            IOUtils.makeDirectories(resource.getFile(), rootFile);
        }
        FileSystemResource relativeResource = (FileSystemResource) resource.createRelative(path);
        if (!relativeResource.exists()) {
            if (relativeResource.getPath().endsWith("/")) {
                IOUtils.makeDirectories(relativeResource.getFile(), resource.getFile());
            } else {
                IOUtils.makeDirectories(relativeResource.getFile().getParentFile(), resource.getFile());
            }
        }
        return relativeResource;
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }
}

From source file:com.apdplat.platform.compass.APDPlatLocalCompassBean.java

public void afterPropertiesSet() throws Exception {
    CompassConfiguration config = this.config;
    if (config == null) {
        config = newConfiguration();//from w ww.  jav  a 2  s.  co m
    }

    if (classLoader != null) {
        config.setClassLoader(getClassLoader());
    }

    if (this.configLocation != null) {
        config.configure(this.configLocation.getURL());
    }

    if (this.configLocations != null) {
        for (Resource configLocation1 : configLocations) {
            config.configure(configLocation1.getURL());
        }
    }

    if (this.mappingScan != null) {
        config.addScan(this.mappingScan);
    }

    if (this.compassSettings != null) {
        config.getSettings().addSettings(this.compassSettings);
    }

    if (this.settings != null) {
        config.getSettings().addSettings(this.settings);
    }

    if (resourceLocations != null) {
        for (Resource resourceLocation : resourceLocations) {
            config.addInputStream(resourceLocation.getInputStream(), resourceLocation.getFilename());
        }
    }

    if (resourceJarLocations != null && !"".equals(resourceJarLocations.trim())) {
        log.info("apdplatcompass2");
        log.info("compass resourceJarLocations:" + resourceJarLocations);
        String[] jars = resourceJarLocations.split(",");
        for (String jar : jars) {
            try {
                FileSystemResource resource = new FileSystemResource(FileUtils.getAbsolutePath(jar));
                config.addJar(resource.getFile());
                log.info("compass resourceJarLocations  find:" + jar);
            } catch (Exception e) {
                log.info("compass resourceJarLocations not exists:" + jar);
            }
        }
    }

    if (classMappings != null) {
        for (String classMapping : classMappings) {
            config.addClass(ClassUtils.forName(classMapping, getClassLoader()));
        }
    }

    if (resourceDirectoryLocations != null && !"".equals(resourceDirectoryLocations.trim())) {
        log.info("apdplatcompass3");
        log.info("compass resourceDirectoryLocations:" + resourceDirectoryLocations);
        String[] dirs = resourceDirectoryLocations.split(",");
        for (String dir : dirs) {
            ClassPathResource resource = new ClassPathResource(dir);
            try {
                File file = resource.getFile();
                if (!file.isDirectory()) {
                    log.info("Resource directory location [" + dir + "] does not denote a directory");
                } else {
                    config.addDirectory(file);
                }
                log.info("compass resourceDirectoryLocations find:" + dir);
            } catch (Exception e) {
                log.info("compass resourceDirectoryLocations not exists:" + dir);
            }
        }
    }

    if (mappingResolvers != null) {
        for (InputStreamMappingResolver mappingResolver : mappingResolvers) {
            config.addMappingResover(mappingResolver);
        }
    }

    if (dataSource != null) {
        ExternalDataSourceProvider.setDataSource(dataSource);
        if (config.getSettings().getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS) == null) {
            config.getSettings().setSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.CLASS,
                    ExternalDataSourceProvider.class.getName());
        }
    }

    String compassTransactionFactory = config.getSettings().getSetting(CompassEnvironment.Transaction.FACTORY);
    if (compassTransactionFactory == null && transactionManager != null) {
        // if the transaciton manager is set and a transcation factory is not set, default to the SpringSync one.
        config.getSettings().setSetting(CompassEnvironment.Transaction.FACTORY,
                SpringSyncTransactionFactory.class.getName());
    }
    if (compassTransactionFactory != null
            && compassTransactionFactory.equals(SpringSyncTransactionFactory.class.getName())) {
        if (transactionManager == null) {
            throw new IllegalArgumentException(
                    "When using SpringSyncTransactionFactory the transactionManager property must be set");
        }
    }
    SpringSyncTransactionFactory.setTransactionManager(transactionManager);

    if (convertersByName != null) {
        for (Map.Entry<String, Converter> entry : convertersByName.entrySet()) {
            config.registerConverter(entry.getKey(), entry.getValue());
        }
    }
    if (config.getSettings().getSetting(CompassEnvironment.NAME) == null) {
        config.getSettings().setSetting(CompassEnvironment.NAME, beanName);
    }

    if (config.getSettings().getSetting(CompassEnvironment.CONNECTION) == null && connection != null) {
        config.getSettings().setSetting(CompassEnvironment.CONNECTION, connection.getFile().getAbsolutePath());
    }

    if (applicationContext != null) {
        String[] names = applicationContext.getBeanNamesForType(PropertyPlaceholderConfigurer.class);
        for (String name : names) {
            try {
                PropertyPlaceholderConfigurer propConfigurer = (PropertyPlaceholderConfigurer) applicationContext
                        .getBean(name);
                Method method = findMethod(propConfigurer.getClass(), "mergeProperties");
                method.setAccessible(true);
                Properties props = (Properties) method.invoke(propConfigurer);
                method = findMethod(propConfigurer.getClass(), "convertProperties", Properties.class);
                method.setAccessible(true);
                method.invoke(propConfigurer, props);
                method = findMethod(propConfigurer.getClass(), "parseStringValue", String.class,
                        Properties.class, Set.class);
                method.setAccessible(true);
                String nullValue = null;
                try {
                    Field field = propConfigurer.getClass().getDeclaredField("nullValue");
                    field.setAccessible(true);
                    nullValue = (String) field.get(propConfigurer);
                } catch (NoSuchFieldException e) {
                    // no field (old spring version)
                }
                for (Map.Entry entry : config.getSettings().getProperties().entrySet()) {
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    value = (String) method.invoke(propConfigurer, value, props, new HashSet());
                    config.getSettings().setSetting(key, value.equals(nullValue) ? null : value);
                }
            } catch (Exception e) {
                log.debug("Failed to apply property placeholder defined in bean [" + name + "]", e);
            }
        }
    }

    if (postProcessor != null) {
        postProcessor.process(config);
    }
    this.compass = newCompass(config);
    this.compass = (Compass) Proxy.newProxyInstance(SpringCompassInvocationHandler.class.getClassLoader(),
            new Class[] { InternalCompass.class }, new SpringCompassInvocationHandler(this.compass));
}

From source file:org.emonocot.harvest.common.MultiResourceDeletingTasklet.java

/**
 * @param contribution Set the step contribution
 * @param chunkContext Set the chunk context
 * @return the repeat status/*from  w w w  .j a  v a2  s .  c  o m*/
 * @throws Exception if there is a problem deleting the resources
 */
public final RepeatStatus execute(final StepContribution contribution, final ChunkContext chunkContext)
        throws Exception {
    for (Resource lResource : resources) {
        FileSystemResource lFileSystemResource = new FileSystemResource(lResource.getFile().getAbsolutePath());
        if (!lFileSystemResource.exists()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Resource " + lFileSystemResource.getDescription()
                        + " does not exist. The resource is ignored");
            }
        } else {
            File lFile = lFileSystemResource.getFile();
            if (lFile.isDirectory()) {
                // supprime le rpertoire et son contenu
                FileUtils.deleteDirectory(lFile);
            } else {
                if (!lFile.delete()) {
                    throw new IOException("The file " + lFile + " cannot be deleted.");
                }
            }
        }
    }
    return RepeatStatus.FINISHED;
}