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.apache.servicemix.platform.testing.support.AbstractIntegrationTest.java

protected Resource locateBundle(String bundleId) {
    Assert.hasText(bundleId, "bundleId should not be empty");

    // parse the String
    String[] artifactId = StringUtils.commaDelimitedListToStringArray(bundleId);

    Assert.isTrue(artifactId.length >= 3, "the CSV string " + bundleId + " contains too few values");
    // TODO: add a smarter mechanism which can handle 1 or 2 values CSVs
    for (int i = 0; i < artifactId.length; i++) {
        artifactId[i] = StringUtils.trimWhitespace(artifactId[i]);
    }//from  ww w . jav  a2  s  . c  om

    File f;
    if (artifactId.length == 3) {
        f = localMavenBundle(artifactId[0], artifactId[1], artifactId[2], null,
                ArtifactLocator.DEFAULT_ARTIFACT_TYPE);
    } else {
        f = localMavenBundle(artifactId[0], artifactId[1], artifactId[2], null, artifactId[3]);
    }
    return new FileSystemResource(f);
}

From source file:org.solmix.runtime.support.spring.ContainerApplicationContext.java

/**
 * @param cfgFile//  w  w  w. j ava 2  s . c o  m
 * @return
 */
public static Resource findResource(final String cfgFile) {
    try {
        return AccessController.doPrivileged(new PrivilegedAction<Resource>() {

            @Override
            public Resource run() {
                Resource cpr = new ClassPathResource(cfgFile);
                if (cpr.exists()) {
                    return cpr;
                }
                try {
                    // see if it's a URL
                    URL url = new URL(cfgFile);
                    cpr = new UrlResource(url);
                    if (cpr.exists()) {
                        return cpr;
                    }
                } catch (MalformedURLException e) {
                    // ignore
                }
                // try loading it our way
                URL url = ClassLoaderUtils.getResource(cfgFile, ContainerApplicationContext.class);
                if (url != null) {
                    cpr = new UrlResource(url);
                    if (cpr.exists()) {
                        return cpr;
                    }
                }
                cpr = new FileSystemResource(cfgFile);
                if (cpr.exists()) {
                    return cpr;
                }
                return null;
            }
        });
    } catch (AccessControlException ex) {
        // cannot read the user config file
        return null;
    }
}

From source file:de.thm.arsnova.config.SecurityConfig.java

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    final PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setLocations(new Resource[] { new ClassPathResource("arsnova.properties.example"),
            new FileSystemResource("file:///etc/arsnova/arsnova.properties"), });
    configurer.setIgnoreResourceNotFound(true);
    configurer.setIgnoreUnresolvablePlaceholders(false);

    return configurer;
}

From source file:edu.harvard.i2b2.pm.util.PMUtil.java

/**
 * Load application property file into memory
 *//*from ww  w  . j a v a 2s  .c om*/
private String getPropertyValue(String propertyName) throws I2B2Exception {
    if (appProperties == null) {
        //read application directory property file
        Properties loadProperties = ServiceLocator.getProperties(APPLICATION_DIRECTORY_PROPERTIES_FILENAME);

        //read application directory property
        String appDir = loadProperties.getProperty(APPLICATIONDIR_PROPERTIES);

        if (appDir == null) {
            throw new I2B2Exception("Could not find " + APPLICATIONDIR_PROPERTIES + "from "
                    + APPLICATION_DIRECTORY_PROPERTIES_FILENAME);
        }

        String appPropertyFile = appDir + "/" + APPLICATION_PROPERTIES_FILENAME;

        try {
            FileSystemResource fileSystemResource = new FileSystemResource(appPropertyFile);
            PropertiesFactoryBean pfb = new PropertiesFactoryBean();
            pfb.setLocation(fileSystemResource);
            pfb.afterPropertiesSet();
            appProperties = (Properties) pfb.getObject();
        } catch (IOException e) {
            throw new I2B2Exception("Application property file(" + appPropertyFile
                    + ") missing entries or not loaded properly");
        }

        if (appProperties == null) {
            throw new I2B2Exception("Application property file(" + appPropertyFile
                    + ") missing entries or not loaded properly");
        }
    }

    String propertyValue = appProperties.getProperty(propertyName);

    if ((propertyValue != null) && (propertyValue.trim().length() > 0)) {
        ;
    } else {
        throw new I2B2Exception("Application property file(" + APPLICATION_PROPERTIES_FILENAME + ") missing "
                + propertyName + " entry");
    }

    return propertyValue;
}

