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:de.langmi.spring.batch.examples.readers.file.archive.ArchiveMultiResourceItemReaderTest.java

/**
 * Test with one ZIP file containing one text file with 20 lines.
 *
 * @throws Exception /*from w  w  w . ja va  2 s  .c o  m*/
 */
@Test
public void testOneZipFile() throws Exception {
    LOG.debug("testOneZipFile");
    ArchiveMultiResourceItemReader<String> mReader = new ArchiveMultiResourceItemReader<String>();
    // setup multResourceReader
    mReader.setArchives(
            new Resource[] { new FileSystemResource("src/test/resources/input/file/archive/input.txt.zip") });

    // 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) {
                assertEquals(String.valueOf(count), item);
                count++;
            }
        } while (item != null);
        assertEquals(20, count);
    } catch (Exception e) {
        throw e;
    } finally {
        mReader.close();
    }
}

From source file:annis.administration.AbstractAdminstrationDao.java

/**
 * executes an SQL script from $ANNIS_HOME/scripts, substituting the
 * parameters found in args//w w w .  j  a  v  a 2s.  c om
 *
 * @param script
 * @param args
 * @return
 */
protected PreparedStatement executeSqlFromScript(String script, MapSqlParameterSource args) {
    File fScript = new File(scriptPath, script);
    if (fScript.canRead() && fScript.isFile()) {
        Resource resource = new FileSystemResource(fScript);
        log.debug("executing SQL script: " + resource.getFilename());
        String sql = readSqlFromResource(resource, args);
        CancelableStatements cancelableStats = new CancelableStatements(sql, statementController);

        // register the statement, so we could try to interrupt it in the gui.
        if (statementController != null) {
            statementController.registerStatement(cancelableStats.statement);
        } else {
            log.debug("statement controller is not initialized");
        }

        jdbcTemplate.execute(cancelableStats, cancelableStats);
        return cancelableStats.statement;
    } else {
        log.debug("SQL script " + fScript.getName() + " does not exist");
        return null;
    }
}

From source file:com.google.api.ads.adwords.jaxws.extensions.processors.ReportProcessorTest.java

@Before
public void setUp() throws InterruptedException, IOException, OAuthException {
    Resource resource = new FileSystemResource("src/test/resources/aw-report-sample.properties");
    DynamicPropertyPlaceholderConfigurer.setDynamicResource(resource);
    properties = PropertiesLoaderUtils.loadProperties(resource);
    appCtx = new ClassPathXmlApplicationContext("classpath:aw-report-test-beans.xml");

    reportProcessor = new ReportProcessor("1", "token", "companyName", "clientId", "clientSecret", 10, 2,
            false);/*from   www . j ava2 s. c  o  m*/

    MockitoAnnotations.initMocks(this);

    when(mockedAuthTokenPersister.getAuthToken(Mockito.anyString())).thenReturn(new AuthMcc("1", "TOKEN"));

    Mockito.doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            return null;
        }
    }).when(mockedReportEntitiesPersister).persistReportEntities(Mockito.<List<? extends Report>>anyObject());

    mockDownloadReports(CIDS.size());

    reportProcessor.setMultipleClientReportDownloader(mockedMultipleClientReportDownloader);
    reportProcessor.setAuthTokenPersister(mockedAuthTokenPersister);
    reportProcessor.setPersister(mockedReportEntitiesPersister);
    reportProcessor.setCsvReportEntitiesMapping(appCtx.getBean(CsvReportEntitiesMapping.class));

    // Mocking the Authentication because in OAuth2 we are force to call buildOAuth2Credentials
    AdWordsSession.Builder builder = new AdWordsSession.Builder().withClientCustomerId("1");
    Mockito.doReturn(builder).when(reportProcessor).authenticate(Mockito.anyBoolean());
}

From source file:org.ng200.openolympus.controller.solution.SolutionDownloadController.java

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN + SecurityExpressionConstants.OR + '('
        + SecurityExpressionConstants.IS_USER + SecurityExpressionConstants.AND
        + SecurityExpressionConstants.USER_IS_OWNER + SecurityExpressionConstants.AND
        + "@oolsec.isSolutionInCurrentContest(#solution)" + ')')
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody ResponseEntity<FileSystemResource> solutionDownload(final HttpServletRequest request,
        final Model model, @RequestParam(value = "id") final Solution solution, final Principal principal) {
    if (principal == null || (!solution.getUser().getUsername().equals(principal.getName())
            && !request.isUserInRole(Role.SUPERUSER))) {
        throw new InsufficientAuthenticationException(
                "You attempted to download a solution that doesn't belong to you!");
    }//w w  w.  jav  a 2 s.  com
    Assertions.resourceExists(solution);

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentDispositionFormData("attachment",
            this.storageService.getSolutionFile(solution).getFileName().toString());
    return new ResponseEntity<FileSystemResource>(
            new FileSystemResource(this.storageService.getSolutionFile(solution).toFile()), headers,
            HttpStatus.OK);
}

From source file:net.sourceforge.vulcan.spring.jdbc.JdbcSchemaMigratorTest.java

public void testSortsMigrationScripts() throws Exception {
    Resource r1 = new FileSystemResource("S001_foo");
    Resource r2 = new FileSystemResource("S002_foo");
    migrator.setMigrationScripts(new Resource[] { r2, r1 });

    assertSame(r1, migrator.getMigrationScripts()[0]);
    assertSame(r2, migrator.getMigrationScripts()[1]);
}

From source file:com.google.api.ads.adwords.awreporting.exporter.ReportExporterTest.java

