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

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

Example 1
Project: javaconfig-ftw-master  File: Main.java View source code
public static void main(String[] args) throws Throwable {
    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(BatchConfiguration.class);
    ac.registerShutdownHook();
    Resource samplesResource = new ClassPathResource("/sample/a.csv");
    CustomerLoaderService customerLoaderService = ac.getBean(CustomerLoaderService.class);
    customerLoaderService.loadCustomersFrom(samplesResource.getFile());
}
Example 2
Project: oauth2-shiro-master  File: TestApplicationContextInitializer.java View source code
@Override
public void initialize(AbstractApplicationContext applicationContext) {
    PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
    //load database.properties
    propertyPlaceholderConfigurer.setLocation(new ClassPathResource("test.properties"));
    applicationContext.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer);
}
Example 3
Project: spring-oauth-server-master  File: TestApplicationContextInitializer.java View source code
@Override
public void initialize(AbstractApplicationContext applicationContext) {
    PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
    //load test.properties
    propertyPlaceholderConfigurer.setLocation(new ClassPathResource("test.properties"));
    applicationContext.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer);
}
Example 4
Project: amqp-spring-master  File: TestContext.java View source code
public static void main(String[] args) {
    assert (new ClassPathResource("META-INF/spring.schemas").exists());
    assert (new ClassPathResource("META-INF/spring.handlers").exists());
    assert (new ClassPathResource("org/springframework/amqp/component/xml/components.xsd").exists());
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
    context.registerShutdownHook();
}
Example 5
Project: Consent2Share-master  File: RuleExecutionWebServiceClientTest.java View source code
@BeforeClass
public static void setUp() throws Exception {
    Resource resource = new ClassPathResource("/jettyServerPortForTesing.properties");
    Properties props = PropertiesLoaderUtils.loadProperties(resource);
    String portNumber = props.getProperty("jettyServerPortForTesing.number");
    address = String.format("http://localhost:%s/services/RuleExecutionService", portNumber);
    ep = Endpoint.publish(address, new RuleExecutionServicePortTypeImpl());
    returnedValueOfAssertAndExecuteClinicalFacts.setRuleExecutionResponseContainer(ruleExecutionResponseContaine);
    RuleExecutionServicePortTypeImpl.returnedValueOfAssertAndExecuteClinicalFacts = returnedValueOfAssertAndExecuteClinicalFacts;
}
Example 6
Project: rapid-framework-master  File: HSQLMemDataSourceFactoryBeanTest.java View source code
@Test
public void test() throws Exception {
    DataSource ds = (DataSource) new HSQLMemDataSourceFactoryBean().getObject();
    ds = (DataSource) new HSQLMemDataSourceFactoryBean(new ClassPathResource("fortest_spring/for_test_hsql_db.sql"), "UTF-8").getObject();
    HSQLMemDataSourceFactoryBean hds = new HSQLMemDataSourceFactoryBean();
    hds.setSqlScript("create table blog(id int);insert into blog values (1);");
    hds.getObject();
    Assert.assertTrue("must be create multi datasource", hds.getObject() != hds.getObject());
}
Example 7
Project: spring-modules-master  File: BeanFactoryLanguageContextLoader.java View source code
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext, ApplicationContext parent) throws BeansException {
    ApplicationContext secondParent = null;
    String bflContextConfigLocation = servletContext.getInitParameter(BFL_CONTEXT_CONFIG_LOCATION);
    String createParentWebApplicationContext = servletContext.getInitParameter(CREATE_PARENT_WEB_APPLICATION_CONTEXT);
    Collection beanReferences = null;
    if (createParentWebApplicationContext != null && createParentWebApplicationContext.toLowerCase().equals("true")) {
        secondParent = super.createWebApplicationContext(servletContext, parent);
    } else {
        secondParent = parent;
    }
    if (bflContextConfigLocation != null) {
        beanReferences = BFLUtils.parse(new ClassPathResource(bflContextConfigLocation), secondParent);
    } else {
        beanReferences = BFLUtils.parse(new ClassPathResource("applicationContext.bfl"), secondParent);
    }
    return new XmlWebApplicationContextDriver().getWebApplicationContext(beanReferences, secondParent);
}
Example 8
Project: wurfl-spring-master  File: WurflManagerFactoryBeanTest.java View source code
@Test
public void customRootAndPatches() throws Exception {
    WurflManagerFactoryBean factory = new WurflManagerFactoryBean(new ClassPathResource("test-wurfl.xml", getClass()));
    factory.setPatchLocations(Collections.singletonList(new ClassPathResource("test-wurfl-patch.xml", getClass())));
    factory.afterPropertiesSet();
    factory.getObject();
}
Example 9
Project: btpka3.github.com-master  File: Main.java View source code
public static void main(String[] args) throws IOException {
    Logger logger = LoggerFactory.getLogger(Main.class);
    ClassPathResource rsc = new ClassPathResource("config.properties");
    logger.info(IOUtils.toString(rsc.getInputStream()));
    Main m = new Main();
    logger.info(Integer.toString(m.add(1, 2)));
    logger.info(m.repeat('A', 3));
}
Example 10
Project: InSpider-master  File: ScriptExecutorTest.java View source code
@Test
public void testExecuter() throws Exception {
    Resource testScript = new ClassPathResource("nl/ipo/cds/etl/util/test-script.sql");
    assertTrue(testScript.exists());
    Mockery context = new Mockery();
    final Connection connection = context.mock(Connection.class);
    final DataSource dataSource = context.mock(DataSource.class);
    final Statement statement = context.mock(Statement.class);
    final ResultSet resultSet = context.mock(ResultSet.class);
    context.checking(new Expectations() {

        {
            oneOf(dataSource).getConnection();
            will(returnValue(connection));
            oneOf(connection).createStatement();
            will(returnValue(statement));
            oneOf(statement).executeQuery("select * from inspire.protected_site limit 10");
            will(returnValue(resultSet));
            oneOf(resultSet).close();
            oneOf(statement).executeQuery("select * from bron.protected_site where id = 100");
            will(returnValue(resultSet));
            oneOf(resultSet).close();
            oneOf(statement).executeQuery("select * from inspire.site_name where site_name = 'Bla;Bla'");
            will(returnValue(resultSet));
            oneOf(resultSet).close();
            oneOf(statement).executeUpdate("update inspire.job set status = 'CREATED'");
            oneOf(statement).close();
            oneOf(connection).close();
        }
    });
    ScriptExecutor executer = new ScriptExecutor(dataSource);
    executer.executeScript(testScript);
    context.assertIsSatisfied();
}
Example 11
Project: javasousuo-master  File: ResourceLoaderTest.java View source code
@Test
public void testResourceLoad() {
    ResourceLoader loader = new DefaultResourceLoader();
    Resource resource = loader.getResource("classpath:cn/javass/spring/chapter4/test1.txt");
    //验�返回的是ClassPathResource
    Assert.assertEquals(ClassPathResource.class, resource.getClass());
    Resource resource2 = loader.getResource("file:cn/javass/spring/chapter4/test1.txt");
    //验�返回的是ClassPathResource
    Assert.assertEquals(UrlResource.class, resource2.getClass());
    Resource resource3 = loader.getResource("cn/javass/spring/chapter4/test1.txt");
    //验�返默认�以加载ClasspathResource
    Assert.assertTrue(resource3 instanceof ClassPathResource);
}
Example 12
Project: moho-master  File: XmlProviderManagerFactory.java View source code
public static XmlProviderManager buildXmlProvider() {
    ClassPathResource res = new ClassPathResource("rayo-providers.xml");
    XmlBeanFactory factory = new XmlBeanFactory(res);
    XmlProviderManager manager = (XmlProviderManager) factory.getBean("xmlProviderManager");
    Validator validator = (Validator) factory.getBean("validator");
    RayoClientProvider rayoClientProvider = new RayoClientProvider();
    rayoClientProvider.setNamespaces(new ArrayList<String>());
    rayoClientProvider.getNamespaces().add("urn:xmpp:rayo:1");
    rayoClientProvider.getNamespaces().add("jabber:client");
    rayoClientProvider.setValidator(validator);
    rayoClientProvider.setClasses(new ArrayList<Class<?>>());
    manager.register(rayoClientProvider);
    return manager;
}
Example 13
Project: rayo-java-client-master  File: XmlProviderManagerFactory.java View source code
public static XmlProviderManager buildXmlProvider() {
    ClassPathResource res = new ClassPathResource("rayo-providers.xml");
    XmlBeanFactory factory = new XmlBeanFactory(res);
    XmlProviderManager manager = (XmlProviderManager) factory.getBean("xmlProviderManager");
    Validator validator = (Validator) factory.getBean("validator");
    RayoClientProvider rayoClientProvider = new RayoClientProvider();
    rayoClientProvider.setNamespaces(new ArrayList<String>());
    rayoClientProvider.getNamespaces().add("urn:xmpp:rayo:1");
    rayoClientProvider.getNamespaces().add("jabber:client");
    rayoClientProvider.setValidator(validator);
    rayoClientProvider.setClasses(new ArrayList<Class<?>>());
    manager.register(rayoClientProvider);
    return manager;
}
Example 14
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 15
Project: Spring-Integration-Web-Services-Batch-Demo-master  File: WSClient.java View source code
private static void sendFile(String fileName) throws IOException {
    WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
    Resource resource = new ClassPathResource(fileName);
    StringResult stringResult = new StringResult();
    webServiceTemplate.sendSourceAndReceiveToResult("http://localhost:8080/orderhandling/services", new StreamSource(resource.getInputStream()), stringResult);
    Assert.assertTrue(stringResult.toString().contains("success"));
    System.out.println("success " + fileName);
}
Example 16
Project: svarog-master  File: SvarogAccessResourcesImpl.java View source code
public ImageIcon loadClassPathIcon(String classpath) throws IOException {
    Resource icon = new ClassPathResource(classpath, this.klass);
    log.debug("trying to load " + icon.getURL());
    try {
        return new ImageIcon(icon.getURL());
    } catch (IOException ex) {
        log.error("WARNING: failed to open icon recource [" + icon + "]", ex);
        throw ex;
    }
}
Example 17
Project: batchers-master  File: MonthlyTaxReportService.java View source code
public byte[] generateReport(Long jobExecutionId, int year, int month) throws PDFGenerationException {
    Resource monthlyReportTemplate = new ClassPathResource("monthly-tax-report-template.docx");
    Map<String, Object> contextMap = new HashMap<>();
    contextMap.put("success_sum", sumOfTaxes.getSuccessSum(year, month));
    contextMap.put("failed_sum", sumOfTaxes.getFailedSum(year, month));
    contextMap.put("date", month + " " + year);
    byte[] pdfBytes = pdfGeneratorService.generatePdfAsByteArray(monthlyReportTemplate, contextMap);
    MonthlyReport monthlyReport = MonthlyReport.from(jobExecutionId, year, month, pdfBytes, DateTime.now());
    monthlyReportRepository.save(monthlyReport);
    return pdfBytes;
}
Example 18
Project: cas-master  File: YamlServiceRegistryConfiguration.java View source code
@Bean
@RefreshScope
public ServiceRegistryDao yamlServiceRegistryDao() {
    final ServiceRegistryProperties registry = casProperties.getServiceRegistry();
    if (registry.getConfig().getLocation() == null) {
        LOGGER.warn("The location of service definitions is undefined for the service registry");
        throw new IllegalArgumentException("Service configuration directory for registry must be defined");
    }
    try {
        if (registry.getConfig().getLocation() instanceof ClassPathResource) {
            LOGGER.warn("The location of service definitions [{}] is on the classpath. It is recommended that the location of service definitions " + "be externalized to allow for easier modifications and better sharing of the configuration.", registry.getConfig().getLocation());
        }
        return new YamlServiceRegistryDao(registry.getConfig().getLocation(), registry.isWatcherEnabled(), eventPublisher);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
Example 19
Project: cf-java-component-master  File: YamlPropertySourceTest.java View source code
@Test
public void properties() throws Exception {
    final YamlDocument yamlDocument = YamlDocument.load(new ClassPathResource("testProperties.yml"));
    final YamlPropertySource propertySource = new YamlPropertySource("test", yamlDocument);
    assertEquals(propertySource.getProperty("foo"), "This is foo");
    assertTrue(propertySource.containsProperty("foo"));
    assertFalse(propertySource.containsProperty("bar"));
    assertTrue(propertySource.containsProperty("root"));
    assertTrue(propertySource.getProperty("root") instanceof Map);
    assertTrue(propertySource.containsProperty("root.level1"));
    assertTrue(propertySource.getProperty("root.level1") instanceof Map);
    assertFalse(propertySource.containsProperty("root.bar"));
    assertFalse(propertySource.containsProperty("root.level1.bar"));
    assertTrue(propertySource.containsProperty("root.value"));
    assertEquals(propertySource.getProperty("root.value"), "Some value");
    assertFalse(propertySource.containsProperty("root.value.bar"));
    assertEquals(propertySource.getProperty("root.value.bar"), null);
    assertTrue(propertySource.containsProperty("root.level1.level2"));
    assertEquals(propertySource.getProperty("root.level1.level2"), "Nested value");
    assertTrue(propertySource.containsProperty("number"));
    assertEquals(propertySource.getProperty("number"), 1);
}
Example 20
Project: cloudbreak-master  File: VersionedApplication.java View source code
private String readVersionFromClasspath(String fileName, boolean onlyVersion) throws IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader br;
    br = new BufferedReader(new InputStreamReader(new ClassPathResource(fileName).getInputStream(), "UTF-8"));
    String line;
    while ((line = br.readLine()) != null) {
        if (onlyVersion) {
            if (line.startsWith("info.app.version=")) {
                line = line.replaceAll("info.app.version=", "");
                return line;
            }
        } else {
            sb.append(line).append("\n");
        }
    }
    return sb.toString();
}
Example 21
Project: cts2-framework-master  File: Cts2v10MarshallerDecorator.java View source code
@Override
public void marshal(Object graph, Result result) throws IOException, XmlMappingException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setURIResolver(new URIResolver() {

        @Override
        public Source resolve(String href, String base) throws TransformerException {
            try {
                return new StreamSource(new ClassPathResource(href).getInputStream());
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        }
    });
    Transformer transformer;
    try {
        transformer = transformerFactory.newTransformer(new StreamSource(new ClassPathResource(CTS211to10_XSL).getInputStream()));
    } catch (TransformerConfigurationException e) {
        throw new IllegalStateException(e);
    }
    StringWriter writer = new StringWriter();
    StreamResult superResult = new StreamResult(writer);
    this.delegate.marshal(graph, superResult);
    try {
        transformer.transform(new StreamSource(IOUtils.toInputStream(writer.toString(), "UTF-8")), result);
    } catch (TransformerException e) {
        throw new IOException(e);
    }
}
Example 22
Project: debop4j-master  File: HibernateConfig.java View source code
@Bean
public DataSource dataSource() {
    EmbeddedDatabaseFactoryBean bean = new EmbeddedDatabaseFactoryBean();
    ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
    databasePopulator.addScript(new ClassPathResource("kr/debop4j/data/hibernate/config/java/schema.sql"));
    bean.setDatabasePopulator(databasePopulator);
    // EmbeddedDatabaseFactoryBean가 FactoryBean�므로 필요합니다.
    bean.afterPropertiesSet();
    return bean.getObject();
}
Example 23
Project: downlords-faf-client-master  File: UninstallMapTaskTest.java View source code
private void copyMap(String directoryName, ClassPathResource classPathResource) throws IOException {
    Path targetDir = mapsDirectory.getRoot().toPath().resolve(directoryName);
    Files.createDirectories(targetDir);
    try (InputStream inputStream = classPathResource.getInputStream();
        OutputStream outputStream = Files.newOutputStream(targetDir.resolve("map_info.lua"))) {
        ByteCopier.from(inputStream).to(outputStream).copy();
    }
}
Example 24
Project: edu-master  File: Client.java View source code
public void run() throws DocumentProcessorException {
    /* create beanfactory - would be done central 
         * and more abstract in real life */
    ClassPathResource resource = new ClassPathResource("spring.xml");
    BeanFactory factory = new XmlBeanFactory(resource);
    /* create a test document holding an item */
    Document doc = (Document) factory.getBean("doc");
    doc.setType(Type.ORDER);
    doc.setCur(chf);
    doc.setReference("client document");
    doc.setId("123");
    Item item = (Item) factory.getBean("item");
    item.setCur(chf);
    item.setCent(1230l);
    item.setId("123");
    item.setDesc("ein item");
    doc.addItem(item);
    /* process document */
    DocumentProcessor proc = (DocumentProcessor) factory.getBean("chain");
    doc = proc.processDocument(doc);
}
Example 25
Project: exist-service-master  File: TestExistManager.java View source code
@Override
public void afterPropertiesSet() {
    try {
        File tmpDir = SystemUtils.getJavaIoTmpDir();
        File file = new File(tmpDir.getAbsolutePath() + "/" + UUID.randomUUID().toString() + "/");
        if (!file.exists()) {
            file.mkdir();
        }
        FileUtils.cleanDirectory(file);
        System.setProperty("exist.home", file.getAbsolutePath());
        Resource confXml = new ClassPathResource("conf.xml");
        File confXmlFile = new File(file.getAbsolutePath() + "/conf.xml");
        confXmlFile.createNewFile();
        StringWriter writer = new StringWriter();
        IOUtils.copy(confXml.getInputStream(), writer);
        FileUtils.writeStringToFile(confXmlFile, writer.toString());
        this.setUri("xmldb:exist:///db/");
        System.setProperty("exist.initdb", "true");
        FileUtils.forceDeleteOnExit(file);
        this.setUserName("admin");
        this.setPassword("");
        super.afterPropertiesSet();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 26
Project: feedme-master  File: AbstractFeedMeTest.java View source code
@Before
public void setUp() {
    if (!hasBeenReset) {
        Resource r = new ClassPathResource("test_script.sql");
        ScriptRunner runner = null;
        try {
            File reset = r.getFile();
            runner = new ScriptRunner(dataSource.getConnection());
            runner.runScript(new FileReader(reset));
        } catch (IOExceptionSQLException |  e) {
            throw new RuntimeException(e);
        } finally {
            runner.closeConnection();
            hasBeenReset = Boolean.TRUE;
        }
    }
}
Example 27
Project: hmac-auth-master  File: PropertyUserRepositoryTest.java View source code
@Test
public void shouldParseAuthJson() throws Exception {
    // given
    String authJson = StreamUtils.copyToString(new ClassPathResource("hmac/auth.json").getInputStream(), Charset.defaultCharset());
    // when
    testee = new PropertyUserRepository(authJson);
    // then
    assertThat(testee.getKey("user1"), is("password1"));
    assertThat(testee.getKey("user2"), is("password2"));
    assertThat(testee.getKey("user3"), is("password3"));
    assertThat(testee.getRolesForUser("user1"), is(containsInAnyOrder("role1")));
    assertThat(testee.getRolesForUser("user2"), is(containsInAnyOrder("role1", "role2")));
    assertThat(testee.getRolesForUser("user3"), is(containsInAnyOrder()));
    assertThat(testee.hasRole("user1", "role1"), is(true));
    assertThat(testee.hasRole("user1", "role2"), is(false));
    assertThat(testee.hasRole("user2", "role1"), is(true));
    assertThat(testee.hasRole("user2", "role2"), is(true));
    assertThat(testee.hasRole("user2", "role3"), is(false));
    assertThat(testee.hasRole("user3", "role1"), is(false));
}
Example 28
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 29
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 30
Project: lognavigator-master  File: DefaultConfigServiceTest.java View source code
@Test
public void reloadLogNavigatorConfigIfNecessary_OK() {
    // Init data
    configService.logNavigatorConfigResource = new ClassPathResource("lognavigator.xml");
    // Execute test
    configService.reloadLogNavigatorConfigIfNecessary();
    // Assertions
    assertNotNull(configService.logAccessConfigs);
    assertFalse(configService.logAccessConfigs.isEmpty());
}
Example 31
Project: MIFOSX-master  File: EmbeddedTomcatWithSSLConfigurationTest.java View source code
protected File checkClassResource(Class<?> clazz) throws IOException {
    String testClasspathResourcePath = clazz.getCanonicalName().replace('.', '/') + ".class";
    Resource r = new ClassPathResource(testClasspathResourcePath);
    File f = new EmbeddedTomcatWithSSLConfiguration().getFile(r);
    assertTrue(f.exists());
    f = new EmbeddedTomcatWithSSLConfiguration().getFile(r);
    assertTrue(f.exists());
    return f;
}
Example 32
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 33
Project: OpenLegislation-master  File: TestConfig.java View source code
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
    logger.info("Test property file loaded");
    PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
    Resource[] resources = new ClassPathResource[] { new ClassPathResource(PROPERTY_FILENAME) };
    pspc.setLocations(resources);
    pspc.setIgnoreUnresolvablePlaceholders(true);
    return pspc;
}
Example 34
Project: openpipe-master  File: MultiXmlDocumentReaderTest.java View source code
@Test
public void testIterator() throws Exception {
    reader.setElemMatch(QName.valueOf("{mynamespace}state"));
    reader.setInput(new ClassPathResource("/dummyXml.xml"));
    int count = 0;
    for (Document document : reader) {
        count++;
        assertNotNull(((DomRawData) document.getRawData()).getDom());
    }
    assertEquals(2, count);
}
Example 35
Project: osm-tools-master  File: TestUtils.java View source code
public static MockRestServiceServer prepareRestTemplateForOsmChange(RestTemplate restTemplate, String url, String oscFile) {
    MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_XML);
    mockServer.expect(RequestMatchers.requestTo(url)).andExpect(RequestMatchers.method(HttpMethod.GET)).andRespond(ResponseCreators.withResponse(new ClassPathResource(oscFile, ClassLoader.getSystemClassLoader()), responseHeaders));
    return mockServer;
}
Example 36
Project: pac4j-master  File: AbstractSAML2ClientTests.java View source code
protected final SAML2Client getClient() {
    final SAML2ClientConfiguration cfg = new SAML2ClientConfiguration(new ClassPathResource("samlKeystore.jks"), "pac4j-demo-passwd", "pac4j-demo-passwd", new ClassPathResource("testshib-providers.xml"));
    cfg.setMaximumAuthenticationLifetime(3600);
    cfg.setDestinationBindingType(getDestinationBindingType());
    cfg.setServiceProviderEntityId("urn:mace:saml:pac4j.org");
    cfg.setServiceProviderMetadataResource(new FileSystemResource(new File("target", "sp-metadata.xml").getAbsolutePath()));
    cfg.setSamlMessageStorageFactory(new HttpSessionStorageFactory());
    final SAML2Client saml2Client = new SAML2Client(cfg);
    saml2Client.setCallbackUrl(getCallbackUrl());
    return saml2Client;
}
Example 37
Project: QuiltPlayer-master  File: ClassPathUtils.java View source code
public static ImageIcon getIconFromClasspath(final String classPathName) {
    Resource gearImage = new ClassPathResource(classPathName);
    ImageIcon icon = null;
    try {
        icon = new ImageIcon(gearImage.getURL());
    } catch (IOException e) {
        return null;
    }
    Image img = icon.getImage();
    img = img.getScaledInstance(SizeHelper.getControlPanelIconSize(), SizeHelper.getControlPanelIconSize(), java.awt.Image.SCALE_SMOOTH);
    icon = new ImageIcon(img);
    return icon;
}
Example 38
Project: RMIT-Examples-master  File: DbUtil.java View source code
public void createDb() {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    try {
        log.info("before query");
        String msg = jdbcTemplate.queryForObject("select message from messages limit 1", String.class);
        log.info("schema found: " + msg);
        log.info("after query");
    } catch (Exception e) {
        log.info("No tables found, creating db");
        Resource script = new ClassPathResource("vn/edu/rmit/sadi/createdb.sql");
        JdbcTestUtils.executeSqlScript(jdbcTemplate, script, true);
    }
}
Example 39
Project: saos-master  File: BatchCoreTestConfiguration.java View source code
//------------------------ PRIVATE --------------------------
private void recreateSpringBatchTables() throws SQLException {
    log.debug("dropping spring batch tables");
    ClassPathResource resource = new ClassPathResource("dropBatchTables.sql");
    ScriptUtils.executeSqlScript(dataSource.getConnection(), new EncodedResource(resource, "UTF-8"));
    log.debug("creating spring batch tables");
    resource = new ClassPathResource("createBatchTables.sql");
    ScriptUtils.executeSqlScript(dataSource.getConnection(), new EncodedResource(resource, "UTF-8"));
}
Example 40
Project: shimmer-master  File: DataPointMapperUnitTests.java View source code
/**
     * @param classPathResourceName the name of the class path resource to load
     * @return the contents of the resource as a {@link JsonNode}
     * @throws RuntimeException if the resource can't be loaded
     */
protected JsonNode asJsonNode(String classPathResourceName) {
    ClassPathResource resource = new ClassPathResource(classPathResourceName);
    try {
        InputStream resourceInputStream = resource.getInputStream();
        return objectMapper.readTree(resourceInputStream);
    } catch (IOException e) {
        throw new RuntimeException(format("The class path resource '%s' can't be loaded as a JSON node.", classPathResourceName), e);
    }
}
Example 41
Project: shopb2b-master  File: LogConfigServiceImpl.java View source code
@Cacheable({ "logConfig" })
public List<LogConfig> getAll() {
    try {
        File localFile = new ClassPathResource(CommonAttributes.HQ_SHOP_XML_PATH).getFile();
        Document localDocument = new SAXReader().read(localFile);
        @SuppressWarnings("unchecked") List<LogConfig> localList = localDocument.selectNodes("/shophq/logConfig");
        ArrayList<LogConfig> localArrayList = new ArrayList<LogConfig>();
        Iterator<LogConfig> localIterator = localList.iterator();
        while (localIterator.hasNext()) {
            Element localElement = (Element) localIterator.next();
            String str1 = localElement.attributeValue("operation");
            String str2 = localElement.attributeValue("urlPattern");
            LogConfig localLogConfig = new LogConfig();
            localLogConfig.setOperation(str1);
            localLogConfig.setUrlPattern(str2);
            localArrayList.add(localLogConfig);
        }
        return localArrayList;
    } catch (Exception localException) {
        localException.printStackTrace();
    }
    return null;
}
Example 42
Project: spring-batch-master  File: CastorUnmarshallingTests.java View source code
@Override
protected Unmarshaller getUnmarshaller() throws Exception {
    CastorMarshaller unmarshaller = new CastorMarshaller();
    unmarshaller.setMappingLocation(new ClassPathResource("mapping-castor.xml", getClass()));
    // alternatively target class can be set
    //unmarshaller.setTargetClass(Trade.class);
    unmarshaller.afterPropertiesSet();
    return unmarshaller;
}
Example 43
Project: spring-boot-sample-master  File: WebJarsController.java View source code
// org.webjars.AssetLocator.getWebJarPath()
@ResponseBody
@RequestMapping("/webjarslocator/{webjar}/**")
public ResponseEntity<Object> locateWebjarAsset(@PathVariable String webjar, HttpServletRequest request) {
    try {
        // This prefix must match the mapping path!
        String mvcPrefix = "/webjarslocator/" + webjar + "/";
        String mvcPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String fullPath = assetLocator.getFullPath(webjar, mvcPath.substring(mvcPrefix.length()));
        return new ResponseEntity<>(new ClassPathResource(fullPath), HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}
Example 44
Project: spring-cloud-aws-master  File: MessagingSchemaWithoutSchemaTest.java View source code
@Test
public void messagingXsd_withoutVersion_shouldNotThrowAnException() throws Exception {
    // Arrange
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
    // Act & Assert
    reader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + ".xml", getClass()));
}
Example 45
Project: spring-social-instagram-master  File: InstagramTemplateTest.java View source code
@Test(expected = MissingAuthorizationException.class)
public void noAccessKey() {
    InstagramTemplate template = new InstagramTemplate("CLIENT_ID");
    MockRestServiceServer server = MockRestServiceServer.createServer(template.getRestTemplate());
    server.expect(requestTo("https://api.instagram.com/v1/users/self/?client_id=CLIENT_ID")).andExpect(method(GET)).andRespond(withResponse(new ClassPathResource("testdata/error-response.json", getClass()), responseHeaders));
    template.userOperations().getUser();
    mockServer.verify();
}
Example 46
Project: spring4-showcase-master  File: SpringCacheTest.java View source code
@Test
public void test() throws IOException {
    //创建底层Cache
    net.sf.ehcache.CacheManager ehcacheManager = new net.sf.ehcache.CacheManager(new ClassPathResource("ehcache.xml").getInputStream());
    //创建Spring的CacheManager
    EhCacheCacheManager cacheCacheManager = new EhCacheCacheManager();
    //设置底层的CacheManager
    cacheCacheManager.setCacheManager(ehcacheManager);
    Long id = 1L;
    User user = new User(id, "zhang", "zhang@gmail.com");
    //æ ¹æ?®ç¼“å­˜å??字获å?–Cache
    Cache cache = cacheCacheManager.getCache("user");
    //往缓存写数�
    cache.put(id, user);
    //从缓存读数�
    Assert.assertNotNull(cache.get(id, User.class));
}
Example 47
Project: Springjutsu-Validation-master  File: NamespaceVersionTest.java View source code
@Test
public void testSpringSchemasMatchesXsdVersion() throws IOException {
    Resource springDotSchemas = new ClassPathResource(SPRING_SCHEMA_LOC);
    Properties springDotSchemasProps = new Properties();
    springDotSchemasProps.load(springDotSchemas.getInputStream());
    assertEquals(1, springDotSchemasProps.size());
    String key = springDotSchemasProps.stringPropertyNames().iterator().next();
    String xsdFileName = key.substring(key.lastIndexOf("/") + 1);
    assertTrue(springDotSchemasProps.getProperty(key).endsWith("/" + xsdFileName));
    Resource xsdFile = new ClassPathResource(XSD_LOC + xsdFileName);
    assertTrue(xsdFile.exists());
}
Example 48
Project: springslim-master  File: FitnesseSpringContext.java View source code
public static AbstractApplicationContext getInstance() {
    if (instance != null)
        return instance;
    if (System.getProperty("spring.context") == null) {
        throw new Error("spring.context environment variable is not defined. please set it to your spring context path");
    }
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions(System.getProperty("spring.context"));
    xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions(new ClassPathResource("embedded-rollback.xml"));
    ctx.refresh();
    ctx.registerShutdownHook();
    instance = ctx;
    return instance;
}
Example 49
Project: stormy-pythian-master  File: PyhtianProperties.java View source code
@Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
    PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
    propertyPlaceholderConfigurer.setLocations(new Resource[] { //
    new ClassPathResource("redis-config.properties"), //
    new ClassPathResource("pythian-config.properties") });
    propertyPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(false);
    return propertyPlaceholderConfigurer;
}
Example 50
Project: ws-proxy-master  File: SimpleSecuredEndpoint.java View source code
public static void main(String args[]) throws IOException {
    // Set WSIT_HOME manually, we're only using this for testing purposes. This way we can have a dynamic path based
    // on the project location in filesystem to resolve the keystores via the WSIT configuratin in META-INF
    System.setProperty("WSIT_HOME", new ClassPathResource("").getFile().getParent() + "/../config/test-keystores/");
    Endpoint.publish("http://localhost:9999/simple", new SimpleWebServiceEndpoint());
}
Example 51
Project: yoga-master  File: StaticContentServletFilter.java View source code
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    String path = ((HttpServletRequest) request).getRequestURI();
    if (path.equals("/")) {
        path = "/index.html";
    }
    ServletOutputStream outputStream = null;
    InputStream resourceAsStream = null;
    try {
        ClassPathResource resource = new ClassPathResource("webapp" + path);
        if (resource.exists()) {
            resourceAsStream = resource.getInputStream();
            outputStream = response.getOutputStream();
            byte buff[] = new byte[2 << 12];
            int read = 0;
            while ((read = resourceAsStream.read(buff)) > 0) {
                outputStream.write(buff, 0, read);
            }
            outputStream.flush();
        } else {
            chain.doFilter(request, response);
        }
    } catch (Exception e) {
    } finally {
        if (outputStream != null)
            outputStream.close();
        if (resourceAsStream != null)
            resourceAsStream.close();
    }
}
Example 52
Project: activemq-artemis-master  File: KahaQueueTest.java View source code
@Override
protected BrokerService createBroker(String uri) throws Exception {
    Resource resource = new ClassPathResource(config);
    BrokerFactoryBean brokerFactory = new BrokerFactoryBean(resource);
    resource = new ClassPathResource(config);
    brokerFactory = new BrokerFactoryBean(resource);
    brokerFactory.afterPropertiesSet();
    return brokerFactory.getBroker();
}
Example 53
Project: activemq-master  File: KahaQueueTest.java View source code
protected BrokerService createBroker(String uri) throws Exception {
    Resource resource = new ClassPathResource(config);
    BrokerFactoryBean brokerFactory = new BrokerFactoryBean(resource);
    resource = new ClassPathResource(config);
    brokerFactory = new BrokerFactoryBean(resource);
    brokerFactory.afterPropertiesSet();
    return brokerFactory.getBroker();
}
Example 54
Project: alfresco-enhanced-script-environment-master  File: RepositoryVersionRegisterableScriptClasspathScanner.java View source code
/**
     *
     * {@inheritDoc}
     */