From source file:net.sourceforge.vulcan.spring.SpringFileStore.java

Resource getConfigurationResource() throws StoreException {
    final File config = getConfigFile();
    final Resource configResource;

    if (config.exists()) {
        configResource = new FileSystemResource(config);
    } else {/*  w ww .j a v  a2 s.co m*/
        eventHandler.reportEvent(new WarningEvent(this, "FileStore.default.config"));
        configResource = new UrlResource(getClass().getResource("default-config.xml"));
    }

    if (!configResource.exists()) {
        throw new StoreException("Resource " + configResource + " does not exist", null);
    }
    return configResource;
}

From source file:com.temenos.interaction.loader.properties.ReloadablePropertiesFactoryBean.java

private List<Resource> getLastChangeAndClear(File f) {
    File lastChangeFileLock = new File(f.getParent(), ".lastChangeLock");
    List<Resource> ret = new ArrayList<>();
    /*/*from ww w.  j  a v  a2 s .com*/
     * Maintain a specific lock to avoid partial file locking.
     */
    try (FileChannel fcLock = new RandomAccessFile(lastChangeFileLock, "rw").getChannel()) {

        try (FileLock lock = fcLock.lock()) {

            try (FileChannel fc = new RandomAccessFile(f, "rws").getChannel()) {

                try (BufferedReader bufR = new BufferedReader(new FileReader(f))) {
                    String sLine = null;
                    boolean bFirst = true;
                    while ((sLine = bufR.readLine()) != null) {
                        if (bFirst) {
                            if (sLine.startsWith("RefreshAll")) {
                                ret = null;
                                break;
                            }
                            bFirst = false;
                        }
                        Resource toAdd = new FileSystemResource(new File(sLine));
                        if (!ret.contains(toAdd)) {
                            ret.add(toAdd);
                        }
                    }
                    /*
                     * Empty the file
                     */
                    fc.truncate(0);
                }
            }
        }
    } catch (Exception e) {
        logger.error("Failed to get the lastChanges contents.", e);
    }

    return ret;
}

From source file:org.jellycastle.maven.Maven.java

/**
 * Gets the Maven POM file resource.// w ww.ja va 2s. c  o m
 * @return
 */
private Resource getPomFile() {
    if (StringUtils.hasText(workingDirectory)) {
        return new FileSystemResource(workingDirectory + "/pom.xml");
    } else {
        return new FileSystemResource("pom.xml");
    }
}

From source file:cn.org.once.cstack.cli.utils.FileUtils.java

public String uploadFile(File path) {
    checkConnectedAndInFileExplorer();//from  w  ww.  j  a  va2  s. c  o m

    File file = path;
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        fileInputStream.available();
        fileInputStream.close();
        FileSystemResource resource = new FileSystemResource(file);
        Map<String, Object> params = new HashMap<>();
        params.put("file", resource);
        params.putAll(authentificationUtils.getMap());
        restUtils.sendPostForUpload(authentificationUtils.finalHost + "/file/container/" + currentContainerId
                + "/application/" + applicationUtils.getCurrentApplication().getName() + "?path=" + currentPath,
                params);
    } catch (IOException e) {
        log.log(Level.SEVERE, "File not found! Check the path file");
        statusCommand.setExitStatut(1);
    }
    return "File uploaded";
}

From source file:com.sinosoft.one.mvc.scanning.MvcScanner.java

/**
 * ????(WEB-INF/classestarget/classes?)/*from  ww  w.j ava  2  s. c o m*/
 * 
 * @return
 * @throws IOException
 * @throws URISyntaxException
 */