@SuppressWarnings("unchecked")
@Before//from  www . j  a  v a 2 s .c  o  m
public <R extends Report> void setUp() throws Exception {
    Resource resource = new FileSystemResource("src/test/resources/aw-report-sample.properties");
    DynamicPropertyPlaceholderConfigurer.setDynamicResource(resource);
    properties = PropertiesLoaderUtils.loadProperties(resource);
    appCtx = new ClassPathXmlApplicationContext("classpath:aw-report-test-beans.xml");

    MockitoAnnotations.initMocks(this);
    doCallRealMethod().when(reportExporter).setCsvReportEntitiesMapping(any(CsvReportEntitiesMapping.class));

    doCallRealMethod().when(reportExporter).setPersister(any(EntityPersister.class));

    doCallRealMethod().when(reportExporter).exportReports(any(Credential.class), anyString(), anyString(),
            anyString(), anySetOf(Long.class), any(Properties.class), any(File.class), any(File.class),
            anyBoolean());

    reportExporter.setCsvReportEntitiesMapping(appCtx.getBean(CsvReportEntitiesMapping.class));
    reportExporter.setPersister(mockedEntitiesPersister);

    reportAccount.setAccountDescriptiveName("TestAccount");
    reportAccount.setAccountId(123L);
    reportAccount.setMonth("20140101");
    reportAccount.setCost(new BigDecimal(456L));
    reportAccount.setImpressions(99L);
    reportAccount.setClicks(999L);
    reportAccount.setAvgCpc(new BigDecimal(12L));
    reportAccount.setAvgCpm(new BigDecimal(4L));

    when(mockedEntitiesPersister.listMonthReports((Class<ReportAccount>) anyObject(), anyLong(),
            any(DateTime.class), any(DateTime.class))).thenReturn(listAccounts);

    when(reportProcessor.retrieveAccountIds(anyString(), anyString())).thenReturn(accountIds);
}

From source file:org.gageot.excel.core.ExcelTemplate.java

/**
 * Construct a new ExcelTemplate, given an Excel File.
 * @param aFile Excel file/*from w w w  .  ja va  2 s.  c om*/
 */
public ExcelTemplate(File aFile) {
    setResource(new FileSystemResource(aFile));
    afterPropertiesSet();
}

From source file:com.consol.citrus.admin.service.ProjectService.java

/**
 * Loads Citrus project from project home.
 * @param projectHomeDir//from   w w w .  ja  va2s.  co  m
 * @return
 */
public void load(String projectHomeDir) {
    Project project = new Project(projectHomeDir);
    if (project.getProjectInfoFile().exists()) {
        project.loadSettings();
    } else if (!validateProject(project)) {
        throw new ApplicationRuntimeException("Invalid project home - not a proper Citrus project");
    }

    if (project.isMavenProject()) {
        try {
            String pomXml = FileUtils.readToString(new FileSystemResource(project.getMavenPomFile()));
            SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
            nsContext.bindNamespaceUri("mvn", "http://maven.apache.org/POM/4.0.0");

            Document pomDoc = XMLUtils.parseMessagePayload(pomXml);
            project.setName(evaluate(pomDoc, "/mvn:project/mvn:artifactId", nsContext));

            String version = evaluate(pomDoc, "/mvn:project/mvn:version", nsContext);
            String parentVersion = evaluate(pomDoc, "/mvn:project/mvn:parent/mvn:version", nsContext);
            if (StringUtils.hasText(version)) {
                project.setVersion(version);
            } else if (StringUtils.hasText(parentVersion)) {
                project.setVersion(parentVersion);
            }

            project.getSettings().setBasePackage(evaluate(pomDoc, "/mvn:project/mvn:groupId", nsContext));

            String citrusVersion = evaluate(pomDoc, "/mvn:project/mvn:properties/mvn:citrus.version",
                    nsContext);
            if (StringUtils.hasText(citrusVersion)) {
                project.getSettings().setCitrusVersion(citrusVersion);
            }

            project.setDescription(evaluate(pomDoc, "/mvn:project/mvn:description", nsContext));

            project.getSettings().setConnectorActive(StringUtils.hasText(evaluate(pomDoc,
                    "/mvn:project/mvn:dependencies/mvn:dependency/mvn:artifactId[. = 'citrus-admin-connector']",
                    nsContext)));
        } catch (IOException e) {
            throw new ApplicationRuntimeException("Unable to open Maven pom.xml file", e);
        }
    } else if (project.isAntProject()) {
        try {
            String buildXml = FileUtils.readToString(new FileSystemResource(project.getAntBuildFile()));
            SimpleNamespaceContext nsContext = new SimpleNamespaceContext();

            Document buildDoc = XMLUtils.parseMessagePayload(buildXml);
            project.setName(evaluate(buildDoc, "/project/@name", nsContext));

            String citrusVersion = evaluate(buildDoc, "/project/property[@name='citrus.version']/@value",
                    nsContext);
            if (StringUtils.hasText(citrusVersion)) {
                project.getSettings().setCitrusVersion(citrusVersion);
            }

            project.setDescription(evaluate(buildDoc, "/project/@description", nsContext));
        } catch (IOException e) {
            throw new ApplicationRuntimeException("Unable to open Apache Ant build.xml file", e);
        }
    }

    saveProject(project);

    this.project = project;
    if (!this.recentlyOpened.contains(projectHomeDir)) {
        if (projectHomeDir.endsWith("/")) {
            this.recentlyOpened.add(projectHomeDir.substring(0, projectHomeDir.length() - 1));
        } else {
            this.recentlyOpened.add(projectHomeDir);
        }
    }
    System.setProperty(Application.PROJECT_HOME, projectHomeDir);
}