@Test public void verifyEmbeddedConfigurationContext() { final PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer(); final Properties properties = new Properties(); properties.setProperty("mongodb.host", "ds061954.mongolab.com"); properties.setProperty("mongodb.port", "61954"); properties.setProperty("mongodb.userId", "casuser"); properties.setProperty("mongodb.userPassword", "Mellon"); properties.setProperty("cas.service.registry.mongo.db", "jasigcas"); configurer.setProperties(properties); final FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext( new String[]{"src/main/resources/META-INF/spring/mongo-services-context.xml"}, false); ctx.getBeanFactoryPostProcessors().add(configurer); ctx.refresh(); final MongoServiceRegistryDao dao = new MongoServiceRegistryDao(); dao.setMongoTemplate(ctx.getBean("mongoTemplate", MongoTemplate.class)); cleanAll(dao); assertTrue(dao.load().isEmpty()); saveAndLoad(dao); }
public static void main(String[] args) { if (args.length != 2) { System.err.println("Usage:"); System.err.println("java " + DbToXML.class.getName() + " <context.xml> <output.xml>"); System.exit(1); } String contextPath = args[0]; File outputFile = new File(args[1]); // Create the Spring context FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(contextPath); DbToXML dbToXML = new DbToXML(context, outputFile); dbToXML.execute(); // Shutdown the Spring context context.close(); }
@Test public void fileSystemXmlApplicationContext() throws IOException { ClassPathResource xml = new ClassPathResource(XML_PATH); File tmpFile = File.createTempFile("test", "xml"); FileCopyUtils.copy(xml.getFile(), tmpFile); // strange - FSXAC strips leading '/' unless prefixed with 'file:' ConfigurableApplicationContext ctx = new FileSystemXmlApplicationContext(new String[] {"file:" + tmpFile.getPath()}, false); ctx.setEnvironment(prodEnv); ctx.refresh(); assertEnvironmentBeanRegistered(ctx); assertHasEnvironment(ctx, prodEnv); assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment()); assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false)); assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true)); }
public static void main(String[] args) throws IOException { ClassPathResource classPathResource = new ClassPathResource("beans.xml"); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); reader.loadBeanDefinitions(classPathResource); Person person = factory.getBean("person",Person.class); System.out.println(person.getHand()); System.out.println(person.getName()); System.out.println(classPathResource.getURL()); System.out.println(classPathResource.getFile().getAbsolutePath()); String fileUrl = classPathResource.getFile().getAbsolutePath(); ApplicationContext context = new FileSystemXmlApplicationContext("/Users/fahai/soft/project/meta/src/main/resources/beans.xml"); Person person1 = (Person) factory.getBean("person"); // System.out.println(person1.getName()); // DefaultListableBeanFactory }
/** * Initialize the security manager using the spring security configuration. */ public void init(Properties properties) throws SecurityException { String configLocation = properties.getProperty(SPRING_SECURITY_CONFIG_LOCATION, "security-config.xml"); if (logger.isLoggable(Level.CONFIG)) { logger.config("spring-security-config-location: " + configLocation + ", absolute path: " + new File(configLocation).getAbsolutePath()); } /* * Extract Spring AuthenticationManager definition */ applicationContext = new FileSystemXmlApplicationContext(configLocation); Map<String, AuthenticationManager> beansOfType = applicationContext.getBeansOfType(AuthenticationManager.class); if (beansOfType.isEmpty()) { throw new SecurityException("No bean of type '"+AuthenticationManager.class.getName()+"' is defined in " + configLocation); } if (beansOfType.size() > 1) { throw new SecurityException("More than one bean of type '"+AuthenticationManager.class.getName()+"' is defined in " + configLocation); } authenticationManager = beansOfType.values().iterator().next(); }
private static ApplicationConfig readConfigFromXmlFile(final String applicationFilePath) throws BeansException { ApplicationConfig config; // Convert to URL to workaround the "everything is a relative paths problem" // see spring documentation 5.7.3 FileSystemResource caveats. String fileUri = new File(applicationFilePath).toURI().toString(); final FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(fileUri); try { //CR: Catch runtime exceptions. convert to AdminException(s) context.refresh(); config = context.getBean(ApplicationConfig.class); } finally { if (context.isActive()) { context.close(); } } return config; }
public static void main(String[] args) { if (args.length == 0 || "".equals(args[0])) { System.out.println( "You need to specify an order ID and optionally a number of calls, e.g. for order ID 1000: " + "'client 1000' for a single call per service or 'client 1000 10' for 10 calls each"); } else { int orderId = Integer.parseInt(args[0]); int nrOfCalls = 1; if (args.length > 1 && !"".equals(args[1])) { nrOfCalls = Integer.parseInt(args[1]); } ListableBeanFactory beanFactory = new FileSystemXmlApplicationContext(CLIENT_CONTEXT_CONFIG_LOCATION); OrderServiceClient client = new OrderServiceClient(beanFactory); client.invokeOrderServices(orderId, nrOfCalls); } }
/** * The standard main method which is used by JVM to start execution of the Java class. * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // Start Spring context for the Consumer FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("src/main/resources/SpringBeans.xml"); String total = null; String host = "localhost"; try { host = args[0]; total = args[1]; _log.info("-------------------------------------"); _log.info("Active MQ host >>>> "+host); _log.info("Total messages to send >>>> "+total); _log.info("-------------------------------------"); // Start the publishing of some messages using regular HTTP POST sendMessage(host, Integer.valueOf(total)); } catch (Exception e) { _log.info("------------------------------------------------------------------------------------------------------------------"); _log.info("PAY ATTENTION!!! You must enter the Active MQ host and a number representing the total messages to produce"); _log.info("------------------------------------------------------------------------------------------------------------------"); _log.info("Example: mvn exec:java -Dexec.args=\"localhost 10\""); System.exit(1); } }
public HapporSpringContext(final ClassLoader classLoader, String filename) { this.classLoader = classLoader; ctx = new FileSystemXmlApplicationContext(filename) { @Override protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) { super.initBeanDefinitionReader(reader); reader.setBeanClassLoader(classLoader); setClassLoader(classLoader); } }; registerAllBeans(); setServer(ctx.getBean(HapporWebserver.class)); try { setWebserverHandler(ctx.getBean(WebserverHandler.class)); } catch (NoSuchBeanDefinitionException e) { logger.warn("has no WebserverHandler"); } }
/** * * @throws Exception If failed. */ private void startNodes() throws Exception { AbstractApplicationContext ctxSpring = new FileSystemXmlApplicationContext(springCfgFileOutTmplName + 0); // We have to deploy Services for service is available at the bean creation time for other nodes. Ignite ignite = (Ignite)ctxSpring.getBean("testIgnite"); ignite.services().deployMultiple(SERVICE_NAME, new DummyServiceImpl(), NODES, 1); // Add other nodes. for (int i = 1; i < NODES; ++i) new FileSystemXmlApplicationContext(springCfgFileOutTmplName + i); assertEquals(NODES, G.allGrids().size()); assertEquals(NODES, ignite.cluster().nodes().size()); }
public static void main(String[] args) { FileSystemXmlApplicationContext applicationContext=new FileSystemXmlApplicationContext("classpath:applicationContext.xml"); // MemcachedCache cache=(MemcachedCache) applicationContext.getBean("memClient"); // IMemcachedCache cc=cache.getCache(); //cache.put("1111", object)'' // System.out.println(cache.get("emp1")); AService a=(AService) applicationContext.getBean("aimpl"); // AService B=(AService) applicationContext.getBean("bimpl"); System.out.println((String)a.testaop("test2")); // B.before(); // System.out.println(emp.getCompanyName()); }
/** * Initializes the web service proxy based on the handle to the File. * * @param configurationFile * The File handle to the configuration file. */ public WebServiceProxy(File configurationFile) { String path = configurationFile.getAbsolutePath(); FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext( "file:" + path); try { this.webProxyConfiguration = applicationContext .getBean(WebProxyConfiguration.class); Map<String, ModuleConfiguration> moduleConfigurations = applicationContext .getBeansOfType(ModuleConfiguration.class); initializeModules(moduleConfigurations.values()); } finally { applicationContext.close(); } }
@Test public void testInjection(){ System.setProperty("log.path", ProjectConfig.getProperty("log.path")); @SuppressWarnings("resource") ApplicationContext context = new FileSystemXmlApplicationContext("src/main/webapp/WEB-INF/spring/applicationContext.xml"); SysSettingService sysSettingService = (SysSettingService)context.getBean("sysSettingService"); // SysSetting sysSetting = new SysSetting(); // // sysSetting.setCreateperson(1); // sysSetting.setEditperson(1); // sysSetting.setCreatetime(new Date()); // sysSetting.setEdittime(new Date()); // sysSetting.setPropKey("系统安全级别"); // sysSetting.setPropValue("高级"); // sysSetting.setRemark("在此安全级别下,任何未授权访问都会被拒绝。"); // // sysSettingService.save(sysSetting); System.err.println(Util.getJsonObject(sysSettingService.selectAll())); }
@Test public void fileSystemXmlApplicationContext() throws IOException { ClassPathResource xml = new ClassPathResource(XML_PATH); File tmpFile = File.createTempFile("test", "xml"); FileCopyUtils.copy(xml.getFile(), tmpFile); // strange - FSXAC strips leading '/' unless prefixed with 'file:' ConfigurableApplicationContext ctx = new FileSystemXmlApplicationContext(new String[] { "file:"+tmpFile.getPath() }, false); ctx.setEnvironment(prodEnv); ctx.refresh(); assertEnvironmentBeanRegistered(ctx); assertHasEnvironment(ctx, prodEnv); assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment()); assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false)); assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true)); }
public static ApplicationContext loadCxt(String path) { try { return new ClassPathXmlApplicationContext(path); } catch(Throwable t) { try { if(t.getCause() instanceof FileNotFoundException) return new FileSystemXmlApplicationContext(path); } catch(Throwable t1) { lg.error("loading spring context fail",t1); return null; } lg.error("loading spring context fail",t); } return null; }
@Before public void initialize(){ String contextFile = "/Users/ilinca/IdeaProjects/PhenoImageShare/PhIS/WebContent/WEB-INF/app-config.xml"; File f = new File(contextFile); if (!f.isFile() || !f.canRead()) { System.err.println("Context file " + contextFile + " not readable."); } else { logger.info("--context OK"); } applicationContext = new FileSystemXmlApplicationContext("file:" + contextFile); updateService = (GenericUpdateService) applicationContext.getBean("genericUpdateService"); cs = (ChannelService) applicationContext.getBean("channelService"); is = (ImageService) applicationContext.getBean("imageService"); rs = (RoiService) applicationContext.getBean("roiService"); }
public AbstractDaoTestCase(String testName, String inputDataFileName) { super(testName); System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, JDBC_DRIVER); System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, DATABASE); System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, USER); System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, PASSWORD); ApplicationContext springApplicationContext = new FileSystemXmlApplicationContext(SPRING_FILE_PATH); springBeanFactory = springApplicationContext; this.inputDataFileName = inputDataFileName; }
/** * Initialization. */ @Before public void initialize() { // context final ApplicationContext context = new FileSystemXmlApplicationContext("conf/context-example5.xml"); machine = new SpringFsm(); machine.setApplicationContext(context); // events read = (Event)context.getBean("eventRead"); cancel = (Event)context.getBean("eventCancel"); reject = (Event)context.getBean("eventReject"); timeout = (Event)context.getBean("eventTimeout"); dispatch = (Event)context.getBean("eventDispatch"); // order order = new Order(); order.setAmount(12.50); order.setName("Telephone"); }
@Override public void execute(ActionMessagePrinter printer) throws CmdLineActionException { FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext( this.beanRepo); try { ProductCrawler pc = (ProductCrawler) appContext .getBean(crawlerId != null ? crawlerId : getName()); pc.setApplicationContext(appContext); if (pc.getDaemonPort() != -1 && pc.getDaemonWait() != -1) { new CrawlDaemon(pc.getDaemonWait(), pc, pc.getDaemonPort()) .startCrawling(); } else { pc.crawl(); } } catch (Exception e) { throw new CmdLineActionException("Failed to launch crawler : " + e.getMessage(), e); } }
public void testLoadAndValidateActions() { ProductCrawler pc = createDummyCrawler(); pc.setApplicationContext(new FileSystemXmlApplicationContext( CRAWLER_CONFIG)); pc.loadAndValidateActions(); assertEquals(0, pc.actionRepo.getActions().size()); pc = createDummyCrawler(); pc.setApplicationContext(new FileSystemXmlApplicationContext( CRAWLER_CONFIG)); pc.setActionIds(Lists.newArrayList("Unique", "DeleteDataFile")); pc.loadAndValidateActions(); assertEquals(Sets.newHashSet( pc.getApplicationContext().getBean("Unique"), pc.getApplicationContext().getBean("DeleteDataFile")), pc.actionRepo.getActions()); }
public AbstractDaoTestCase(String testName) { super(testName); ApplicationContext springApplicationContext = new FileSystemXmlApplicationContext(SPRING_FILE_PATH); springBeanFactory = springApplicationContext; DriverManagerDataSource dmds = (DriverManagerDataSource)springBeanFactory.getBean("dataSource"); System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, JDBC_DRIVER); System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, dmds.getUrl()); System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, dmds.getUsername()); System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, dmds.getPassword()); }
public static void main(String[] args) { ApplicationContext ctx = new FileSystemXmlApplicationContext( "src/com/prototype/remoting/SpringHttp/conf/persistenceManager.xml"); PersistenceManager pm = (PersistenceManager)ctx.getBean("persistenceManagerService"); //System.out.println(helloWorld.getMessage()); try{ pm.getPersonById("333"); }catch(Exception pex){ //pex.printStackTrace(); System.out.println("Something happened"+pex.getMessage()); } /** Person person = new Person(); person.setName("Spring_xyz_12993"); try{ person = pm.createPerson(person); }catch(Exception ex){ System.out.println("The Message is:"+ex.getMessage()); } System.out.println("Person's Id is : " + person.getId()); */ }
protected void loadVisualizationFile(File file) { try { FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(new String[]{file.getPath()}, false); context.setClassLoader(getClass().getClassLoader()); context.refresh(); Map beans = context.getBeansOfType(IVisualization.class); for (Object key : beans.keySet()) { IVisualization vis = (IVisualization)beans.get(key); if (vis.getOrder() >= 0) { visualizations.add(vis); } } } catch (XmlBeanDefinitionStoreException e) { // TODO: introduce logging e.printStackTrace(); } }
protected void InitAction() { webRootPath = ServletActionContext.getServletContext().getRealPath("/"); String xmlPath=webRootPath + "WEB-INF\\applicationContext.xml"; ApplicationContext appContext = new FileSystemXmlApplicationContext(xmlPath); //Resource res = new FileSystemResource(webRootPath // + "WEB-INF\\applicationContext.xml"); //XmlBeanFactory factory = new XmlBeanFactory(res); BeanFactory factory = appContext; mService = (MessageService) factory.getBean("messageService"); uService = (UserService) factory.getBean("userService"); jMail = (Jmail) factory.getBean("jmail"); mailServiceMdp = (MailServiceMdp) factory.getBean("mailServiceMdp"); factory.getBean("listnerContainer"); ActionContext ctx = ActionContext.getContext(); Map<String, Object> session = ctx.getSession(); currentUserFromSession = (User) session.get("user"); }
@org.junit.Test public void init() { ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:spring-test.xml"); IBlogService blogService = (IBlogService) ctx.getBean("blogService"); logger.info("start"); List<Blog> blogs = blogService.getBanner(); logger.info("end"); }
/** * 私有构造函数,默认为UI组件WEB-INF目录下的applicationContext.xml配置文件 */ private BeanFactoryUtil() { String fileUrl = PathTool.getWebinfPath(); //这里只对UI组件WEB-INF目录下的applicationContext.xml配置文件 defaultAC = new FileSystemXmlApplicationContext( new String[]{fileUrl + "spring/basic-applicationContext.xml", fileUrl + "spring/dao-applicationContext.xml"}); }
public static void main(String[] args) { ApplicationContext ctx = new FileSystemXmlApplicationContext("src/main/resources/spring-context.xml"); KirjanpitoInt kirjanpito = (Kirjanpito)ctx.getBean("kirjanpito"); Kauppa kauppa = ctx.getBean(Kauppa.class); // kauppa hoitaa yhden asiakkaan kerrallaan seuraavaan tapaan: kauppa.aloitaAsiointi(); kauppa.lisaaKoriin(1); kauppa.lisaaKoriin(3); kauppa.lisaaKoriin(3); kauppa.poistaKorista(1); kauppa.tilimaksu("Pekka Mikkola", "1234-12345"); // seuraava asiakas kauppa.aloitaAsiointi(); for (int i = 0; i < 24; i++) { kauppa.lisaaKoriin(5); } kauppa.tilimaksu("Arto Vihavainen", "3425-1652"); // kirjanpito for (String tapahtuma : kirjanpito.getTapahtumat()) { System.out.println(tapahtuma); } }
public static void main(String[] args) { ApplicationContext ctx = new FileSystemXmlApplicationContext("src/main/resources/spring-context.xml"); //Laskin laskin = (Laskin) ctx.getBean("laskin"); Laskin laskin = ctx.getBean(Laskin.class); laskin.suorita(); }
public static void main(String args[]){ ApplicationContext context = new FileSystemXmlApplicationContext(".\\src\\main\\webapp\\WEB-INF\\applicationContext.xml"); //Calculation calculation = (Calculation)context.getBean("calculationBeanHessian"); InvoiceProductRequest request = new InvoiceProductRequest(); request.setInvoiceId(123); WebServiceTemplate wsTemplate = (WebServiceTemplate) context.getBean("webServiceTemplate"); InvoiceProductResponse response = (InvoiceProductResponse) wsTemplate.marshalSendAndReceive(request); InvoicedProducts product = response.getInvoicedProduct(); System.out.println(product.getId()); }
public static void main(String[] args) { loger.info("userService starting"); SimpleIceUserServer server = new SimpleIceUserServer(); final FileSystemXmlApplicationContext cx = new FileSystemXmlApplicationContext("classpath*:spring-config.xml"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { cx.close(); } }); server.startIceServer(args); loger.info("userService started"); }
public static void main(String[] args) throws Base64DecodingException { AesCipherService aesCipherService = new AesCipherService(); aesCipherService.setKeySize(128); FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("src/main/resources/applicationContext.xml"); JdbcTemplate template = (JdbcTemplate) context.getBean("jdbcTemplate"); Key key = aesCipherService.generateNewKey(); final byte[] bytes = key.getEncoded(); final String password = aesCipherService.encrypt(ByteSource.Util.bytes("123456").getBytes(), bytes).toBase64(); System.out.println(password); System.out.println(new String(Base64.decode(aesCipherService.decrypt(Base64.decode(password), bytes).toBase64()))); for(byte b : bytes){ System.out.print(b+","); } template.execute("insert into security_user(password,username,password_key) values(?,?,?)", new PreparedStatementCallback(){ @Override public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { ps.setString(1, password); ps.setString(2, "admin"); ps.setBytes(3, bytes); ps.execute(); return null; } }); }
public boolean start() { if (ctx != null) IocInterceptor.ctx = ctx; else if (configurations != null) IocInterceptor.ctx = new FileSystemXmlApplicationContext(configurations); else IocInterceptor.ctx = new FileSystemXmlApplicationContext(PathKit.getWebRootPath() + "/WEB-INF/applicationContext.xml"); return true; }
public static void main(String[] args) throws IOException { int nrOfCalls = 1; if (args.length > 1 && !"".equals(args[1])) { nrOfCalls = Integer.parseInt(args[1]); } ApplicationContext context = new FileSystemXmlApplicationContext(CONTEXT_CONFIG_LOCATION); ImageDatabase idb = (ImageDatabase) context.getBean("imageDatabase"); StandaloneImageTool tool = new StandaloneImageTool(idb); tool.listImages(nrOfCalls); }
private AbstractXmlApplicationContext createSpringApplicationContext(String configuration, boolean fromClassPath) { if (fromClassPath) { log.debug("classpath configuration"); return new ClassPathXmlApplicationContext(configuration); } if (new File(configuration).exists()) { log.debug("File configuration"); return new FileSystemXmlApplicationContext(configuration); } else { throw new EPException("Spring configuration file not found."); } }
/** * Instantiates a Distiller object using the specified configuration and * returns it. * * @param path the path where the config file is located * @return a Distiller ready to work. */ public static Distiller loadFromXML(File path) { // We add the file:// thing before because, for some ??? reason, // the Spring Framework decided that all paths are relative paths. // So, we get the file, retrieve is absolute path, and then add the // file:// prefix to be sure that the Spring Frameworks treats // all paths as absolute paths. // This is less problematic, because the Java platform will handle the // File and produce its absolute path, even if it has been created // using a relative one. ApplicationContext context = new FileSystemXmlApplicationContext( "file://" + path.getAbsolutePath()); return (Distiller) context.getBean("distiller"); }
public JarContainerServer(String filename) { FileSystemXmlApplicationContext serverContext = new FileSystemXmlApplicationContext(filename); HapporServerElement element = serverContext.getBean(HapporServerElement.class); server = element.getServer(); containerConfig = element.getConfigs().get("container"); log4jConfig = element.getConfigs().get("log4j"); serverContext.close(); }