public List<ResourceRef> getClassesFolderResources() throws IOException {
    if (classesFolderResources == null) {
        if (logger.isInfoEnabled()) {
            logger.info("[classesFolder] start to found available classes folders ...");
        }
        List<ResourceRef> classesFolderResources = new ArrayList<ResourceRef>();
        Enumeration<URL> founds = resourcePatternResolver.getClassLoader().getResources("");
        while (founds.hasMoreElements()) {
            URL urlObject = founds.nextElement();
            if (!"file".equals(urlObject.getProtocol())) {
                if (logger.isDebugEnabled()) {
                    logger.debug("[classesFolder] Ignored classes folder because " + "not a file protocol url: "
                            + urlObject);
                }
                continue;
            }
            String path = urlObject.getPath();
            Assert.isTrue(path.endsWith("/"));
            if (!path.endsWith("/classes/") && !path.endsWith("/test-classes/") && !path.endsWith("/bin/")) {
                if (logger.isInfoEnabled()) {
                    logger.info("[classesFolder] Ignored classes folder because "
                            + "not ends with '/classes/' or '/bin/': " + urlObject);
                }
                continue;
            }
            File file;
            try {
                file = new File(urlObject.toURI());
            } catch (URISyntaxException e) {
                throw new IOException(e.getLocalizedMessage());
            }
            if (file.isFile()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("[classesFolder] Ignored because not a directory: " + urlObject);
                }
                continue;
            }
            Resource resource = new FileSystemResource(file);
            ResourceRef resourceRef = ResourceRef.toResourceRef(resource);
            if (classesFolderResources.contains(resourceRef)) {
                // ???
                if (logger.isDebugEnabled()) {
                    logger.debug("[classesFolder] remove replicated classes folder: " + resourceRef);
                }
            } else {
                classesFolderResources.add(resourceRef);
                if (logger.isDebugEnabled()) {
                    logger.debug("[classesFolder] add classes folder: " + resourceRef);
                }
            }
        }
        // ?????
        Collections.sort(classesFolderResources);
        List<ResourceRef> toRemove = new LinkedList<ResourceRef>();
        for (int i = 0; i < classesFolderResources.size(); i++) {
            ResourceRef ref = classesFolderResources.get(i);
            String refURI = ref.getResource().getURI().toString();
            for (int j = i + 1; j < classesFolderResources.size(); j++) {
                ResourceRef refj = classesFolderResources.get(j);
                String refjURI = refj.getResource().getURI().toString();
                if (refURI.startsWith(refjURI)) {
                    toRemove.add(refj);
                    if (logger.isInfoEnabled()) {
                        logger.info("[classesFolder] remove wrapper classes folder: " //
                                + refj);
                    }
                } else if (refjURI.startsWith(refURI) && refURI.length() != refjURI.length()) {
                    toRemove.add(ref);
                    if (logger.isInfoEnabled()) {
                        logger.info("[classesFolder] remove wrapper classes folder: " //
                                + ref);
                    }
                }
            }
        }
        classesFolderResources.removeAll(toRemove);
        //
        this.classesFolderResources = new ArrayList<ResourceRef>(classesFolderResources);
        if (logger.isInfoEnabled()) {
            logger.info("[classesFolder] found " + classesFolderResources.size() + " classes folders: "
                    + classesFolderResources);
        }
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("[classesFolder] found cached " + classesFolderResources.size() + " classes folders: "
                    + classesFolderResources);
        }
    }
    return Collections.unmodifiableList(classesFolderResources);
}

From source file:com.rxx.common.util.MailUtil.java

/**
 * html//w w  w .j  a va2s . c o  m
 *
 * @param host 
 * @param port
 * @param userName
 * @param password
 * @param title
 * @param contenthtml
 * @param fileslist<Map<key:,value:>>
 * @param toUser
 * @throws javax.mail.MessagingException
 */
public static void sendAttached(String host, int port, String userName, String password, String title,
        String content, List<Map<String, String>> files, String[] toUser)
        throws MessagingException, javax.mail.MessagingException {
    JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

    // mail server
    senderImpl.setHost(host);
    // ,html
    MimeMessage mailMessage = senderImpl.createMimeMessage();
    // boolean,MimeMessageHelpertrue
    // multipart true html
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

    // 
    messageHelper.setTo(toUser);
    messageHelper.setFrom(userName);
    messageHelper.setSubject(title);
    // true HTML
    messageHelper.setText(content, true);

    for (Map<String, String> filePath : files) {
        Iterator<String> it = filePath.keySet().iterator();
        String fileName = it.next();
        FileSystemResource file = new FileSystemResource(new File(filePath.get(fileName)));
        // 
        messageHelper.addAttachment(fileName, file);
    }

    senderImpl.setUsername(userName); // ,username
    senderImpl.setPassword(password); // , password
    Properties prop = new Properties();
    prop.put("mail.smtp.auth", "true"); // true,
    prop.put("mail.smtp.timeout", "25000");
    senderImpl.setJavaMailProperties(prop);
    // 
    senderImpl.send(mailMessage);
}