Java Examples for org.springframework.core.io.FileSystemResource

The following java examples will help you to understand the usage of org.springframework.core.io.FileSystemResource. These source code samples are taken from different open source projects.

Example 1
Project: spring-shiro-webapp-master  File: PropertiesConfiguration.java View source code
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
    String propertiesLocation = System.getProperty("defaultProperties.location");
    PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
    ppc.setLocation(new FileSystemResource(propertiesLocation));
    ppc.setIgnoreUnresolvablePlaceholders(true);
    return ppc;
}
Example 2
Project: TOYS-master  File: XmlConfigWithBeanFactory.java View source code
public static void main(String[] args) {
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    BeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
    reader.loadBeanDefinitions(new FileSystemResource("src/main/resources/spring.xml"));
    HelloWorld helloWorld = (HelloWorld) beanFactory.getBean("helloWorld");
    System.out.println(helloWorld.helloWorld());
}
Example 3
Project: camelinaction2-master  File: InitDatabase.java View source code
public static void main(String[] args) throws Exception {
    String url = "jdbc:postgresql://localhost:5432/quartz";
    Class.forName("org.postgresql.Driver");
    Connection db = DriverManager.getConnection(url, "quartz", "quartz");
    System.out.println("Initializing database and creating tables");
    db.setAutoCommit(false);
    ScriptUtils.executeSqlScript(db, new FileSystemResource("tables_postgres.sql"));
    db.setAutoCommit(true);
    db.close();
    System.out.println("Database initialized");
}
Example 4
Project: jw-community-master  File: JogetCommonsMultipartResolver.java View source code
@Override
public MultipartHttpServletRequest resolveMultipart(final HttpServletRequest request) throws MultipartException {
    Assert.notNull(request, "Request must not be null");
    try {
        // reset profile and set hostname
        HostManager.initHost();
        if (HostManager.isVirtualHostEnabled()) {
            String path = SetupManager.getBaseDirectory() + File.separator + "temp";
            File uploadTempDir = new File(path);
            if (!uploadTempDir.isDirectory()) {
                uploadTempDir.mkdir();
            }
            setUploadTempDir(new FileSystemResource(uploadTempDir));
        }
    } catch (Exception e) {
        LogUtil.error(JogetCommonsMultipartResolver.class.getName(), e, "");
    }
    return super.resolveMultipart(request);
}
Example 5
Project: pac4j-master  File: SAML2ClientTests.java View source code
@Test
public void testSaml2ConfigurationOfKeyStore() throws Exception {
    final Resource rs = new FileSystemResource("testKeystore.jks");
    if (rs.exists() && !rs.getFile().delete()) {
        throw new TechnicalException("File could not be deleted");
    }
    final SAML2ClientConfiguration cfg = new SAML2ClientConfiguration("testKeystore.jks", "pac4j-test-passwd", "pac4j-test-passwd", "resource:testshib-providers.xml");
    cfg.init();
    final KeyStoreCredentialProvider p = new KeyStoreCredentialProvider(cfg);
    assertNotNull(p.getKeyInfoGenerator());
    assertNotNull(p.getCredentialResolver());
    assertNotNull(p.getKeyInfo());
    assertNotNull(p.getKeyInfoCredentialResolver());
    assertNotNull(p.getCredential());
}
Example 6
Project: ws-proxy-master  File: PropertySources.java View source code
@Bean
@Autowired
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(ApplicationContext applicationContext) {
    PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    propertySourcesPlaceholderConfigurer.setLocation(new FileSystemResource(applicationContext.getEnvironment().getProperty("project.root.dir") + "/config/wsproxy-local-config/wsproxy_local_demo.properties"));
    return propertySourcesPlaceholderConfigurer;
}
Example 7
Project: invesdwin-util-master  File: Resources.java View source code
public static String resourceToPatternString(final Resource resource) {
    if (resource instanceof ClassPathResource) {
        final ClassPathResource cResource = (ClassPathResource) resource;
        return "classpath:" + cResource.getPath();
    } else if (resource instanceof FileSystemResource) {
        final FileSystemResource cResource = (FileSystemResource) resource;
        return "file:" + cResource.getPath();
    } else {
        try {
            final URI uri = resource.getURI();
            if (uri != null) {
                return uri.toString();
            } else {
                //fallback garbage
                return resource.toString();
            }
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
    }
}
Example 8
Project: jumbodb-master  File: JumboConfigurationLoader.java View source code
public Properties loadConfiguration() throws IOException {
    Properties properties = new Properties();
    PropertiesLoaderUtils.fillProperties(properties, new ClassPathResource("org/jumbodb/database/service/jumbodb.conf"));
    if (globalConfigFile.exists()) {
        PropertiesLoaderUtils.fillProperties(properties, new FileSystemResource(globalConfigFile));
    }
    String jumboConfig = System.getProperty("jumbodb.config");
    if (StringUtils.isNotEmpty(jumboConfig)) {
        PropertiesLoaderUtils.fillProperties(properties, new FileSystemResource(jumboConfig));
    }
    String userHome = System.getProperty("user.home");
    Set<String> keys = properties.stringPropertyNames();
    Properties result = new Properties();
    for (String key : keys) {
        String property = properties.getProperty(key);
        property = StringUtils.replace(property, "$USER_HOME", userHome);
        property = StringUtils.replace(property, "%USER_HOME%", userHome);
        result.setProperty(key, property);
    }
    return result;
}
Example 9
Project: nimbus-master  File: NimbusFileSystemXmlApplicationContext.java View source code
@Override
protected Resource getResourceByPath(String path) {
    if (this.nimbusHomePathResolver == null) {
        this.nimbusHomePathResolver = new NimbusHomePathResolver();
    }
    final String resolved = this.nimbusHomePathResolver.resolvePath(path);
    if (resolved != null) {
        return new FileSystemResource(resolved);
    }
    return super.getResourceByPath(path);
}
Example 10
Project: oauth2-provider-master  File: PropertiesConfiguration.java View source code
@Bean
public PropertySourcesPlaceholderConfigurer getProperties() {
    String profile = System.getProperty("spring.profiles.active", "default");
    PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
    Resource[] resources = new Resource[] { new ClassPathResource("properties/application.properties"), new ClassPathResource("properties/app-" + profile + ".properties"), new FileSystemResource(System.getProperty("PROPERTY_FILE_LOCATION", "")) };
    pspc.setLocations(resources);
    pspc.setIgnoreUnresolvablePlaceholders(IGNORE_UNRESOLVABLE_PLACEHOLDERS);
    pspc.setIgnoreResourceNotFound(true);
    return pspc;
}
Example 11
Project: simpleframework-master  File: ApplicationLauncher.java View source code
public static void main(String[] list) throws Exception {
    if (list.length < 1) {
        System.out.println("usage: " + ApplicationLauncher.class.getName() + " [configFile] [propertyFile 1] .. [propertyFile N]");
        System.exit(-1);
    }
    Resource configFile = new FileSystemResource(list[0]);
    if (!configFile.exists()) {
        System.out.println("error: " + ApplicationLauncher.class.getName() + " could not resolve config file " + list[0]);
        System.exit(-1);
    }
    Resource[] propertyFiles = new Resource[list.length - 1];
    for (int i = 0; i < propertyFiles.length; i++) {
        Resource resource = new FileSystemResource(list[i + 1]);
        if (!resource.exists()) {
            System.out.println("error: " + ApplicationLauncher.class.getName() + " could not resolve property file " + list[i + 1]);
            System.exit(-1);
        }
        propertyFiles[i] = resource;
    }
    ConfigurationLoader service = new ConfigurationLoader(configFile, propertyFiles);
    service.start();
}
Example 12
Project: spring-framework-issues-master  File: Common.java View source code
public static void routeTest(ProducerTemplate producerTemplate) throws Exception {
    Resource input = new ClassPathResource("/msg-01.hl7");
    producerTemplate.requestBody("direct:input", input.getInputStream());
    Resource result = new FileSystemResource("target/output/HZL.hl7");
    assertEquals(MessageAdapters.load("msg-01.hl7.expected").toString(), MessageAdapters.make(result.getInputStream()).toString());
}
Example 13
Project: spring-modules-master  File: RepositoryFactoryBean.java View source code
/**
	 * @see org.springmodules.jcr.RepositoryFactoryBean#resolveConfigurationResource()
	 */
protected void resolveConfigurationResource() throws Exception {
    // read the configuration object
    if (repositoryConfig != null)
        return;
    if (this.configuration == null) {
        if (log.isDebugEnabled())
            log.debug("no configuration resource specified, using the default one:" + DEFAULT_CONF_FILE);
        configuration = new ClassPathResource(DEFAULT_CONF_FILE);
    }
    if (homeDir == null) {
        if (log.isDebugEnabled())
            log.debug("no repository home dir specified, using the default one:" + DEFAULT_REP_DIR);
        homeDir = new FileSystemResource(DEFAULT_REP_DIR);
    }
    repositoryConfig = RepositoryConfig.create(new InputSource(configuration.getInputStream()), homeDir.getFile().getAbsolutePath());
}
Example 14
Project: spring-ws-master  File: SaxUtilsTest.java View source code
@Test
public void testGetSystemId() throws Exception {
    Resource resource = new FileSystemResource("/path with spaces/file with spaces.txt");
    String systemId = SaxUtils.getSystemId(resource);
    Assert.assertNotNull("No systemId returned", systemId);
    Assert.assertTrue("Invalid system id", systemId.endsWith("path%20with%20spaces/file%20with%20spaces.txt"));
}
Example 15
Project: activemq-master  File: ResourceLoadingSslContext.java View source code
public static Resource resourceFromString(String uri) throws MalformedURLException {
    Resource resource;
    File file = new File(uri);
    if (file.exists()) {
        resource = new FileSystemResource(uri);
    } else if (ResourceUtils.isUrl(uri)) {
        resource = new UrlResource(uri);
    } else {
        resource = new ClassPathResource(uri);
    }
    return resource;
}
Example 16
Project: AGIA-master  File: ZipFilesTasklet.java View source code
protected void zipResource(Resource sSourceResource, ZipArchiveOutputStream sZipArchiveOutputStream, StepContribution sContribution, ChunkContext sChunkContext) throws IOException, ZipFilesException {
    // TODO : use a queue to reduce the callstack overhead
    if (sSourceResource.exists()) {
        File aSourceFile = sSourceResource.getFile();
        String aSourcePath = aSourceFile.getCanonicalPath();
        if (!aSourcePath.startsWith(sourceBaseDirectoryPath)) {
            throw new ZipFilesException("Source file " + aSourcePath + " does not match base directory " + sourceBaseDirectoryPath);
        }
        if (sContribution != null) {
            sContribution.incrementReadCount();
        }
        String aZipEntryName = aSourcePath.substring(sourceBaseDirectoryPath.length() + 1);
        sZipArchiveOutputStream.putArchiveEntry(new ZipArchiveEntry(aZipEntryName));
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Zipping {} to {}", sSourceResource.getFile().getCanonicalPath(), aZipEntryName);
        }
        if (aSourceFile.isFile()) {
            InputStream aInputStream = sSourceResource.getInputStream();
            IOUtils.copy(aInputStream, sZipArchiveOutputStream);
            aInputStream.close();
            sZipArchiveOutputStream.closeArchiveEntry();
        } else {
            sZipArchiveOutputStream.closeArchiveEntry();
            for (File aFile : aSourceFile.listFiles((FileFilter) (recursive ? TrueFileFilter.TRUE : FileFileFilter.FILE))) {
                zipResource(new FileSystemResource(aFile), sZipArchiveOutputStream, sContribution, sChunkContext);
            }
        }
        if (sContribution != null) {
            sContribution.incrementWriteCount(1);
        }
    } else if (LOGGER.isInfoEnabled()) {
        LOGGER.info("{} does not exist", sSourceResource.getFilename());
    }
}
Example 17
Project: bi-platform-v2-master  File: StandaloneSpringPentahoObjectFactoryTest.java View source code
public void testInitFromObject() throws Exception {
    StandaloneSession session = new StandaloneSession();
    StandaloneSpringPentahoObjectFactory factory = new StandaloneSpringPentahoObjectFactory();
    File f = new File("test-src/solution/system/pentahoObjects.spring.xml");
    FileSystemResource fsr = new FileSystemResource(f);
    GenericApplicationContext appCtx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appCtx);
    xmlReader.loadBeanDefinitions(fsr);
    factory.init("test-src/solution/system/pentahoObjects.spring.xml", appCtx);
    IPentahoSession session2 = factory.get(IPentahoSession.class, "systemStartupSession", session);
    assertNotNull(session2);
    assertEquals(SystemStartupSession.class, factory.getImplementingClass("systemStartupSession"));
    Object obj = factory.get(Object.class, "systemStartupSession", session);
    assertNotNull(obj);
    assertTrue(obj instanceof IPentahoSession);
}
Example 18
Project: cachecloud-master  File: AliasesResourceSqlSessionFactoryBean.java View source code
public void setTypeAliasesClassResources(Resource[] resources) {
    ArrayList<Class<?>> classList = new ArrayList<Class<?>>();
    for (int i = 0; i < resources.length; i++) {
        Resource resource = resources[i];
        try {
            String className;
            if (resource instanceof ClassPathResource) {
                String path = ((ClassPathResource) resource).getPath();
                className = getClassNameByPath(path);
            } else if (resource instanceof FileSystemResource) {
                String path = ((FileSystemResource) resource).getPath();
                className = getClassNameByPath(path);
            } else {
                throw new RuntimeException("resources is unsupported");
            }
            className = packages + className;
            Class<?> clazz = ClassUtils.resolveClassName(className, Thread.currentThread().getContextClassLoader());
            classList.add(clazz);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    this.setTypeAliases(classList.toArray(new Class[0]));
}
Example 19
Project: camel-cookbook-examples-master  File: EmbeddedDataSourceFactory.java View source code
public static JdbcDataSource getJdbcDataSource(String initScriptLocation) {
    Validate.notEmpty(initScriptLocation, "initScriptLocation is empty");
    String mavenRelativePath = "src/main/resources/" + initScriptLocation;
    String mavenRootRelativePath = "camel-cookbook-transactions/" + mavenRelativePath;
    // check that we can load the init script
    FileLocator locator = new FileLocator().with(initScriptLocation).with(mavenRelativePath).with(mavenRootRelativePath);
    File file = locator.find();
    Validate.notNull(file, locator.getErrorMessage());
    FileSystemResource script = new FileSystemResource(file);
    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1");
    dataSource.setUser("sa");
    dataSource.setPassword("");
    DataSourceInitializer.initializeDataSource(dataSource, script);
    return dataSource;
}
Example 20
Project: cas-server-4.0.1-master  File: WiringTests.java View source code
@Before
public void setUp() {
    applicationContext = new XmlWebApplicationContext();
    applicationContext.setConfigLocations(new String[] { "file:src/main/webapp/WEB-INF/cas-servlet.xml", "file:src/main/webapp/WEB-INF/deployerConfigContext.xml", "file:src/main/webapp/WEB-INF/spring-configuration/*.xml" });
    applicationContext.setServletContext(new MockServletContext(new ResourceLoader() {

        @Override
        public Resource getResource(final String location) {
            return new FileSystemResource("src/main/webapp" + location);
        }

        @Override
        public ClassLoader getClassLoader() {
            return getClassLoader();
        }
    }));
    applicationContext.refresh();
}
Example 21
Project: fi-smp-master  File: PDFController.java View source code
@RequestMapping(value = "/elmo", method = RequestMethod.GET)
@ResponseBody
public FileSystemResource elmo(HttpServletResponse response, Model model, @CookieValue(value = "elmoSessionId") String sessionIdCookie) throws Exception {
    final String decodedXml = (String) context.getSession().getAttribute("elmoxmlstring");
    new PdfGen().generatePdf(decodedXml, "/tmp/elmo.pdf");
    response.setHeader("Content-disposition", "attachment;filename=elmo.pdf");
    response.setContentType("application/pdf");
    return new FileSystemResource("/tmp/elmo.pdf");
}
Example 22
Project: grails-core-master  File: GroovyPageUnitTestResourceLoader.java View source code
@Override
public Resource getResource(String location) {
    if (location.startsWith(WEB_INF_PREFIX)) {
        location = location.substring(WEB_INF_PREFIX.length());
    }
    if (groovyPages.containsKey(location)) {
        try {
            return new ByteArrayResource(groovyPages.get(location).getBytes("UTF-8"), location);
        } catch (UnsupportedEncodingException e) {
        }
    }
    if (basePath == null) {
        String basedir = BuildSettings.BASE_DIR.getAbsolutePath();
        basePath = basedir + File.separatorChar + GrailsResourceUtils.VIEWS_DIR_PATH;
    }
    String path = basePath + location;
    path = makeCanonical(path);
    return new FileSystemResource(path);
}
Example 23
Project: grails-master  File: GroovyPageUnitTestResourceLoader.java View source code
@Override
public Resource getResource(String location) {
    if (location.startsWith(WEB_INF_PREFIX)) {
        location = location.substring(WEB_INF_PREFIX.length());
    }
    if (groovyPages.containsKey(location)) {
        try {
            return new ByteArrayResource(groovyPages.get(location).getBytes("UTF-8"), location);
        } catch (UnsupportedEncodingException e) {
        }
    }
    if (basePath == null) {
        String basedir = BuildSettings.BASE_DIR.getAbsolutePath();
        basePath = basedir + File.separatorChar + GrailsResourceUtils.VIEWS_DIR_PATH;
    }
    String path = basePath + location;
    path = makeCanonical(path);
    return new FileSystemResource(path);
}
Example 24
Project: gwt-sl-master  File: ResourceLoaderSupport.java View source code
@Override
public Resource getResource(String arg) {
    Matcher matcher = serialisationPolicyPattern.matcher(arg);
    boolean serializationPolicyFound = matcher.find();
    logger.debug("Looking up resource " + arg + " " + serializationPolicyFound);
    if (!serializationPolicyFound)
        return super.getResource(arg);
    String newResource = "target/webapp/static/" + matcher.group(2);
    logger.debug("Translating resource to " + newResource);
    return new FileSystemResource(newResource);
}
Example 25
Project: head-master  File: ApplicationContextFactory.java View source code
// TODO Suprised that Spring didn't have something like this already? 
/* package-local */
static ConfigurableApplicationContext createApplicationContext(Resource resource) throws BeansException, IOException {
    if (resource instanceof ClassPathResource) {
        return new ClassPathXmlApplicationContextFactory(resource).createApplicationContext();
    } else if (resource instanceof FileSystemResource) {
        return new FileSystemXmlApplicationContext(resource.getFile().toString());
    } else {
        throw new IOException(resource.getDescription() + " is neither a ClassPathResource nor a FileSystemResource, I don't know what to do");
    }
}
Example 26
Project: hello-world-master  File: TcAliyunOssServiceTest.java View source code
@Test
public void test() throws IOException {
    Assert.assertTrue(tcAliyunOssService.exists(DEFAULT_BUCKET, DEMO_FOLDER));
    // upload
    String filename = UUID.randomUUID().toString().concat(".jpg");
    org.springframework.core.io.Resource rs = new FileSystemResource("/Users/zhangyaowu/Desktop/IMG_0154.JPG");
    tcAliyunOssService.set(DEFAULT_BUCKET, DEMO_FOLDER, filename, rs.getInputStream());
    Assert.assertTrue(tcAliyunOssService.exists(DEFAULT_BUCKET, DEMO_FOLDER, filename));
    try (InputStream inputStream = tcAliyunOssService.get(DEFAULT_BUCKET, DEMO_FOLDER, filename)) {
        FileOutputStream fos = new FileOutputStream("/Users/zhangyaowu/Desktop/1.JPG");
        IOUtils.copy(inputStream, fos);
    }
    tcAliyunOssService.del(DEFAULT_BUCKET, DEMO_FOLDER, filename);
    Assert.assertFalse(tcAliyunOssService.exists(DEFAULT_BUCKET, DEMO_FOLDER, filename));
}
Example 27
Project: mifos-head-master  File: ApplicationContextFactory.java View source code
// TODO Suprised that Spring didn't have something like this already? 
/* package-local */
static ConfigurableApplicationContext createApplicationContext(Resource resource) throws BeansException, IOException {
    if (resource instanceof ClassPathResource) {
        return new ClassPathXmlApplicationContextFactory(resource).createApplicationContext();
    } else if (resource instanceof FileSystemResource) {
        return new FileSystemXmlApplicationContext(resource.getFile().toString());
    } else {
        throw new IOException(resource.getDescription() + " is neither a ClassPathResource nor a FileSystemResource, I don't know what to do");
    }
}
Example 28
Project: opennms_dashboard-master  File: XmlDataCollectionConfigDaoJaxb.java View source code
/**
     * Parses the XML groups.
     *
     * @param source the XML source
     */
private void parseXmlGroups(XmlSource source) {
    if (!source.hasImportGroups()) {
        return;
    }
    for (String importGroup : source.getImportGroupsList()) {
        File file = new File(ConfigFileConstants.getHome(), "/etc/" + importGroup);
        log().debug("parseXmlGroups: parsing " + file);
        XmlGroups groups = JaxbUtils.unmarshal(XmlGroups.class, new FileSystemResource(file));
        source.getXmlGroups().addAll(groups.getXmlGroups());
    }
}
Example 29
Project: portal-de-servicos-master  File: ImportadorParaPaginasEstaticas.java View source code
@SneakyThrows
Iterable<PaginaEstatica> importar(RepositorioCartasServico repositorio) {
    File dir = repositorio.get(PAGINA_ESTATICA.getCaminhoPasta()).getFile();
    log.info("Importando páginas temáticas em {}", dir);
    return repository.save(Stream.of(dir.listFiles(( d,  n) -> n.endsWith(PAGINA_ESTATICA.getExtensao()))).map(FileSystemResource::new).map(this::fromResource).peek( s -> log.debug("{} importado com sucesso", s.getId())).collect(toList()));
}
Example 30
Project: psicquic-master  File: MitabCalimochoReaderTest.java View source code
@Test
public void read_mitab_27() throws Exception {
    MitabCalimochoReader reader = new MitabCalimochoReader();
    reader.setResource(new FileSystemResource(MitabCalimochoReader.class.getResource("/samples/sampleFileNegative.txt").getFile()));
    reader.doOpen();
    Row row = reader.read();
    reader.close();
    Assert.assertNotNull(row);
    Assert.assertEquals(139, row.getAllFields().size());
}
Example 31
Project: Solr-Advert-master  File: SolrXmlApplicationContext.java View source code
@Override
protected Resource getResourceByPath(String path) {
    File f = new File(path);
    if (f.isAbsolute()) {
        // if the path is absolute, check if it exists
        if (f.exists()) {
            return new FileSystemResource(f);
        }
    } else {
        // if the path is relative, check inside the config dir
        f = new File(configDir, path);
        if (f.exists()) {
            return new FileSystemResource(f);
        }
    }
    // if we didn't find the resource, check in the classpath
    URL resUrl = loader.getClassLoader().getResource(path);
    if (resUrl != null) {
        return new UrlResource(resUrl);
    }
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unable to locate resource: " + path);
}
Example 32
Project: spring-batch-examples-readers-master  File: SimplePeekableItemReaderTest.java View source code
/**
     * Test should read succesfully.
     *
     * @throws Exception 
     */
@Test
public void testSuccessfulPeekAhead() throws Exception {
    // init delegate
    delegateReader.setLineMapper(new PassThroughLineMapper());
    delegateReader.setResource(new FileSystemResource(INPUT_FILE));
    // init peekable
    SingleItemPeekableItemReader<String> peekable = new SingleItemPeekableItemReader<String>();
    peekable.setDelegate(delegateReader);
    // open, provide "mock" ExecutionContext
    peekable.open(MetaDataInstanceFactory.createStepExecution().getExecutionContext());
    // read
    try {
        int count = 0;
        String line;
        while ((line = peekable.read()) != null) {
            assertEquals(String.valueOf(count), line);
            // test for peek
            String lineAhead = peekable.peek();
            if (count + 1 < EXPECTED_COUNT) {
                assertEquals(String.valueOf(count + 1), lineAhead);
            } else {
                assertNull(lineAhead);
            }
            count++;
        }
        assertEquals(EXPECTED_COUNT, count);
    } catch (Exception e) {
        throw e;
    } finally {
        peekable.close();
    }
}
Example 33
Project: spring-batch-master  File: LastModifiedResourceComparatorTests.java View source code
@Test
public void testCompareNewWithOldAfterCopy() throws Exception {
    File temp1 = new File("build/temp1.txt");
    File temp2 = new File("build/temp2.txt");
    if (temp1.exists())
        temp1.delete();
    if (temp2.exists())
        temp2.delete();
    temp1.getParentFile().mkdirs();
    temp2.createNewFile();
    assertTrue(!temp1.exists() && temp2.exists());
    // For Linux sleep here otherwise files show same
    // modified date
    Thread.sleep(1000);
    // Need to explicitly ask not to preserve the last modified date when we
    // copy...
    FileUtils.copyFile(new FileSystemResource(FILE_PATH).getFile(), temp1, false);
    assertEquals(1, comparator.compare(new FileSystemResource(temp1), new FileSystemResource(temp2)));
}
Example 34
Project: spring-boot-starter-master  File: AdditionalConfigurationMetadataTest.java View source code
@Test
public void testProperties() throws IOException {
    DocumentContext documentContext = JsonPath.parse(new FileSystemResource("src/main/resources/META-INF/additional-spring-configuration-metadata.json").getInputStream());
    List<Map<String, String>> properties = documentContext.read("$.properties");
    assertThat(properties.size(), is(1));
    // assert for default-scripting-language
    {
        Map<String, String> element = properties.get(0);
        assertThat(element.get("sourceType"), is("org.apache.ibatis.session.Configuration"));
        assertThat(element.get("defaultValue"), is("org.apache.ibatis.scripting.xmltags.XMLLanguageDriver"));
        assertThat(element.get("name"), is("mybatis.configuration.default-scripting-language"));
        assertThat(element.get("type"), is("java.lang.Class<? extends org.apache.ibatis.scripting.LanguageDriver>"));
    }
}
Example 35
Project: spring-ide-master  File: JavaModelSourceLocation.java View source code
public Resource getResource() {
    try {
        IJavaElement element = JdtUtils.getByHandle(handleIdentifier);
        if (element != null) {
            IResource resource = element.getUnderlyingResource();
            if (resource != null) {
                return new FileResource(resource.getFullPath().toString());
            }
            resource = element.getCorrespondingResource();
            if (resource != null) {
                return new FileResource(resource.getFullPath().toString());
            }
            resource = element.getResource();
            if (resource != null) {
                return new FileResource(resource.getFullPath().toString());
            }
            IPath path = element.getPath();
            if (path != null && path.toFile().exists()) {
                if (path.isAbsolute()) {
                    return new FileSystemResource(path.toFile());
                } else {
                    return new FileResource(path.toString());
                }
            }
        }
    } catch (JavaModelException e) {
    }
    return null;
}
Example 36
Project: spring-property-annotations-master  File: PropertyFileLoaderTest.java View source code
@Test
public void testCheckResourcesForUpdates() throws Exception {
    File test3 = new File(System.getProperty("java.io.tmpdir") + File.separator + "test3.properties");
    FileOutputStream output = new FileOutputStream(test3);
    Properties properties = new Properties();
    properties.setProperty("test3", "test3");
    properties.store(output, null);
    resources.add(new FileSystemResource(test3));
    loader.loadProperties();
    MockPropertyListener listener = new MockPropertyListener();
    loader.registerPropertyListener(listener);
    Thread.sleep(1000);
    properties.setProperty("test3", "updated");
    properties.store(output, null);
    loader.checkResourcesForUpdates();
    assertNotNull("property changed event not sent", listener.getEvent());
    assertEquals("property not found", "test3", listener.getEvent().getKey());
    assertEquals("property not correctly updated", "updated", listener.getEvent().getValue());
}
Example 37
Project: spring-security-kerberos-master  File: SpnegoConfig.java View source code
@Bean
public SunJaasKerberosTicketValidator sunJaasKerberosTicketValidator() {
    SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator();
    ticketValidator.setServicePrincipal("HTTP/servicehost.example.org@EXAMPLE.ORG");
    ticketValidator.setKeyTabLocation(new FileSystemResource("/tmp/service.keytab"));
    ticketValidator.setDebug(true);
    return ticketValidator;
}
Example 38
Project: strongbox-master  File: ConfigurationResourceResolver.java View source code
/**
     * @param configurationPath    The configuration file's path. If null, either propertyKey,
     *                             or propertyKeyDefaultValue must be specified.
     * @param propertyKey          The system property key to use when trying to load the configuration.
     * @param propertyDefaultValue The default property key value.
     * @return
     * @throws IOException
     */
public static Resource getConfigurationResource(String configurationPath, String propertyKey, String propertyDefaultValue) throws IOException {
    String filename;
    Resource resource;
    if (configurationPath != null && (!configurationPath.startsWith("classpath") && !(new File(configurationPath)).exists())) {
        configurationPath = null;
    }
    if (configurationPath != null) {
        if (configurationPath.toLowerCase().startsWith("classpath")) {
            // Load the resource from the classpath
            resource = new ClassPathResource(configurationPath);
        } else {
            // Load the resource from the file system
            resource = new FileSystemResource(new File(configurationPath).getAbsoluteFile());
        }
    } else {
        if (System.getProperty(propertyKey) != null) {
            filename = System.getProperty(propertyKey);
            resource = new FileSystemResource(new File(filename).getAbsoluteFile());
        } else {
            if (new File(propertyDefaultValue).exists()) {
                filename = propertyDefaultValue;
                resource = new FileSystemResource(new File(filename).getAbsoluteFile());
            } else {
                // This should only really be used for development and testing
                // of Strongbox and is not advised for production.
                resource = new ClassPathResource(propertyDefaultValue);
            }
        }
    }
    return resource;
}
Example 39
Project: tasq-master  File: RootConfig.java View source code
/**
     * Try to load properties file. First VM arg is searched, then Context paramater , and if non was passed default
     * application.properties is taken from resources
     *
     * @param environment
     * @return
     */
@Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(Environment environment) {
    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    String propertyLocation = System.getProperty("properties.location");
    String contextPropertyLocation = environment.getProperty("propertiesPath");
    if (StringUtils.isNotBlank(propertyLocation)) {
        ppc.setLocations(new FileSystemResource(propertyLocation));
    } else if (StringUtils.isNotBlank(contextPropertyLocation)) {
        ppc.setLocations(new FileSystemResource(contextPropertyLocation));
    } else {
        ppc.setLocations(new ClassPathResource("/application.properties"));
    }
    ppc.setIgnoreUnresolvablePlaceholders(true);
    return ppc;
}
Example 40
Project: yum-repo-server-master  File: PropertyConfig.java View source code
public Resource[] getPropertiesFileResources() {
    List<Resource> propertyResources = new ArrayList<>();
    for (String propertiesFile : PROPERTY_FILES) {
        Resource configurationResource = new ClassPathResource(propertiesFile);
        if (configurationResource.exists()) {
            propertyResources.add(configurationResource);
        }
    }
    if (System.getProperty(CONFIGURATION_FILE_PROPERTY) != null) {
        for (String propertyFilePath : commaDelimitedListToSet(System.getProperty(CONFIGURATION_FILE_PROPERTY))) {
            FileSystemResource configurationResource = new FileSystemResource(propertyFilePath);
            if (configurationResource.exists()) {
                propertyResources.add(configurationResource);
            }
        }
    }
    return propertyResources.toArray(new Resource[propertyResources.size()]);
}
Example 41
Project: building-microservices-master  File: BatchConfiguration.java View source code
@Bean
@StepScope
FlatFileItemReader<Person> flatFileItemReader(@Value("#{jobParameters[file]}") File file) {
    FlatFileItemReader<Person> r = new FlatFileItemReader<>();
    r.setResource(new FileSystemResource(file));
    r.setLineMapper(new DefaultLineMapper<Person>() {

        {
            this.setLineTokenizer(new DelimitedLineTokenizer(",") {

                {
                    this.setNames(new String[] { "first", "last", "email" });
                }
            });
            this.setFieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {

                {
                    this.setTargetType(Person.class);
                }
            });
        }
    });
    return r;
}
Example 42
Project: c24-spring-master  File: FileWriterSourceTests.java View source code
@Test
public void testResource() throws IOException {
    // Confirm that FileWriterSource uses the resource if we supply one
    // Get somewhere temporary to write out to    
    File outputFile = File.createTempFile("ItemWriterTest-", ".csv");
    outputFile.deleteOnExit();
    String outputFileName = outputFile.getAbsolutePath();
    FileSystemResource resource = new FileSystemResource(outputFileName);
    FileWriterSource source = new FileWriterSource();
    source.setResource(resource);
    // Mock up JobParams without output.file
    JobParameters params = mock(JobParameters.class);
    StepExecution execution = mock(StepExecution.class);
    when(execution.getJobParameters()).thenReturn(params);
    source.initialise(execution);
    final String testString = "testDefaultResource";
    source.getWriter().write(testString);
    source.close();
    // Read the file back and confirm it contains the test string
    BufferedReader reader = new BufferedReader(new FileReader(outputFile));
    assertThat(reader.readLine(), is(testString));
    reader.close();
}
Example 43
Project: citrus-master  File: PropertyPlaceholderTests.java View source code
@Test
public void systemPropertyValue() {
    System.setProperty("productionMode", "true");
    factory = new XmlApplicationContext(new FileSystemResource(new File(srcdir, "property-placeholder.xml")));
    conf = (Configuration) factory.getBean("simpleConfiguration");
    // ${productionMode:false}
    assertEquals(true, conf.isProductionMode());
}
Example 44
Project: constellation-master  File: ImageResolverController.java View source code
@RequestMapping(value = "/{mdIdentifierSHA1}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity get(@PathVariable("mdIdentifierSHA1") String mdIdentifierSHA1, final HttpServletResponse response) {
    if (mdIdentifierSHA1 != null) {
        final File metadataCfgDir = ConfigDirectory.getMetadataDirectory();
        final File metadataFolder = new File(metadataCfgDir, mdIdentifierSHA1);
        final File quickLook = new File(metadataFolder, mdIdentifierSHA1);
        if (metadataFolder.exists()) {
            response.setCharacterEncoding("UTF-8");
            final HttpHeaders responseHeaders = new HttpHeaders();
            try {
                //try to get the content type of the file
                final String contentType = Files.probeContentType(quickLook.toPath());
                final String mediaType = MediaType.valueOf(contentType).toString();
                response.setContentType(mediaType);
                responseHeaders.set("Content-Type", mediaType);
            } catch (Exception ex) {
                LOGGER.warn(ex.getLocalizedMessage(), ex);
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                responseHeaders.set("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
            }
            final FileSystemResource fsResource = new FileSystemResource(quickLook);
            return new ResponseEntity<>(fsResource, responseHeaders, HttpStatus.OK);
        }
    }
    return null;
}
Example 45
Project: cougar-master  File: X509CertificateUtilsTest.java View source code
@Test
public void javaToJavaxToJava() throws Exception {
    KeyStoreManagement ksm = KeyStoreManagement.getKeyStoreManagement("JKS", new FileSystemResource(KeyStoreManagementTest.getKeystorePath()), "password");
    KeyStore ks = ksm.getKeyStore();
    long start = System.nanoTime();
    java.security.cert.X509Certificate c1 = (java.security.cert.X509Certificate) ks.getCertificate("selfsigned");
    javax.security.cert.X509Certificate c2 = X509CertificateUtils.convert(c1);
    java.security.cert.X509Certificate c3 = X509CertificateUtils.convert(c2);
    long total = System.nanoTime() - start;
    System.out.println("Total time: " + total);
    assertEquals(c1, c3);
}
Example 46
Project: crux-security-core-master  File: ResourceSecurityWrapperStore.java View source code
public void loadWrappers(String[] locations) throws ResourceStoreException {
    for (String location : locations) {
        File file = new File(location);
        FileSystemResource resource = new FileSystemResource(file);
        try {
            loadWrappers(resource.getURL().toExternalForm());
        } catch (IOException ioe) {
            throw new ResourceStoreException(ioe);
        }
    }
}
Example 47
Project: cta-otp-master  File: GraphBuilderMain.java View source code
public static ApplicationContext createContext(Iterable<String> paths, Map<String, BeanDefinition> additionalBeans) {
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    for (String path : paths) {
        if (path.startsWith(CLASSPATH_PREFIX)) {
            path = path.substring(CLASSPATH_PREFIX.length());
            xmlReader.loadBeanDefinitions(new ClassPathResource(path));
        } else if (path.startsWith(FILE_PREFIX)) {
            path = path.substring(FILE_PREFIX.length());
            xmlReader.loadBeanDefinitions(new FileSystemResource(path));
        } else {
            xmlReader.loadBeanDefinitions(new FileSystemResource(path));
        }
    }
    for (Map.Entry<String, BeanDefinition> entry : additionalBeans.entrySet()) ctx.registerBeanDefinition(entry.getKey(), entry.getValue());
    ctx.refresh();
    ctx.registerShutdownHook();
    return ctx;
}
Example 48
Project: eMonocot-master  File: StaxWriterTest.java View source code
/**
	 * @throws Exception
	 */
@Before
public void setUp() throws Exception {
    writer = new StaxEventItemWriter();
    writer.setResource(new FileSystemResource("target/test-outputs/StaxWriterTest.xml"));
    writer.setRootTagName("urlset");
    XStreamMarshaller marshaller = new XStreamMarshaller();
    Map<String, Object> aliases = new HashMap<String, Object>();
    aliases.put("url", Url.class);
    marshaller.setAliases(aliases);
    writer.setMarshaller(marshaller);
    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put("xmlns", "http://www.sitemaps.org/schemas/sitemap");
    writer.setRootElementAttributes(attributes);
}
Example 49
Project: genie-master  File: JobConfigIntegrationTest.java View source code
/**
     * Returns a temporary directory as the jobs resource.
     *
     * @return The job dir as a resource.
     * @throws IOException If there is a problem.
     */
@Bean
public Resource jobsDir() throws IOException {
    this.jobsDir = Files.createTempDir();
    if (!this.jobsDir.exists() && !this.jobsDir.mkdirs()) {
        throw new IllegalArgumentException("Unable to create directories: " + this.jobsDir);
    }
    String jobsDirPath = this.jobsDir.getAbsolutePath();
    final String slash = "/";
    if (!jobsDirPath.endsWith(slash)) {
        jobsDirPath = jobsDirPath + slash;
    }
    return new FileSystemResource(jobsDirPath);
}
Example 50
Project: jabm-master  File: BeanFactorySingleton.java View source code
public static void initialiseFactory() {
    Properties systemProperties = SystemProperties.jabsConfiguration();
    String configFile = systemProperties.getProperty(SystemProperties.PROPERTY_CONFIG);
    if (configFile == null) {
        throw new IllegalArgumentException("Must specify a configuration file by setting the system property " + SystemProperties.PROPERTY_BASE + "." + SystemProperties.PROPERTY_CONFIG);
    }
    initialiseFactory(new FileSystemResource(configFile));
}
Example 51
Project: kylo-master  File: KerberosSpnegoConfiguration.java View source code
@Bean
public SunJaasKerberosTicketValidator sunJaasKerberosTicketValidator() {
    SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator();
    ticketValidator.setServicePrincipal(servicePrincipal);
    ticketValidator.setKeyTabLocation(new FileSystemResource(keytabLocation));
    ticketValidator.setDebug(true);
    return ticketValidator;
}
Example 52
Project: magnificent-mileage-master  File: GraphBuilderMain.java View source code
public static ApplicationContext createContext(Iterable<String> paths, Map<String, BeanDefinition> additionalBeans) {
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    for (String path : paths) {
        if (path.startsWith(CLASSPATH_PREFIX)) {
            path = path.substring(CLASSPATH_PREFIX.length());
            xmlReader.loadBeanDefinitions(new ClassPathResource(path));
        } else if (path.startsWith(FILE_PREFIX)) {
            path = path.substring(FILE_PREFIX.length());
            xmlReader.loadBeanDefinitions(new FileSystemResource(path));
        } else {
            xmlReader.loadBeanDefinitions(new FileSystemResource(path));
        }
    }
    for (Map.Entry<String, BeanDefinition> entry : additionalBeans.entrySet()) ctx.registerBeanDefinition(entry.getKey(), entry.getValue());
    ctx.refresh();
    ctx.registerShutdownHook();
    return ctx;
}
Example 53
Project: nifi-master  File: KerberosServiceFactoryBean.java View source code
private KerberosTicketValidator createTicketValidator() throws Exception {
    SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator();
    ticketValidator.setServicePrincipal(properties.getKerberosSpnegoPrincipal());
    ticketValidator.setKeyTabLocation(new FileSystemResource(properties.getKerberosSpnegoKeytabLocation()));
    ticketValidator.afterPropertiesSet();
    return ticketValidator;
}
Example 54
Project: Raildelays-master  File: ResourceLocatorItemStreamWriterTest.java View source code
/**
     * We expect that the onWrite() method build a path by appending items into one String.
     */
@Test
public void testWrite() throws Exception {
    ExecutionContext executionContext = new ExecutionContext();
    delegator.setResourceLocator(new CountingItemResourceLocator<String>() {

        @Override
        public void onWrite(String item, ResourceContext context) throws ItemStreamException {
            context.changeResource(new FileSystemResource(item));
        }
    });
    delegator.open(executionContext);
    delegator.write(Arrays.asList("a", "b", "c"));
    delegator.update(executionContext);
    try {
        Assert.assertEquals("c", delegate.getResource().getFile().getPath());
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
    delegator.close();
}
Example 55
Project: rayo-server-master  File: PropertiesBasedStorageServiceClient.java View source code
/**
	 * Initializes the client
	 */
public void init(ApplicationContext context, Properties properties) {
    logger.info("Initializing data store");
    storageService = new DefaultGatewayStorageService();
    String propertiesFile = properties.getProperty(ROUTING_PROPERTIES_FILE);
    if (propertiesFile == null) {
        propertiesFile = DEFAULT_ROUTING_PROPERTIES_FILE;
    }
    Resource resource = null;
    File pFile = new File(propertiesFile);
    if (pFile.exists()) {
        resource = new FileSystemResource(pFile);
    } else {
        resource = new ClassPathResource(propertiesFile);
    }
    logger.debug("Loading configuration file from classpath [%s]", propertiesFile);
    if (!resource.isReadable()) {
        logger.debug("Could not find configuration file in classpath. Loading it from file system instead.");
        resource = new FileSystemResource(propertiesFile);
        if (!resource.isReadable()) {
            throw new IllegalStateException(String.format("Could not find configuration file [%s]", propertiesFile));
        }
    }
    int interval = DEFAULT_RELOAD_INTERVAL;
    String reloadInterval = properties.getProperty(PROPERTIES_RELOAD_INTERVAL);
    if (reloadInterval != null) {
        try {
            interval = Integer.valueOf(reloadInterval);
        } catch (NumberFormatException nfe) {
            logger.error(nfe.getMessage(), nfe);
        }
    }
    try {
        store = new PropertiesBasedDatastore(resource, interval);
    } catch (IOException e) {
        throw new IllegalStateException("Could not load storage client configuration", e);
    }
    ((DefaultGatewayStorageService) storageService).setStore(store);
}
Example 56
Project: spring-batch-examples-complex-master  File: GetLineCountTaskletTest.java View source code
@Test
public void testExecute() throws Exception {
    // setup
    tasklet = new GetLineCountTasklet();
    tasklet.setResource(new FileSystemResource(INPUT));
    StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution();
    // execute
    RepeatStatus status = tasklet.execute(new StepContribution(stepExecution), new ChunkContext(new StepContext(stepExecution)));
    // assertions
    assertEquals(RepeatStatus.FINISHED, status);
    assertEquals(EXPECTED_COUNT, stepExecution.getExecutionContext().get("line.count"));
}
Example 57
Project: spring-boot-master  File: LogFileMvcEndpoint.java View source code
private Resource getLogFileResource() {
    if (this.externalFile != null) {
        return new FileSystemResource(this.externalFile);
    }
    LogFile logFile = LogFile.get(getEnvironment());
    if (logFile == null) {
        logger.debug("Missing 'logging.file' or 'logging.path' properties");
        return null;
    }
    return new FileSystemResource(logFile.toString());
}
Example 58
Project: spring-crypto-utils-master  File: DefaultKeyStoreFactoryBean.java View source code
public void afterPropertiesSet() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, InitializationException {
    final String keyStoreLocation = System.getProperty("javax.net.ssl.keyStore");
    if (keyStoreLocation == null || keyStoreLocation.trim().length() == 0) {
        throw new InitializationException("no value was specified for the system property: javax.net.ssl.keyStore");
    }
    final String password = System.getProperty("javax.net.ssl.keyStorePassword");
    final Resource location = new FileSystemResource(keyStoreLocation);
    keystore = KeyStore.getInstance("JKS");
    keystore.load(location.getInputStream(), password.toCharArray());
}
Example 59
Project: spring-integration-samples-master  File: ScriptTests.java View source code
@Test
public void testRuby() {
    ScriptExecutor executor = ScriptExecutorFactory.getScriptExecutor("ruby");
    Order order = new Order(0);
    order.addItem(DrinkType.LATTE, 2, false);
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("payload", order.getItems().get(0));
    variables.put("timeToPrepare", 1L);
    Object obj = executor.executeScript(new ResourceScriptSource(new FileSystemResource("scripts/ruby/barista.rb")), variables);
    assertNotNull(obj);
    assertTrue(obj instanceof Drink);
}
Example 60
Project: spring-modules-jcr-master  File: RepositoryFactoryBean.java View source code
/**
	 * @see org.springmodules.jcr.RepositoryFactoryBean#resolveConfigurationResource()
	 */
protected void resolveConfigurationResource() throws Exception {
    // read the configuration object
    if (repositoryConfig != null)
        return;
    if (this.configuration == null) {
        if (log.isDebugEnabled())
            log.debug("no configuration resource specified, using the default one:" + DEFAULT_CONF_FILE);
        configuration = new ClassPathResource(DEFAULT_CONF_FILE);
    }
    if (homeDir == null) {
        if (log.isDebugEnabled())
            log.debug("no repository home dir specified, using the default one:" + DEFAULT_REP_DIR);
        homeDir = new FileSystemResource(DEFAULT_REP_DIR);
    }
    repositoryConfig = RepositoryConfig.create(new InputSource(configuration.getInputStream()), homeDir.getFile().getAbsolutePath());
}
Example 61
Project: spring-social-flickr-master  File: Main.java View source code
/**
     * I do this because I don't want to constantly specify the properties on the command line and I don't wan to check in
     * the properties on github in a public repository since I'm working with my own photos.
     * <p/>
     * Refer to the code below to see the properties required. They are fairly self explanatory.
     *
     * @param applicationContext the application context
     * @param <T>                the exception
     * @throws Throwable
     */
private static <T extends AbstractApplicationContext> void registerPropertiesForFlickrConnection(T applicationContext) throws Throwable {
    File propertiesFile = new File(new File(SystemUtils.getUserHome(), "Desktop"), "flickr.properties");
    Assert.isTrue(propertiesFile.exists(), "the flickr.properties file must exist.");
    Resource propertiesResource = new FileSystemResource(propertiesFile);
    Properties properties = new Properties();
    properties.load(propertiesResource.getInputStream());
    PropertiesPropertySource mapPropertySource = new PropertiesPropertySource("flickr", properties);
    applicationContext.getEnvironment().getPropertySources().addLast(mapPropertySource);
}
Example 62
Project: webanno-master  File: WebAnnoApplicationContextInitializer.java View source code
@Override
public void initialize(ConfigurableApplicationContext aApplicationContext) {
    LoggingFilter.setLoggingUsername("SYSTEM");
    log.info("  _      __    __   ___                ");
    log.info(" | | /| / /__ / /  / _ | ___  ___  ___ ");
    log.info(" | |/ |/ / -_) _ \\/ __ |/ _ \\/ _ \\/ _ \\");
    log.info(" |__/|__/\\__/_.__/_/ |_/_//_/_//_/\\___/");
    log.info(SettingsUtil.getVersionString());
    ConfigurableEnvironment aEnvironment = aApplicationContext.getEnvironment();
    File settings = SettingsUtil.getSettingsFile();
    // If settings were found, add them to the environment
    if (settings != null) {
        log.info("Settings: " + settings);
        try {
            aEnvironment.getPropertySources().addFirst(new ResourcePropertySource(new FileSystemResource(settings)));
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
    // Activate bean profile depending on authentication mode
    if (AUTH_MODE_PREAUTH.equals(aEnvironment.getProperty(SettingsUtil.CFG_AUTH_MODE))) {
        aEnvironment.setActiveProfiles(PROFILE_PREAUTH);
        log.info("Authentication: pre-auth");
    } else {
        aEnvironment.setActiveProfiles(PROFILE_DATABASE);
        log.info("Authentication: database");
    }
}
Example 63
Project: com.revolsys.open-master  File: Resource.java View source code
static File getFileOrCreateTempFile(final Resource resource) {
    try {
        if (resource instanceof FileSystemResource) {
            return resource.getFile();
        } else {
            final String filename = resource.getFilename();
            final String baseName = FileUtil.getBaseName(filename);
            final String fileExtension = FileNames.getFileNameExtension(filename);
            return File.createTempFile(baseName, fileExtension);
        }
    } catch (final IOException e) {
        throw new RuntimeException("Unable to get file for " + resource, e);
    }
}
Example 64
Project: activemq-artemis-master  File: ResourceLoadingSslContext.java View source code
public static Resource resourceFromString(String uri) throws MalformedURLException {
    Resource resource;
    File file = new File(uri);
    if (file.exists()) {
        resource = new FileSystemResource(uri);
    } else if (ResourceUtils.isUrl(uri)) {
        resource = new UrlResource(uri);
    } else {
        resource = new ClassPathResource(uri);
    }
    return resource;
}
Example 65
Project: cagrid2-master  File: ConfigureGlobusToTrustDorian.java View source code
public static void main(String[] args) {
    Options options = new Options();
    Option help = new Option(HELP_OPT, HELP_OPT_FULL, false, "Prints this message.");
    Option conf = new Option(CONFIG_FILE_OPT, CONFIG_FILE_FULL, true, "The config file for the Dorian CA.");
    conf.setRequired(true);
    Option props = new Option(PROPERTIES_FILE_OPT, PROPERTIES_FILE_FULL, true, "The properties file for the Dorian CA.");
    props.setRequired(true);
    options.addOption(props);
    options.addOption(help);
    options.addOption(conf);
    try {
        CommandLineParser parser = new PosixParser();
        CommandLine line = parser.parse(options, args);
        if (line.getOptionValue(HELP_OPT) != null) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(ConfigureGlobusToTrustDorian.class.getName(), options);
            System.exit(0);
        } else {
            String configFile = line.getOptionValue(CONFIG_FILE_OPT);
            String propertiesFile = line.getOptionValue(PROPERTIES_FILE_OPT);
            BeanUtils utils = new BeanUtils(new FileSystemResource(configFile), new FileSystemResource(propertiesFile));
            utils.getDatabase().createDatabaseIfNeeded();
            CertificateAuthority ca = utils.getCertificateAuthority();
            X509Certificate cacert = ca.getCACertificate();
            File dir = Utils.getTrustedCerificatesDirectory();
            File caFile = new File(dir.getAbsolutePath() + File.separator + CertUtil.getHashCode(cacert) + ".0");
            File policyFile = new File(dir.getAbsolutePath() + File.separator + CertUtil.getHashCode(cacert) + ".signing_policy");
            CertUtil.writeCertificate(cacert, caFile);
            CertUtil.writeSigningPolicy(cacert, policyFile);
            System.out.println("Succesfully configured Globus to trust the Dorian CA: " + cacert.getSubjectDN().getName());
            System.out.println("Succesfully wrote CA certificate to " + caFile.getAbsolutePath());
            System.out.println("Succesfully wrote CA signing policy to " + policyFile.getAbsolutePath());
        }
    } catch (ParseException exp) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ConfigureGlobusToTrustDorian.class.getName(), options, false);
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}
Example 66
Project: cas-master  File: RegisteredServicePublicKeyImpl.java View source code
@Override
public PublicKey createInstance() throws Exception {
    try {
        final PublicKeyFactoryBean factory = this.publicKeyFactoryBeanClass.newInstance();
        if (this.location.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {
            factory.setLocation(new ClassPathResource(StringUtils.removeStart(this.location, ResourceUtils.CLASSPATH_URL_PREFIX)));
        } else {
            factory.setLocation(new FileSystemResource(this.location));
        }
        factory.setAlgorithm(this.algorithm);
        factory.setSingleton(false);
        return factory.getObject();
    } catch (final Exception e) {
        LOGGER.warn(e.getMessage(), e);
        throw Throwables.propagate(e);
    }
}
Example 67
Project: cms-ce-master  File: VirtualHostResolver.java View source code
/**
     * Configure property.
     */
public void configureVirtualHosts() {
    final File file = new File(this.configFile);
    if (file.exists()) {
        try {
            final ArrayList<VirtualHost> virtualHosts = new ArrayList<VirtualHost>();
            final Properties properties = PropertiesLoaderUtils.loadProperties(new FileSystemResource(file));
            for (final Object key : properties.keySet()) {
                final String pattern = key.toString();
                final String targetPath = properties.getProperty(pattern);
                addVirtualHost(virtualHosts, pattern, targetPath);
            }
            // strange sort, that may introduce problems.
            Collections.sort(virtualHosts);
            this.virtualHosts.lazySet(virtualHosts);
        } catch (Exception e) {
            LOG.error("cannot configure virtual hosts !", e);
        }
    } else {
        this.virtualHosts.lazySet(new ArrayList<VirtualHost>());
    }
}
Example 68
Project: cruisecontrol-master  File: TemplateRenderService.java View source code
private void loadTemplate(String name) throws IOException {
    Resource resource;
    if (servletContext != null) {
        resource = new ServletContextResource(servletContext, resourceLoaderPath + "/" + name);
    } else {
        resource = new FileSystemResource("webapp/" + resourceLoaderPath + "/" + name);
    }
    if (!resource.exists()) {
        throw new RuntimeException("Failed to load template from [" + resource.getFile().getAbsolutePath() + "].");
    }
    templates.put(name, IOUtils.toString(resource.getInputStream()));
}
Example 69
Project: fcrepo-before33-master  File: AkubraLowlevelStorageModule.java View source code
@Override
public void postInitModule() throws ModuleInitializationException {
    File beanFile = new File(new File(Constants.FEDORA_HOME), "server/config/akubra-llstore.xml");
    try {
        Resource beanResource = new FileSystemResource(beanFile);
        BeanFactory factory = new XmlBeanFactory(beanResource);
        impl = (ILowlevelStorage) factory.getBean(getRole());
    } catch (BeansException e) {
        throw new ModuleInitializationException("Error initializing " + "from " + beanFile.getPath(), getRole(), e);
    }
}
Example 70
Project: geoserver-enterprise-master  File: JMSPropertyPlaceholderConfigurer.java View source code
@Override
public void afterPropertiesSet() throws Exception {
    File properties = new File(config.getConfiguration(EmbeddedBrokerConfiguration.EMBEDDED_BROKER_PROPERTIES_KEY).toString());
    if (!properties.isAbsolute() && !properties.isFile()) {
        // try to resolve as absolute
        properties = new File(JMSConfiguration.getConfigPathDir(), properties.getPath());
        if (!properties.isFile()) {
            // copy the defaults
            IOUtils.copy(defaults.getFile(), properties);
        }
    }
    final Resource res = new FileSystemResource(properties);
    super.setLocation(res);
    // make sure the activemq.base is set to a valuable default 
    final Properties props = new Properties();
    props.setProperty("activemq.base", (String) config.getConfiguration("CLUSTER_CONFIG_DIR"));
    props.setProperty("instanceName", (String) config.getConfiguration("instanceName"));
    setProperties(props);
}
Example 71
Project: hdiv-archive-master  File: FreeMarkerConfigurerTests.java View source code
public void testFreemarkerConfigurationFactoryBeanWithConfigLocation() throws TemplateException {
    FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
    fcfb.setConfigLocation(new FileSystemResource("myprops.properties"));
    Properties props = new Properties();
    props.setProperty("myprop", "/mydir");
    fcfb.setFreemarkerSettings(props);
    try {
        fcfb.afterPropertiesSet();
        fail("Should have thrown IOException");
    } catch (IOException ex) {
    }
}
Example 72
Project: InSpider-master  File: FeatureCompletenessChecker.java View source code
private List<Resource> createGetFeatureResourcesAllDatasets() throws JaxenException, XMLStreamException, FactoryConfigurationError, IOException {
    List<Resource> getFeatureResourcesAllDatasets = new ArrayList<Resource>();
    List<Dataset> datasets = managerDao.getAllDatasets();
    int quantityDatasetsLoadedInInspireSchema = 0;
    for (Iterator<Dataset> datasetIterator = datasets.iterator(); datasetIterator.hasNext(); ) {
        Dataset dataset = (Dataset) datasetIterator.next();
        EtlJob job = managerDao.getLastSuccessfullImportJob(dataset.getBronhouder(), dataset.getDatasetType(), dataset.getUuid());
        if (job != null) {
            //fileCache.getFiledir(job);
            String fileCacheDir = null;
            //fileCache.getFilename(job);
            String file = null;
            Resource cachedResource = new FileSystemResource(fileCacheDir + System.getProperty("file.separator") + file);
            logger.debug("Adding cachedResource(" + quantityDatasetsLoadedInInspireSchema + ") " + "\"" + cachedResource.getDescription() + "\" to the cached-resources-list.");
            getFeatureResourcesAllDatasets.add(cachedResource);
            quantityDatasetsLoadedInInspireSchema++;
        }
    }
    logger.debug("Quantity of datasets that resulted in features in inspire schema:" + quantityDatasetsLoadedInInspireSchema);
    return getFeatureResourcesAllDatasets;
}
Example 73
Project: iris-master  File: SpringDSLPropertiesFactoryBean.java View source code
@Override
public void setLocations(Resource[] locations) {
    List<Resource> tmpLocations = new ArrayList<Resource>();
    Map<String, Boolean> fileNames = new HashMap<String, Boolean>();
    tmpLocations.addAll(Arrays.asList(locations));
    for (String pathToDirectory : configLoader.getIrisConfigDirPaths()) {
        File irisResourceDir = new File(pathToDirectory);
        File[] files = irisResourceDir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.matches(filenamePattern);
            }
        });
        for (File file : files) {
            // Create a resource for a current file and add it to the collection of properties resources
            if (!fileNames.containsKey(file.getName())) {
                fileNames.put(file.getName(), true);
                tmpLocations.add(new FileSystemResource(file));
            }
        }
    }
    super.setLocations(tmpLocations.toArray(new Resource[0]));
}
Example 74
Project: java-buildpack-auto-reconfiguration-master  File: StandardCloudUtilsTest.java View source code
@Test
public void isUsingCloudServices() throws IOException {
    when(this.applicationContext.getResources("classpath*:/META-INF/cloud/cloud-services")).thenReturn(new Resource[] { new FileSystemResource("src/test/resources/cloud-services") });
    when(this.applicationContext.getBeanNamesForType(UnusedCloudService.class, true, false)).thenReturn(new String[0]);
    when(this.applicationContext.getBeanNamesForType(UsedCloudService.class, true, false)).thenReturn(new String[] { "used-cloud-service-bean-name" });
    assertTrue(this.cloudUtils.isUsingCloudServices(this.applicationContext));
}
Example 75
Project: javasousuo-master  File: InstantiatingContainerTest.java View source code
@Test
public void testXmlBeanFactoryBaseOnFileSystem() {
    //1.准备�置文件,从文件系统获��置文件,默认是相对路径,�以指定�对路径
    File file = new File("fileSystemConfig.xml");
    Resource resource = new FileSystemResource(file);
    //2.�始化容器
    BeanFactory beanFactory = new XmlBeanFactory(resource);
    //2�从容器中获�Bean
    HelloApi helloApi = beanFactory.getBean("hello", HelloApi.class);
    //3�执行业务逻辑
    helloApi.sayHello();
}
Example 76
Project: jcr-springextension-master  File: RepositoryFactoryBean.java View source code
/**
     * @see org.springframework.extensions.jcr.RepositoryFactoryBean#resolveConfigurationResource()
     */
protected void resolveConfigurationResource() throws Exception {
    // read the configuration object
    if (repositoryConfig != null)
        return;
    if (this.configuration == null) {
        if (LOG.isDebugEnabled())
            LOG.debug("no configuration resource specified, using the default one:" + DEFAULT_CONF_FILE);
        configuration = new ClassPathResource(DEFAULT_CONF_FILE);
    }
    if (homeDir == null) {
        if (LOG.isDebugEnabled())
            LOG.debug("no repository home dir specified, using the default one:" + DEFAULT_REP_DIR);
        homeDir = new FileSystemResource(DEFAULT_REP_DIR);
    }
    repositoryConfig = RepositoryConfig.create(new InputSource(configuration.getInputStream()), homeDir.getFile().getAbsolutePath());
}
Example 77
Project: jwebsocket-server-api-master  File: JWebSocketBeanFactory.java View source code
/**
     * Load beans from a configuration file into a specific bean factory
     *
     * @param aNamespace
     * @param aPath
     * @param aClassLoader
     */
public static void load(String aNamespace, String aPath, ClassLoader aClassLoader) {
    String lPath = Tools.expandEnvVarsAndProps(aPath);
    XmlBeanDefinitionReader lXmlReader;
    if (null != aNamespace) {
        lXmlReader = new XmlBeanDefinitionReader(getInstance(aNamespace));
    } else {
        lXmlReader = new XmlBeanDefinitionReader(getInstance());
    }
    lXmlReader.setBeanClassLoader(aClassLoader);
    // System.out.println("getJWebSocketHome: '" + JWebSocketConfig.getJWebSocketHome() + "'...");
    if (JWebSocketConfig.getJWebSocketHome().isEmpty()) {
        // System.out.println("Loading resource from classpath: " + aPath + "...");
        lXmlReader.loadBeanDefinitions(new ClassPathResource(lPath));
    } else {
        // System.out.println("Loading resource from filesystem: " + aPath + "...");
        lXmlReader.loadBeanDefinitions(new FileSystemResource(lPath));
    }
}
Example 78
Project: karate-master  File: UploadController.java View source code
@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));
}
Example 79
Project: ldp4j-master  File: MonitorizedPropertyPlaceholderConfigurerTest.java View source code
@Before
public void setUp() throws Exception {
    Properties property = new Properties();
    property.setProperty("finalProperty", "other value");
    File tmpFile = folder.newFile("dynamicValues.cfg");
    OutputStream out = null;
    try {
        out = new FileOutputStream(tmpFile);
        property.store(out, "Test values");
    } finally {
        out.close();
    }
    File otherFile = folder.newFile("otherValues.cfg");
    property.setProperty("finalProperty", "my value");
    try {
        out = new FileOutputStream(otherFile);
        property.store(out, "Other test values");
    } finally {
        out.close();
    }
    this.customResource = CustomInputStreamResource.create(otherFile);
    this.locations = new Resource[] { new FileSystemResource(tmpFile), new ClassPathResource("resource.properties"), new ClassPathResource("nonExistingResource.properties"), this.customResource, new UrlResource(this.getClass().getResource("/otherResource.cfg")), new OsgiBundleResource(new CustomBundle(BUNDLE_ID, BUNDLE_SYMBOLIC_NAME), "/path") };
}
Example 80
Project: manager.v3-master  File: AnchoredFileSystemXmlApplicationContext.java View source code
/**
   * Resolve resource paths as file system paths.
   * <p>Note: Even if a given path starts with a slash, it will get
   * interpreted as relative to the baseDirectory.
   * This is consistent with the semantics in a Servlet container.
   *
   * @param path path to the resource
   * @return Resource handle
   */