@Override
protected RegisterableScript<ScriptLocation> getScript(final String resourcePath) {
    final RegisterableScript<ScriptLocation> result;
    if (resourcePath.matches("^(classpath(\\*)?:)+.*$")) {
        final ClasspathRegisterableScript script = new ClasspathRegisterableScript();
        final String simplePath = resourcePath.replaceAll("classpath(\\*)?:", "");
        final ClassPathResource classpathResource = new ClassPathResource(simplePath);
        script.setScriptResource(classpathResource);
        result = script;
    } else {
        LOGGER.warn("Can't create script from {} - needs to be a classpath resource", resourcePath);
        result = null;
    }
    return result;
}
Example 55
Project: bearchoke-master  File: CityDBInit.java View source code
@Override
public boolean initIfNotExist() {
    boolean result = false;
    log.info("Persisting locations in Elasticsearch");
    ClassPathResource json = new ClassPathResource(JSON);
    if (json.exists() && json.isReadable()) {
        try {
            List<Location> locations = objectMapper.readValue(json.getInputStream(), new TypeReference<List<Location>>() {
            });
            log.info(String.format("Persisting %d locations", locations.size()));
            searchIndexingService.indexLocations(locations);
            result = true;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        log.warn(String.format("Could not access '%s'", JSON));
    }
    return result;
}
Example 56
Project: bioportal-service-master  File: AssociationTransformTest.java View source code
@Before
public void buildTransform() throws Exception {
    this.associationTransform = new AssociationTransform();
    IdentityConverter idConverter = EasyMock.createMock(IdentityConverter.class);
    UrlConstructor urlConstructor = EasyMock.createNiceMock(UrlConstructor.class);
    EasyMock.expect(idConverter.ontologyIdToCodeSystemName("1104")).andReturn("testCsName").anyTimes();
    EasyMock.expect(idConverter.ontologyVersionIdToCodeSystemVersionName("1104", "44450")).andReturn("testCsVersionName").anyTimes();
    EasyMock.expect(idConverter.getCodeSystemAbout("csName", "http://purl.bioontology.org/ontology/")).andReturn("http://test.doc.uri").anyTimes();
    EasyMock.expect(idConverter.getCodeSystemAbout("ICD10", "http://purl.bioontology.org/ontology/")).andReturn("http://test.doc.uri").anyTimes();
    EasyMock.expect(idConverter.codeSystemVersionNameToVersion("ICD10")).andReturn("ICD10").anyTimes();
    EasyMock.replay(idConverter, urlConstructor);
    this.associationTransform.setIdentityConverter(idConverter);
    this.associationTransform.setUrlConstructor(urlConstructor);
    Resource resource = new ClassPathResource("bioportalXml/entityDescription.xml");
    StringWriter sw = new StringWriter();
    IOUtils.copy(resource.getInputStream(), sw);
    this.xml = sw.toString();
}
Example 57
Project: Blog-Projects-master  File: PropertiesFactoryBeanAutowireTest.java View source code
@Test
public void testCreateProperties() {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(stringEncryptor);
    Resource location = new ClassPathResource("props-test.properties");
    propertiesFactoryBean.setLocation(location);
    try {
        Properties props = propertiesFactoryBean.createProperties();
        assertNotNull(props);
        String pass = (String) props.getProperty("pass");
        assertNotNull(pass);
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.toString());
    }
}
Example 58
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 59
Project: camel-master  File: ResourceConverterTest.java View source code
public void testNonNullConversion() throws IOException {
    Resource resource = new ClassPathResource("testresource.txt", ResourceConverterTest.class);
    Assert.assertTrue(resource.exists());
    InputStream inputStream = getResourceTypeConverter().convertTo(InputStream.class, resource);
    byte[] resourceBytes = IOConverter.toBytes(resource.getInputStream());
    byte[] inputStreamBytes = IOConverter.toBytes(inputStream);
    Assert.assertArrayEquals(resourceBytes, inputStreamBytes);
}
Example 60
Project: Canova-master  File: SVMRecordWriterTest.java View source code
@Test
public void testWriter() throws Exception {
    InputStream is = new ClassPathResource("iris.dat").getInputStream();
    assumeNotNull(is);
    File tmp = new File("iris.txt");
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmp));
    IOUtils.copy(is, bos);
    bos.flush();
    bos.close();
    InputSplit split = new FileSplit(tmp);
    tmp.deleteOnExit();
    RecordReader reader = new CSVRecordReader();
    List<Collection<Writable>> records = new ArrayList<>();
    reader.initialize(split);
    int count = 0;
    while (reader.hasNext()) {
        Collection<Writable> record = reader.next();
        records.add(record);
        assertEquals(5, record.size());
        records.add(record);
        count++;
    }
    assertEquals(150, count);
    File out = new File("iris_out.txt");
    out.deleteOnExit();
    RecordWriter writer = new SVMLightRecordWriter(out, true);
    for (Collection<Writable> record : records) writer.write(record);
    writer.close();
    RecordReader svmReader = new SVMLightRecordReader();
    InputSplit svmSplit = new FileSplit(out);
    svmReader.initialize(svmSplit);
    assertTrue(svmReader.hasNext());
    while (svmReader.hasNext()) {
        Collection<Writable> record = svmReader.next();
        records.add(record);
        assertEquals(5, record.size());
        records.add(record);
        count++;
    }
}
Example 61
Project: Carolina-Digital-Repository-master  File: ZipFileUtilTest.java View source code
/*
	 * Test that entries with relative paths pointing outside the directory to
	 * which we're unzipping will cause an IOException.
	 */
