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.gzj.tulip.load.RoseScanner.java

public List<ResourceRef> getJarOrClassesFolderResources(String[] scope) throws IOException {
    if (logger.isInfoEnabled()) {
        logger.info("[findFiles] start to found classes folders " + "or rosed jar files by scope:"
                + Arrays.toString(scope));
    }// www .  j a va2 s.  com
    List<ResourceRef> resources;
    if (scope == null) {
        resources = new LinkedList<ResourceRef>();
        if (logger.isDebugEnabled()) {
            logger.debug("[findFiles] call 'classesFolder'");
        }
        resources.addAll(getClassesFolderResources());
        //
        if (logger.isDebugEnabled()) {
            logger.debug("[findFiles] exits from 'classesFolder'");
            logger.debug("[findFiles] call 'jarFile'");
        }
        resources.addAll(getJarResources());
        if (logger.isDebugEnabled()) {
            logger.debug("[findFiles] exits from 'jarFile'");
        }
    } else if (scope.length == 0) {
        return new ArrayList<ResourceRef>();
    } else {
        resources = new LinkedList<ResourceRef>();
        for (String scopeEntry : scope) {
            String packagePath = scopeEntry.replace('.', '/');
            Resource[] packageResources = resourcePatternResolver.getResources("classpath*:" + packagePath);
            for (Resource pkgResource : packageResources) {
                String uri = pkgResource.getURI().toString();
                uri = StringUtils.removeEnd(uri, "/");
                packagePath = StringUtils.removeEnd(packagePath, "/");
                uri = StringUtils.removeEnd(uri, packagePath);
                int beginIndex = uri.lastIndexOf("file:");
                if (beginIndex == -1) {
                    beginIndex = 0;
                } else {
                    beginIndex += "file:".length();
                }
                int endIndex = uri.lastIndexOf('!');
                if (endIndex == -1) {
                    endIndex = uri.length();
                }
                String path = uri.substring(beginIndex, endIndex);
                Resource folder = new FileSystemResource(path);
                ResourceRef ref = ResourceRef.toResourceRef(folder);
                if (!resources.contains(ref)) {
                    resources.add(ref);
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "[findFiles] found classes folders " + "or rosed jar files by scope:" + ref);
                    }
                }
            }
        }
    }
    //
    if (logger.isInfoEnabled()) {
        logger.info("[findFiles] found " + resources.size() + " classes folders " + "or rosed jar files : "
                + resources);
    }

    return resources;
}

From source file:com.siberhus.tdfl.DflSimpleTest.java

@Test
public void testStopLoader() throws DataFileLoaderException {
    BreakDfp dfp = new BreakDfp();
    employeeDfl.setDataFileProcessor(dfp);
    employeeDfl.setResource(new FileSystemResource(XLS_FILE_IN_NAME));
    employeeDfl.load();//ww w .j av  a 2s . c o m
    Assert.assertEquals(5, dfp.processItemCount);
    Assert.assertTrue(dfp.onFinishExecuted);
}

From source file:coral.reef.web.ReefController.java

@RequestMapping(value = "/assets/**")
public void icon(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {

    String path = ((String) httpRequest.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));

    Resource res = appContext.getResource("classpath:" + path);

    File f = res.getFile();//  www .j av  a 2  s .co m
    FileSystemResource fr = new FileSystemResource(f);
    String type = servletContext.getMimeType(f.getAbsolutePath());
    httpResponse.setContentType(type);

    IOUtils.copy(fr.getInputStream(), httpResponse.getOutputStream());
}

From source file:edu.harvard.i2b2.fr.util.FRUtil.java

/**
 * Load application property file into memory
 *//*from  w  w  w  .  ja va  2s  . c  om*/