@Override
protected Resource getResourceByPath(String path) {
    if (path != null && path.startsWith("/")) {
        path = path.substring(1);
    }
    if (new File(path).isAbsolute()) {
        // We could still get an absolute path via the file: url work-around.
        return new FileSystemResource(path);
    } else {
        return new FileSystemResource(new File(baseDirectory, path));
    }
}
Example 81
Project: micro-server-master  File: PropertyFileConfig.java View source code
private Optional<Resource> loadProperties(String applicationPropertyFileName, String type) {
    Optional<Resource> resource = Optional.empty();
    if (new File("./" + applicationPropertyFileName).exists()) {
        resource = Optional.of(new FileSystemResource(new File("./" + applicationPropertyFileName)));
        logger.info("./" + applicationPropertyFileName + " added");
    }
    URL urlResource = PropertyFileConfig.class.getClassLoader().getResource(applicationPropertyFileName);
    if (urlResource != null) {
        resource = Optional.of(new UrlResource(urlResource));
        logger.info(applicationPropertyFileName + " added");
    }
    if (System.getProperty(type + ".env") != null) {
        URL envResource = PropertyFileConfig.class.getClassLoader().getResource(createEnvBasedPropertyFileName(applicationPropertyFileName));
        if (envResource != null) {
            resource = Optional.of(new UrlResource(envResource));
            logger.info(createEnvBasedPropertyFileName(applicationPropertyFileName) + " added");
        }
    }
    if (System.getProperty(type + ".property.file") != null) {
        resource = Optional.of(new FileSystemResource(new File(System.getProperty(type + ".property.file"))));
        logger.info(System.getProperty("application.property.file") + " added");
    }
    return resource;
}
Example 82
Project: OpenSpaces-master  File: PUPathMatchingResourcePatternResolver.java View source code
protected Set doFindMatchingFileSystemResources(File rootDir, String subPattern) throws IOException {
    Set result = super.doFindMatchingFileSystemResources(rootDir, subPattern);
    Set actualResult = new LinkedHashSet();
    for (Object val : result) {
        if (!(val instanceof FileSystemResource)) {
            continue;
        }
        FileSystemResource fsResource = (FileSystemResource) val;
        if (fsResource.getFile() instanceof WebsterFile) {
            WebsterFile websterFile = (WebsterFile) fsResource.getFile();
            actualResult.add(new UrlResource(websterFile.toURL()));
        } else {
            actualResult.add(fsResource);
        }
    }
    return actualResult;
}
Example 83
Project: orchidae-master  File: Starter.java View source code
private ServletContextHandler getServletContextHandler(AnnotationConfigWebApplicationContext context) throws IOException {
    ServletContextHandler servletContext = new ServletContextHandler();
    servletContext.addEventListener(new ContextLoaderListener(context));
    ServletHolder holder = new ServletHolder("default", new DispatcherServlet(context));
    holder.getRegistration().setMultipartConfig(new MultipartConfigElement("./tmp", 20000000, 20000000, 200000));
    servletContext.addServlet(holder, "/*");
    servletContext.addEventListener(new ServletListener(context));
    servletContext.setResourceBase(new FileSystemResource(new File("./")).toString());
    servletContext.setSessionHandler(new SessionHandler());
    return servletContext;
}
Example 84
Project: pentaho-platform-master  File: GwtRpcProxyServlet.java View source code
protected ApplicationContext getAppContext() {
    WebApplicationContext parent = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
    ConfigurableWebApplicationContext wac = new XmlWebApplicationContext() {

        @Override
        protected Resource getResourceByPath(String path) {
            return new FileSystemResource(new File(path));
        }
    };
    wac.setParent(parent);
    wac.setServletContext(getServletContext());
    wac.setServletConfig(getServletConfig());
    wac.setNamespace(getServletName());
    String springFile = PentahoSystem.getApplicationContext().getSolutionPath(//$NON-NLS-1$ //$NON-NLS-2$
    "system" + File.separator + "pentahoServices.spring.xml");
    wac.setConfigLocations(new String[] { springFile });
    wac.refresh();
    return wac;
}
Example 85
Project: project-latex-master  File: EmailCameraDataWriter.java View source code
void sendMail(File imageFile) {
    int attemptCount = 0;
    boolean success = false;
    while (!success && attemptCount < maxNumberOfEmailAttempts) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setTo(toAddress);
            messageHelper.setFrom(fromAddress);
            messageHelper.setSubject(imageFile.getName());
            messageHelper.setText(EMAIL_BODY_TEXT);
            FileSystemResource fileResource = new FileSystemResource(imageFile);
            messageHelper.addAttachment(imageFile.getName(), fileResource);
            mailSender.send(message);
            success = true;
        } catch (MailExceptionMessagingException |  e) {
            logger.error("Email attempt " + attemptCount + " failed: " + e.getMessage());
            try {
                Thread.sleep(delayBetweenEmailAttemptsMs);
            } catch (InterruptedException ex) {
                logger.error(ex.getMessage());
            }
        } finally {
            ++attemptCount;
        }
    }
    if (!success) {
        logger.error("Failed to send email containing " + imageFile.getName());
    }
}
Example 86
Project: smsc-server-master  File: SpringConfigTest.java View source code
public void test() throws Throwable {
    // FIXME: Hasan variable not expanded
    System.setProperty("SMSC_HOME", "./target/");
    XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("src/test/resources/spring-config/config-spring-1.xml"));
    DefaultSmscServer server = (DefaultSmscServer) factory.getBean("server");
    Assert.assertEquals(500, server.getServerContext().getConnectionConfig().getMaxBinds());
    Assert.assertEquals(124, server.getServerContext().getConnectionConfig().getMaxBindFailures());
    Assert.assertEquals(125, server.getServerContext().getConnectionConfig().getBindFailureDelay());
    Assert.assertEquals(4, server.getServerContext().getConnectionConfig().getMinThreads());
    Assert.assertEquals(16, server.getServerContext().getConnectionConfig().getMaxThreads());
    Assert.assertEquals(2, server.getServerContext().getDeliveryManagerConfig().getManagerThreads());
    Assert.assertEquals(8, server.getServerContext().getDeliveryManagerConfig().getMinThreads());
    Assert.assertEquals(24, server.getServerContext().getDeliveryManagerConfig().getMaxThreads());
    Assert.assertEquals(1000, server.getServerContext().getSessionLockTimeout());
    Map<String, Listener> listeners = server.getServerContext().getListeners();
    Assert.assertEquals(3, listeners.size());
    Listener listener = listeners.get("listener1");
    Assert.assertNotNull(listener);
    Assert.assertTrue(listener instanceof MyCustomListener);
    Assert.assertEquals(2223, listener.getPort());
    listener = listeners.get("listener2");
    Assert.assertNotNull(listener);
    Assert.assertTrue(listener instanceof MyCustomListener);
    Assert.assertEquals(2224, listener.getPort());
    CommandFactory cf = server.getCommandFactory();
    Assert.assertTrue(cf.getCommand(9) instanceof BindCommand);
    Assert.assertTrue(cf.getCommand(21) instanceof EnquireLinkCommand);
    Assert.assertEquals(2, server.getSmsclets().size());
    Assert.assertEquals(123, ((TestSmsclet) server.getSmsclets().get("smsclet1")).getFoo());
    Assert.assertEquals(223, ((TestSmsclet) server.getSmsclets().get("smsclet2")).getFoo());
    Assert.assertNotNull(server.getServerContext().getMessageManager());
}
Example 87
Project: spring-framework-2.5.x-master  File: FreeMarkerConfigurerTests.java View source code
public void testFreemarkerConfigurationFactoryBeanWithConfigLocation() throws TemplateException {
    FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
    fcfb.setConfigLocation(new FileSystemResource("myprops.properties"));
    Properties props = new Properties();
    props.setProperty("myprop", "/mydir");
    fcfb.setFreemarkerSettings(props);
    try {
        fcfb.afterPropertiesSet();
        fail("Should have thrown IOException");
    } catch (IOException ex) {
    }
}
Example 88
Project: spring-framework-master  File: FreeMarkerConfigurerTests.java View source code
@Test(expected = IOException.class)
public void freeMarkerConfigurationFactoryBeanWithConfigLocation() throws Exception {
    FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
    fcfb.setConfigLocation(new FileSystemResource("myprops.properties"));
    Properties props = new Properties();
    props.setProperty("myprop", "/mydir");
    fcfb.setFreemarkerSettings(props);
    fcfb.afterPropertiesSet();
}
Example 89
Project: spring-integration-master  File: PropertiesPersistingMetadataStoreTests.java View source code
@Test
public void validateWithDefaultBaseDir() throws Exception {
    File file = new File(System.getProperty("java.io.tmpdir") + "/spring-integration/metadata-store.properties");
    file.delete();
    PropertiesPersistingMetadataStore metadataStore = new PropertiesPersistingMetadataStore();
    metadataStore.afterPropertiesSet();
    assertTrue(file.exists());
    assertNull(metadataStore.putIfAbsent("foo", "baz"));
    assertNotNull(metadataStore.putIfAbsent("foo", "baz"));
    assertFalse(metadataStore.replace("foo", "xxx", "bar"));
    assertTrue(metadataStore.replace("foo", "baz", "bar"));
    metadataStore.close();
    Properties persistentProperties = PropertiesLoaderUtils.loadProperties(new FileSystemResource(file));
    assertNotNull(persistentProperties);
    assertEquals(1, persistentProperties.size());
    assertEquals("bar", persistentProperties.get("foo"));
    file.delete();
}
Example 90
Project: spring-webflow-master  File: WebFlowUpgrader.java View source code
public static void main(String[] args) {
    if (args.length < 1) {
        System.err.println("The file path to the flow to convert is required");
        System.exit(-1);
    }
    WebFlowUpgrader converter = new WebFlowUpgrader();
    String result = converter.convert(new FileSystemResource(args[0]));
    System.out.println(result);
}
Example 91
Project: spring-xd-master  File: SparkAppTests.java View source code
/**
	 * Initialize Fixture and copy the SparkApp Jar to the XD Instance.
	 */
