@Test public void prototypeCreationReevaluatesExpressions() { GenericApplicationContext ac = new GenericApplicationContext(); AnnotationConfigUtils.registerAnnotationConfigProcessors(ac); RootBeanDefinition rbd = new RootBeanDefinition(PrototypeTestBean.class); rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); rbd.getPropertyValues().add("country", "#{systemProperties.country}"); rbd.getPropertyValues().add("country2", new TypedStringValue("#{systemProperties.country}")); ac.registerBeanDefinition("test", rbd); ac.refresh(); try { System.getProperties().put("name", "juergen1"); System.getProperties().put("country", "UK1"); PrototypeTestBean tb = (PrototypeTestBean) ac.getBean("test"); assertEquals("juergen1", tb.getName()); assertEquals("UK1", tb.getCountry()); assertEquals("UK1", tb.getCountry2()); System.getProperties().put("name", "juergen2"); System.getProperties().put("country", "UK2"); tb = (PrototypeTestBean) ac.getBean("test"); assertEquals("juergen2", tb.getName()); assertEquals("UK2", tb.getCountry()); assertEquals("UK2", tb.getCountry2()); } finally { System.getProperties().remove("name"); System.getProperties().remove("country"); } }
/** * Assert that the attributes returned from the data connector match the provided attributes. * * @param dataConnectorName the data connector name * @param principalName the principalName * @param correctMap the correct attributes */ private void runAttributeDefinitionTest( String dataConnectorName, String principalName, AttributeMap correctMap, String attributeDefinitionName) { try { GenericApplicationContext gContext = BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG); ShibbolethResolutionContext ctx = getShibContext(principalName); // resolve data connector dependency GroupDataConnector gdc = (GroupDataConnector) gContext.getBean(dataConnectorName); gdc.resolve(ctx); ctx.getResolvedPlugins().put(gdc.getId(), gdc); // resolve attribute definition AttributeDefinition ad = (AttributeDefinition) gContext.getBean(attributeDefinitionName); BaseAttribute attr = ad.resolve(ctx); // assert equality AttributeMap currentMap = new AttributeMap(); currentMap.setAttribute(attr); LOG.debug("correctMap\n{}", correctMap); LOG.debug("currentMap\n{}", currentMap); assertEquals(correctMap, currentMap); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
@Test public void testAutowiredFieldResolvesWithMultipleQualifierValuesAndExplicitDefaultValue() { GenericApplicationContext context = new GenericApplicationContext(); ConstructorArgumentValues cavs1 = new ConstructorArgumentValues(); cavs1.addGenericArgumentValue(JUERGEN); RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null); AutowireCandidateQualifier qualifier = new AutowireCandidateQualifier(TestQualifierWithMultipleAttributes.class); qualifier.setAttribute("number", 456); person1.addQualifier(qualifier); ConstructorArgumentValues cavs2 = new ConstructorArgumentValues(); cavs2.addGenericArgumentValue(MARK); RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null); AutowireCandidateQualifier qualifier2 = new AutowireCandidateQualifier(TestQualifierWithMultipleAttributes.class); qualifier2.setAttribute("number", 123); qualifier2.setAttribute("value", "default"); person2.addQualifier(qualifier2); context.registerBeanDefinition(JUERGEN, person1); context.registerBeanDefinition(MARK, person2); context.registerBeanDefinition( "autowired", new RootBeanDefinition(QualifiedFieldWithMultipleAttributesTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); QualifiedFieldWithMultipleAttributesTestBean bean = (QualifiedFieldWithMultipleAttributesTestBean) context.getBean("autowired"); assertEquals(MARK, bean.getPerson().getName()); }
@Test public void prototypeCreationIsFastEnough() { if (factoryLog.isTraceEnabled() || factoryLog.isDebugEnabled()) { // Skip this test: Trace logging blows the time limit. return; } GenericApplicationContext ac = new GenericApplicationContext(); RootBeanDefinition rbd = new RootBeanDefinition(TestBean.class); rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); rbd.getConstructorArgumentValues().addGenericArgumentValue("#{systemProperties.name}"); rbd.getPropertyValues().add("country", "#{systemProperties.country}"); ac.registerBeanDefinition("test", rbd); ac.refresh(); StopWatch sw = new StopWatch(); sw.start("prototype"); System.getProperties().put("name", "juergen"); System.getProperties().put("country", "UK"); try { for (int i = 0; i < 100000; i++) { TestBean tb = (TestBean) ac.getBean("test"); assertEquals("juergen", tb.getName()); assertEquals("UK", tb.getCountry()); } sw.stop(); } finally { System.getProperties().remove("country"); System.getProperties().remove("name"); } assertTrue( "Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 6000); }
/** * Will load additional settings from the web app config. Creates a map object that contains * workflow parameters to be provided as input to the runner * * @param form form definition of the workflow being run * @return a map of the settings */ private static Map<String, String> settingsFromConfig(FormDefinition form) { try { Map<String, String> settings = new HashMap<String, String>(); // Get the workspace basedir from application.conf String workspace = ConfigFactory.defaultApplication().getString("jython.workspace"); // Load workflow yaml file to check parameters GenericApplicationContext springContext = new GenericApplicationContext(); YamlBeanDefinitionReader yamlBeanReader = new YamlBeanDefinitionReader(springContext); yamlBeanReader.loadBeanDefinitions(loadYamlStream(form.yamlFile), "-"); springContext.refresh(); WorkflowConfig workflowConfig = springContext.getBean(WorkflowConfig.class); // Create a workspace Path path = Paths.get(workspace, "workspace_" + UUID.randomUUID()); path.toFile().mkdir(); // If the "workspace" parameter is present in the workflow set it to the path defined in the // config if (workflowConfig.getParameters().containsKey("workspace")) { settings.put("workspace", path.toString()); } return settings; } catch (IOException e) { throw new RuntimeException("Error creating workspace directory.", e); } catch (Exception e) { throw new RuntimeException("Error reading yaml file for parameters.", e); } }
@Test public void testIncrementing() { GenericApplicationContext context = new GenericApplicationContext(); context.registerBeanDefinition( "bfpp", new RootBeanDefinition(DefaultConfiguringBeanFactoryPostProcessor.class)); context.registerBeanDefinition( "foo", new RootBeanDefinition(SimpleIncrementingIdGenerator.class)); context.refresh(); IdGenerator idGenerator = context.getBean(IdGenerator.class); MessageHeaders headers = new MessageHeaders(null); assertEquals(0, headers.getId().getMostSignificantBits()); assertEquals(1, headers.getId().getLeastSignificantBits()); headers = new MessageHeaders(null); assertEquals(0, headers.getId().getMostSignificantBits()); assertEquals(2, headers.getId().getLeastSignificantBits()); AtomicLong bottomBits = TestUtils.getPropertyValue(idGenerator, "bottomBits", AtomicLong.class); bottomBits.set(0xffffffff); headers = new MessageHeaders(null); assertEquals(1, headers.getId().getMostSignificantBits()); assertEquals(0, headers.getId().getLeastSignificantBits()); headers = new MessageHeaders(null); assertEquals(1, headers.getId().getMostSignificantBits()); assertEquals(1, headers.getId().getLeastSignificantBits()); context.close(); }
@Test public void testBeanNameAttrToServiceBeanNameProperty() throws Exception { OsgiServiceProxyFactoryBean factory = (OsgiServiceProxyFactoryBean) appContext.getBean("&importerWithBeanName"); Object obj = TestUtils.getFieldValue(factory, "serviceBeanName"); assertEquals("bean-name attr hasn't been properly parsed", "someBean", obj); }
public void testFilterExactAttribute() { try { GenericApplicationContext gContext = BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG); GroupDataConnector gdc = (GroupDataConnector) gContext.getBean("testFilterExactAttribute"); Filter filter = gdc.getFilter(); Set<Group> groups = filter.getResults(grouperSession); assertEquals(1, groups.size()); assertTrue(groups.contains(groupA)); assertFalse(groups.contains(groupB)); assertFalse(groups.contains(groupC)); assertTrue(filter.matches(groupA)); assertFalse(filter.matches(groupB)); assertFalse(filter.matches(groupC)); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
@Test public void testSimpleReference() throws Exception { Object factoryBean = appContext.getBean("&serializable"); assertTrue(factoryBean instanceof OsgiServiceProxyFactoryBean); OsgiServiceProxyFactoryBean proxyFactory = (OsgiServiceProxyFactoryBean) factoryBean; Class<?>[] intfs = (Class[]) TestUtils.getFieldValue(proxyFactory, "interfaces"); assertEquals(1, intfs.length); assertSame(Serializable.class, intfs[0]); // get the factory product Object bean = appContext.getBean("serializable"); assertTrue(bean instanceof Serializable); assertTrue(Proxy.isProxyClass(bean.getClass())); }
@Test public void testMultipleInterfaces() throws Exception { OsgiServiceProxyFactoryBean factory = (OsgiServiceProxyFactoryBean) appContext.getBean("&multi-interfaces"); Class<?>[] intfs = (Class[]) TestUtils.getFieldValue(factory, "interfaces"); assertNotNull(intfs); assertEquals(2, intfs.length); assertTrue(Arrays.equals(new Class<?>[] {Serializable.class, Externalizable.class}, intfs)); }
public void testGroupNotFound() { try { GenericApplicationContext gContext = BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG); GroupDataConnector gdc = (GroupDataConnector) gContext.getBean("testAttributesOnly"); Map<String, BaseAttribute> map = gdc.resolve(getShibContext("notfound")); assertTrue(map.isEmpty()); } catch (Exception e) { throw new RuntimeException(e); } }
@Test public void testDefaultInitAndDestroyMethodsDefined() { GenericApplicationContext context = new GenericApplicationContext(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultInitAndDestroyMethodsTests.xml"); context.refresh(); DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME); assertTrue("bean should have been initialized", bean.isInitialized()); context.close(); assertTrue("bean should have been destroyed", bean.isDestroyed()); }
@Test public void testAutowireNo() { GenericApplicationContext context = new GenericApplicationContext(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultAutowireNoTests.xml"); context.refresh(); DefaultsTestBean bean = (DefaultsTestBean) context.getBean(TEST_BEAN_NAME); assertNull("no dependencies should have been autowired", bean.getConstructorDependency()); assertNull("no dependencies should have been autowired", bean.getPropertyDependency1()); assertNull("no dependencies should have been autowired", bean.getPropertyDependency2()); }
@Test public void testLazyInitTrue() { GenericApplicationContext context = new GenericApplicationContext(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context); reader.loadBeanDefinitions(LOCATION_PREFIX + "defaultLazyInitTrueTests.xml"); assertTrue("lazy-init should be true", context.getBeanDefinition(TEST_BEAN_NAME).isLazyInit()); assertEquals("initCount should be 0", 0, DefaultsTestBean.INIT_COUNT); context.refresh(); assertEquals("bean should not have been instantiated yet", 0, DefaultsTestBean.INIT_COUNT); context.getBean(TEST_BEAN_NAME); assertEquals("bean should have been instantiated", 1, DefaultsTestBean.INIT_COUNT); }
/** * Assert that the attributes returned from the data connector match the provided attributes. * * @param dataConnectorName the data connector name * @param group the group * @param correctMap the correct attributes */ private void runResolveTest(String dataConnectorName, Group group, AttributeMap correctMap) { try { GenericApplicationContext gContext = BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG); GroupDataConnector gdc = (GroupDataConnector) gContext.getBean(dataConnectorName); AttributeMap currentMap = new AttributeMap(gdc.resolve(getShibContext(group.getName()))); LOG.debug("correctMap\n{}", correctMap); LOG.debug("currentMap\n{}", currentMap); assertEquals(correctMap, currentMap); } catch (Exception e) { throw new RuntimeException(e); } }
@Test public void testPostConstructAndPreDestroyWithApplicationContextAndPostProcessor() { GenericApplicationContext ctx = new GenericApplicationContext(); ctx.registerBeanDefinition("bpp1", new RootBeanDefinition(InitDestroyBeanPostProcessor.class)); ctx.registerBeanDefinition("bpp2", new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class)); ctx.registerBeanDefinition("annotatedBean", new RootBeanDefinition(AnnotatedInitDestroyBean.class)); ctx.refresh(); AnnotatedInitDestroyBean bean = (AnnotatedInitDestroyBean) ctx.getBean("annotatedBean"); assertTrue(bean.initCalled); ctx.close(); assertTrue(bean.destroyCalled); }
@Test public void testJdk() { GenericApplicationContext context = new GenericApplicationContext(); context.registerBeanDefinition( "bfpp", new RootBeanDefinition(DefaultConfiguringBeanFactoryPostProcessor.class)); context.registerBeanDefinition("foo", new RootBeanDefinition(JdkIdGenerator.class)); context.refresh(); MessageHeaders headers = new MessageHeaders(null); assertSame( context.getBean(IdGenerator.class), TestUtils.getPropertyValue(headers, "idGenerator")); context.close(); }
/** * Create a parent context that initializes a {@link * org.apache.camel.spi.PackageScanClassResolver} to exclude a set of given classes from being * resolved. Typically this is used at test time to exclude certain routes, which might otherwise * be just noisy, from being discovered and initialized. * * <p>To use this filtering mechanism it is necessary to provide the {@link ApplicationContext} * returned from here as the parent context to your test context e.g. * * <pre> * protected AbstractXmlApplicationContext createApplicationContext() { * return new ClassPathXmlApplicationContext(new String[] {"test-context.xml"}, getRouteExcludingApplicationContext()); * } * </pre> * * This will, in turn, call the template methods <code>excludedRoutes</code> and <code> * excludedRoute</code> to determine the classes to be excluded from scanning. * * @return ApplicationContext a parent {@link ApplicationContext} configured to exclude certain * classes from package scanning */ protected ApplicationContext getRouteExcludingApplicationContext() { GenericApplicationContext routeExcludingContext = new GenericApplicationContext(); routeExcludingContext.registerBeanDefinition( "excludingResolver", new RootBeanDefinition(ExcludingPackageScanClassResolver.class)); routeExcludingContext.refresh(); ExcludingPackageScanClassResolver excludingResolver = (ExcludingPackageScanClassResolver) routeExcludingContext.getBean("excludingResolver"); List<Class<?>> excluded = CastUtils.cast(Arrays.asList(excludeRoutes())); excludingResolver.setExcludedClasses(new HashSet<Class<?>>(excluded)); return routeExcludingContext; }
@Test public void viaBeanRegistration() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerBeanDefinition( "componentScanAnnotatedConfig", genericBeanDefinition(ComponentScanAnnotatedConfig.class).getBeanDefinition()); bf.registerBeanDefinition( "configurationClassPostProcessor", genericBeanDefinition(ConfigurationClassPostProcessor.class).getBeanDefinition()); GenericApplicationContext ctx = new GenericApplicationContext(bf); ctx.refresh(); ctx.getBean(ComponentScanAnnotatedConfig.class); ctx.getBean(TestBean.class); assertThat( "config class bean not found", ctx.containsBeanDefinition("componentScanAnnotatedConfig"), is(true)); assertThat( "@ComponentScan annotated @Configuration class registered " + "as bean definition did not trigger component scanning as expected", ctx.containsBean("fooServiceImpl"), is(true)); }
public void testMatchFilterMinus() { try { GenericApplicationContext gContext = BaseDataConnectorTest.createSpringContext(RESOLVER_CONFIG); GroupDataConnector gdc = (GroupDataConnector) gContext.getBean("testFilterMinus"); assertTrue( "map should not be empty", !gdc.resolve(getShibContext(groupA.getName())).isEmpty()); assertTrue("map should be empty", gdc.resolve(getShibContext(groupB.getName())).isEmpty()); assertTrue("map should be empty", gdc.resolve(getShibContext(groupC.getName())).isEmpty()); } catch (Exception e) { throw new RuntimeException(e); } }
@Test public void stringConcatenationWithDebugLogging() { GenericApplicationContext ac = new GenericApplicationContext(); AnnotationConfigUtils.registerAnnotationConfigProcessors(ac); GenericBeanDefinition bd = new GenericBeanDefinition(); bd.setBeanClass(String.class); bd.getConstructorArgumentValues() .addGenericArgumentValue("test-#{ T(java.lang.System).currentTimeMillis() }"); ac.registerBeanDefinition("str", bd); ac.refresh(); String str = ac.getBean("str", String.class); assertTrue(str.startsWith("test-")); }
@Test public void testAutowiredFieldWithSingleQualifiedCandidate() { GenericApplicationContext context = new GenericApplicationContext(); ConstructorArgumentValues cavs = new ConstructorArgumentValues(); cavs.addGenericArgumentValue(JUERGEN); RootBeanDefinition person = new RootBeanDefinition(Person.class, cavs, null); person.addQualifier(new AutowireCandidateQualifier(TestQualifier.class)); context.registerBeanDefinition(JUERGEN, person); context.registerBeanDefinition( "autowired", new RootBeanDefinition(QualifiedFieldTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); QualifiedFieldTestBean bean = (QualifiedFieldTestBean) context.getBean("autowired"); assertEquals(JUERGEN, bean.getPerson().getName()); }
private PlaceholderTargetSource createValue(String name, String value) throws Exception { String input = IOUtils.toString( new ClassPathResource(getClass().getSimpleName() + "-context.xml", getClass()) .getInputStream()); input = input.replace( "<!-- INSERT -->", String.format("<property name=\"%s\" value=\"%s\" />", name, value)); Resource resource = new ByteArrayResource(input.getBytes()); GenericApplicationContext context = new GenericApplicationContext(); new XmlBeanDefinitionReader(context).loadBeanDefinitions(resource); context.refresh(); // XmlBeanFactory context = new XmlBeanFactory(resource); return (PlaceholderTargetSource) context.getBean("value"); }
@Test public void testAutowiredMethodParameterWithStaticallyQualifiedCandidate() { GenericApplicationContext context = new GenericApplicationContext(); ConstructorArgumentValues cavs = new ConstructorArgumentValues(); cavs.addGenericArgumentValue(JUERGEN); RootBeanDefinition person = new RootBeanDefinition(QualifiedPerson.class, cavs, null); context.registerBeanDefinition( JUERGEN, ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(person, JUERGEN), context, true) .getBeanDefinition()); context.registerBeanDefinition( "autowired", new RootBeanDefinition(QualifiedMethodParameterTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); QualifiedMethodParameterTestBean bean = (QualifiedMethodParameterTestBean) context.getBean("autowired"); assertEquals(JUERGEN, bean.getPerson().getName()); }
@Test public void testAutowiredMethodParameterWithStaticallyQualifiedCandidateAmongOthers() { GenericApplicationContext context = new GenericApplicationContext(); ConstructorArgumentValues cavs = new ConstructorArgumentValues(); cavs.addGenericArgumentValue(JUERGEN); RootBeanDefinition person = new RootBeanDefinition(QualifiedPerson.class, cavs, null); ConstructorArgumentValues cavs2 = new ConstructorArgumentValues(); cavs2.addGenericArgumentValue(MARK); RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null); context.registerBeanDefinition(JUERGEN, person); context.registerBeanDefinition(MARK, person2); context.registerBeanDefinition( "autowired", new RootBeanDefinition(QualifiedMethodParameterTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); QualifiedMethodParameterTestBean bean = (QualifiedMethodParameterTestBean) context.getBean("autowired"); assertEquals(JUERGEN, bean.getPerson().getName()); }
@Test public void testFullReference() throws Exception { OsgiServiceProxyFactoryBean factory = (OsgiServiceProxyFactoryBean) appContext.getBean("&full-options"); factory.getObject(); // required to initialise proxy and hook // listeners into the binding process OsgiServiceLifecycleListener[] listeners = (OsgiServiceLifecycleListener[]) TestUtils.getFieldValue(factory, "listeners"); assertNotNull(listeners); assertEquals(5, listeners.length); assertEquals( "already registered service should have been discovered", 4, DummyListener.BIND_CALLS); assertEquals(0, DummyListener.UNBIND_CALLS); listeners[1].bind(null, null); assertEquals(6, DummyListener.BIND_CALLS); listeners[1].unbind(null, null); assertEquals(2, DummyListener.UNBIND_CALLS); assertEquals(1, DummyListenerServiceSignature.BIND_CALLS); listeners[4].bind(null, null); assertEquals(2, DummyListenerServiceSignature.BIND_CALLS); assertEquals(0, DummyListenerServiceSignature.UNBIND_CALLS); listeners[4].unbind(null, null); assertEquals(1, DummyListenerServiceSignature.UNBIND_CALLS); assertEquals(1, DummyListenerServiceSignature2.BIND_CALLS); listeners[3].bind(null, null); assertEquals(2, DummyListenerServiceSignature2.BIND_CALLS); assertEquals(0, DummyListenerServiceSignature2.UNBIND_CALLS); listeners[3].unbind(null, null); assertEquals(1, DummyListenerServiceSignature2.UNBIND_CALLS); }
@Test public void testAutowiredFieldResolvesWithDefaultValueAndExplicitDefaultValueOnBeanDefinition() { GenericApplicationContext context = new GenericApplicationContext(); ConstructorArgumentValues cavs1 = new ConstructorArgumentValues(); cavs1.addGenericArgumentValue(JUERGEN); RootBeanDefinition person1 = new RootBeanDefinition(Person.class, cavs1, null); // qualifier added, and value matches the default person1.addQualifier( new AutowireCandidateQualifier(TestQualifierWithDefaultValue.class, "default")); ConstructorArgumentValues cavs2 = new ConstructorArgumentValues(); cavs2.addGenericArgumentValue(MARK); RootBeanDefinition person2 = new RootBeanDefinition(Person.class, cavs2, null); context.registerBeanDefinition(JUERGEN, person1); context.registerBeanDefinition(MARK, person2); context.registerBeanDefinition( "autowired", new RootBeanDefinition(QualifiedFieldWithDefaultValueTestBean.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); context.refresh(); QualifiedFieldWithDefaultValueTestBean bean = (QualifiedFieldWithDefaultValueTestBean) context.getBean("autowired"); assertEquals(JUERGEN, bean.getPerson().getName()); }
private static DataServiceManager getDataServiceManager(GenericApplicationContext ctx) { DataServiceManager mgr = null; try { String[] beanNames = ctx.getBeanNamesForType(DataServiceManager.class, true, false); if (beanNames == null || 1 != beanNames.length) { throw new WMRuntimeException( com.wavemaker.common.MessageResource.NO_DATA_SERVICE_MGR_BEAN_FOUND, Arrays.toString(beanNames)); } mgr = (DataServiceManager) ctx.getBean(beanNames[0]); } catch (RuntimeException ex) { try { ctx.close(); } catch (Exception ignore) { } throw ex; } return new SpringDataServiceManagerWrapper(mgr, ctx); }
@Test public void systemPropertiesSecurityManager() { GenericApplicationContext ac = new GenericApplicationContext(); AnnotationConfigUtils.registerAnnotationConfigProcessors(ac); GenericBeanDefinition bd = new GenericBeanDefinition(); bd.setBeanClass(TestBean.class); bd.getPropertyValues().add("country", "#{systemProperties.country}"); ac.registerBeanDefinition("tb", bd); SecurityManager oldSecurityManager = System.getSecurityManager(); try { System.setProperty("country", "NL"); SecurityManager securityManager = new SecurityManager() { @Override public void checkPropertiesAccess() { throw new AccessControlException("Not Allowed"); } @Override public void checkPermission(Permission perm) { // allow everything else } }; System.setSecurityManager(securityManager); ac.refresh(); TestBean tb = ac.getBean("tb", TestBean.class); assertEquals("NL", tb.getCountry()); } finally { System.setSecurityManager(oldSecurityManager); System.getProperties().remove("country"); } }
private void doTestJaxWsPortAccess(Object... features) throws Exception { GenericApplicationContext ac = new GenericApplicationContext(); GenericBeanDefinition serviceDef = new GenericBeanDefinition(); serviceDef.setBeanClass(OrderServiceImpl.class); ac.registerBeanDefinition("service", serviceDef); GenericBeanDefinition exporterDef = new GenericBeanDefinition(); exporterDef.setBeanClass(SimpleJaxWsServiceExporter.class); exporterDef.getPropertyValues().add("baseAddress", "http://localhost:9999/"); ac.registerBeanDefinition("exporter", exporterDef); GenericBeanDefinition clientDef = new GenericBeanDefinition(); clientDef.setBeanClass(JaxWsPortProxyFactoryBean.class); clientDef.getPropertyValues().add("wsdlDocumentUrl", "http://localhost:9999/OrderService?wsdl"); clientDef.getPropertyValues().add("namespaceUri", "http://jaxws.remoting.springframework.org/"); clientDef.getPropertyValues().add("username", "juergen"); clientDef.getPropertyValues().add("password", "hoeller"); clientDef.getPropertyValues().add("serviceName", "OrderService"); clientDef.getPropertyValues().add("serviceInterface", OrderService.class); clientDef.getPropertyValues().add("lookupServiceOnStartup", Boolean.FALSE); if (features != null) { clientDef.getPropertyValues().add("webServiceFeatures", features); } ac.registerBeanDefinition("client", clientDef); GenericBeanDefinition serviceFactoryDef = new GenericBeanDefinition(); serviceFactoryDef.setBeanClass(LocalJaxWsServiceFactoryBean.class); serviceFactoryDef .getPropertyValues() .add("wsdlDocumentUrl", "http://localhost:9999/OrderService?wsdl"); serviceFactoryDef .getPropertyValues() .add("namespaceUri", "http://jaxws.remoting.springframework.org/"); serviceFactoryDef.getPropertyValues().add("serviceName", "OrderService"); ac.registerBeanDefinition("orderService", serviceFactoryDef); ac.registerBeanDefinition("accessor", new RootBeanDefinition(ServiceAccessor.class)); AnnotationConfigUtils.registerAnnotationConfigProcessors(ac); try { ac.refresh(); OrderService orderService = ac.getBean("client", OrderService.class); assertTrue(orderService instanceof BindingProvider); ((BindingProvider) orderService).getRequestContext(); String order = orderService.getOrder(1000); assertEquals("order 1000", order); try { orderService.getOrder(0); fail("Should have thrown OrderNotFoundException"); } catch (OrderNotFoundException ex) { // expected } ServiceAccessor serviceAccessor = ac.getBean("accessor", ServiceAccessor.class); order = serviceAccessor.orderService.getOrder(1000); assertEquals("order 1000", order); try { serviceAccessor.orderService.getOrder(0); fail("Should have thrown OrderNotFoundException"); } catch (OrderNotFoundException ex) { // expected } } catch (BeanCreationException ex) { if ("exporter".equals(ex.getBeanName()) && ex.getRootCause() instanceof ClassNotFoundException) { // ignore - probably running on JDK < 1.6 without the JAX-WS impl present } else { throw ex; } } finally { ac.close(); } }