private String getPropertyValue(String propertyName) throws I2B2Exception {
    if (appProperties == null) {
        //read application directory property file
        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:fr.acxio.tools.agia.tasks.FileCopyTaskletTest.java

@Test
public void testCannotDeleteOrigin() throws Exception {
    FileCopyTasklet aTasklet = new FileCopyTasklet();
    aTasklet.setOrigin(new FileSystemResource("src/test/resources/testFiles/input.csv"));
    aTasklet.setDestination(new FileSystemResource("target/input-copy4.csv"));
    aTasklet.execute(null, null);/*from  w w  w  .  java 2s. co 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.setDeleteOrigin(true);
    aTasklet.setOrigin(new FileSystemResource("target/input-copy4.csv"));
    aTasklet.setDestination(new FileSystemResource("target/input-copy5.csv"));
    try {
        aTasklet.execute(null, null);
        fail("Must throw a FileCopyException");
    } catch (FileCopyException e) {
        // Fallthrough
    } finally {
        aLock.release();
        aInputStream.close();
    }
}

From source file:com.qpark.eip.core.spring.security.https.HttpsRequester.java

@PostConstruct
public void init() throws Exception {
    if (this.trustManager == null) {
        // HTTP AUTH
        if (this.httpAuthUser != null && this.httpAuthUser.length() > 0) {
            this.httpAuthBase64 = new String(Base64.encode(new StringBuffer(256).append(this.httpAuthUser)
                    .append(":").append(this.httpAuthPwd == null ? "" : this.httpAuthPwd).toString()
                    .getBytes("UTF-8")), "UTF-8");
        }//from   w  w  w  .ja  v a2s.com
        // Keystore handler trust manager
        Resource keystore = null;
        if (this.keystoreSource == null) {
            Assert.isNull(this.keystoreSource);
        } else {
            if (this.keystoreSource.startsWith("classpath:")) {
                keystore = new ClassPathResource(this.keystoreSource);
            } else {
                keystore = new FileSystemResource(this.keystoreSource);
            }
        }
        if (keystore == null) {
            Assert.isNull(keystore);
        }
        this.trustManager = new EipX509TrustManager();
        this.trustManager.setKeystore(keystore);
        this.trustManager.setKeystorePassword(new String(this.keystorePwd));
        this.trustManager.init();
    }
    // SSL Context
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, new TrustManager[] { this.trustManager }, null);
    SSLContext.setDefault(ctx);
}

From source file:com.laxser.blitz.scanning.BlitzScanner.java

public List<ResourceRef> getJarOrClassesFolderResources(String[] scope) throws IOException {
    if (logger.isInfoEnabled()) {
        logger.info("[findFiles] start to found classes folders " + "or blitzd jar files by scope:"
                + Arrays.toString(scope));
    }//from   w w w . j av a 2  s.  co  m
    List<ResourceRef> resources;
    if (scope == null) {
        resources = new LinkedList<ResourceRef>();
        if (logger.isDebugEnabled()) {
            logger.debug("[findFiles] call 'classesFolder'");
        }
        resources.addAll(getClassesFolderResources());
        //
        if (logger.isDebugEnabled()) {
            logger.debug("[findFiles] exits from 'classesFolder'");
            logger.debug("[findFiles] call 'jarFile'");
        }
        resources.addAll(getJarResources());
        if (logger.isDebugEnabled()) {
            logger.debug("[findFiles] exits from 'jarFile'");
        }
    } else if (scope.length == 0) {
        return new ArrayList<ResourceRef>();
    } else {
        resources = new LinkedList<ResourceRef>();
        for (String scopeEntry : scope) {
            String packagePath = scopeEntry.replace('.', '/');
            Resource[] packageResources = resourcePatternResolver.getResources("classpath*:" + packagePath);
            for (Resource pkgResource : packageResources) {
                String uri = pkgResource.getURI().toString();
                uri = StringUtils.removeEnd(uri, "/");
                packagePath = StringUtils.removeEnd(packagePath, "/");
                uri = StringUtils.removeEnd(uri, packagePath);
                int beginIndex = uri.lastIndexOf("file:");
                if (beginIndex == -1) {
                    beginIndex = 0;
                } else {
                    beginIndex += "file:".length();
                }
                int endIndex = uri.lastIndexOf('!');
                if (endIndex == -1) {
                    endIndex = uri.length();
                }
                String path = uri.substring(beginIndex, endIndex);
                Resource folder = new FileSystemResource(path);
                ResourceRef ref = ResourceRef.toResourceRef(folder);
                if (!resources.contains(ref)) {
                    resources.add(ref);
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "[findFiles] found classes folders " + "or blitzd jar files by scope:" + ref);
                    }
                }
            }
        }
    }
    //
    if (logger.isInfoEnabled()) {
        logger.info("[findFiles] found " + resources.size() + " classes folders " + "or blitzd jar files : "
                + resources);
    }

    return resources;
}

From source file:org.springframework.cloud.dataflow.server.service.impl.validation.DefaultAppValidationServiceTests.java

private void initializeSuccessfulRegistry(AppRegistryService appRegistry) {
    when(appRegistry.find(anyString(), any(ApplicationType.class))).thenReturn(
            new AppRegistration("some-name", ApplicationType.task, URI.create("https://helloworld")));
    when(appRegistry.getAppResource(any()))
            .thenReturn(new FileSystemResource("src/test/resources/apps/foo-task"));
    when(appRegistry.getAppMetadataResource(any())).thenReturn(null);
}

From source file:net.oneandone.stool.overview.StageController.java

@RequestMapping(value = "/{name}/logs/{log}", method = RequestMethod.GET)
public ResponseEntity<Resource> log(@PathVariable(value = "name") String stageName,
        @PathVariable(value = "log") String log) throws Exception {
    Stage stage;/* ww w . j a  v a2s .c o  m*/
    String logfile;
    stage = resolveStage(stageName);
    if (log.endsWith(".log")) {
        logfile = log;
    } else {
        logfile = log + ".log";
    }

    try {
        Resource resource;
        resource = new FileSystemResource(stage.logs().file(logfile));

        return new ResponseEntity<>(resource, HttpStatus.OK);

    } catch (NodeNotFoundException e) {
        throw new ResourceNotFoundException();
    }
}

From source file:org.jdtaus.core.container.mojo.SpringDescriptorMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    final ClassLoader mavenLoader = Thread.currentThread().getContextClassLoader();

    Writer writer = null;/*  w  ww  .  j a  v a 2  s.c  o  m*/
    OutputStream out = null;

    try {
        final ClassLoader runtimeLoader = this.getRuntimeClassLoader(mavenLoader);

        Thread.currentThread().setContextClassLoader(runtimeLoader);
        enableThreadContextClassLoader();

        final BeansElement springModel = this.getModelManager().getSpringModel(this.getFactoryBean(),
                ModelFactory.newModel().getModules());

        if (springModel.getImportOrAliasOrBean().size() > 0) {
            if (!this.getSpringDescriptorFile().getParentFile().exists()) {
                this.getSpringDescriptorFile().getParentFile().mkdirs();
            }

            out = new FileOutputStream(this.getSpringDescriptorFile());

            this.getModelManager().getSpringMarshaller().marshal(springModel, out);

            out.close();
            out = null;

            this.getLog().info(SpringDescriptorMojoBundle.getInstance().getGeneratedDescriptorMessage(
                    Locale.getDefault(), this.getSpringDescriptorFile().getCanonicalPath()));

            final BeanFactory beanFactory = new XmlBeanFactory(
                    new FileSystemResource(this.getSpringDescriptorFile()));

            beanFactory.containsBean("TEST");

            final JavaArtifact artifact = new JavaArtifact(this.getFactoryBean());

            final File source = new File(this.getSourceRoot(),
                    artifact.getPackagePath() + File.separator + artifact.getName() + ".java");

            if (!source.getParentFile().exists() && !source.getParentFile().mkdirs()) {
                throw new MojoExecutionException(
                        SpringDescriptorMojoBundle.getInstance().getCannotCreateDirectoryMessage(
                                Locale.getDefault(), source.getParentFile().getAbsolutePath()));

            }

            if (this.getEncoding() == null) {
                writer = new FileWriter(source);
            } else {
                writer = new OutputStreamWriter(new FileOutputStream(source), this.getEncoding());

            }

            final VelocityContext ctx = new VelocityContext();
            ctx.put("artifact", artifact);
            ctx.put("project", this.getMavenProject());

            this.getVelocity().mergeTemplate(FACTORY_BEAN_TEMPLATE_LOCATION, "UTF-8", ctx, writer);

            writer.close();
            writer = null;

            this.getMavenProject().addCompileSourceRoot(this.getSourceRoot().getAbsolutePath());

            this.getLog().info(SpringDescriptorMojoBundle.getInstance()
                    .getGeneratedFactoryBeanMessage(Locale.getDefault(), source.getCanonicalPath()));

        } else {
            this.getLog().info(SpringDescriptorMojoBundle.getInstance()
                    .getEmptyDescriptorMessage(Locale.getDefault(), this.springDescriptor.getCanonicalPath()));

        }
    } catch (final ContextError e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (final ContainerError e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (final ModelError e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (final Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        disableThreadContextClassLoader();
        Thread.currentThread().setContextClassLoader(mavenLoader);

        try {
            if (out != null) {
                out.close();
            }
        } catch (final IOException e) {
            this.getLog().error(e);
        }

        try {
            if (writer != null) {
                writer.close();
            }
        } catch (final IOException e) {
            this.getLog().error(e);
        }
    }
}