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.opennms.tools.EventsGeneratorTest.java

/**
 * Test generator./*from w  w  w . j  a v a 2  s .c  om*/
 *
 * @throws Exception the exception
 */
@Test
public void testGenerator() throws Exception {
    File onmsHome = new File(System.getProperty("opennms.home"));
    Assert.assertTrue(onmsHome.exists());
    EventsGenerator generator = new EventsGenerator(new ThresholdEventProcessor());
    generator.generateThresholdEvents(onmsHome);
    File target = new File("target/opennms-home/etc/events/Thresholds-Categorized.events.xml");
    Assert.assertTrue(target.exists());

    Events events = CastorUtils.unmarshal(Events.class, new FileSystemResource(target), true);

    // Problem that has a possible resolution
    Event e = findEvent(events, "uei.opennms.org/threshold/windows/cpu/high/major/exceeded");
    Assert.assertNotNull(e);
    System.err.println(e.getEventLabel());
    System.err.println(e.getLogmsg().getContent());
    Assert.assertEquals("Major", e.getSeverity());
    Assert.assertEquals(1, e.getAlarmData().getAlarmType().intValue());
    Assert.assertTrue(e.getLogmsg().getContent().matches(".*results.htm.*with.*on instance.*"));

    // Problem resolution
    e = findEvent(events, "uei.opennms.org/threshold/windows/cpu/high/major/rearmed");
    Assert.assertNotNull(e);
    System.err.println(e.getEventLabel());
    System.err.println(e.getLogmsg().getContent());
    Assert.assertEquals("Normal", e.getSeverity());
    Assert.assertEquals(2, e.getAlarmData().getAlarmType().intValue());
    Assert.assertTrue(e.getLogmsg().getContent().matches(".*results.htm.*with.*on instance.*"));

    // Problem without possible resolution
    e = findEvent(events, "uei.opennms.org/threshold/apc/ups/vac-in/warning/ac/exceeded");
    Assert.assertNotNull(e);
    System.err.println(e.getEventLabel());
    System.err.println(e.getLogmsg().getContent());
    Assert.assertEquals("Warning", e.getSeverity());
    Assert.assertEquals(3, e.getAlarmData().getAlarmType().intValue());
    Assert.assertTrue(e.getLogmsg().getContent().contains("changed from"));
}

From source file:magoffin.matt.sobriquet.test.DirectoryServerStatement.java

public static InMemoryDirectoryServer startServer(final int port, final String baseDN, final String authDN,
        final String authPassword, final String[] ldifFiles, final String[] schemaFiles)
        throws LDIFException, LDAPException, IOException {
    final InMemoryListenerConfig listenerConfig = InMemoryListenerConfig.createLDAPConfig("default", port);
    final InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(new DN(baseDN));
    config.setListenerConfigs(listenerConfig);
    config.addAdditionalBindCredentials(authDN, authPassword);
    if (schemaFiles != null && schemaFiles.length > 0) {
        // merge custom schemas with default standard schemas
        List<File> files = new ArrayList<File>(schemaFiles.length);
        for (String name : schemaFiles) {
            // try fs first
            Resource r = new FileSystemResource(name);
            if (r.exists()) {
                files.add(r.getFile());//from  www. ja v a  2 s  .c o m
            } else {
                r = new ClassPathResource(name);
                if (r.exists()) {
                    files.add(r.getFile());
                }
            }
        }
        if (files.size() > 0) {
            config.setSchema(Schema.mergeSchemas(Schema.getDefaultStandardSchema(), Schema.getSchema(files)));
        }
    }
    final InMemoryDirectoryServer server = new InMemoryDirectoryServer(config);
    server.add(new Entry(baseDN, new Attribute("objectclass", "domain", "top")));
    server.startListening();
    if (ldifFiles != null) {
        for (final String ldifFile : ldifFiles) {
            DirectoryServerUtils.loadData(server, ldifFile);
        }
    }
    return server;
}

From source file:com.sitewhere.configuration.TomcatConfigurationResolver.java

@Override
public ApplicationContext resolveSiteWhereContext(IVersion version) throws SiteWhereException {
    LOGGER.info("Loading Spring configuration ...");
    File sitewhereConf = getSiteWhereConfigFolder();
    File serverConfigFile = new File(sitewhereConf, SERVER_CONFIG_FILE_NAME);
    if (!serverConfigFile.exists()) {
        throw new SiteWhereException(
                "SiteWhere server configuration not found: " + serverConfigFile.getAbsolutePath());
    }/*from  w w w. java2 s  .  c o  m*/
    GenericApplicationContext context = new GenericApplicationContext();

    // Plug in custom property source.
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("sitewhere.edition", version.getEditionIdentifier().toLowerCase());

    MapPropertySource source = new MapPropertySource("sitewhere", properties);
    context.getEnvironment().getPropertySources().addLast(source);

    // Read context from XML configuration file.
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
    reader.loadBeanDefinitions(new FileSystemResource(serverConfigFile));

    context.refresh();
    return context;
}

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

@Test
public void testExecuteFileNotFound() {
    FileCopyTasklet aTasklet = new FileCopyTasklet();
    aTasklet.setOrigin(new FileSystemResource("src/test/resources/testFiles/notfound.csv"));
    aTasklet.setDestination(new FileSystemResource("target/input-copy.csv"));
    try {/*ww w.j a va 2  s.c om*/
        aTasklet.execute(null, null);
        fail("Must return an exception if the input file is not found");
    } catch (Exception e) {
    }
}