@Test
public void testUnzipRelativePathsOutsideDir() throws IOException {
    File zipFile;
    ClassPathResource resource = new ClassPathResource("/samples/bad-zip-with-relative-path.zip");
    zipFile = resource.getFile();
    File tempDir = File.createTempFile("test", null);
    tempDir.delete();
    tempDir.mkdir();
    tempDir.deleteOnExit();
    try {
        ZipFileUtil.unzipToDir(zipFile, tempDir);
        fail("Expected IOException to be thrown");
    } catch (IOException e) {
    }
}
Example 62
Project: cf-java-client-master  File: BuildpacksTest.java View source code
@Test
public void createBuildpack() throws IOException {
    String buildpackName = this.nameFactory.getBuildpackName();
    this.cloudFoundryOperations.buildpacks().create(CreateBuildpackRequest.builder().buildpack(new ClassPathResource("test-buildpack.zip").getFile().toPath()).fileName("test-buildpack.zip").name(buildpackName).position(Integer.MAX_VALUE).build()).thenMany(this.cloudFoundryOperations.buildpacks().list()).filter( buildpack -> buildpackName.equals(buildpack.getName())).as(StepVerifier::create).expectNextCount(1).expectComplete().verify(Duration.ofMinutes(5));
}
Example 63
Project: cleverbus-master  File: ChangesController.java View source code
@RequestMapping(value = CHANGES_URI, method = RequestMethod.GET)
@ResponseBody
public String getChangesContent() throws IOException {
    ClassPathResource resource = new ClassPathResource("changes.txt");
    // add end of lines
    String resStr = "";
    List<String> lines = IOUtils.readLines(resource.getInputStream(), "utf-8");
    for (String line : lines) {
        resStr += line;
        resStr += "<br/>\n";
    }
    return resStr;
}
Example 64
Project: cloud-rest-service-master  File: LogBackLoadConfigureListener.java View source code
@Override
public void contextInitialized(ServletContextEvent sce) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    try {
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(context);
        context.reset();
        ClassPathResource resource = new ClassPathResource("logback-default.xml");
        if (!resource.exists()) {
            String profile = EnvUtil.getProfile();
            resource = new ClassPathResource("META-INF/logback/logback-" + profile + ".xml");
        }
        configurator.doConfigure(resource.getInputStream());
        logger.info("加载logback�置文件:" + resource.getURL().getPath());
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
Example 65
Project: corespring-master  File: HibernateRestaurantRepositoryTests.java View source code
private SessionFactory createTestSessionFactory() throws Exception {
    // simulate the Spring bean initialization lifecycle
    LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
    factoryBean.setDataSource(createTestDataSource());
    Resource[] mappingLocations = new ClassPathResource[] { new ClassPathResource("Restaurant.hbm.xml", Restaurant.class) };
    factoryBean.setMappingLocations(mappingLocations);
    factoryBean.afterPropertiesSet();
    return (SessionFactory) factoryBean.getObject();
}
Example 66
Project: deccanplato-master  File: ZoHoCRMAdapterTest.java View source code
@Test
public void zohoTest() {
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions(new ClassPathResource("applicationContext.xml"));
    ctx.refresh();
    ProviderRegistry registry = (ProviderRegistry) ctx.getBean("registry");
    List<String> busiMethod = new ArrayList<String>();
    busiMethod.add("user");
    busiMethod.add("account");
    busiMethod.add("lead");
    busiMethod.add("campaign");
    busiMethod.add("call");
    busiMethod.add("case");
    busiMethod.add("contact");
    busiMethod.add("event");
    busiMethod.add("potential");
    busiMethod.add("solution");
    busiMethod.add("task");
    List<String> busiActivity = new ArrayList<String>();
    busiActivity.add("create");
    busiActivity.add("list");
    busiActivity.add("update");
    busiActivity.add("delete");
    for (String function : busiMethod) {
        for (String activity : busiActivity) {
            CommonTest ctest = new CommonTest();
            RequestData reqData;
            reqData = ctest.commonTest(function, activity, ZOHOCRM);
            if (function.equals("user") && activity.equals("create")) {
                testAdapterAccess(reqData);
            }
            ctest.testBusinessImpl();
        }
    }
}
Example 67
Project: dhisreport-master  File: ImportSummaryTest.java View source code
@Test
public void unMarshallImportSummary() throws Exception {
    ClassPathResource resource = new ClassPathResource("importSummary.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(ImportSummary.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    ImportSummary importSummary = (ImportSummary) jaxbUnmarshaller.unmarshal(resource.getInputStream());
    assertEquals(3, importSummary.getDataValueCount().getImported());
    assertEquals(0, importSummary.getDataValueCount().getUpdated());
    assertEquals(1, importSummary.getDataValueCount().getIgnored());
}
Example 68
Project: domain4cat-master  File: StartupListener.java View source code
private void setWebProperty() {
    Resource r = new ClassPathResource("web.properties");
    Properties p = new Properties();
    try {
        p.load(r.getInputStream());
        context.setAttribute("", p.get(""));
        context.setAttribute("", p.get(""));
    } catch (IOException e) {
        log.error("�置读�失败", e);
    }
}
Example 69
Project: eMonocot-master  File: AbstractXmlEventReaderTest.java View source code
/**
	 *
	 * @param filename The filename of the XML resource
	 * @return An XMLEventReader
	 */
protected static XMLEventReader getXMLEventReader(final String filename) {
    XMLInputFactory xmlif = null;
    XMLEventReader xmlr = null;
    try {
        xmlif = XMLInputFactory.newInstance();
        xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        xmlif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        Resource resource = new ClassPathResource(filename);
        xmlr = xmlif.createXMLEventReader(resource.getInputStream());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return xmlr;
}
Example 70
Project: Fudan-Sakai-master  File: FactoryUtil.java View source code
public static SamigoApiFactory lookup() throws Exception {
    // the instance is provided by Spring-injection
    if (useLocator) {
        SpringBeanLocator locator = SpringBeanLocator.getInstance();
        return (SamigoApiFactory) locator.getBean("samigoApiFactory");
    } else // unit testing
    {
        Resource res = new ClassPathResource(CONFIGURATION);
        BeanFactory factory = new XmlBeanFactory(res);
        return (SamigoApiFactory) factory.getBean("samigoApiFactory");
    }
}
Example 71
Project: gemini.blueprint-master  File: LocalFileSystemMavenRepositoryTest.java View source code
public void testLocalSettingsFile() throws Exception {
    repository = new LocalFileSystemMavenRepository();
    Resource res = new ClassPathResource("/org/eclipse/gemini/blueprint/test/provisioning/internal/settings.xml");
    String location = repository.getMavenSettingsLocalRepository(res);
    assertNotNull("location hasn't been picked up", location);
    assertEquals("wrong location discovered", location, "fake/location");
}
Example 72
Project: hdiv-archive-master  File: AbstractTestCase.java View source code
protected void setUp() throws Exception {
    XmlBeanFactory context = new XmlBeanFactory(new ClassPathResource("/org/hdiv/config/hdiv-core-applicationContext.xml"));
    context = new XmlBeanFactory(new ClassPathResource("/hdiv-validations.xml"), context);
    context = new XmlBeanFactory(new ClassPathResource("/hdiv-config.xml"), context);
    this.config = (HDIVConfig) context.getBean("config");
}
Example 73
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 74
Project: hello-world-master  File: TcShiroFilterFactoryBean.java View source code
@Override
public void setFilterChainDefinitions(String definitionFile) {
    checkArgument(definitionFile.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX), "definition file must be a classpath file, and it must start with 'classpath:'");
    String realPath = definitionFile.split(ResourceUtils.CLASSPATH_URL_PREFIX)[1];
    checkNotNull(realPath, "empty real path is not allowed");
    Resource filterChainDefinitionResource = new ClassPathResource(realPath);
    String definitions;
    try {
        log.info("start load shiro filter definition [{}]", realPath);
        definitions = FileUtils.readFileToString(filterChainDefinitionResource.getFile(), StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new IllegalStateException("shiro filter initialize need an valid filter chain definition " + "resource file, it's must start with [classpath:], and then is a valid file path, but get [" + definitionFile + "]", e);
    }
    checkNotNull(definitions, "empty definitions is not allowed");
    super.setFilterChainDefinitions(definitions);
}
Example 75
Project: ical-combinator-master  File: IcalWriterTest.java View source code
@Test
public void shouldSupportJapanese() throws IOException {
    Calendar calendar = new Calendar();
    Resource resource = new ClassPathResource("/japanese.ics");
    when(response.getResponseCode()).thenReturn(200);
    when(response.getContent()).thenReturn(IOUtils.toByteArray(resource.getInputStream()));
    calendar = IcalWriter.merge(calendar, response);
    assertThat(calendar.getComponents().size(), greaterThan(0));
    assertThat(calendar.getComponents().get(0), instanceOf(VEvent.class));
    VEvent event = (VEvent) calendar.getComponents().get(0);
    String snippet = "第82回";
    assertThat(event.getDescription().getValue(), containsString(snippet));
}
Example 76
Project: identity-binder-master  File: BinderApplication.java View source code
@Bean
public static PropertyPlaceholderConfigurer properties() {
    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    ClassPathResource[] resources = new ClassPathResource[] { new ClassPathResource("websecurity.properties"), new ClassPathResource("idps.properties") };
    ppc.setLocations(resources);
    ppc.setIgnoreUnresolvablePlaceholders(true);
    return ppc;
}
Example 77
Project: jcaptcha-trunk-master  File: SimpleBufferedEngineContainerTest.java View source code
public void testExecute() throws Exception {
    Resource ressource = new ClassPathResource("testSimpleBufferedEngine.xml");
    ConfigurableBeanFactory bf = new XmlBeanFactory(ressource);
    BufferedEngineContainer container = (BufferedEngineContainer) bf.getBean("container");
    Thread.sleep(8000);
    for (int i = 0; i < 30; i++) {
        assertNotNull(container.getNextCaptcha(Locale.US));
    }
    Thread.sleep(4000);
    ((SimpleBufferedEngineContainer) container).stopDaemon();
}
Example 78
Project: jena-sparql-api-master  File: ServletSparqlServiceImpl.java View source code
@GET
@Produces(MediaType.TEXT_HTML)
public Response executeRequestXml() throws Exception {
    InputStream r = new ClassPathResource("snorql/index.html").getInputStream();
    Response result;
    if (r == null) {
        result = Response.ok("SPARQL HTML front end not configured", MediaType.TEXT_HTML).build();
    } else {
        result = Response.ok(r, MediaType.TEXT_HTML).build();
    }
    //        Response result = Response.status(Status.NOT_FOUND).build();
    return result;
}
Example 79
Project: jmx2snmp-master  File: SpringTestCase.java View source code
@Test
public void testStartup() throws Exception {
    // BasicConfigurator.configure();		
    final BeanFactory factory = new XmlBeanFactory(new ClassPathResource("org/vafer/jmx2snmp/spring/beans.xml"));
    // this should not be required
    factory.getBean("exporter");
    final JmxServer jmxServer = new JmxServer(InetAddress.getByName("localhost"));
    jmxServer.start();
    final URL url = SpringTestCase.class.getResource("/org/vafer/jmx2snmp/mapping.properties");
    assertNotNull(url);
    final JmxMib jmxMapping = new JmxMib();
    jmxMapping.load(new FileReader(url.getFile()));
    final JmxIndex jmxIndex = new JmxIndex();
    final SnmpBridge snmpBridge = new SnmpBridge(InetAddress.getByName("localhost"), 1161, jmxIndex, jmxMapping);
    snmpBridge.start();
    assertNotNull(jmxServer);
    assertNotNull(jmxIndex);
    assertNotNull(snmpBridge);
    snmpBridge.stop();
    jmxServer.stop();
}
Example 80
Project: jsonhome-master  File: DocControllerTest.java View source code
@Test
public void shouldReturnMarkdown() throws IOException {
    // given
    final DocController controller = new DocController();
    controller.setRootDir(new ClassPathResource("/test/**"));
    // when
    final String markdown = controller.getMarkdown(new MockHttpServletRequest("GET", "/test/doc/test.md"));
    // then
    assertTrue(markdown.startsWith("Test"));
}
Example 81
Project: kalipo-master  File: DatabaseConfiguration.java View source code
@Bean
public Mongeez mongeez() {
    log.debug("Configuring Mongeez");
    Mongeez mongeez = new Mongeez();
    mongeez.setFile(new ClassPathResource("/config/mongeez/master.xml"));
    mongeez.setMongo(mongo);
    mongeez.setDbName(propertyResolver.getProperty("databaseName"));
    mongeez.process();
    return mongeez;
}
Example 82
Project: kylo-master  File: QuartzSpringConfiguration.java View source code
@Bean(name = "schedulerFactoryBean")
public SchedulerFactoryBean schedulerFactoryBean(@Qualifier("dataSource") DataSource dataSource) {
    SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
    scheduler.setApplicationContextSchedulerContextKey("applicationContext");
    Resource resource = new ClassPathResource("quartz.properties");
    if (resource.exists()) {
        scheduler.setConfigLocation(resource);
        scheduler.setDataSource(dataSource);
    }
    //Enable autowiring of Beans inside each QuartzJobBean
    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    scheduler.setJobFactory(jobFactory);
    return scheduler;
}
Example 83
Project: lavagna-master  File: ExportImportServiceTest.java View source code
@Test
public void testImportAndExport() throws IOException {
    Path tmp = Files.createTempFile(null, null);
    try (InputStream is = new ClassPathResource("io/lavagna/export2.zip").getInputStream()) {
        Files.copy(is, tmp, StandardCopyOption.REPLACE_EXISTING);
        exportImportService.importData(false, tmp);
        // TODO additional checks
        exportImportService.exportData(new ByteArrayOutputStream());
    } finally {
        if (tmp != null) {
            Files.deleteIfExists(tmp);
        }
    }
}
Example 84
Project: magma-master  File: SchemaTestExecutionListener.java View source code
private void handleAnnotation(TestContext testContext, TestSchema testSchemaAnnotation, boolean before) throws Exception {
    DataSource dataSource = (DataSource) testContext.getApplicationContext().getBean(testSchemaAnnotation.dataSourceBean());
    String sqlScript = before ? testSchemaAnnotation.beforeSchema() : testSchemaAnnotation.afterSchema();
    if (!sqlScript.isEmpty()) {
        String schemaLocation = testSchemaAnnotation.schemaLocation();
        if (!schemaLocation.isEmpty()) {
            sqlScript = schemaLocation + "/" + sqlScript;
        }
        JdbcTestUtils.executeSqlScript(new JdbcTemplate(dataSource), new ClassPathResource(sqlScript), true);
    }
}
Example 85
Project: MavenOneCMDB-master  File: Validate.java View source code
public static void main(String argv[]) {
    // Startup Spring context.
    Resource res2 = new ClassPathResource("bean-provider-application.xml");
    XmlBeanFactory beanFactory2 = new XmlBeanFactory(res2);
    GenericApplicationContext svrctx2 = new GenericApplicationContext(beanFactory2);
    BeanScope scope = (BeanScope) svrctx2.getBean("importer");
    scope.process();
}
Example 86
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 87
Project: MineKnowContainer-master  File: SchedulerJobCluster.java View source code
private Properties quartzProperties() {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
    try {
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    } catch (IOException e) {
        log.error("read quartz.properties file error: {}", e.getMessage());
    }
    return null;
}
Example 88
Project: ml-javaclient-util-master  File: XmlExtensionMetadataProviderTest.java View source code
@Test
public void test() throws IOException {
    DefaultExtensionMetadataProvider p = new DefaultExtensionMetadataProvider();
    Resource resource = new ClassPathResource("sample-base-dir/services/sample.xqy");
    ExtensionMetadataAndParams emap = p.provideExtensionMetadataAndParams(resource);
    assertEquals("Sample Service", emap.metadata.getTitle());
    assertEquals("<p>You can use <b>HTML</b> in this or any other XML that you like.</p>", emap.metadata.getDescription());
    List<MethodParameters> methods = emap.methods;
    assertEquals(3, methods.size());
    MethodParameters method = methods.get(1);
    assertEquals(MethodType.POST, method.getMethod());
    assertEquals(2, method.size());
    assertEquals("xs:string is the default when no type param is provided", "xs:string", method.get("sourceId").get(0));
    assertEquals("xs:boolean", method.get("edit").get(0));
}
Example 89
Project: ngrinder-master  File: FileDownloadUtilsTest.java View source code
@Test
public void testDownloadFileHttpServletResponseString() throws IOException {
    File downFile = new ClassPathResource("TEST_USER.zip").getFile();
    String filePath = downFile.getAbsolutePath();
    MockHttpServletResponse resp = new MockHttpServletResponse();
    FileDownloadUtils.downloadFile(resp, filePath);
    String lengthHeader = resp.getHeader("Content-Length");
    assertThat(lengthHeader, is(String.valueOf(downFile.length())));
}
Example 90
Project: oas-master  File: AccessControlSchemaProviderImpl.java View source code
/**
   * Initializes this class.
   */
@PostConstruct
public void initialize() {
    if (this.initialized) {
        return;
    }
    LOG.debug("Initializing.");
    if (this.accessControlSchemaMapper == null) {
        this.accessControlSchemaMapper = new AccessControlSchemaXmlMapper();
    }
    if (this.accessControlSchema == null) {
        this.accessControlSchema = new ClassPathResource("config/app/security/access-control-schema.xml");
    }
    this.initialized = true;
}
Example 91
Project: oasp4j-master  File: AccessControlSchemaProviderImpl.java View source code
/**
   * Initializes this class.
   */
@PostConstruct
public void initialize() {
    if (this.initialized) {
        return;
    }
    LOG.debug("Initializing.");
    if (this.accessControlSchemaMapper == null) {
        this.accessControlSchemaMapper = new AccessControlSchemaXmlMapper();
    }
    if (this.accessControlSchema == null) {
        this.accessControlSchema = new ClassPathResource("config/app/security/access-control-schema.xml");
    }
    this.initialized = true;
}
Example 92
Project: OG-Platform-master  File: CalendarUtils.java View source code
public static void parseRegionCalendar(String file, HolidayMaster holidayMaster) throws IOException {
    Map<Integer, ManageableHoliday> holidays = new HashMap<>();
    Reader reader = new BufferedReader(new InputStreamReader(new ClassPathResource(file).getInputStream()));
    try {
        CSVReader csvReader = new CSVReader(reader);
        String[] headers = csvReader.readNext();
        for (int i = 0; i < headers.length; i++) {
            ManageableHoliday manageableHoliday = new ManageableHoliday();
            manageableHoliday.setType(HolidayType.BANK);
            manageableHoliday.setRegionExternalId(ExternalSchemes.financialRegionId(headers[i]));
            holidays.put(i, manageableHoliday);
        }
        String[] line;
        while ((line = csvReader.readNext()) != null) {
            for (int i = 0; i < line.length; i++) {
                if (line[i] != null && line[i].length() > 0) {
                    holidays.get(i).getHolidayDates().add(LocalDate.parse(line[i]));
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    for (ManageableHoliday holiday : holidays.values()) {
        HolidayDocument document = new HolidayDocument(holiday);
        holidayMaster.add(document);
    }
}
Example 93
Project: onebusaway-application-modules-master  File: XmlTextModificationsFactoryTest.java View source code
@Test
public void go() throws IOException, SAXException {
    ClassPathResource resource = new ClassPathResource("org/onebusaway/presentation/impl/text/text-modifications.xml");
    XmlTextModificationsFactory factory = new XmlTextModificationsFactory();
    factory.setResource(resource);
    TextModification modification = factory.create();
    String result = modification.modify("they left the dog in the car");
    assertEquals("they right the cat in the car", result);
    result = modification.modify("the value is ( 1 )");
    assertEquals("the value is left paren #1 right paren", result);
}
Example 94
Project: OpenConext-teams-master  File: VootClientTest.java View source code
@Test
public void testGroups() throws Exception {
    String groupsJson = IOUtils.toString(new ClassPathResource("mocks/oauth-client-credentials.json").getInputStream());
    String oauthJson = IOUtils.toString(new ClassPathResource("mocks/voot-groups.json").getInputStream());
    stubFor(post(urlEqualTo("/oauth/token")).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(groupsJson)));
    stubFor(get(urlEqualTo("/internal/external-groups/" + personId)).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(oauthJson)));
    List<ExternalGroup> groups = client.groups(personId);
    assertEquals(2, groups.size());
    ExternalGroup group = groups.get(0);
    assertEquals("urn:collab:group:foo:go", group.getIdentifier());
    assertEquals("go", group.getName());
    assertEquals("Go description", group.getDescription());
    assertEquals("foo", group.getGroupProvider().getIdentifier());
}
Example 95
Project: OpenESPI-ThirdParty-java-master  File: MockRestTemplate.java View source code
@SuppressWarnings("unchecked")
public <T> T getForObject(String url, Class<T> responseType, Object... urlVariables) throws RestClientException {
    ClassPathResource sourceFile = new ClassPathResource("/fixtures/test_usage_data.xml");
    String inputStreamString;
    try {
        inputStreamString = new Scanner(sourceFile.getInputStream(), "UTF-8").useDelimiter("\\A").next();
        return (T) inputStreamString;
    } catch (IOException e) {
        e.printStackTrace();
        throw new RestClientException("The file import broke.");
    }
}
Example 96
Project: OpenMEAP-master  File: Log4JConfiguratorListener.java View source code
@Override
public void contextInitialized(ServletContextEvent arg0) {
    BasicConfigurator.configure();
    ServletContext servletContext = arg0.getServletContext();
    String xmlLoc = servletContext.getInitParameter("openmeap-log4j-xml");
    if (xmlLoc == null) {
        return;
    }
    try {
        Resource res = new ClassPathResource(xmlLoc);
        DOMConfigurator.configure(XmlUtils.getDocument(res.getInputStream()).getDocumentElement());
    } catch (Exception ioe) {
        servletContext.log("The configuration failed.", ioe);
    }
}
Example 97
Project: openmrs-core-master  File: CacheConfig.java View source code
@Bean(name = "apiCacheManagerFactoryBean")
public EhCacheManagerFactoryBean apiCacheManagerFactoryBean() {
    OpenmrsCacheManagerFactoryBean cacheManagerFactoryBean = new OpenmrsCacheManagerFactoryBean();
    cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache-api.xml"));
    cacheManagerFactoryBean.setShared(false);
    cacheManagerFactoryBean.setAcceptExisting(true);
    return cacheManagerFactoryBean;
}
Example 98
Project: openolat-master  File: UpgradeDefinitionTest.java View source code
/**
	 * tests if one of the upgrade files needed for upgrading the database are accessible via
	 * classpath
	 */
@Test
public void testFileResourceFromClasspath() {
    UpgradesDefinitions defs = upgradesDefinitions;
    for (OLATUpgrade upgrade : defs.getUpgrades()) {
        String path = "/database/mysql/" + upgrade.getAlterDbStatements();
        Resource file = new ClassPathResource(path);
        assertTrue("file not found: " + path, file.exists());
    }
}
Example 99
Project: owsi-core-parent-master  File: ScssStylesheetInformation.java View source code
private boolean isUpToDate(String path) {
    ClassPathResource resource = new ClassPathResource(path);
    try {
        return resource.lastModified() <= lastModifiedTime;
    } catch (IOException e) {
        LOGGER.error("Error while trying to determine if resource " + path + " is up to date. Assuming it is outdated.", e);
        return false;
    }
}
Example 100
Project: Raildelays-master  File: SimpleResourceItemSearchTest.java View source code
/**
     * We expect to find the item and we get the expected index.
     */
@Test
public void testIndexOfFound() throws Exception {
    itemSearch.setReader(new AbstractIndexedResourceAccessibleItemStreamReader<String>() {

        @Override
        public String read() throws Exception {
            return "foo";
        }

        @Override
        public int getCurrentIndex() {
            return EXPECTED_INDEX;
        }
    });
    int index = itemSearch.indexOf("foo", new ClassPathResource("./"));
    Assert.assertEquals(EXPECTED_INDEX, index);
}
Example 101
Project: ratpack-master  File: RatpackPropertiesTests.java View source code
@Test
public void defaultBaseDirIsAbsoluteWhenInJar() throws Exception {
    Resource basedir = new ClassPathResource("META-INF/io.netty.versions.properties");
    URI uri = basedir.getURI();
    assertTrue(uri.toString().startsWith("jar:file"));
    basedir = new UrlResource(uri.toString().replace("META-INF/io.netty.versions.properties", ""));
    ratpack.setBasedir(basedir);
    assertTrue(ratpack.getBasepath().isAbsolute());
}