@Before
public void initialize() {
    sparkAppJob = jobs.sparkAppJob();
    jobName = "SA" + UUID.randomUUID().toString();
    FileSystemResource jarSystemResource = new FileSystemResource(sparkAppJob.getSparkAppJar());
    URI jarDestination = sparkAppJob.getJarURI(jarSystemResource.getFile().getParent());
    List<File> jars = new ArrayList<>();
    jars.add(new File(sparkAppJob.getSparkAppJarSource()));
    copyFileToCluster(jarDestination, jars);
}
Example 92
Project: SpringBoot-Learning-master  File: ApplicationTests.java View source code
@Test
public void sendAttachmentsMail() throws Exception {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setFrom("dyc87112@qq.com");
    helper.setTo("dyc87112@qq.com");
    helper.setSubject("主题:有附件");
    helper.setText("有附件的邮件");
    FileSystemResource file = new FileSystemResource(new File("weixin.jpg"));
    helper.addAttachment("附件-1.jpg", file);
    helper.addAttachment("附件-2.jpg", file);
    mailSender.send(mimeMessage);
}
Example 93
Project: symmetric-ds-master  File: TypedPropertiesFactory.java View source code
protected Resource[] buildLocations(File propertiesFile) {
    /*
         * System properties always override the properties found in
         * these files. System properties are merged in the parameter
         * service.
         */
    List<Resource> resources = new ArrayList<Resource>();
    resources.add(new ClassPathResource("/symmetric-default.properties"));
    resources.add(new ClassPathResource("/symmetric-console-default.properties"));
    resources.add(new FileSystemResource(AppUtils.getSymHome() + "/conf/symmetric.properties"));
    resources.add(new ClassPathResource("/symmetric.properties"));
    resources.add(new ClassPathResource("/symmetric-console-default.properties"));
    resources.add(new ClassPathResource("/symmetric-override.properties"));
    if (propertiesFile != null && propertiesFile.exists()) {
        resources.add(new FileSystemResource(propertiesFile.getAbsolutePath()));
    }
    return resources.toArray(new Resource[resources.size()]);
}
Example 94
Project: test-rebase-strategy-master  File: PentahoSystemHelper.java View source code
private static ApplicationContext getSpringApplicationContext() {
    String[] fns = { "pentahoObjects.spring.xml", "adminPlugins.xml", "sessionStartupActions.xml", "systemListeners.xml", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
    "pentahoSystemConfig.xml" };
    GenericApplicationContext appCtx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appCtx);
    for (String fn : fns) {
        //$NON-NLS-1$
        File f = new File(getSolutionPath() + SYSTEM_FOLDER + "/" + fn);
        if (f.exists()) {
            FileSystemResource fsr = new FileSystemResource(f);
            xmlReader.loadBeanDefinitions(fsr);
        }
    }
    String[] beanNames = appCtx.getBeanDefinitionNames();
    //$NON-NLS-1$
    System.out.println("Loaded Beans: ");
    for (String n : beanNames) {
        //$NON-NLS-1$
        System.out.println("bean: " + n);
    }
    return appCtx;
}
Example 95
Project: transgalactica-master  File: FicheSalairePdfItemWriterTest.java View source code
@Test
public void testWriteDefaultLocale() throws Exception {
    SalaireTo salaire = BeanUtils.instantiateClass(BasicSalaireTo.class);
    salaire.setNomEmploye("Wedge Antilles");
    salaire.setTypeEmploye(EmployeType.PILOTE);
    salaire.setDateEmbaucheEmploye(LocalDate.of(2000, 2, 23));
    salaire.setSalaireBase(new BigDecimal("8000"));
    salaire.setPrimeExperience(new BigDecimal("7"));
    salaire.setPrimeAnciennete(new BigDecimal("700"));
    salaire.setSalaire(new BigDecimal("8707"));
    writer.write(Collections.singletonList(salaire));
    assertTrue(new FileSystemResource(TARGET_PATH + "Wedge Antilles_2011-12.pdf").exists());
// TODO : voir pour controler le contenu du fichier (hors metadata)
}
Example 96
Project: wayback-machine-master  File: SpringReader.java View source code
/**
	 * Read the single Spring XML configuration file located at the specified
	 * path, performing PropertyPlaceHolder interpolation, extracting all beans
	 * which implement the RequestHandler interface, and construct a 
	 * RequestMapper for those RequestHandlers, on the specified ServletContext. 
	 * @param configPath the path to the Spring XML file containing the 
	 * configuration.
	 * @param servletContext the ServletContext where the RequestHandlers should
	 * be mapped
	 * @return a new ReqeustMapper which delegates requests for the 
	 * ServletContext
	 */