From source file:io.sample.sshd.utilities.EmbeddedSftpServer.java

@Override
public void afterPropertiesSet() throws Exception {
    final PublicKey allowedKey = decodePublicKey();

    this.server.setPublickeyAuthenticator(new PublickeyAuthenticator() {
        @Override/*from  www .  ja  v  a 2s .  c  o  m*/
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return key.equals(allowedKey);
        }
    });
    this.server.setPasswordAuthenticator(new PasswordAuthenticator() {
        public boolean authenticate(String username, String password, ServerSession session) {
            return username != null && username.equals(password);
        }
    });
    this.server.setPublickeyAuthenticator(new PublickeyAuthenticator() {
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            //File f = new File("/Users/" + username + "/.ssh/authorized_keys");
            return true;
        }
    });

    this.server.setPort(this.port);
    this.server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("src/test/resources/keys/hostkey.ser"));
    this.server.setSubsystemFactories(
            Collections.<NamedFactory<Command>>singletonList(new SftpSubsystem.Factory()));
    final String virtualDir = new FileSystemResource("src/test/resources/remote/").getFile().getAbsolutePath();
    server.setFileSystemFactory(new VirtualFileSystemFactory(virtualDir));
}

From source file:com.intuit.karate.demo.controller.UploadController.java

@GetMapping("/{id:.+}")
public ResponseEntity<Resource> download(@PathVariable String id) throws Exception {
    String filePath = FILES_BASE + id;
    File file = new File(filePath);
    File meta = new File(filePath + "_meta.txt");
    String name = FileUtils.readFileToString(meta, "utf-8");
    return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + name + "\"")
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)
            .body(new FileSystemResource(file));
}

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

@SuppressWarnings("unchecked")
@Before/*from   ww  w.  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(reportProcessor).setCsvReportEntitiesMapping(any(CsvReportEntitiesMapping.class));

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

    doCallRealMethod().when(reportProcessor).getReportDefinition(any(ReportDefinitionReportType.class),
            any(ReportDefinitionDateRangeType.class), anyString(), anyString(), anyString(),
            any(Properties.class));

    doCallRealMethod().when(reportProcessor).instantiateReportDefinition(any(ReportDefinitionReportType.class),
            any(ReportDefinitionDateRangeType.class), any(Selector.class), any(Properties.class));

    reportProcessor.setCsvReportEntitiesMapping(appCtx.getBean(CsvReportEntitiesMapping.class));
    reportProcessor.setPersister(mockedEntitiesPersister);
    reportProcessor.setAuthentication(authenticator);

    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())).thenReturn(accountIds);
}

From source file:de.langmi.spring.batch.examples.readers.file.gzip.GZipBufferedReaderFactoryTest.java

@Test
public void testFailWithFileNotInGzipFormat() throws Exception {
    // adjust suffix
    gzbrf.setGzipSuffixes(new ArrayList<String>() {

        {//w w w  .j a  v a 2 s.  co m
            add(".txt");
        }
    });

    try {
        gzbrf.create(new FileSystemResource(PATH_TO_UNCOMPRESSED_TEST_FILE), Charset.defaultCharset().name());
        fail();
    } catch (Exception e) {
        assertTrue(e instanceof IOException);
        assertTrue(e.getMessage().contains("Not in GZIP format"));
    }
}

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

@Test
public void testStopLoadingFile() throws DataFileLoaderException {
    Runnable dfl = new Runnable() {
        public void run() {
            employeeDfl.setDataFileProcessor(longRunningDfp);
            employeeDfl.setResource(new FileSystemResource(XLS_FILE_IN_NAME));
            try {
                employeeDfl.load();/*  w ww. j av a2  s.  com*/
                Assert.fail();
            } catch (DataFileLoaderException e) {
                Assert.assertEquals(2, longRunningDfp.getSuccessCounter());
                Assert.assertEquals("Interrupt exception", "STOP", e.getMessage());
            }
        }
    };
    Thread thread = new Thread(dfl);
    thread.start();

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    thread.interrupt();
}

From source file:org.psikeds.knowledgebase.xml.StaxParserTest.java

/**
 * Test method for {@link org.psikeds.knowledgebase.xml.impl.XSDValidator}
 *///  w  w  w . jav a  2 s . c om
@Test
public void testXsdValidatorWithSpringResources() {
    try {
        LOGGER.info("Validating XML " + XML + " against XSD " + XSD + " using Spring-Resources ...");
        final Resource xsd = new FileSystemResource(XSD);
        final Resource xml = new FileSystemResource(XML);
        final KBValidator validator = new XSDValidator(xsd, xml);
        validator.validate();
        LOGGER.info("... done. XML " + XML + " is valid against XSD " + XSD);
    } catch (final SAXException saxex) {
        final String message = "Invalid XML: " + saxex.getMessage();
        LOGGER.info(message);
        fail(message);
    } catch (final IOException ioex) {
        final String message = "Could not validate XML: " + ioex.getMessage();
        LOGGER.info(message);
        fail(message);
    }
}