@Override public void execute() throws MojoExecutionException, MojoFailureException { // Create test context try (final GenericXmlApplicationContext generateContext = new GenericXmlApplicationContext()) { generateContext.load("classpath:generate-context.xml"); generateContext.refresh(); final DataSource dataSource = generateContext.getBean(DataSource.class); final Generator generator = new Generator(getLog(), this::processRecord); getLog().info("Loading templates from: " + source.getAbsolutePath()); getLog().info("Package: " + packageName); for (final File file : source.listFiles(this::acceptAllFiles)) { generator.generate(dataSource, file, destination, packageName); } } }
@Test public void configuredThroughNamespace() { GenericXmlApplicationContext context = new GenericXmlApplicationContext(); context.load(new ClassPathResource("taskNamespaceTests.xml", getClass())); context.refresh(); ITestBean testBean = context.getBean("target", ITestBean.class); testBean.test(); testBean.await(3000); Thread asyncThread = testBean.getThread(); assertTrue(asyncThread.getName().startsWith("testExecutor")); TestableAsyncUncaughtExceptionHandler exceptionHandler = context.getBean("exceptionHandler", TestableAsyncUncaughtExceptionHandler.class); assertFalse("handler should not have been called yet", exceptionHandler.isCalled()); testBean.failWithVoid(); exceptionHandler.await(3000); Method m = ReflectionUtils.findMethod(TestBean.class, "failWithVoid"); exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class); context.close(); }
@Test public void testJavaBean() { context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName()+"-java-context.xml"); TestService bean = context.getBean("javaBean", TestService.class); LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); assertEquals(0, logAdvice.getCountThrows()); try { bean.sayHello(); fail("Expected exception"); } catch (RuntimeException ex) { assertEquals("TestServiceImpl", ex.getMessage()); } assertEquals(1, logAdvice.getCountThrows()); }
@Test public void testGroovyBeanInterface() { context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName()+"-groovy-interface-context.xml"); TestService bean = context.getBean("groovyBean", TestService.class); LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); assertEquals(0, logAdvice.getCountThrows()); try { bean.sayHello(); fail("Expected exception"); } catch (RuntimeException ex) { assertEquals("GroovyServiceImpl", ex.getMessage()); } assertEquals(1, logAdvice.getCountThrows()); }
@Test public void testGroovyBeanDynamic() { context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName()+"-groovy-dynamic-context.xml"); TestService bean = context.getBean("groovyBean", TestService.class); LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); assertEquals(0, logAdvice.getCountThrows()); try { bean.sayHello(); fail("Expected exception"); } catch (RuntimeException ex) { assertEquals("GroovyServiceImpl", ex.getMessage()); } // No proxy here because the pointcut only applies to the concrete class, not the interface assertEquals(0, logAdvice.getCountThrows()); assertEquals(0, logAdvice.getCountBefore()); }
@Test public void testGroovyBeanProxyTargetClass() { context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName()+"-groovy-proxy-target-class-context.xml"); TestService bean = context.getBean("groovyBean", TestService.class); LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); assertEquals(0, logAdvice.getCountThrows()); try { bean.sayHello(); fail("Expected exception"); } catch (TestException ex) { assertEquals("GroovyServiceImpl", ex.getMessage()); } assertEquals(1, logAdvice.getCountBefore()); assertEquals(1, logAdvice.getCountThrows()); }
@Test public void xml() { ConfigurableApplicationContext ctx = new GenericXmlApplicationContext( getClass(), "DestroyMethodInferenceTests-context.xml"); WithLocalCloseMethod x1 = ctx.getBean("x1", WithLocalCloseMethod.class); WithLocalCloseMethod x2 = ctx.getBean("x2", WithLocalCloseMethod.class); WithLocalCloseMethod x3 = ctx.getBean("x3", WithLocalCloseMethod.class); WithNoCloseMethod x4 = ctx.getBean("x4", WithNoCloseMethod.class); WithInheritedCloseMethod x8 = ctx.getBean("x8", WithInheritedCloseMethod.class); assertThat(x1.closed, is(false)); assertThat(x2.closed, is(false)); assertThat(x3.closed, is(false)); assertThat(x4.closed, is(false)); ctx.close(); assertThat(x1.closed, is(false)); assertThat(x2.closed, is(true)); assertThat(x3.closed, is(true)); assertThat(x4.closed, is(false)); assertThat(x8.closed, is(false)); }
@PostConstruct public void configureMergedItems() { Set<Resource> temp = new LinkedHashSet<Resource>(); if (mergedEntityContexts != null && !mergedEntityContexts.isEmpty()) { for (String location : mergedEntityContexts) { temp.add(webApplicationContext.getResource(location)); } } if (entityContexts != null) { for (Resource resource : entityContexts) { temp.add(resource); } } entityContexts = temp.toArray(new Resource[temp.size()]); applicationcontext = new GenericXmlApplicationContext(entityContexts); }
public static ProcessEngine buildProcessEngine(URL resource) { log.fine("==== BUILDING SPRING APPLICATION CONTEXT AND PROCESS ENGINE ========================================="); ApplicationContext applicationContext = new GenericXmlApplicationContext(new UrlResource(resource)); Map<String, ProcessEngine> beansOfType = applicationContext.getBeansOfType(ProcessEngine.class); if ( (beansOfType==null) || (beansOfType.isEmpty()) ) { throw new ActivitiException("no "+ProcessEngine.class.getName()+" defined in the application context "+resource.toString()); } ProcessEngine processEngine = beansOfType.values().iterator().next(); log.fine("==== SPRING PROCESS ENGINE CREATED =================================================================="); return processEngine; }
private static void renewTestData() { ctx = new GenericXmlApplicationContext(); ctx.load("classpath:datasource-context-h2-embedded.xml"); ctx.refresh(); fileEntityDao = ctx.getBean("fileEntityDao", FileEntityDao.class); assertNotNull(fileEntityDao); try { FileUtils.deleteDirectory(new File(filesHomePath)); } catch (IOException e) { e.printStackTrace(); } TestUtil.touchTestFilesForFileBox(fileEntityDao); }
private void enhanceExistingSpringWebApplicationContext(ServletContextEvent sce, WebApplicationContext wac) { LOGGER.info("Enhancing existing Spring application context..."); String cosmoContextLocation = sce.getServletContext().getInitParameter(CONTEXT_PARAM_NAME); @SuppressWarnings("resource") GenericXmlApplicationContext cosmoAppCtxt = new GenericXmlApplicationContext(); cosmoAppCtxt.setEnvironment((ConfigurableEnvironment) wac.getEnvironment()); cosmoAppCtxt.load(cosmoContextLocation); cosmoAppCtxt.refresh(); cosmoAppCtxt.start(); //make beans that are required from web components (as delegating filter proxy) accesible ((AbstractRefreshableWebApplicationContext)wac).getBeanFactory().setParentBeanFactory(cosmoAppCtxt.getBeanFactory()); LOGGER.info("Enhanced existing Spring application context started"); }
/** * The main method. * * @param args * the arguments * @throws Exception * the exception */ public static void main(String[] args) throws Exception { logger.info("Starting at {}...", new Date().toString()); try { GenericXmlApplicationContext context = new GenericXmlApplicationContext(); context.load("classpath:/META-INF/spring/applicationContext*.xml"); context.refresh(); } catch (Exception e) { logger.error("Error occurred:", e); throw e; } while (true) { } }
@Test public void bootstrapAppFromXml() { // Here cannot use WEB-INF/spring/root-context.xml GenericXmlApplicationContext context = new GenericXmlApplicationContext(); context.load("classpath:META-INF/spring/applicationContext*.xml"); context.refresh(); assertThat(context, is(notNullValue())); // EchoSignPollingService EsignaturePollingService esignaturePollingService = (EsignaturePollingService)(context.getBean("esignaturePollingService")); assertNotNull(esignaturePollingService); // EchoSignPollingService //EchoSignPollingService echoSignPollingService = (EchoSignPollingService)(context.getBean("esignaturePollingService")); //assertNotNull(echoSignPollingService); }
public void unsubscribe(String subscriptionID) { ApplicationContext ctx = new GenericXmlApplicationContext( "classpath:MongoConfig.xml"); MongoOperations mongoOperation = (MongoOperations) ctx .getBean("mongoTemplate"); // Its size should be 0 or 1 List<SubscriptionType> subscriptions = mongoOperation.find(new Query( Criteria.where("subscriptionID").is(subscriptionID)), SubscriptionType.class); for (int i = 0; i < subscriptions.size(); i++) { SubscriptionType subscription = subscriptions.get(i); // Remove from current Quartz removeScheduleFromQuartz(subscription); // Remove from DB list removeScheduleFromDB(mongoOperation, subscription); } ((AbstractApplicationContext) ctx).close(); }
public String getSubscriptionIDsREST(@PathVariable String queryName) { ApplicationContext ctx = new GenericXmlApplicationContext( "classpath:MongoConfig.xml"); MongoOperations mongoOperation = (MongoOperations) ctx .getBean("mongoTemplate"); List<SubscriptionType> allSubscription = mongoOperation.find(new Query( Criteria.where("queryName").is(queryName)), SubscriptionType.class); JSONArray retArray = new JSONArray(); for (int i = 0; i < allSubscription.size(); i++) { SubscriptionType subscription = allSubscription.get(i); retArray.put(subscription.getSubscriptionID()); } ((AbstractApplicationContext) ctx).close(); return retArray.toString(1); }
public List<String> getSubscriptionIDs(String queryName) { ApplicationContext ctx = new GenericXmlApplicationContext( "classpath:MongoConfig.xml"); MongoOperations mongoOperation = (MongoOperations) ctx .getBean("mongoTemplate"); List<SubscriptionType> allSubscription = mongoOperation.find(new Query( Criteria.where("queryName").is(queryName)), SubscriptionType.class); List<String> retList = new ArrayList<String>(); for (int i = 0; i < allSubscription.size(); i++) { SubscriptionType subscription = allSubscription.get(i); retList.add(subscription.getSubscriptionID()); } ((AbstractApplicationContext) ctx).close(); return retList; }
@Test public void xml() { ConfigurableApplicationContext ctx = new GenericXmlApplicationContext( getClass(), "DestroyMethodInferenceTests-context.xml"); WithLocalCloseMethod x1 = ctx.getBean("x1", WithLocalCloseMethod.class); WithLocalCloseMethod x2 = ctx.getBean("x2", WithLocalCloseMethod.class); WithLocalCloseMethod x3 = ctx.getBean("x3", WithLocalCloseMethod.class); WithNoCloseMethod x4 = ctx.getBean("x4", WithNoCloseMethod.class); assertThat(x1.closed, is(false)); assertThat(x2.closed, is(false)); assertThat(x3.closed, is(false)); assertThat(x4.closed, is(false)); ctx.close(); assertThat(x1.closed, is(false)); assertThat(x2.closed, is(true)); assertThat(x3.closed, is(true)); assertThat(x4.closed, is(false)); }
@Test public void genericXmlApplicationContext() { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); assertHasStandardEnvironment(ctx); ctx.setEnvironment(prodEnv); ctx.load(XML_PATH); ctx.refresh(); assertHasEnvironment(ctx, prodEnv); assertEnvironmentBeanRegistered(ctx); assertEnvironmentAwareInvoked(ctx, prodEnv); assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false)); assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true)); }
private NetworkDiscoverer createNetworkDiscoverer(String projectPath, String version, int initialNumberOfThreads, int maxNumberOfThreads) { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.load("classpath:netDiscoverer/netDiscoverer.xml"); ctx.load("classpath:csvConnectionDetails/csvConnectionDetailsFactory.xml"); AbstractBeanDefinition projectPathBeanDefinition = BeanDefinitionBuilder.rootBeanDefinition(String.class) .addConstructorArgValue(projectPath).getBeanDefinition(); BeanDefinition labelDirNameBeanDefinition = BeanDefinitionBuilder. rootBeanDefinition(String.class) .addConstructorArgValue(version).getBeanDefinition(); BeanDefinition versionBeanDefinition = BeanDefinitionBuilder. rootBeanDefinition(String.class) .addConstructorArgValue(version).getBeanDefinition(); ctx.registerBeanDefinition("projectPath", projectPathBeanDefinition); ctx.registerBeanDefinition("labelDirName", labelDirNameBeanDefinition); ctx.registerBeanDefinition("version", versionBeanDefinition); ctx.refresh(); NetworkDiscoverer discoverer = ctx.getBean("parallelSnmpDiscovery", NetworkDiscoverer.class); return discoverer; }
@Before public void setup() { String baseDir = System.getProperty("base.dir"); if (baseDir==null){ baseDir="."; } System.out.println("BaseDir:"+new File(baseDir).getAbsolutePath()); Map<String,String> properties = new HashMap<>(); String projectDir = new File(baseDir,"projectManager/fileBasedProjectManager/src/test/resources").getAbsolutePath(); properties.put("baseDir", baseDir); GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.refresh(); ctx.load("classpath:fileBasedProjectManager/fileBasedProjectManager.xml"); FileBasedProjectManagerFactory fileBasedProjectManagerFactory = ctx.getBean("projectManagerFactory", FileBasedProjectManagerFactory.class); fileBasedProjectManager = fileBasedProjectManagerFactory.createProjectManager(properties); projectName = fileBasedProjectManager.randomProjectNameGenerator(projectDir); }
private TopologyViewer createTopologyViewer(String projectPath, String projectType) { GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.load("classpath:discoveryResultTopologyViewer/discoveryResultTopologyViewer.xml"); ctx.load("classpath:xmlTopologyViewerConfig/xmlTopologyViewerConfig.xml"); ctx.load("classpath:xmlNodeDataProvider/xmlNodeDataProvider.xml"); AbstractBeanDefinition projectPathBeanDefinition = BeanDefinitionBuilder.rootBeanDefinition(String.class) .addConstructorArgValue(projectPath).getBeanDefinition(); AbstractBeanDefinition projectTypeBeanDefinition = BeanDefinitionBuilder.rootBeanDefinition(String.class) .addConstructorArgValue(projectType).getBeanDefinition(); ctx.registerBeanDefinition("projectPath", projectPathBeanDefinition); ctx.registerBeanDefinition("projectType", projectTypeBeanDefinition); ctx.refresh(); TopologyViewer topologyViewer = ctx.getBean("discoveryResultTopologyViewer", TopologyViewer.class); return topologyViewer; }
@Test public void resourceIdResolver_stackConfiguration_resourceIdResolverBeanExposed() { // Arrange GenericXmlApplicationContext applicationContext = new GenericXmlApplicationContext(); AmazonCloudFormation amazonCloudFormation = Mockito.mock(AmazonCloudFormation.class); when(amazonCloudFormation.listStackResources(new ListStackResourcesRequest().withStackName("IntegrationTestStack"))). thenReturn(new ListStackResourcesResult().withStackResourceSummaries(new StackResourceSummary())); applicationContext.load(new ClassPathResource(getClass().getSimpleName() + "-staticStackName.xml", getClass())); applicationContext.getBeanFactory().registerSingleton(getBeanName(AmazonCloudFormation.class.getName()), amazonCloudFormation); applicationContext.refresh(); // Act ResourceIdResolver resourceIdResolver = applicationContext.getBean(ResourceIdResolver.class); // Assert assertThat(resourceIdResolver, is(not(nullValue()))); }
@Test public void stackResourceRegistry_stackConfigurationWithStaticName_stackResourceRegistryBeanExposedUnderStaticStackName() throws Exception { // Arrange GenericXmlApplicationContext applicationContext = new GenericXmlApplicationContext(); AmazonCloudFormation amazonCloudFormation = Mockito.mock(AmazonCloudFormation.class); when(amazonCloudFormation.listStackResources(new ListStackResourcesRequest().withStackName("IntegrationTestStack"))). thenReturn(new ListStackResourcesResult().withStackResourceSummaries(new StackResourceSummary())); applicationContext.load(new ClassPathResource(getClass().getSimpleName() + "-staticStackName.xml", getClass())); applicationContext.getBeanFactory().registerSingleton(getBeanName(AmazonCloudFormation.class.getName()), amazonCloudFormation); applicationContext.refresh(); // Act StackResourceRegistry staticStackNameProviderBasedStackResourceRegistry = applicationContext.getBean("IntegrationTestStack", StackResourceRegistry.class); // Assert assertThat(staticStackNameProviderBasedStackResourceRegistry, is(not(nullValue()))); }
@Test public void resourceIdResolverResolveToPhysicalResourceId_stackConfigurationWithStaticNameAndLogicalResourceIdOfExistingResourceProvided_returnsPhysicalResourceId() { // Arrange GenericXmlApplicationContext applicationContext = new GenericXmlApplicationContext(); AmazonCloudFormation amazonCloudFormation = Mockito.mock(AmazonCloudFormation.class); when(amazonCloudFormation.listStackResources(new ListStackResourcesRequest().withStackName("IntegrationTestStack"))). thenReturn(new ListStackResourcesResult().withStackResourceSummaries( new StackResourceSummary().withLogicalResourceId("EmptyBucket").withPhysicalResourceId("integrationteststack-emptybucket-foo"))); applicationContext.load(new ClassPathResource(getClass().getSimpleName() + "-staticStackName.xml", getClass())); applicationContext.getBeanFactory().registerSingleton(getBeanName(AmazonCloudFormation.class.getName()), amazonCloudFormation); applicationContext.refresh(); ResourceIdResolver resourceIdResolver = applicationContext.getBean(ResourceIdResolver.class); // Act String physicalResourceId = resourceIdResolver.resolveToPhysicalResourceId("EmptyBucket"); // Assert assertThat(physicalResourceId, startsWith("integrationteststack-emptybucket-")); }
@Test public void resourceIdResolverResolveToPhysicalResourceId_logicalResourceIdOfNonExistingResourceProvided_returnsLogicalResourceIdAsPhysicalResourceId() { // Arrange GenericXmlApplicationContext applicationContext = new GenericXmlApplicationContext(); AmazonCloudFormation amazonCloudFormation = Mockito.mock(AmazonCloudFormation.class); when(amazonCloudFormation.listStackResources(new ListStackResourcesRequest().withStackName("IntegrationTestStack"))). thenReturn(new ListStackResourcesResult().withStackResourceSummaries(new StackResourceSummary())); applicationContext.load(new ClassPathResource(getClass().getSimpleName() + "-staticStackName.xml", getClass())); applicationContext.getBeanFactory().registerSingleton(getBeanName(AmazonCloudFormation.class.getName()), amazonCloudFormation); applicationContext.refresh(); ResourceIdResolver resourceIdResolver = applicationContext.getBean(ResourceIdResolver.class); // Act String physicalResourceId = resourceIdResolver.resolveToPhysicalResourceId("nonExistingLogicalResourceId"); // Assert assertThat(physicalResourceId, is("nonExistingLogicalResourceId")); }
private LuceneMatcher getConfiguration(String config) throws Throwable { logger.debug("Considering initialising match controller with configuration {}", config); // Load up the matchers from the specified files if (!matchers.containsKey(config)){ String configurationFile = "/META-INF/spring/reconciliation-service/" + config + ".xml"; logger.debug("Loading configuration {} from {}", config, configurationFile); ConfigurableApplicationContext context = new GenericXmlApplicationContext(configurationFile); LuceneMatcher matcher = context.getBean("engine", LuceneMatcher.class); matcher.loadData(); logger.debug("Loaded data for configuration {}", config); matchers.put(config, matcher); logger.debug("Stored matcher with name {} from configuration {}", matcher.getConfig().getName(), config); } return matchers.get(config); }
public static void main(String[] args) throws Exception { // Some arguments possibly want to be picked up from the command-line CommandLine line = getParsedCommandLine(args); // where is the work directory that contains the design configuration as well // as the data files? String workDir = "."; if (line.hasOption("d")) workDir = line.getOptionValue("d").trim(); // the name of the core configuration file that contains the dedup/match design // NOTE this is relative to the working directory String configFileName = "config.xml"; if (line.hasOption("c")) configFileName = line.getOptionValue("c").trim(); String dedupDesign = "file:" + new File(new File(workDir), configFileName).toPath(); runEngineAndCache(new GenericXmlApplicationContext(dedupDesign)); }
public static void main(String[] args) throws IOException, ParseException { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml"); Musics musicas = ctx.getBean(Musics.class); MusicService service = ctx.getBean(MusicService.class); for (Music musica: musicas.getMusics()) { service.save(musica); } LuceneUtil.INSTANCE.backupToHD(); System.out.println(service.findMusicByLyric("lepo lepo")); System.out.println(service.findMusicByLyric("aMoR")); System.out.println(service.findMusicByAuthor("Luan Santana")); System.out.println(service.findMusicByAuthor("Santana")); System.out.println(service.findMusicByAuthor("Psirico")); }
public static ProcessEngine buildProcessEngine(URL resource) { log.debug("==== BUILDING SPRING APPLICATION CONTEXT AND PROCESS ENGINE ========================================="); ApplicationContext applicationContext = new GenericXmlApplicationContext(new UrlResource(resource)); Map<String, ProcessEngine> beansOfType = applicationContext.getBeansOfType(ProcessEngine.class); if ( (beansOfType==null) || (beansOfType.isEmpty()) ) { throw new ActivitiException("no "+ProcessEngine.class.getName()+" defined in the application context "+resource.toString()); } ProcessEngine processEngine = beansOfType.values().iterator().next(); log.debug("==== SPRING PROCESS ENGINE CREATED =================================================================="); return processEngine; }
public static ProcessEngine buildProcessEngine(URL resource) { log.fine("==== BUILDING SPRING APPLICATION CONTEXT AND PROCESS ENGINE ========================================="); ApplicationContext applicationContext = new GenericXmlApplicationContext(new UrlResource(resource)); Map<String, ProcessEngine> beansOfType = applicationContext.getBeansOfType(ProcessEngine.class); if ( (beansOfType==null) || (beansOfType.isEmpty()) ) { throw new ProcessEngineException("no "+ProcessEngine.class.getName()+" defined in the application context "+resource.toString()); } ProcessEngine processEngine = beansOfType.values().iterator().next(); log.fine("==== SPRING PROCESS ENGINE CREATED =================================================================="); return processEngine; }
@Override public Ignite startCluster(int clusterSize) { this.clusterSize = clusterSize; clientNode = new GenericXmlApplicationContext(CONFIG_XML).getBean(Ignite.class); processes = new ArrayList<>(clusterSize); startServerNodes(clusterSize); igniteStopper = new IgniteStopper(clientNode); cacheConfigs = getNonSystemCacheConfigs(); serviceConfigs = clientNode.configuration().getServiceConfiguration(); return clientNode; }
private static IgniteConfiguration getIgniteConfigFromCommandLineArgs(String[] args) { if (args.length < 1) { throw new RuntimeException("Xml config path not passed"); } ApplicationContext appContext = new GenericXmlApplicationContext(args[0]); return appContext.getBean(IgniteConfiguration.class); }