@SuppressWarnings("unchecked")
public static RequestMapper readSpringConfig(String configPath, ServletContext servletContext) {
    LOGGER.info("Loading from config file " + configPath);
    Resource resource = new FileSystemResource(configPath);
    XmlBeanFactory factory = new XmlBeanFactory(resource);
    Map map = factory.getBeansOfType(PropertyPlaceholderConfigurer.class);
    if (map != null) {
        Collection<PropertyPlaceholderConfigurer> macros = map.values();
        for (PropertyPlaceholderConfigurer macro : macros) {
            macro.postProcessBeanFactory(factory);
        }
    }
    LOGGER.info("Pre-instanting Singletons starting");
    factory.preInstantiateSingletons();
    LOGGER.info("Pre-instanting Singletons complete");
    Map<String, RequestHandler> beans = factory.getBeansOfType(RequestHandler.class, false, false);
    return new RequestMapper(beans.values(), servletContext);
}
Example 97
Project: wooki-master  File: ImportServiceImpl.java View source code
public Book importApt(Resource apt) {
    try {
        String from = "apt";
        File out = File.createTempFile("fromAptToXHTML", ".html");
        String to = "html";
        Converter converter = new DefaultConverter();
        InputFileWrapper input = InputFileWrapper.valueOf(apt.getFilename(), from, "ISO-8859-1", converter.getInputFormats());
        OutputFileWrapper output = OutputFileWrapper.valueOf(out.getAbsolutePath(), to, "UTF-8", converter.getOutputFormats());
        converter.convert(input, output);
        return importDocbook(fromAptToDocbook.performTransformation(new FileSystemResource(out)));
    } catch (UnsupportedFormatException e) {
        e.printStackTrace();
    } catch (ConverterException e) {
        e.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return null;
}
Example 98
Project: automation-test-engine-master  File: CaseDataProcessor.java View source code
/**
	 * {@inheritDoc}
	 */
@Override
public void postProcessBeanFactory(@Nullable ConfigurableListableBeanFactory beanFactory) throws BeansException {
    if (beanFactory == null)
        throw new IllegalStateException("Spring Container initialization error");
    String[] homePageNames = beanFactory.getBeanNamesForType(Homepage.class, true, false);
    String[] lastPageNames = beanFactory.getBeanNamesForType(Lastpage.class, true, false);
    String[] regularPageNames = beanFactory.getBeanNamesForType(RegularPage.class, true, false);
    if (allPageNames != null)
        ArrayUtils.removeAll(allPageNames);
    allPageNames = ArrayUtils.addAll(homePageNames, lastPageNames);
    allPageNames = ArrayUtils.addAll(allPageNames, regularPageNames);
    pageBeanDefs.clear();
    for (int i = 0; i < getAllPageNames().length; i++) {
        pageBeanDefs.add(beanFactory.getBeanDefinition(getAllPageNames()[i]));
    }
    caseDataFiles.clear();
    for (int j = 0; j < pageBeanDefs.size(); j++) {
        if (null != pageBeanDefs.get(j).getPropertyValues().getPropertyValue(XsdElementConstants.ATTR_BASEPAGEOBJECT_DATAFILE)) {
            caseDataFiles.add(new FileSystemResource((String) pageBeanDefs.get(j).getPropertyValues().getPropertyValue(XsdElementConstants.ATTR_BASEPAGEOBJECT_DATAFILE).getValue()));
        }
    }
    if (!caseDataFiles.isEmpty()) {
        dbInit = GlobalUtils.findDBInitializer(beanFactory);
        try {
            getDbInit().setInitXmlFiles(caseDataFiles);
        } catch (IOException e) {
            throw new BeanDefinitionValidationException("Page data file in page attribute can't be read!", e);
        }
        try {
            getDbInit().initialize(beanFactory);
        } catch (MalformedURLExceptionDatabaseUnitException | SQLException |  e) {
            throw new FatalBeanException("Case database creation error!", e);
        }
    }
}
Example 99
Project: camel-trade-master  File: TestCaseAppContextBuilder.java View source code
/**
	 * Creates a new application context using the file found at <code>ROOT_RESOURCE_DIR + clazz.getPackageName + fileName</code>
	 * @param fileName The filename in the calculated directory
	 * @param clazz The clazz we're launching the app context for
	 * @return the app context
	 */
public static GenericXmlApplicationContext buildFor(String fileName, Class<?> clazz) {
    if (clazz == null)
        throw new IllegalArgumentException("Passed class was null", new Throwable());
    File springXml = new File(ROOT_RESOURCE_DIR + clazz.getPackage().getName().replace('.', '/') + "/" + fileName);
    if (!springXml.canRead()) {
        throw new RuntimeException("Failed to read Spring XML file at [" + springXml + "]", new Throwable());
    }
    return service(new GenericXmlApplicationContext(new FileSystemResource[] { new FileSystemResource(springXml.getAbsoluteFile()) }));
}
Example 100
Project: cosmos-message-master  File: InitConfigPath.java View source code
private static void init() {
    //1.默认是在web.xml中�置
    String paramsPath = defaultParamsHome;
    //2.�动�数获�
    if (StringUtils.isEmpty(paramsPath)) {
        paramsPath = System.getProperty(SYSTEM_PARAM_PATH);
    }
    //3.环境��获�
    if (StringUtils.isEmpty(paramsPath)) {
        paramsPath = System.getenv(ENV_PARAM_PATH);
    }
    if (StringUtils.isEmpty(paramsPath)) {
        throw new ConfigException(10008, "读��置文件错误�需�设置web.xml�数或者�动�数[params.home]或者环境��[PARAMS_HOME],并且web.xml中�置 > �动�数 > 环境��");
    }
    //判断路径是��有classpath或者file
    if (StringUtils.indexOf(paramsPath, PREFIX_CLASSPATH) == 0) {
        paramsPath = StringUtils.removeStart(paramsPath, PREFIX_CLASSPATH);
        Resource resource = new ClassPathResource(paramsPath, InitConfigPath.class.getClassLoader());
        if (resource == null) {
            throw new ConfigException(10008, "�数�置文件[" + (paramsPath) + "]�存在");
        }
        try {
            paramsPath = resource.getURL().getPath();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new ConfigException(10008, "解��置文件路径异常!");
        }
    } else if (StringUtils.indexOf(paramsPath, PREFIX_SYSTEM) == 0) {
        paramsPath = StringUtils.removeStart(paramsPath, PREFIX_SYSTEM);
    }
    Resource paramsResource = new FileSystemResource(paramsPath + File.separator + ROOT_PARAM_FILE_NAME);
    if (!paramsResource.exists()) {
        throw new ConfigException(10008, "�数�置文件[" + (paramsPath + File.separator + ROOT_PARAM_FILE_NAME) + "]�存在");
    }
    Properties properties;
    try {
        properties = PropertiesLoaderUtils.loadProperties(paramsResource);
    } catch (IOException e) {
        throw new ConfigException(10008, "加载�置文件[" + paramsResource + "]�生IO异常");
    }
    String root = properties.getProperty(ROOT_PARAM_KEY);
    if (StringUtils.isEmpty(root)) {
        throw new ConfigException(10008, "�置文件中没有rootKey:[" + ROOT_PARAM_KEY + "]");
    }
    paramsRoot = paramsPath + File.separator + root;
    logger.debug("获�到的�置文件路径为:'{}'", paramsRoot);
}
Example 101
Project: cxf-master  File: SpringServiceBuilderFactory.java View source code
/**
     * This is factored out to permit use in a unit test.
     *
     * @param bus
     * @return
     */
public static ApplicationContext getApplicationContext(List<String> additionalFilePathnames) {
    BusApplicationContext busApplicationContext = BusFactory.getDefaultBus().getExtension(BusApplicationContext.class);
    GenericApplicationContext appContext = new GenericApplicationContext(busApplicationContext);
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
    List<URL> urls = ClassLoaderUtils.getResources("META-INF/cxf/java2wsbeans.xml", SpringServiceBuilderFactory.class);
    for (URL url : urls) {
        reader.loadBeanDefinitions(new UrlResource(url));
    }
    for (String pathname : additionalFilePathnames) {
        try {
            reader.loadBeanDefinitions(new FileSystemResource(pathname));
        } catch (BeanDefinitionStoreException bdse) {
            throw new ToolException("Unable to open bean definition file " + pathname, bdse.getCause());
        }
    }
    appContext.refresh();
    return appContext;
}