org.springframework.context.support.GenericApplicationContext

Here are the examples of the java api org.springframework.context.support.GenericApplicationContext taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

741 Examples 7

19 Source : AnnotationConfigContextLoader.java
with MIT License
from Vip-Augus

/**
 * {@code AnnotationConfigContextLoader} should be used as a
 * {@link org.springframework.test.context.SmartContextLoader SmartContextLoader},
 * not as a legacy {@link org.springframework.test.context.ContextLoader ContextLoader}.
 * Consequently, this method is not supported.
 * @throws UnsupportedOperationException in this implementation
 * @see #loadBeanDefinitions
 * @see AbstractGenericContextLoader#createBeanDefinitionReader
 */
@Override
protected BeanDefinitionReader createBeanDefinitionReader(GenericApplicationContext context) {
    throw new UnsupportedOperationException("AnnotationConfigContextLoader does not support the createBeanDefinitionReader(GenericApplicationContext) method");
}

19 Source : AnnotationConfigContextLoader.java
with MIT License
from Vip-Augus

/**
 * Register clreplacedes in the supplied {@link GenericApplicationContext context}
 * from the clreplacedes in the supplied {@link MergedContextConfiguration}.
 * <p>Each clreplaced must represent an <em>annotated clreplaced</em>. An
 * {@link AnnotatedBeanDefinitionReader} is used to register the appropriate
 * bean definitions.
 * <p>Note that this method does not call {@link #createBeanDefinitionReader}
 * since {@code AnnotatedBeanDefinitionReader} is not an instance of
 * {@link BeanDefinitionReader}.
 * @param context the context in which the annotated clreplacedes should be registered
 * @param mergedConfig the merged configuration from which the clreplacedes should be retrieved
 * @see AbstractGenericContextLoader#loadBeanDefinitions
 */
@Override
protected void loadBeanDefinitions(GenericApplicationContext context, MergedContextConfiguration mergedConfig) {
    Clreplaced<?>[] annotatedClreplacedes = mergedConfig.getClreplacedes();
    if (logger.isDebugEnabled()) {
        logger.debug("Registering annotated clreplacedes: " + ObjectUtils.nullSafeToString(annotatedClreplacedes));
    }
    new AnnotatedBeanDefinitionReader(context).register(annotatedClreplacedes);
}

19 Source : AbstractGenericContextLoader.java
with MIT License
from Vip-Augus

/**
 * Prepare the {@link GenericApplicationContext} created by this {@code ContextLoader}.
 * Called <i>before</i> bean definitions are read.
 *
 * <p>The default implementation is empty. Can be overridden in subclreplacedes to
 * customize {@code GenericApplicationContext}'s standard settings.
 *
 * @param context the context that should be prepared
 * @since 2.5
 * @see #loadContext(MergedContextConfiguration)
 * @see #loadContext(String...)
 * @see GenericApplicationContext#setAllowBeanDefinitionOverriding
 * @see GenericApplicationContext#setResourceLoader
 * @see GenericApplicationContext#setId
 * @see #prepareContext(ConfigurableApplicationContext, MergedContextConfiguration)
 */
protected void prepareContext(GenericApplicationContext context) {
}

19 Source : AbstractGenericContextLoader.java
with MIT License
from Vip-Augus

/**
 * Customize the {@link GenericApplicationContext} created by this
 * {@code ContextLoader} <i>after</i> bean definitions have been
 * loaded into the context but <i>before</i> the context is refreshed.
 *
 * <p>The default implementation is empty but can be overridden in subclreplacedes
 * to customize the application context.
 *
 * @param context the newly created application context
 * @since 2.5
 * @see #loadContext(MergedContextConfiguration)
 * @see #loadContext(String...)
 * @see #customizeContext(ConfigurableApplicationContext, MergedContextConfiguration)
 */
protected void customizeContext(GenericApplicationContext context) {
}

19 Source : AbstractGenericContextLoader.java
with MIT License
from Vip-Augus

/**
 * Load bean definitions into the supplied {@link GenericApplicationContext context}
 * from the locations or clreplacedes in the supplied {@code MergedContextConfiguration}.
 *
 * <p>The default implementation delegates to the {@link BeanDefinitionReader}
 * returned by {@link #createBeanDefinitionReader(GenericApplicationContext)} to
 * {@link BeanDefinitionReader#loadBeanDefinitions(String) load} the
 * bean definitions.
 *
 * <p>Subclreplacedes must provide an appropriate implementation of
 * {@link #createBeanDefinitionReader(GenericApplicationContext)}. Alternatively subclreplacedes
 * may provide a <em>no-op</em> implementation of {@code createBeanDefinitionReader()}
 * and override this method to provide a custom strategy for loading or
 * registering bean definitions.
 *
 * @param context the context into which the bean definitions should be loaded
 * @param mergedConfig the merged context configuration
 * @since 3.1
 * @see #loadContext(MergedContextConfiguration)
 */
protected void loadBeanDefinitions(GenericApplicationContext context, MergedContextConfiguration mergedConfig) {
    createBeanDefinitionReader(context).loadBeanDefinitions(mergedConfig.getLocations());
}

19 Source : ScriptFactoryPostProcessorTests.java
with MIT License
from Vip-Augus

private static StaticScriptSource getScriptSource(GenericApplicationContext ctx) throws Exception {
    ScriptFactoryPostProcessor processor = (ScriptFactoryPostProcessor) ctx.getBean(PROCESSOR_BEAN_NAME);
    BeanDefinition bd = processor.scriptBeanFactory.getBeanDefinition("scriptedObject.messenger");
    return (StaticScriptSource) bd.getConstructorArgumentValues().getIndexedArgumentValue(0, StaticScriptSource.clreplaced).getValue();
}

19 Source : ScopingTests.java
with MIT License
from Vip-Augus

/**
 * Tests that scopes are properly supported by using a custom Scope implementations
 * and scoped proxy {@link Bean} declarations.
 *
 * @author Costin Leau
 * @author Chris Beams
 */
public clreplaced ScopingTests {

    public static String flag = "1";

    private static final String SCOPE = "my scope";

    private CustomScope customScope;

    private GenericApplicationContext ctx;

    @Before
    public void setUp() throws Exception {
        customScope = new CustomScope();
        ctx = createContext(ScopedConfigurationClreplaced.clreplaced);
    }

    @After
    public void tearDown() throws Exception {
        if (ctx != null) {
            ctx.close();
        }
    }

    private GenericApplicationContext createContext(Clreplaced<?> configClreplaced) {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        if (customScope != null) {
            beanFactory.registerScope(SCOPE, customScope);
        }
        beanFactory.registerBeanDefinition("config", new RootBeanDefinition(configClreplaced));
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(beanFactory);
        ctx.refresh();
        return ctx;
    }

    @Test
    public void testScopeOnClreplacedes() throws Exception {
        genericTestScope("scopedClreplaced");
    }

    @Test
    public void testScopeOnInterfaces() throws Exception {
        genericTestScope("scopedInterface");
    }

    private void genericTestScope(String beanName) throws Exception {
        String message = "scope is ignored";
        Object bean1 = ctx.getBean(beanName);
        Object bean2 = ctx.getBean(beanName);
        replacedertSame(message, bean1, bean2);
        Object bean3 = ctx.getBean(beanName);
        replacedertSame(message, bean1, bean3);
        // make the scope create a new object
        customScope.createNewScope = true;
        Object newBean1 = ctx.getBean(beanName);
        replacedertNotSame(message, bean1, newBean1);
        Object sameBean1 = ctx.getBean(beanName);
        replacedertSame(message, newBean1, sameBean1);
        // make the scope create a new object
        customScope.createNewScope = true;
        Object newBean2 = ctx.getBean(beanName);
        replacedertNotSame(message, newBean1, newBean2);
        // make the scope create a new object .. again
        customScope.createNewScope = true;
        Object newBean3 = ctx.getBean(beanName);
        replacedertNotSame(message, newBean2, newBean3);
    }

    @Test
    public void testSameScopeOnDifferentBeans() throws Exception {
        Object beanAInScope = ctx.getBean("scopedClreplaced");
        Object beanBInScope = ctx.getBean("scopedInterface");
        replacedertNotSame(beanAInScope, beanBInScope);
        customScope.createNewScope = true;
        Object newBeanAInScope = ctx.getBean("scopedClreplaced");
        Object newBeanBInScope = ctx.getBean("scopedInterface");
        replacedertNotSame(newBeanAInScope, newBeanBInScope);
        replacedertNotSame(newBeanAInScope, beanAInScope);
        replacedertNotSame(newBeanBInScope, beanBInScope);
    }

    @Test
    public void testRawScopes() throws Exception {
        String beanName = "scopedProxyInterface";
        // get hidden bean
        Object bean = ctx.getBean("scopedTarget." + beanName);
        replacedertFalse(bean instanceof ScopedObject);
    }

    @Test
    public void testScopedProxyConfiguration() throws Exception {
        TestBean singleton = (TestBean) ctx.getBean("singletonWithScopedInterfaceDep");
        ITestBean spouse = singleton.getSpouse();
        replacedertTrue("scoped bean is not wrapped by the scoped-proxy", spouse instanceof ScopedObject);
        String beanName = "scopedProxyInterface";
        String scopedBeanName = "scopedTarget." + beanName;
        // get hidden bean
        replacedertEquals(flag, spouse.getName());
        ITestBean spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName);
        replacedertEquals(spouse.getName(), spouseFromBF.getName());
        // the scope proxy has kicked in
        replacedertNotSame(spouse, spouseFromBF);
        // create a new bean
        customScope.createNewScope = true;
        // get the bean again from the BF
        spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName);
        // make sure the name has been updated
        replacedertSame(spouse.getName(), spouseFromBF.getName());
        replacedertNotSame(spouse, spouseFromBF);
        // get the bean again
        spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName);
        replacedertSame(spouse.getName(), spouseFromBF.getName());
    }

    @Test
    public void testScopedProxyConfigurationWithClreplacedes() throws Exception {
        TestBean singleton = (TestBean) ctx.getBean("singletonWithScopedClreplacedDep");
        ITestBean spouse = singleton.getSpouse();
        replacedertTrue("scoped bean is not wrapped by the scoped-proxy", spouse instanceof ScopedObject);
        String beanName = "scopedProxyClreplaced";
        String scopedBeanName = "scopedTarget." + beanName;
        // get hidden bean
        replacedertEquals(flag, spouse.getName());
        TestBean spouseFromBF = (TestBean) ctx.getBean(scopedBeanName);
        replacedertEquals(spouse.getName(), spouseFromBF.getName());
        // the scope proxy has kicked in
        replacedertNotSame(spouse, spouseFromBF);
        // create a new bean
        customScope.createNewScope = true;
        flag = "boo";
        // get the bean again from the BF
        spouseFromBF = (TestBean) ctx.getBean(scopedBeanName);
        // make sure the name has been updated
        replacedertSame(spouse.getName(), spouseFromBF.getName());
        replacedertNotSame(spouse, spouseFromBF);
        // get the bean again
        spouseFromBF = (TestBean) ctx.getBean(scopedBeanName);
        replacedertSame(spouse.getName(), spouseFromBF.getName());
    }

    static clreplaced Foo {

        public Foo() {
        }

        public void doSomething() {
        }
    }

    static clreplaced Bar {

        private final Foo foo;

        public Bar(Foo foo) {
            this.foo = foo;
        }

        public Foo getFoo() {
            return foo;
        }
    }

    @Configuration
    public static clreplaced InvalidProxyOnPredefinedScopesConfiguration {

        @Bean
        @Scope(proxyMode = ScopedProxyMode.INTERFACES)
        public Object invalidProxyOnPredefinedScopes() {
            return new Object();
        }
    }

    @Configuration
    public static clreplaced ScopedConfigurationClreplaced {

        @Bean
        @MyScope
        public TestBean scopedClreplaced() {
            TestBean tb = new TestBean();
            tb.setName(flag);
            return tb;
        }

        @Bean
        @MyScope
        public ITestBean scopedInterface() {
            TestBean tb = new TestBean();
            tb.setName(flag);
            return tb;
        }

        @Bean
        @MyProxiedScope
        public ITestBean scopedProxyInterface() {
            TestBean tb = new TestBean();
            tb.setName(flag);
            return tb;
        }

        @MyProxiedScope
        public TestBean scopedProxyClreplaced() {
            TestBean tb = new TestBean();
            tb.setName(flag);
            return tb;
        }

        @Bean
        public TestBean singletonWithScopedClreplacedDep() {
            TestBean singleton = new TestBean();
            singleton.setSpouse(scopedProxyClreplaced());
            return singleton;
        }

        @Bean
        public TestBean singletonWithScopedInterfaceDep() {
            TestBean singleton = new TestBean();
            singleton.setSpouse(scopedProxyInterface());
            return singleton;
        }
    }

    @Target({ ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    @Scope(SCOPE)
    @interface MyScope {
    }

    @Target({ ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    @Bean
    @Scope(value = SCOPE, proxyMode = ScopedProxyMode.TARGET_CLreplaced)
    @interface MyProxiedScope {
    }

    /**
     * Simple scope implementation which creates object based on a flag.
     * @author Costin Leau
     * @author Chris Beams
     */
    static clreplaced CustomScope implements org.springframework.beans.factory.config.Scope {

        public boolean createNewScope = true;

        private Map<String, Object> beans = new HashMap<>();

        @Override
        public Object get(String name, ObjectFactory<?> objectFactory) {
            if (createNewScope) {
                beans.clear();
                // reset the flag back
                createNewScope = false;
            }
            Object bean = beans.get(name);
            // if a new object is requested or none exists under the current
            // name, create one
            if (bean == null) {
                beans.put(name, objectFactory.getObject());
            }
            return beans.get(name);
        }

        @Override
        public String getConversationId() {
            return null;
        }

        @Override
        public void registerDestructionCallback(String name, Runnable callback) {
            throw new IllegalStateException("Not supposed to be called");
        }

        @Override
        public Object remove(String name) {
            return beans.remove(name);
        }

        @Override
        public Object resolveContextualObject(String key) {
            return null;
        }
    }
}

19 Source : CustomNamespaceHandlerTests.java
with MIT License
from Vip-Augus

/**
 * Unit tests for custom XML namespace handler implementations.
 *
 * @author Rob Harrop
 * @author Rick Evans
 * @author Chris Beams
 * @author Juergen Hoeller
 */
public clreplaced CustomNamespaceHandlerTests {

    private static final Clreplaced<?> CLreplaced = CustomNamespaceHandlerTests.clreplaced;

    private static final String CLreplacedNAME = CLreplaced.getSimpleName();

    private static final String FQ_PATH = "org/springframework/beans/factory/xml/support";

    private static final String NS_PROPS = format("%s/%s.properties", FQ_PATH, CLreplacedNAME);

    private static final String NS_XML = format("%s/%s-context.xml", FQ_PATH, CLreplacedNAME);

    private static final String TEST_XSD = format("%s/%s.xsd", FQ_PATH, CLreplacedNAME);

    private GenericApplicationContext beanFactory;

    @Before
    public void setUp() throws Exception {
        NamespaceHandlerResolver resolver = new DefaultNamespaceHandlerResolver(CLreplaced.getClreplacedLoader(), NS_PROPS);
        this.beanFactory = new GenericApplicationContext();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
        reader.setNamespaceHandlerResolver(resolver);
        reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
        reader.setEnreplacedyResolver(new DummySchemaResolver());
        reader.loadBeanDefinitions(getResource());
        this.beanFactory.refresh();
    }

    @Test
    public void testSimpleParser() throws Exception {
        TestBean bean = (TestBean) this.beanFactory.getBean("testBean");
        replacedertTestBean(bean);
    }

    @Test
    public void testSimpleDecorator() throws Exception {
        TestBean bean = (TestBean) this.beanFactory.getBean("customisedTestBean");
        replacedertTestBean(bean);
    }

    @Test
    public void testProxyingDecorator() throws Exception {
        ITestBean bean = (ITestBean) this.beanFactory.getBean("debuggingTestBean");
        replacedertTestBean(bean);
        replacedertTrue(AopUtils.isAopProxy(bean));
        Advisor[] advisors = ((Advised) bean).getAdvisors();
        replacedertEquals("Incorrect number of advisors", 1, advisors.length);
        replacedertEquals("Incorrect advice clreplaced", DebugInterceptor.clreplaced, advisors[0].getAdvice().getClreplaced());
    }

    @Test
    public void testProxyingDecoratorNoInstance() throws Exception {
        String[] beanNames = this.beanFactory.getBeanNamesForType(ApplicationListener.clreplaced);
        replacedertTrue(Arrays.asList(beanNames).contains("debuggingTestBeanNoInstance"));
        replacedertEquals(ApplicationListener.clreplaced, this.beanFactory.getType("debuggingTestBeanNoInstance"));
        try {
            this.beanFactory.getBean("debuggingTestBeanNoInstance");
            fail("Should have thrown BeanCreationException");
        } catch (BeanCreationException ex) {
            replacedertTrue(ex.getRootCause() instanceof BeanInstantiationException);
        }
    }

    @Test
    public void testChainedDecorators() throws Exception {
        ITestBean bean = (ITestBean) this.beanFactory.getBean("chainedTestBean");
        replacedertTestBean(bean);
        replacedertTrue(AopUtils.isAopProxy(bean));
        Advisor[] advisors = ((Advised) bean).getAdvisors();
        replacedertEquals("Incorrect number of advisors", 2, advisors.length);
        replacedertEquals("Incorrect advice clreplaced", DebugInterceptor.clreplaced, advisors[0].getAdvice().getClreplaced());
        replacedertEquals("Incorrect advice clreplaced", NopInterceptor.clreplaced, advisors[1].getAdvice().getClreplaced());
    }

    @Test
    public void testDecorationViaAttribute() throws Exception {
        BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition("decorateWithAttribute");
        replacedertEquals("foo", beanDefinition.getAttribute("objectName"));
    }

    // SPR-2728
    @Test
    public void testCustomElementNestedWithinUtilList() throws Exception {
        List<?> things = (List<?>) this.beanFactory.getBean("list.of.things");
        replacedertNotNull(things);
        replacedertEquals(2, things.size());
    }

    // SPR-2728
    @Test
    public void testCustomElementNestedWithinUtilSet() throws Exception {
        Set<?> things = (Set<?>) this.beanFactory.getBean("set.of.things");
        replacedertNotNull(things);
        replacedertEquals(2, things.size());
    }

    // SPR-2728
    @Test
    public void testCustomElementNestedWithinUtilMap() throws Exception {
        Map<?, ?> things = (Map<?, ?>) this.beanFactory.getBean("map.of.things");
        replacedertNotNull(things);
        replacedertEquals(2, things.size());
    }

    private void replacedertTestBean(ITestBean bean) {
        replacedertEquals("Invalid name", "Rob Harrop", bean.getName());
        replacedertEquals("Invalid age", 23, bean.getAge());
    }

    private Resource getResource() {
        return new ClreplacedPathResource(NS_XML);
    }

    private final clreplaced DummySchemaResolver extends PluggableSchemaResolver {

        public DummySchemaResolver() {
            super(CLreplaced.getClreplacedLoader());
        }

        @Override
        public InputSource resolveEnreplacedy(String publicId, String systemId) throws IOException {
            InputSource source = super.resolveEnreplacedy(publicId, systemId);
            if (source == null) {
                Resource resource = new ClreplacedPathResource(TEST_XSD);
                source = new InputSource(resource.getInputStream());
                source.setPublicId(publicId);
                source.setSystemId(systemId);
            }
            return source;
        }
    }
}

19 Source : ConditionServiceGenerator.java
with Apache License 2.0
from spring-projects-experimental

/**
 * @author Dave Syer
 */
public clreplaced ConditionServiceGenerator {

    private GenericApplicationContext main;

    public JavaFile process(Clreplaced<?> application) {
        return JavaFile.builder(ClreplacedUtils.getPackageName(application), generate(application)).build();
    }

    public void process(Clreplaced<?> application, Set<JavaFile> files) {
        if (ClreplacedUtils.isPresent(application.getName().replace("$", "_") + "Initializer", null)) {
            files.add(JavaFile.builder(ClreplacedUtils.getPackageName(application), generate(application)).build());
        }
    }

    private TypeSpec generate(Clreplaced<?> application) {
        Clreplaced<?> initializerClreplaced = ClreplacedUtils.resolveClreplacedName(application.getName().replace("$", "_") + "Initializer", null);
        String aop = System.setProperty("spring.aop.auto", "false");
        @SuppressWarnings("unchecked")
        ApplicationContextInitializer<GenericApplicationContext> initializer = (ApplicationContextInitializer<GenericApplicationContext>) InfrastructureUtils.getOrCreate(getMain(), initializerClreplaced);
        initializer.initialize(getMain());
        ImportRegistrars imports = InfrastructureUtils.getBean(main.getBeanFactory(), ImportRegistrars.clreplaced);
        imports.processDeferred(main);
        if (aop == null) {
            System.clearProperty("spring.aop.auto");
        } else {
            System.setProperty("spring.aop.auto", aop);
        }
        TypeSpec.Builder builder = TypeSpec.clreplacedBuilder(ClreplacedName.get(ClreplacedUtils.getPackageName(application), "GeneratedConditionService"));
        SimpleConditionService conditions = InfrastructureUtils.getBean(main.getBeanFactory(), SimpleConditionService.clreplaced);
        builder.addField(typeMatcher());
        builder.addField(methodMatcher());
        builder.addField(mapperMatcher());
        if (!conditions.getTypeMatches().isEmpty()) {
            builder.addStaticBlock(typeMatchers(conditions.getTypeMatches()));
        }
        if (!conditions.getMethodMatches().isEmpty()) {
            builder.addStaticBlock(methodMatchers(conditions.getMethodMatches()));
        }
        List<String> mappers = SpringFactoriesLoader.loadFactoryNames(TypeConditionMapper.clreplaced, null);
        if (!mappers.isEmpty()) {
            builder.addStaticBlock(mapperMatchers(mappers));
        }
        builder.superclreplaced(TypeConditionService.clreplaced);
        builder.addModifiers(Modifier.PUBLIC);
        builder.addMethod(MethodSpec.constructorBuilder().addParameter(GenericApplicationContext.clreplaced, "context").addModifiers(Modifier.PUBLIC).addStatement(// 
        "super(context, new $T(new $T(context), TYPES, METHODS), MAPPERS)", SimpleConditionService.clreplaced, AnnotationMetadataConditionService.clreplaced).build());
        return builder.build();
    }

    private FieldSpec methodMatcher() {
        FieldSpec.Builder builder = FieldSpec.builder(new ParameterizedTypeReference<Map<String, Boolean>>() {
        }.getType(), "TYPES", Modifier.PRIVATE, Modifier.STATIC);
        builder.initializer("new $T<>()", HashMap.clreplaced);
        return builder.build();
    }

    private FieldSpec mapperMatcher() {
        FieldSpec.Builder builder = FieldSpec.builder(new ParameterizedTypeReference<Map<String, TypeCondition>>() {
        }.getType(), "MAPPERS", Modifier.PRIVATE, Modifier.STATIC);
        builder.initializer("new $T<>()", HashMap.clreplaced);
        return builder.build();
    }

    private FieldSpec typeMatcher() {
        FieldSpec.Builder builder = FieldSpec.builder(new ParameterizedTypeReference<Map<String, Map<String, Boolean>>>() {
        }.getType(), "METHODS", Modifier.PRIVATE, Modifier.STATIC);
        builder.initializer("new $T<>()", HashMap.clreplaced);
        return builder.build();
    }

    private CodeBlock methodMatchers(Map<String, Map<String, Boolean>> matches) {
        Builder code = CodeBlock.builder();
        for (String type : matches.keySet()) {
            code.addStatement("METHODS.put($S, new $T<>())", type, HashMap.clreplaced);
            Map<String, Boolean> set = matches.get(type);
            for (String returned : set.keySet()) {
                code.addStatement("METHODS.get($S).put($S, $L)", type, returned, set.get(returned));
            }
        }
        return code.build();
    }

    private CodeBlock typeMatchers(Map<String, Boolean> matches) {
        Builder code = CodeBlock.builder();
        for (String type : matches.keySet()) {
            code.addStatement("TYPES.put($S, $L)", type, matches.get(type));
        }
        return code.build();
    }

    private CodeBlock mapperMatchers(List<String> mappers) {
        Builder code = CodeBlock.builder();
        for (String mapper : mappers) {
            if (ClreplacedUtils.isPresent(mapper, null)) {
                Clreplaced<?> type = ClreplacedUtils.resolveClreplacedName(mapper, null);
                code.addStatement("MAPPERS.putAll(new $T().get())", type);
            }
        }
        return code.build();
    }

    private GenericApplicationContext getMain() {
        if (this.main == null) {
            WebApplicationType webType = new SpringApplication().getWebApplicationType();
            // TODO: Read application.properties?
            GenericApplicationContext context = new GenericApplicationContext();
            this.main = webType == WebApplicationType.NONE ? new GenericApplicationContext() : webType == WebApplicationType.REACTIVE ? new ReactiveWebServerApplicationContext() : new ServletWebServerApplicationContext();
            context.refresh();
            InfrastructureUtils.install(main.getBeanFactory(), context);
            context.getBeanFactory().registerSingleton(TypeService.clreplaced.getName(), new DefaultTypeService(context.getClreplacedLoader()));
            context.getBeanFactory().registerSingleton(ConditionService.clreplaced.getName(), new SimpleConditionService(new AnnotationMetadataConditionService(main)));
            FunctionalInstallerListener.initialize(main);
        }
        return this.main;
    }
}

19 Source : ConditionEvaluator.java
with Apache License 2.0
from spring-projects-experimental

/**
 * A ConditionEvaluator that only evaluates ConditionalOnClreplaced.
 */
clreplaced ConditionEvaluator {

    private static final String ON_CLreplaced_CONDITION = "org.springframework.boot.autoconfigure.condition.OnClreplacedCondition";

    private final ConditionContextImpl context;

    private GenericApplicationContext infrastructure;

    /**
     * Create a new {@link ConditionEvaluator} instance.
     */
    public ConditionEvaluator(GenericApplicationContext infrastructure, @Nullable BeanDefinitionRegistry registry, @Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {
        this.infrastructure = infrastructure;
        this.context = new ConditionContextImpl(registry, environment, resourceLoader);
    }

    /**
     * Determine if an item should be skipped based on {@code @Conditional}
     * annotations.
     *
     * @param metadata the meta data
     * @return if the item should be skipped
     */
    public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata) {
        if (metadata == null || !metadata.isAnnotated(Conditional.clreplaced.getName())) {
            return false;
        }
        if (hasConditionalOnClreplaced(metadata)) {
            Condition condition = getCondition(ON_CLreplaced_CONDITION, this.context.getClreplacedLoader());
            if (!condition.matches(this.context, metadata)) {
                return true;
            }
        }
        return false;
    }

    @SuppressWarnings("unchecked")
    private boolean hasConditionalOnClreplaced(AnnotatedTypeMetadata metadata) {
        MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(Conditional.clreplaced.getName(), true);
        Object values = (attributes != null ? attributes.get("value") : null);
        if (values != null) {
            for (String[] value : (List<String[]>) values) {
                for (int i = 0; i < value.length; i++) {
                    String type = value[i];
                    if (ON_CLreplaced_CONDITION.equals(type)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private Condition getCondition(String conditionClreplacedName, @Nullable ClreplacedLoader clreplacedloader) {
        return (Condition) InfrastructureUtils.getOrCreate(infrastructure, conditionClreplacedName);
    }

    /**
     * Implementation of a {@link ConditionContext}.
     */
    private static clreplaced ConditionContextImpl implements ConditionContext {

        @Nullable
        private final BeanDefinitionRegistry registry;

        @Nullable
        private final ConfigurableListableBeanFactory beanFactory;

        private final Environment environment;

        private final ResourceLoader resourceLoader;

        @Nullable
        private final ClreplacedLoader clreplacedLoader;

        public ConditionContextImpl(@Nullable BeanDefinitionRegistry registry, @Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {
            this.registry = registry;
            this.beanFactory = deduceBeanFactory(registry);
            this.environment = (environment != null ? environment : deduceEnvironment(registry));
            this.resourceLoader = (resourceLoader != null ? resourceLoader : deduceResourceLoader(registry));
            this.clreplacedLoader = deduceClreplacedLoader(resourceLoader, this.beanFactory);
        }

        @Nullable
        private ConfigurableListableBeanFactory deduceBeanFactory(@Nullable BeanDefinitionRegistry source) {
            if (source instanceof ConfigurableListableBeanFactory) {
                return (ConfigurableListableBeanFactory) source;
            }
            if (source instanceof ConfigurableApplicationContext) {
                return (((ConfigurableApplicationContext) source).getBeanFactory());
            }
            return null;
        }

        private Environment deduceEnvironment(@Nullable BeanDefinitionRegistry source) {
            if (source instanceof EnvironmentCapable) {
                return ((EnvironmentCapable) source).getEnvironment();
            }
            return new StandardEnvironment();
        }

        private ResourceLoader deduceResourceLoader(@Nullable BeanDefinitionRegistry source) {
            if (source instanceof ResourceLoader) {
                return (ResourceLoader) source;
            }
            return new DefaultResourceLoader();
        }

        @Nullable
        private ClreplacedLoader deduceClreplacedLoader(@Nullable ResourceLoader resourceLoader, @Nullable ConfigurableListableBeanFactory beanFactory) {
            if (resourceLoader != null) {
                ClreplacedLoader clreplacedLoader = resourceLoader.getClreplacedLoader();
                if (clreplacedLoader != null) {
                    return clreplacedLoader;
                }
            }
            if (beanFactory != null) {
                return beanFactory.getBeanClreplacedLoader();
            }
            return ClreplacedUtils.getDefaultClreplacedLoader();
        }

        @Override
        public BeanDefinitionRegistry getRegistry() {
            replacedert.state(this.registry != null, "No BeanDefinitionRegistry available");
            return this.registry;
        }

        @Override
        @Nullable
        public ConfigurableListableBeanFactory getBeanFactory() {
            return this.beanFactory;
        }

        @Override
        public Environment getEnvironment() {
            return this.environment;
        }

        @Override
        public ResourceLoader getResourceLoader() {
            return this.resourceLoader;
        }

        @Override
        @Nullable
        public ClreplacedLoader getClreplacedLoader() {
            return this.clreplacedLoader;
        }
    }
}

19 Source : InfrastructureUtils.java
with Apache License 2.0
from spring-projects-experimental

public static <T> T getOrCreate(GenericApplicationContext main, Clreplaced<T> initializerType) {
    return getOrCreate(main, initializerType.getName(), initializerType);
}

19 Source : ConditionEvaluator.java
with Apache License 2.0
from spring-projects-experimental

/**
 * Internal clreplaced used to evaluate {@link Conditional} annotations.
 *
 * @author Phillip Webb
 * @author Juergen Hoeller
 * @since 4.0
 */
clreplaced ConditionEvaluator {

    /**
     */
    private static final String ON_CLreplaced_CONDITION = "org.springframework.boot.autoconfigure.condition.OnClreplacedCondition";

    private final DefaultConditionContext context;

    private GenericApplicationContext infrastructure;

    /**
     * Create a new {@link ConditionEvaluator} instance.
     */
    public ConditionEvaluator(GenericApplicationContext infrastructure, @Nullable BeanDefinitionRegistry registry, @Nullable Environment environment, @Nullable ResourceLoader resourceLoader) {
        this.infrastructure = infrastructure;
        this.context = new DefaultConditionContext(registry, environment, resourceLoader);
    }

    /**
     * Determine if an item should be skipped based on {@code @Conditional} annotations.
     * The {@link ConfigurationPhase} will be deduced from the type of item (i.e. a
     * {@code @Configuration} clreplaced will be
     * {@link ConfigurationPhase#PARSE_CONFIGURATION})
     * @param metadata the meta data
     * @return if the item should be skipped
     */
    public boolean shouldSkip(AnnotatedTypeMetadata metadata) {
        return shouldSkip(metadata, null);
    }

    /**
     * Determine if an item should be skipped based on {@code @Conditional} annotations.
     * @param metadata the meta data
     * @param phase the phase of the call
     * @return if the item should be skipped
     */
    public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
        if (metadata == null || !metadata.isAnnotated(Conditional.clreplaced.getName())) {
            return false;
        }
        if (phase == null) {
            return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
        }
        List<Condition> conditions = new ArrayList<>();
        for (String[] conditionClreplacedes : getConditionClreplacedes(metadata)) {
            for (String conditionClreplaced : conditionClreplacedes) {
                Condition condition = getCondition(conditionClreplaced, this.context.getClreplacedLoader());
                if (ON_CLreplaced_CONDITION.equals(conditionClreplaced)) {
                    if (!condition.matches(this.context, metadata)) {
                        return true;
                    }
                }
                conditions.add(condition);
            }
        }
        AnnotationAwareOrderComparator.sort(conditions);
        for (Condition condition : conditions) {
            ConfigurationPhase requiredPhase = null;
            if (condition instanceof ConfigurationCondition) {
                requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
            }
            if ((requiredPhase == null || requiredPhase.compareTo(phase) <= 0) && !condition.matches(this.context, metadata)) {
                return true;
            }
        }
        return false;
    }

    @SuppressWarnings("unchecked")
    private List<String[]> getConditionClreplacedes(AnnotatedTypeMetadata metadata) {
        MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(Conditional.clreplaced.getName(), true);
        Object values = (attributes != null ? attributes.get("value") : null);
        List<String[]> result = new ArrayList<>();
        if (values != null) {
            for (String[] value : (List<String[]>) values) {
                boolean isClreplacedCondition = false;
                for (int i = 0; i < value.length; i++) {
                    String type = value[i];
                    if (ON_CLreplaced_CONDITION.equals(type)) {
                        isClreplacedCondition = true;
                        if (i > 0) {
                            String tmp = value[0];
                            value[0] = type;
                            value[i] = tmp;
                        }
                    }
                }
                if (isClreplacedCondition) {
                    result.add(0, value);
                } else {
                    result.add(value);
                }
            }
        }
        return result;
    }

    private Condition getCondition(String conditionClreplacedName, @Nullable ClreplacedLoader clreplacedloader) {
        return (Condition) InfrastructureUtils.getOrCreate(infrastructure, conditionClreplacedName);
    }
}

19 Source : ThymeleafDsl.java
with Apache License 2.0
from spring-projects-experimental

public void initializeServlet(GenericApplicationContext context) {
    this.initialize(context);
    new ThymeleafServletWebInitializer(properties).initialize(context);
}

19 Source : ThymeleafDsl.java
with Apache License 2.0
from spring-projects-experimental

public void initializeReactive(GenericApplicationContext context) {
    this.initialize(context);
    new ThymeleafReactiveWebInitializer(properties).initialize(context);
}

19 Source : MustacheDsl.java
with Apache License 2.0
from spring-projects-experimental

public void initializeReactive(GenericApplicationContext context) {
    this.initialize(context);
    new MustacheReactiveWebInitializer(properties).initialize(context);
}

19 Source : MustacheDsl.java
with Apache License 2.0
from spring-projects-experimental

public void initializeServlet(GenericApplicationContext context) {
    this.initialize(context);
    new MustacheServletWebInitializer(properties).initialize(context);
}

19 Source : JdbcDsl.java
with Apache License 2.0
from spring-projects-experimental

@Override
public void initialize(GenericApplicationContext context) {
    super.initialize(context);
    this.dsl.accept(this);
    new EmbeddedDataSourceConfigurationInitializer(dataSourceProperties).initialize(context);
    new JdbcTemplateConfigurationInitializer(jdbcProperties).initialize(context);
    new DataSourceTransactionManagerAutoConfigurationInitializer().initialize(context);
    new DataSourceInitializerInvokerInitializer(dataSourceProperties).initialize(context);
}

19 Source : AbstractDsl.java
with Apache License 2.0
from spring-projects-experimental

/**
 * Base clreplaced for Jafu DSL.
 *
 * Make sure to invoke {@code super.initialize(context)} from {@link #initialize(GenericApplicationContext)} in
 * inherited clreplacedes to get the context initialized.
 *
 * @author Sebastien Deleuze
 */
public abstract clreplaced AbstractDsl implements ApplicationContextInitializer<GenericApplicationContext> {

    protected GenericApplicationContext context;

    /**
     * Get a reference to the bean by type.
     * @param beanClreplaced type the bean must match, can be an interface or superclreplaced
     */
    public <T> T ref(Clreplaced<T> beanClreplaced) {
        return this.context.getBean(beanClreplaced);
    }

    /**
     * Get a reference to the bean by type + name.
     * @param beanClreplaced type the bean must match, can be an interface or superclreplaced
     */
    public <T> T ref(Clreplaced<T> beanClreplaced, String name) {
        return this.context.getBean(name, beanClreplaced);
    }

    /**
     * Shortcut the get the environment.
     */
    public Environment env() {
        return context.getEnvironment();
    }

    /**
     * Shortcut the get the active profiles.
     */
    public List<String> profiles() {
        return Arrays.asList(context.getEnvironment().getActiveProfiles());
    }

    /**
     * Override return type in inherited clreplacedes to return the concrete clreplaced type and make it public where you want
     * to make it available.
     */
    protected AbstractDsl enable(ApplicationContextInitializer<GenericApplicationContext> dsl) {
        dsl.initialize(context);
        return this;
    }

    @Override
    public void initialize(GenericApplicationContext context) {
        this.context = context;
    }
}

19 Source : FunctionExporterInitializer.java
with Apache License 2.0
from spring-cloud

private void registerWebClient(GenericApplicationContext context) {
    if (ClreplacedUtils.isPresent("org.springframework.web.reactive.function.client.WebClient", getClreplaced().getClreplacedLoader())) {
        if (context.getBeanFactory().getBeanNamesForType(WebClient.Builder.clreplaced, false, false).length == 0) {
            context.registerBean(WebClient.Builder.clreplaced, new Supplier<WebClient.Builder>() {

                @Override
                public Builder get() {
                    return WebClient.builder();
                }
            });
        }
    }
}

19 Source : FunctionEndpointInitializer.java
with Apache License 2.0
from spring-cloud

private HttpWebHandlerAdapter httpHandler(GenericApplicationContext context) {
    return (HttpWebHandlerAdapter) RouterFunctions.toHttpHandler(context.getBean(RouterFunction.clreplaced), HandlerStrategies.empty().exceptionHandler(context.getBean(WebExceptionHandler.clreplaced)).codecs(config -> config.registerDefaults(true)).build());
}

19 Source : FunctionEndpointInitializer.java
with Apache License 2.0
from spring-cloud

private void registerEndpoint(GenericApplicationContext context) {
    context.registerBean(RequestProcessor.clreplaced, () -> new RequestProcessor(context.getBeanProvider(JsonMapper.clreplaced), context.getBeanProvider(ServerCodecConfigurer.clreplaced)));
    context.registerBean(FunctionEndpointFactory.clreplaced, () -> new FunctionEndpointFactory(context.getBean(FunctionCatalog.clreplaced), context.getBean(RequestProcessor.clreplaced), context.getEnvironment()));
    RouterFunctionRegister.register(context);
}

19 Source : FunctionalSpringApplication.java
with Apache License 2.0
from spring-cloud

private Object handler(GenericApplicationContext generic, Object handler, Clreplaced<?> type) {
    if (handler == null) {
        handler = generic.getAutowireCapableBeanFactory().createBean(type);
    }
    return handler;
}

19 Source : FunctionalSpringApplication.java
with Apache License 2.0
from spring-cloud

private void register(GenericApplicationContext context, Object function, Clreplaced<?> functionType) {
    context.registerBean("function", FunctionRegistration.clreplaced, () -> new FunctionRegistration<>(handler(context, function, functionType)).type(FunctionType.of(functionType)));
}

19 Source : BeanFactoryAwareFunctionRegistry.java
with Apache License 2.0
from spring-cloud

/**
 * Implementation of {@link FunctionRegistry} capable of discovering functioins in {@link BeanFactory}.
 *
 * @author Oleg Zhurakousky
 */
public clreplaced BeanFactoryAwareFunctionRegistry extends SimpleFunctionRegistry implements ApplicationContextAware {

    private GenericApplicationContext applicationContext;

    public BeanFactoryAwareFunctionRegistry(ConversionService conversionService, CompositeMessageConverter messageConverter, JsonMapper jsonMapper, @Nullable FunctionInvocationHelper<Message<?>> functionInvocationHelper) {
        super(conversionService, messageConverter, jsonMapper, functionInvocationHelper);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = (GenericApplicationContext) applicationContext;
    }

    /*
	 * Basically gives an approximation only including function registrations and SFC.
	 * Excludes possible POJOs that can be treated as functions
	 */
    @Override
    public int size() {
        return this.applicationContext.getBeanNamesForType(Supplier.clreplaced).length + this.applicationContext.getBeanNamesForType(Function.clreplaced).length + this.applicationContext.getBeanNamesForType(Consumer.clreplaced).length + super.size();
    }

    /*
	 * Doesn't account for POJO so we really don't know until it's been lookedup
	 */
    @Override
    public Set<String> getNames(Clreplaced<?> type) {
        Set<String> registeredNames = super.getNames(type);
        if (type == null) {
            registeredNames.addAll(Arrays.asList(this.applicationContext.getBeanNamesForType(Function.clreplaced)));
            registeredNames.addAll(Arrays.asList(this.applicationContext.getBeanNamesForType(Supplier.clreplaced)));
            registeredNames.addAll(Arrays.asList(this.applicationContext.getBeanNamesForType(Consumer.clreplaced)));
        } else {
            registeredNames.addAll(Arrays.asList(this.applicationContext.getBeanNamesForType(type)));
        }
        return registeredNames;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public <T> T lookup(Clreplaced<?> type, String functionDefinition, String... expectedOutputMimeTypes) {
        functionDefinition = StringUtils.hasText(functionDefinition) ? functionDefinition : this.applicationContext.getEnvironment().getProperty(FunctionProperties.FUNCTION_DEFINITION, "");
        functionDefinition = this.normalizeFunctionDefinition(functionDefinition);
        if (!StringUtils.hasText(functionDefinition)) {
            logger.info("Can't determine default function definition. Please " + "use 'spring.cloud.function.definition' property to explicitly define it.");
            return null;
        }
        FunctionInvocationWrapper function = this.doLookup(type, functionDefinition, expectedOutputMimeTypes);
        if (function == null) {
            Set<String> functionRegistratioinNames = super.getNames(null);
            String[] functionNames = StringUtils.delimitedListToStringArray(functionDefinition.replaceAll(",", "|").trim(), "|");
            for (String functionName : functionNames) {
                if (functionRegistratioinNames.contains(functionName) && logger.isDebugEnabled()) {
                    logger.debug("Skipping function '" + functionName + "' since it is already present");
                } else {
                    Object functionCandidate = this.discoverFunctionInBeanFactory(functionName);
                    if (functionCandidate != null) {
                        Type functionType = null;
                        FunctionRegistration functionRegistration = null;
                        if (functionCandidate instanceof FunctionRegistration) {
                            functionRegistration = (FunctionRegistration) functionCandidate;
                        } else if (this.isFunctionPojo(functionCandidate, functionName)) {
                            Method functionalMethod = FunctionTypeUtils.discoverFunctionalMethod(functionCandidate.getClreplaced());
                            functionCandidate = this.proxyTarget(functionCandidate, functionalMethod);
                            functionType = FunctionTypeUtils.fromFunctionMethod(functionalMethod);
                        } else if (this.isSpecialFunctionRegistration(functionNames, functionName)) {
                            functionRegistration = this.applicationContext.getBean(functionName + FunctionRegistration.REGISTRATION_NAME_SUFFIX, FunctionRegistration.clreplaced);
                        } else {
                            functionType = FunctionTypeUtils.discoverFunctionType(functionCandidate, functionName, this.applicationContext);
                        }
                        if (functionRegistration == null) {
                            functionRegistration = new FunctionRegistration(functionCandidate, functionName).type(functionType);
                        }
                        this.register(functionRegistration);
                    } else {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Function '" + functionName + "' is not available in FunctionCatalog or BeanFactory");
                        }
                    }
                }
            }
            function = super.doLookup(type, functionDefinition, expectedOutputMimeTypes);
        }
        return (T) function;
    }

    private Object discoverFunctionInBeanFactory(String functionName) {
        Object functionCandidate = null;
        if (this.applicationContext.containsBean(functionName)) {
            functionCandidate = this.applicationContext.getBean(functionName);
        } else {
            try {
                functionCandidate = BeanFactoryAnnotationUtils.qualifiedBeanOfType(this.applicationContext.getBeanFactory(), Object.clreplaced, functionName);
            } catch (Exception e) {
            // ignore since there is no safe isAvailable-kind of method
            }
        }
        return functionCandidate;
    }

    @Override
    protected boolean containsFunction(String functionName) {
        return super.containsFunction(functionName) ? true : this.applicationContext.containsBean(functionName);
    }

    private boolean isFunctionPojo(Object functionCandidate, String functionName) {
        return !functionCandidate.getClreplaced().isSynthetic() && !(functionCandidate instanceof Supplier) && !(functionCandidate instanceof Function) && !(functionCandidate instanceof Consumer) && !this.applicationContext.containsBean(functionName + FunctionRegistration.REGISTRATION_NAME_SUFFIX);
    }

    /**
     * At the moment 'special function registration' simply implies that a bean under the provided functionName
     * may have already been wrapped and registered as FunuctionRegistration with BeanFactory under the name of
     * the function suffixed with {@link FunctionRegistration#REGISTRATION_NAME_SUFFIX}
     * (e.g., 'myKotlinFunction_registration').
     * <br><br>
     * At the moment only Kotlin module does this
     *
     * @param functionCandidate candidate for FunctionInvocationWrapper instance
     * @param functionName the name of the function
     * @return true if this function candidate qualifies
     */
    private boolean isSpecialFunctionRegistration(Object functionCandidate, String functionName) {
        return this.applicationContext.containsBean(functionName + FunctionRegistration.REGISTRATION_NAME_SUFFIX);
    }

    private Object proxyTarget(Object targetFunction, Method actualMethodToCall) {
        ProxyFactory pf = new ProxyFactory(targetFunction);
        pf.setProxyTargetClreplaced(true);
        pf.setInterfaces(Function.clreplaced);
        pf.addAdvice(new MethodInterceptor() {

            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                return actualMethodToCall.invoke(invocation.getThis(), invocation.getArguments());
            }
        });
        return pf.getProxy();
    }
}

19 Source : AnnotationConfigContextLoader.java
with Apache License 2.0
from SourceHot

/**
 * Register clreplacedes in the supplied {@link GenericApplicationContext context}
 * from the clreplacedes in the supplied {@link MergedContextConfiguration}.
 * <p>Each clreplaced must represent a <em>component clreplaced</em>. An
 * {@link AnnotatedBeanDefinitionReader} is used to register the appropriate
 * bean definitions.
 * <p>Note that this method does not call {@link #createBeanDefinitionReader}
 * since {@code AnnotatedBeanDefinitionReader} is not an instance of
 * {@link BeanDefinitionReader}.
 * @param context the context in which the component clreplacedes should be registered
 * @param mergedConfig the merged configuration from which the clreplacedes should be retrieved
 * @see AbstractGenericContextLoader#loadBeanDefinitions
 */
@Override
protected void loadBeanDefinitions(GenericApplicationContext context, MergedContextConfiguration mergedConfig) {
    Clreplaced<?>[] componentClreplacedes = mergedConfig.getClreplacedes();
    if (logger.isDebugEnabled()) {
        logger.debug("Registering component clreplacedes: " + ObjectUtils.nullSafeToString(componentClreplacedes));
    }
    new AnnotatedBeanDefinitionReader(context).register(componentClreplacedes);
}

19 Source : ScopingTests.java
with Apache License 2.0
from SourceHot

/**
 * Tests that scopes are properly supported by using a custom Scope implementations
 * and scoped proxy {@link Bean} declarations.
 *
 * @author Costin Leau
 * @author Chris Beams
 */
public clreplaced ScopingTests {

    public static String flag = "1";

    private static final String SCOPE = "my scope";

    private CustomScope customScope;

    private GenericApplicationContext ctx;

    @BeforeEach
    public void setUp() throws Exception {
        customScope = new CustomScope();
        ctx = createContext(ScopedConfigurationClreplaced.clreplaced);
    }

    @AfterEach
    public void tearDown() throws Exception {
        if (ctx != null) {
            ctx.close();
        }
    }

    private GenericApplicationContext createContext(Clreplaced<?> configClreplaced) {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        if (customScope != null) {
            beanFactory.registerScope(SCOPE, customScope);
        }
        beanFactory.registerBeanDefinition("config", new RootBeanDefinition(configClreplaced));
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(beanFactory);
        ctx.refresh();
        return ctx;
    }

    @Test
    public void testScopeOnClreplacedes() throws Exception {
        genericTestScope("scopedClreplaced");
    }

    @Test
    public void testScopeOnInterfaces() throws Exception {
        genericTestScope("scopedInterface");
    }

    private void genericTestScope(String beanName) throws Exception {
        String message = "scope is ignored";
        Object bean1 = ctx.getBean(beanName);
        Object bean2 = ctx.getBean(beanName);
        replacedertThat(bean2).as(message).isSameAs(bean1);
        Object bean3 = ctx.getBean(beanName);
        replacedertThat(bean3).as(message).isSameAs(bean1);
        // make the scope create a new object
        customScope.createNewScope = true;
        Object newBean1 = ctx.getBean(beanName);
        replacedertThat(newBean1).as(message).isNotSameAs(bean1);
        Object sameBean1 = ctx.getBean(beanName);
        replacedertThat(sameBean1).as(message).isSameAs(newBean1);
        // make the scope create a new object
        customScope.createNewScope = true;
        Object newBean2 = ctx.getBean(beanName);
        replacedertThat(newBean2).as(message).isNotSameAs(newBean1);
        // make the scope create a new object .. again
        customScope.createNewScope = true;
        Object newBean3 = ctx.getBean(beanName);
        replacedertThat(newBean3).as(message).isNotSameAs(newBean2);
    }

    @Test
    public void testSameScopeOnDifferentBeans() throws Exception {
        Object beanAInScope = ctx.getBean("scopedClreplaced");
        Object beanBInScope = ctx.getBean("scopedInterface");
        replacedertThat(beanBInScope).isNotSameAs(beanAInScope);
        customScope.createNewScope = true;
        Object newBeanAInScope = ctx.getBean("scopedClreplaced");
        Object newBeanBInScope = ctx.getBean("scopedInterface");
        replacedertThat(newBeanBInScope).isNotSameAs(newBeanAInScope);
        replacedertThat(beanAInScope).isNotSameAs(newBeanAInScope);
        replacedertThat(beanBInScope).isNotSameAs(newBeanBInScope);
    }

    @Test
    public void testRawScopes() throws Exception {
        String beanName = "scopedProxyInterface";
        // get hidden bean
        Object bean = ctx.getBean("scopedTarget." + beanName);
        boolean condition = bean instanceof ScopedObject;
        replacedertThat(condition).isFalse();
    }

    @Test
    public void testScopedProxyConfiguration() throws Exception {
        TestBean singleton = (TestBean) ctx.getBean("singletonWithScopedInterfaceDep");
        ITestBean spouse = singleton.getSpouse();
        boolean condition = spouse instanceof ScopedObject;
        replacedertThat(condition).as("scoped bean is not wrapped by the scoped-proxy").isTrue();
        String beanName = "scopedProxyInterface";
        String scopedBeanName = "scopedTarget." + beanName;
        // get hidden bean
        replacedertThat(spouse.getName()).isEqualTo(flag);
        ITestBean spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName);
        replacedertThat(spouseFromBF.getName()).isEqualTo(spouse.getName());
        // the scope proxy has kicked in
        replacedertThat(spouseFromBF).isNotSameAs(spouse);
        // create a new bean
        customScope.createNewScope = true;
        // get the bean again from the BF
        spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName);
        // make sure the name has been updated
        replacedertThat(spouseFromBF.getName()).isSameAs(spouse.getName());
        replacedertThat(spouseFromBF).isNotSameAs(spouse);
        // get the bean again
        spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName);
        replacedertThat(spouseFromBF.getName()).isSameAs(spouse.getName());
    }

    @Test
    public void testScopedProxyConfigurationWithClreplacedes() throws Exception {
        TestBean singleton = (TestBean) ctx.getBean("singletonWithScopedClreplacedDep");
        ITestBean spouse = singleton.getSpouse();
        boolean condition = spouse instanceof ScopedObject;
        replacedertThat(condition).as("scoped bean is not wrapped by the scoped-proxy").isTrue();
        String beanName = "scopedProxyClreplaced";
        String scopedBeanName = "scopedTarget." + beanName;
        // get hidden bean
        replacedertThat(spouse.getName()).isEqualTo(flag);
        TestBean spouseFromBF = (TestBean) ctx.getBean(scopedBeanName);
        replacedertThat(spouseFromBF.getName()).isEqualTo(spouse.getName());
        // the scope proxy has kicked in
        replacedertThat(spouseFromBF).isNotSameAs(spouse);
        // create a new bean
        customScope.createNewScope = true;
        flag = "boo";
        // get the bean again from the BF
        spouseFromBF = (TestBean) ctx.getBean(scopedBeanName);
        // make sure the name has been updated
        replacedertThat(spouseFromBF.getName()).isSameAs(spouse.getName());
        replacedertThat(spouseFromBF).isNotSameAs(spouse);
        // get the bean again
        spouseFromBF = (TestBean) ctx.getBean(scopedBeanName);
        replacedertThat(spouseFromBF.getName()).isSameAs(spouse.getName());
    }

    static clreplaced Foo {

        public Foo() {
        }

        public void doSomething() {
        }
    }

    static clreplaced Bar {

        private final Foo foo;

        public Bar(Foo foo) {
            this.foo = foo;
        }

        public Foo getFoo() {
            return foo;
        }
    }

    @Configuration
    public static clreplaced InvalidProxyOnPredefinedScopesConfiguration {

        @Bean
        @Scope(proxyMode = ScopedProxyMode.INTERFACES)
        public Object invalidProxyOnPredefinedScopes() {
            return new Object();
        }
    }

    @Configuration
    public static clreplaced ScopedConfigurationClreplaced {

        @Bean
        @MyScope
        public TestBean scopedClreplaced() {
            TestBean tb = new TestBean();
            tb.setName(flag);
            return tb;
        }

        @Bean
        @MyScope
        public ITestBean scopedInterface() {
            TestBean tb = new TestBean();
            tb.setName(flag);
            return tb;
        }

        @Bean
        @MyProxiedScope
        public ITestBean scopedProxyInterface() {
            TestBean tb = new TestBean();
            tb.setName(flag);
            return tb;
        }

        @MyProxiedScope
        public TestBean scopedProxyClreplaced() {
            TestBean tb = new TestBean();
            tb.setName(flag);
            return tb;
        }

        @Bean
        public TestBean singletonWithScopedClreplacedDep() {
            TestBean singleton = new TestBean();
            singleton.setSpouse(scopedProxyClreplaced());
            return singleton;
        }

        @Bean
        public TestBean singletonWithScopedInterfaceDep() {
            TestBean singleton = new TestBean();
            singleton.setSpouse(scopedProxyInterface());
            return singleton;
        }
    }

    @Target({ ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    @Scope(SCOPE)
    @interface MyScope {
    }

    @Target({ ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    @Bean
    @Scope(value = SCOPE, proxyMode = ScopedProxyMode.TARGET_CLreplaced)
    @interface MyProxiedScope {
    }

    /**
     * Simple scope implementation which creates object based on a flag.
     * @author Costin Leau
     * @author Chris Beams
     */
    static clreplaced CustomScope implements org.springframework.beans.factory.config.Scope {

        public boolean createNewScope = true;

        private Map<String, Object> beans = new HashMap<>();

        @Override
        public Object get(String name, ObjectFactory<?> objectFactory) {
            if (createNewScope) {
                beans.clear();
                // reset the flag back
                createNewScope = false;
            }
            Object bean = beans.get(name);
            // if a new object is requested or none exists under the current
            // name, create one
            if (bean == null) {
                beans.put(name, objectFactory.getObject());
            }
            return beans.get(name);
        }

        @Override
        public String getConversationId() {
            return null;
        }

        @Override
        public void registerDestructionCallback(String name, Runnable callback) {
            throw new IllegalStateException("Not supposed to be called");
        }

        @Override
        public Object remove(String name) {
            return beans.remove(name);
        }

        @Override
        public Object resolveContextualObject(String key) {
            return null;
        }
    }
}

19 Source : CustomNamespaceHandlerTests.java
with Apache License 2.0
from SourceHot

/**
 * Unit tests for custom XML namespace handler implementations.
 *
 * @author Rob Harrop
 * @author Rick Evans
 * @author Chris Beams
 * @author Juergen Hoeller
 */
public clreplaced CustomNamespaceHandlerTests {

    private static final Clreplaced<?> CLreplaced = CustomNamespaceHandlerTests.clreplaced;

    private static final String CLreplacedNAME = CLreplaced.getSimpleName();

    private static final String FQ_PATH = "org/springframework/beans/factory/xml/support";

    private static final String NS_PROPS = format("%s/%s.properties", FQ_PATH, CLreplacedNAME);

    private static final String NS_XML = format("%s/%s-context.xml", FQ_PATH, CLreplacedNAME);

    private static final String TEST_XSD = format("%s/%s.xsd", FQ_PATH, CLreplacedNAME);

    private GenericApplicationContext beanFactory;

    @BeforeEach
    public void setUp() throws Exception {
        NamespaceHandlerResolver resolver = new DefaultNamespaceHandlerResolver(CLreplaced.getClreplacedLoader(), NS_PROPS);
        this.beanFactory = new GenericApplicationContext();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
        reader.setNamespaceHandlerResolver(resolver);
        reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
        reader.setEnreplacedyResolver(new DummySchemaResolver());
        reader.loadBeanDefinitions(getResource());
        this.beanFactory.refresh();
    }

    @Test
    public void testSimpleParser() throws Exception {
        TestBean bean = (TestBean) this.beanFactory.getBean("testBean");
        replacedertTestBean(bean);
    }

    @Test
    public void testSimpleDecorator() throws Exception {
        TestBean bean = (TestBean) this.beanFactory.getBean("customisedTestBean");
        replacedertTestBean(bean);
    }

    @Test
    public void testProxyingDecorator() throws Exception {
        ITestBean bean = (ITestBean) this.beanFactory.getBean("debuggingTestBean");
        replacedertTestBean(bean);
        replacedertThat(AopUtils.isAopProxy(bean)).isTrue();
        Advisor[] advisors = ((Advised) bean).getAdvisors();
        replacedertThat(advisors.length).as("Incorrect number of advisors").isEqualTo(1);
        replacedertThat(advisors[0].getAdvice().getClreplaced()).as("Incorrect advice clreplaced").isEqualTo(DebugInterceptor.clreplaced);
    }

    @Test
    public void testProxyingDecoratorNoInstance() throws Exception {
        String[] beanNames = this.beanFactory.getBeanNamesForType(ApplicationListener.clreplaced);
        replacedertThat(Arrays.asList(beanNames).contains("debuggingTestBeanNoInstance")).isTrue();
        replacedertThat(this.beanFactory.getType("debuggingTestBeanNoInstance")).isEqualTo(ApplicationListener.clreplaced);
        replacedertThatExceptionOfType(BeanCreationException.clreplaced).isThrownBy(() -> this.beanFactory.getBean("debuggingTestBeanNoInstance")).satisfies(ex -> replacedertThat(ex.getRootCause()).isInstanceOf(BeanInstantiationException.clreplaced));
    }

    @Test
    public void testChainedDecorators() throws Exception {
        ITestBean bean = (ITestBean) this.beanFactory.getBean("chainedTestBean");
        replacedertTestBean(bean);
        replacedertThat(AopUtils.isAopProxy(bean)).isTrue();
        Advisor[] advisors = ((Advised) bean).getAdvisors();
        replacedertThat(advisors.length).as("Incorrect number of advisors").isEqualTo(2);
        replacedertThat(advisors[0].getAdvice().getClreplaced()).as("Incorrect advice clreplaced").isEqualTo(DebugInterceptor.clreplaced);
        replacedertThat(advisors[1].getAdvice().getClreplaced()).as("Incorrect advice clreplaced").isEqualTo(NopInterceptor.clreplaced);
    }

    @Test
    public void testDecorationViaAttribute() throws Exception {
        BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition("decorateWithAttribute");
        replacedertThat(beanDefinition.getAttribute("objectName")).isEqualTo("foo");
    }

    // SPR-2728
    @Test
    public void testCustomElementNestedWithinUtilList() throws Exception {
        List<?> things = (List<?>) this.beanFactory.getBean("list.of.things");
        replacedertThat(things).isNotNull();
        replacedertThat(things.size()).isEqualTo(2);
    }

    // SPR-2728
    @Test
    public void testCustomElementNestedWithinUtilSet() throws Exception {
        Set<?> things = (Set<?>) this.beanFactory.getBean("set.of.things");
        replacedertThat(things).isNotNull();
        replacedertThat(things.size()).isEqualTo(2);
    }

    // SPR-2728
    @Test
    public void testCustomElementNestedWithinUtilMap() throws Exception {
        Map<?, ?> things = (Map<?, ?>) this.beanFactory.getBean("map.of.things");
        replacedertThat(things).isNotNull();
        replacedertThat(things.size()).isEqualTo(2);
    }

    private void replacedertTestBean(ITestBean bean) {
        replacedertThat(bean.getName()).as("Invalid name").isEqualTo("Rob Harrop");
        replacedertThat(bean.getAge()).as("Invalid age").isEqualTo(23);
    }

    private Resource getResource() {
        return new ClreplacedPathResource(NS_XML);
    }

    private final clreplaced DummySchemaResolver extends PluggableSchemaResolver {

        public DummySchemaResolver() {
            super(CLreplaced.getClreplacedLoader());
        }

        @Override
        public InputSource resolveEnreplacedy(String publicId, String systemId) throws IOException {
            InputSource source = super.resolveEnreplacedy(publicId, systemId);
            if (source == null) {
                Resource resource = new ClreplacedPathResource(TEST_XSD);
                source = new InputSource(resource.getInputStream());
                source.setPublicId(publicId);
                source.setSystemId(systemId);
            }
            return source;
        }
    }
}

19 Source : AnnotationConfigContextLoader.java
with Apache License 2.0
from langtianya

/**
 * {@code AnnotationConfigContextLoader} should be used as a
 * {@link org.springframework.test.context.SmartContextLoader SmartContextLoader},
 * not as a legacy {@link org.springframework.test.context.ContextLoader ContextLoader}.
 * Consequently, this method is not supported.
 *
 * @see #loadBeanDefinitions
 * @see AbstractGenericContextLoader#createBeanDefinitionReader
 * @throws UnsupportedOperationException
 */
@Override
protected BeanDefinitionReader createBeanDefinitionReader(GenericApplicationContext context) {
    throw new UnsupportedOperationException("AnnotationConfigContextLoader does not support the createBeanDefinitionReader(GenericApplicationContext) method");
}

19 Source : AnnotationConfigContextLoader.java
with Apache License 2.0
from langtianya

/**
 * Register clreplacedes in the supplied {@link GenericApplicationContext context}
 * from the clreplacedes in the supplied {@link MergedContextConfiguration}.
 *
 * <p>Each clreplaced must represent an <em>annotated clreplaced</em>. An
 * {@link AnnotatedBeanDefinitionReader} is used to register the appropriate
 * bean definitions.
 *
 * <p>Note that this method does not call {@link #createBeanDefinitionReader}
 * since {@code AnnotatedBeanDefinitionReader} is not an instance of
 * {@link BeanDefinitionReader}.
 *
 * @param context the context in which the annotated clreplacedes should be registered
 * @param mergedConfig the merged configuration from which the clreplacedes should be retrieved
 *
 * @see AbstractGenericContextLoader#loadBeanDefinitions
 */
@Override
protected void loadBeanDefinitions(GenericApplicationContext context, MergedContextConfiguration mergedConfig) {
    Clreplaced<?>[] annotatedClreplacedes = mergedConfig.getClreplacedes();
    if (logger.isDebugEnabled()) {
        logger.debug("Registering annotated clreplacedes: " + ObjectUtils.nullSafeToString(annotatedClreplacedes));
    }
    new AnnotatedBeanDefinitionReader(context).register(annotatedClreplacedes);
}

19 Source : AbstractGenericContextLoader.java
with Apache License 2.0
from langtianya

/**
 * Customize the {@link GenericApplicationContext} created by this
 * {@code ContextLoader} <i>after</i> bean definitions have been
 * loaded into the context but <i>before</i> the context is refreshed.
 *
 * <p>The default implementation is empty but can be overridden in subclreplacedes
 * to customize the application context.
 *
 * @param context the newly created application context
 * @see #loadContext(MergedContextConfiguration)
 * @see #loadContext(String...)
 * @since 2.5
 */
protected void customizeContext(GenericApplicationContext context) {
}

19 Source : AbstractGenericContextLoader.java
with Apache License 2.0
from langtianya

/**
 * Load bean definitions into the supplied {@link GenericApplicationContext context}
 * from the locations or clreplacedes in the supplied {@code MergedContextConfiguration}.
 *
 * <p>The default implementation delegates to the {@link BeanDefinitionReader}
 * returned by {@link #createBeanDefinitionReader(GenericApplicationContext)} to
 * {@link BeanDefinitionReader#loadBeanDefinitions(String) load} the
 * bean definitions.
 *
 * <p>Subclreplacedes must provide an appropriate implementation of
 * {@link #createBeanDefinitionReader(GenericApplicationContext)}. Alternatively subclreplacedes
 * may provide a <em>no-op</em> implementation of {@code createBeanDefinitionReader()}
 * and override this method to provide a custom strategy for loading or
 * registering bean definitions.
 *
 * @param context the context into which the bean definitions should be loaded
 * @param mergedConfig the merged context configuration
 * @see #loadContext(MergedContextConfiguration)
 * @since 3.1
 */
protected void loadBeanDefinitions(GenericApplicationContext context, MergedContextConfiguration mergedConfig) {
    createBeanDefinitionReader(context).loadBeanDefinitions(mergedConfig.getLocations());
}

19 Source : AbstractGenericContextLoader.java
with Apache License 2.0
from langtianya

/**
 * Prepare the {@link GenericApplicationContext} created by this {@code ContextLoader}.
 * Called <i>before</i> bean definitions are read.
 *
 * <p>The default implementation is empty. Can be overridden in subclreplacedes to
 * customize {@code GenericApplicationContext}'s standard settings.
 *
 * @param context the context that should be prepared
 * @see #loadContext(MergedContextConfiguration)
 * @see #loadContext(String...)
 * @see GenericApplicationContext#setAllowBeanDefinitionOverriding
 * @see GenericApplicationContext#setResourceLoader
 * @see GenericApplicationContext#setId
 * @since 2.5
 */
protected void prepareContext(GenericApplicationContext context) {
}

19 Source : ScopingTests.java
with Apache License 2.0
from langtianya

/**
 * Tests that scopes are properly supported by using a custom Scope implementations
 * and scoped proxy {@link Bean} declarations.
 *
 * @author Costin Leau
 * @author Chris Beams
 */
public clreplaced ScopingTests {

    public static String flag = "1";

    private static final String SCOPE = "my scope";

    private CustomScope customScope;

    private GenericApplicationContext ctx;

    @Before
    public void setUp() throws Exception {
        customScope = new CustomScope();
        ctx = createContext(ScopedConfigurationClreplaced.clreplaced);
    }

    @After
    public void tearDown() throws Exception {
        if (ctx != null) {
            ctx.close();
        }
    }

    private GenericApplicationContext createContext(Clreplaced<?> configClreplaced) {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        if (customScope != null) {
            beanFactory.registerScope(SCOPE, customScope);
        }
        beanFactory.registerBeanDefinition("config", new RootBeanDefinition(configClreplaced));
        GenericApplicationContext ctx = new GenericApplicationContext(beanFactory);
        ctx.addBeanFactoryPostProcessor(new ConfigurationClreplacedPostProcessor());
        ctx.refresh();
        return ctx;
    }

    @Test
    public void testScopeOnClreplacedes() throws Exception {
        genericTestScope("scopedClreplaced");
    }

    @Test
    public void testScopeOnInterfaces() throws Exception {
        genericTestScope("scopedInterface");
    }

    private void genericTestScope(String beanName) throws Exception {
        String message = "scope is ignored";
        Object bean1 = ctx.getBean(beanName);
        Object bean2 = ctx.getBean(beanName);
        replacedertSame(message, bean1, bean2);
        Object bean3 = ctx.getBean(beanName);
        replacedertSame(message, bean1, bean3);
        // make the scope create a new object
        customScope.createNewScope = true;
        Object newBean1 = ctx.getBean(beanName);
        replacedertNotSame(message, bean1, newBean1);
        Object sameBean1 = ctx.getBean(beanName);
        replacedertSame(message, newBean1, sameBean1);
        // make the scope create a new object
        customScope.createNewScope = true;
        Object newBean2 = ctx.getBean(beanName);
        replacedertNotSame(message, newBean1, newBean2);
        // make the scope create a new object .. again
        customScope.createNewScope = true;
        Object newBean3 = ctx.getBean(beanName);
        replacedertNotSame(message, newBean2, newBean3);
    }

    @Test
    public void testSameScopeOnDifferentBeans() throws Exception {
        Object beanAInScope = ctx.getBean("scopedClreplaced");
        Object beanBInScope = ctx.getBean("scopedInterface");
        replacedertNotSame(beanAInScope, beanBInScope);
        customScope.createNewScope = true;
        Object newBeanAInScope = ctx.getBean("scopedClreplaced");
        Object newBeanBInScope = ctx.getBean("scopedInterface");
        replacedertNotSame(newBeanAInScope, newBeanBInScope);
        replacedertNotSame(newBeanAInScope, beanAInScope);
        replacedertNotSame(newBeanBInScope, beanBInScope);
    }

    @Test
    public void testRawScopes() throws Exception {
        String beanName = "scopedProxyInterface";
        // get hidden bean
        Object bean = ctx.getBean("scopedTarget." + beanName);
        replacedertFalse(bean instanceof ScopedObject);
    }

    @Test
    public void testScopedProxyConfiguration() throws Exception {
        TestBean singleton = (TestBean) ctx.getBean("singletonWithScopedInterfaceDep");
        ITestBean spouse = singleton.getSpouse();
        replacedertTrue("scoped bean is not wrapped by the scoped-proxy", spouse instanceof ScopedObject);
        String beanName = "scopedProxyInterface";
        String scopedBeanName = "scopedTarget." + beanName;
        // get hidden bean
        replacedertEquals(flag, spouse.getName());
        ITestBean spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName);
        replacedertEquals(spouse.getName(), spouseFromBF.getName());
        // the scope proxy has kicked in
        replacedertNotSame(spouse, spouseFromBF);
        // create a new bean
        customScope.createNewScope = true;
        // get the bean again from the BF
        spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName);
        // make sure the name has been updated
        replacedertSame(spouse.getName(), spouseFromBF.getName());
        replacedertNotSame(spouse, spouseFromBF);
        // get the bean again
        spouseFromBF = (ITestBean) ctx.getBean(scopedBeanName);
        replacedertSame(spouse.getName(), spouseFromBF.getName());
    }

    @Test
    public void testScopedProxyConfigurationWithClreplacedes() throws Exception {
        TestBean singleton = (TestBean) ctx.getBean("singletonWithScopedClreplacedDep");
        ITestBean spouse = singleton.getSpouse();
        replacedertTrue("scoped bean is not wrapped by the scoped-proxy", spouse instanceof ScopedObject);
        String beanName = "scopedProxyClreplaced";
        String scopedBeanName = "scopedTarget." + beanName;
        // get hidden bean
        replacedertEquals(flag, spouse.getName());
        TestBean spouseFromBF = (TestBean) ctx.getBean(scopedBeanName);
        replacedertEquals(spouse.getName(), spouseFromBF.getName());
        // the scope proxy has kicked in
        replacedertNotSame(spouse, spouseFromBF);
        // create a new bean
        customScope.createNewScope = true;
        flag = "boo";
        // get the bean again from the BF
        spouseFromBF = (TestBean) ctx.getBean(scopedBeanName);
        // make sure the name has been updated
        replacedertSame(spouse.getName(), spouseFromBF.getName());
        replacedertNotSame(spouse, spouseFromBF);
        // get the bean again
        spouseFromBF = (TestBean) ctx.getBean(scopedBeanName);
        replacedertSame(spouse.getName(), spouseFromBF.getName());
    }

    @Test
    public void testScopedConfigurationBeanDefinitionCount() throws Exception {
        // count the beans
        // 6 @Beans + 1 Configuration + 2 scoped proxy + 1 importRegistry + 1 enhanced config post processor
        replacedertEquals(11, ctx.getBeanDefinitionCount());
    }

    static clreplaced Foo {

        public Foo() {
        }

        public void doSomething() {
        }
    }

    static clreplaced Bar {

        private final Foo foo;

        public Bar(Foo foo) {
            this.foo = foo;
        }

        public Foo getFoo() {
            return foo;
        }
    }

    @Configuration
    public static clreplaced InvalidProxyOnPredefinedScopesConfiguration {

        @Bean
        @Scope(proxyMode = ScopedProxyMode.INTERFACES)
        public Object invalidProxyOnPredefinedScopes() {
            return new Object();
        }
    }

    @Configuration
    public static clreplaced ScopedConfigurationClreplaced {

        @Bean
        @MyScope
        public TestBean scopedClreplaced() {
            TestBean tb = new TestBean();
            tb.setName(flag);
            return tb;
        }

        @Bean
        @MyScope
        public ITestBean scopedInterface() {
            TestBean tb = new TestBean();
            tb.setName(flag);
            return tb;
        }

        @Bean
        @MyProxiedScope
        public ITestBean scopedProxyInterface() {
            TestBean tb = new TestBean();
            tb.setName(flag);
            return tb;
        }

        @MyProxiedScope
        public TestBean scopedProxyClreplaced() {
            TestBean tb = new TestBean();
            tb.setName(flag);
            return tb;
        }

        @Bean
        public TestBean singletonWithScopedClreplacedDep() {
            TestBean singleton = new TestBean();
            singleton.setSpouse(scopedProxyClreplaced());
            return singleton;
        }

        @Bean
        public TestBean singletonWithScopedInterfaceDep() {
            TestBean singleton = new TestBean();
            singleton.setSpouse(scopedProxyInterface());
            return singleton;
        }
    }

    @Target({ ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    @Scope(SCOPE)
    @interface MyScope {
    }

    @Target({ ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    @Bean
    @Scope(value = SCOPE, proxyMode = ScopedProxyMode.TARGET_CLreplaced)
    @interface MyProxiedScope {
    }

    /**
     * Simple scope implementation which creates object based on a flag.
     * @author Costin Leau
     * @author Chris Beams
     */
    static clreplaced CustomScope implements org.springframework.beans.factory.config.Scope {

        public boolean createNewScope = true;

        private Map<String, Object> beans = new HashMap<String, Object>();

        @Override
        public Object get(String name, ObjectFactory<?> objectFactory) {
            if (createNewScope) {
                beans.clear();
                // reset the flag back
                createNewScope = false;
            }
            Object bean = beans.get(name);
            // if a new object is requested or none exists under the current
            // name, create one
            if (bean == null) {
                beans.put(name, objectFactory.getObject());
            }
            return beans.get(name);
        }

        @Override
        public String getConversationId() {
            return null;
        }

        @Override
        public void registerDestructionCallback(String name, Runnable callback) {
        // do nothing
        }

        @Override
        public Object remove(String name) {
            return beans.remove(name);
        }

        @Override
        public Object resolveContextualObject(String key) {
            return null;
        }
    }
}

19 Source : CustomNamespaceHandlerTests.java
with Apache License 2.0
from langtianya

/**
 * Unit tests for custom XML namespace handler implementations.
 *
 * @author Rob Harrop
 * @author Rick Evans
 * @author Chris Beams
 * @author Juergen Hoeller
 */
public clreplaced CustomNamespaceHandlerTests {

    private static final Clreplaced<?> CLreplaced = CustomNamespaceHandlerTests.clreplaced;

    private static final String CLreplacedNAME = CLreplaced.getSimpleName();

    private static final String FQ_PATH = "org/springframework/beans/factory/xml/support";

    private static final String NS_PROPS = format("%s/%s.properties", FQ_PATH, CLreplacedNAME);

    private static final String NS_XML = format("%s/%s-context.xml", FQ_PATH, CLreplacedNAME);

    private static final String TEST_XSD = format("%s/%s.xsd", FQ_PATH, CLreplacedNAME);

    private GenericApplicationContext beanFactory;

    @Before
    public void setUp() throws Exception {
        NamespaceHandlerResolver resolver = new DefaultNamespaceHandlerResolver(CLreplaced.getClreplacedLoader(), NS_PROPS);
        this.beanFactory = new GenericApplicationContext();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
        reader.setNamespaceHandlerResolver(resolver);
        reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
        reader.setEnreplacedyResolver(new DummySchemaResolver());
        reader.loadBeanDefinitions(getResource());
        this.beanFactory.refresh();
    }

    @Test
    public void testSimpleParser() throws Exception {
        TestBean bean = (TestBean) this.beanFactory.getBean("testBean");
        replacedertTestBean(bean);
    }

    @Test
    public void testSimpleDecorator() throws Exception {
        TestBean bean = (TestBean) this.beanFactory.getBean("customisedTestBean");
        replacedertTestBean(bean);
    }

    @Test
    public void testProxyingDecorator() throws Exception {
        ITestBean bean = (ITestBean) this.beanFactory.getBean("debuggingTestBean");
        replacedertTestBean(bean);
        replacedertTrue(AopUtils.isAopProxy(bean));
        Advisor[] advisors = ((Advised) bean).getAdvisors();
        replacedertEquals("Incorrect number of advisors", 1, advisors.length);
        replacedertEquals("Incorrect advice clreplaced.", DebugInterceptor.clreplaced, advisors[0].getAdvice().getClreplaced());
    }

    @Test
    public void testProxyingDecoratorNoInstance() throws Exception {
        String[] beanNames = this.beanFactory.getBeanNamesForType(ApplicationListener.clreplaced);
        replacedertTrue(Arrays.asList(beanNames).contains("debuggingTestBeanNoInstance"));
        replacedertEquals(ApplicationListener.clreplaced, this.beanFactory.getType("debuggingTestBeanNoInstance"));
        try {
            this.beanFactory.getBean("debuggingTestBeanNoInstance");
            fail("Should have thrown BeanCreationException");
        } catch (BeanCreationException ex) {
            replacedertTrue(ex.getRootCause() instanceof BeanInstantiationException);
        }
    }

    @Test
    public void testChainedDecorators() throws Exception {
        ITestBean bean = (ITestBean) this.beanFactory.getBean("chainedTestBean");
        replacedertTestBean(bean);
        replacedertTrue(AopUtils.isAopProxy(bean));
        Advisor[] advisors = ((Advised) bean).getAdvisors();
        replacedertEquals("Incorrect number of advisors", 2, advisors.length);
        replacedertEquals("Incorrect advice clreplaced.", DebugInterceptor.clreplaced, advisors[0].getAdvice().getClreplaced());
        replacedertEquals("Incorrect advice clreplaced.", NopInterceptor.clreplaced, advisors[1].getAdvice().getClreplaced());
    }

    @Test
    public void testDecorationViaAttribute() throws Exception {
        BeanDefinition beanDefinition = this.beanFactory.getBeanDefinition("decorateWithAttribute");
        replacedertEquals("foo", beanDefinition.getAttribute("objectName"));
    }

    /**
     * http://opensource.atlreplacedian.com/projects/spring/browse/SPR-2728
     */
    @Test
    public void testCustomElementNestedWithinUtilList() throws Exception {
        List<?> things = (List<?>) this.beanFactory.getBean("list.of.things");
        replacedertNotNull(things);
        replacedertEquals(2, things.size());
    }

    /**
     * http://opensource.atlreplacedian.com/projects/spring/browse/SPR-2728
     */
    @Test
    public void testCustomElementNestedWithinUtilSet() throws Exception {
        Set<?> things = (Set<?>) this.beanFactory.getBean("set.of.things");
        replacedertNotNull(things);
        replacedertEquals(2, things.size());
    }

    /**
     * http://opensource.atlreplacedian.com/projects/spring/browse/SPR-2728
     */
    @Test
    public void testCustomElementNestedWithinUtilMap() throws Exception {
        Map<?, ?> things = (Map<?, ?>) this.beanFactory.getBean("map.of.things");
        replacedertNotNull(things);
        replacedertEquals(2, things.size());
    }

    private void replacedertTestBean(ITestBean bean) {
        replacedertEquals("Invalid name", "Rob Harrop", bean.getName());
        replacedertEquals("Invalid age", 23, bean.getAge());
    }

    private Resource getResource() {
        return new ClreplacedPathResource(NS_XML);
    }

    private final clreplaced DummySchemaResolver extends PluggableSchemaResolver {

        public DummySchemaResolver() {
            super(CLreplaced.getClreplacedLoader());
        }

        @Override
        public InputSource resolveEnreplacedy(String publicId, String systemId) throws IOException {
            InputSource source = super.resolveEnreplacedy(publicId, systemId);
            if (source == null) {
                Resource resource = new ClreplacedPathResource(TEST_XSD);
                source = new InputSource(resource.getInputStream());
                source.setPublicId(publicId);
                source.setSystemId(systemId);
            }
            return source;
        }
    }
}

19 Source : SpringDependencyAnalyzer.java
with MIT License
from jillesvangurp

/**
 * Spring dependency replacedyzer that works with any GenericApplicationContext.
 */
public clreplaced SpringDependencyreplacedyzer {

    private final GenericApplicationContext context;

    /**
     * @param context create your spring context the usual way and inject it here.
     */
    public SpringDependencyreplacedyzer(GenericApplicationContext context) {
        this.context = context;
    }

    /**
     * Long lists of dependencies indicate low cohesiveness and high coupling. This helps you identify the problematic beans.
     *
     * @return map of dependencies for all beans in the context
     */
    public Map<String, Set<String>> getBeanDependencies() {
        Map<String, Set<String>> beanDeps = new TreeMap<>();
        ConfigurableListableBeanFactory factory = context.getBeanFactory();
        for (String beanName : factory.getBeanDefinitionNames()) {
            if (factory.getBeanDefinition(beanName).isAbstract()) {
                continue;
            }
            String[] dependenciesForBean = factory.getDependenciesForBean(beanName);
            Set<String> set = beanDeps.get(beanName);
            if (set == null) {
                set = new TreeSet<>();
                beanDeps.put(beanName, set);
            }
            for (String dependency : dependenciesForBean) {
                set.add(dependency);
            }
        }
        return beanDeps;
    }

    /**
     * If you have a lot of beans that are not depended on or only once, maybe they shouldn't be a bean at all.
     *
     * @return map of reverse dependencies for all beans in the context
     */
    public Map<String, Set<String>> getReverseBeanDependencies() {
        Map<String, Set<String>> reverseBeanDeps = new TreeMap<>();
        Map<String, Set<String>> beanDeps = getBeanDependencies();
        beanDeps.forEach((beanName, deps) -> {
            for (String dep : deps) {
                Set<String> set = reverseBeanDeps.get(dep);
                if (set == null) {
                    set = new TreeSet<>();
                    reverseBeanDeps.put(dep, set);
                }
                set.add(beanName);
            }
        });
        return reverseBeanDeps;
    }

    /**
     * Organizes the graph of configuration clreplacedes in layers that depend on each other.
     * Clreplacedes in the same layer can only import clreplacedes in lower layers. Spring does not allow import cycles.
     * A good pattern is to have a RootConfig for your application that simply imports everything else you need.
     * The more layers you have the more complex your dependencies.
     *
     * @param configurationClreplaced the root configuration clreplaced that you want to replacedyze
     * @return treemap with layers of configuratino
     */
    public Map<Integer, Set<Clreplaced<?>>> getConfigurationLayers(Clreplaced<?> configurationClreplaced) {
        SimpleGraph<Clreplaced<?>> rootGraph = getConfigurationGraph(configurationClreplaced);
        return rootGraph.getLayers();
    }

    private void validateIsConfigurationClreplaced(Clreplaced<?> configurationClreplaced) {
        boolean isConfigClreplaced = false;
        for (Annotation annotation : configurationClreplaced.getAnnotations()) {
            Clreplaced<? extends Annotation> type = annotation.annotationType();
            if (Configuration.clreplaced.equals(type)) {
                isConfigClreplaced = true;
            }
        }
        if (!isConfigClreplaced) {
            throw new IllegalArgumentException("not a spring configuration clreplaced");
        }
    }

    /**
     * @param configurationClreplaced spring configuration root clreplaced from which to calculate the configuration hierarchy
     * @return a graph of the configuration clreplacedes
     */
    public SimpleGraph<Clreplaced<?>> getConfigurationGraph(Clreplaced<?> configurationClreplaced) {
        validateIsConfigurationClreplaced(configurationClreplaced);
        return SimpleGraph.treeBuilder(configurationClreplaced, SpringDependencyreplacedyzer::getConfigurationImportsFor);
    }

    public SimpleGraph<String> getBeanGraph() {
        Map<String, Set<String>> beanDeps = getBeanDependencies();
        Map<String, Set<String>> reverseBeanDeps = getReverseBeanDependencies();
        SimpleGraph<String> graph = new SimpleGraph<>();
        beanDeps.forEach((bean, deps) -> {
            if (deps.isEmpty()) {
                // bean has no deps, so we can figure out everything that depends on this bean here
                SimpleGraph<String> depGraph = new SimpleGraph<>();
                Set<String> simpleGraphs = new HashSet<>();
                SimpleGraph.buildGraph(depGraph, bean, b -> reverseBeanDeps.get(b), simpleGraphs);
                graph.put(bean, depGraph);
            }
        });
        // FIXME technically this is a reverse dependency graph, We need to revert it.
        return graph;
    }

    private static List<Clreplaced<?>> getConfigurationImportsFor(Clreplaced<?> clazz) {
        List<Clreplaced<?>> list = new ArrayList<>();
        for (Annotation annotation : clazz.getAnnotations()) {
            Clreplaced<? extends Annotation> type = annotation.annotationType();
            if (Import.clreplaced.equals(type)) {
                try {
                    Method method = type.getMethod("value");
                    Clreplaced<?>[] imports = (Clreplaced<?>[]) method.invoke(annotation, (Object[]) null);
                    if (imports != null && imports.length > 0) {
                        for (Clreplaced<?> c : imports) {
                            list.add(c);
                        }
                    }
                } catch (Throwable e) {
                    throw new IllegalStateException(e);
                }
            }
        }
        return list;
    }

    public String configurationGraphCypher(Clreplaced<?> rootClreplaced) {
        return getConfigurationGraph(rootClreplaced).toCypher("ConfigClreplaced", "Imports", c -> c.getSimpleName());
    }

    public String beanGraphCypher() {
        return getBeanGraph().toCypher("Bean", "DEPENDSON", s -> s.replace(".", "_").replace("-", "__"));
    }

    public void printReport(Clreplaced<?> springConfigurationClreplaced) {
        System.err.println("Configuration layers:\n");
        getConfigurationLayers(springConfigurationClreplaced).forEach((layer, clreplacedes) -> {
            System.err.println("" + layer + "\t" + StringUtils.join(clreplacedes, ','));
        });
        System.err.println("\n\nDependencies:\n");
        Map<String, Set<String>> beanDependencies = getBeanDependencies();
        beanDependencies.forEach((name, dependencies) -> {
            System.err.println(name + ": " + StringUtils.join(dependencies, ','));
        });
        System.err.println("\n\nReverse dependencies:\n");
        Map<String, Set<String>> reverseBeanDependencies = getReverseBeanDependencies();
        reverseBeanDependencies.forEach((name, dependencies) -> {
            System.err.println(name + ": " + StringUtils.join(dependencies, ','));
        });
        System.err.println("\n\nBean dependency graph:\n");
        System.err.println(getBeanGraph());
        System.err.println("Bean layers:\n");
        getBeanGraph().getLayers().forEach((layer, clreplacedes) -> {
            System.err.println("" + layer + "\t" + StringUtils.join(clreplacedes, ','));
        });
    }

    public String getCircularDependencyStatisticJson() {
        Map<String, Set<String>> beanDependencies = getBeanDependencies();
        LinkedHashMap<String, BeanDependency> map = new LinkedHashMap<>();
        beanDependencies.forEach((name, dependencies) -> {
            Set<String> circularDependencyDescriptions = new HashSet<>();
            findCycleDependencies(circularDependencyDescriptions, beanDependencies, dependencies, new LinkedHashSet<>(), name, 0, 4);
            map.put(name, new BeanDependency(dependencies.size(), new ArrayList<>(dependencies), circularDependencyDescriptions.size(), new ArrayList<>(circularDependencyDescriptions)));
        });
        int count = 0;
        for (Map.Entry<String, BeanDependency> stringBeanDependencyEntry : map.entrySet()) {
            count = count + stringBeanDependencyEntry.getValue().getCircularDependencyCount();
        }
        LinkedHashMap<String, BeanDependency> collect = map.entrySet().stream().sorted((o1, o2) -> {
            BeanDependency value1 = o1.getValue();
            BeanDependency value2 = o2.getValue();
            int i = value2.getCircularDependencyCount().compareTo(value1.getCircularDependencyCount());
            return i == 0 ? o1.getKey().compareTo(o2.getKey()) : i;
        }).collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
        BeanDependencyStatistic beanDependencyStatistic = new BeanDependencyStatistic();
        beanDependencyStatistic.setCreateDate(new Date());
        beanDependencyStatistic.setDependencyMap(collect);
        beanDependencyStatistic.setAllBeanCircularDependencyCount(count);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String result = gson.toJson(beanDependencyStatistic);
        return result;
    }

    private void findCycleDependencies(Set<String> circularDependencyDescriptions, Map<String, Set<String>> allBeansDependenciesMap, Set<String> dependecies, Set<String> dependencyNameChain, String targetName, int currentDepth, int maxDepth) {
        currentDepth++;
        int stepDepthValue = currentDepth;
        for (String dep : dependecies) {
            Set<String> currentStepNameChain = new LinkedHashSet<>(dependencyNameChain);
            Set<String> dependeciesOfBeanDep = allBeansDependenciesMap.get(dep);
            if (dependeciesOfBeanDep == null || dependeciesOfBeanDep.isEmpty()) {
                currentStepNameChain.remove(dep);
                continue;
            }
            if (dependeciesOfBeanDep.contains(targetName) && !currentStepNameChain.contains(targetName)) {
                StringBuilder sb = new StringBuilder(targetName);
                if (!currentStepNameChain.isEmpty())
                    sb.append('-').append(StringUtils.join(currentStepNameChain, '-'));
                sb.append('-').append(dep).append('-').append(targetName);
                circularDependencyDescriptions.add(sb.toString());
            }
            if (stepDepthValue + 1 <= maxDepth) {
                currentStepNameChain.add(dep);
                findCycleDependencies(circularDependencyDescriptions, allBeansDependenciesMap, dependeciesOfBeanDep, currentStepNameChain, targetName, stepDepthValue, maxDepth);
            }
        }
    }
}

19 Source : ServiceLocator.java
with MIT License
from InnovateUKGitHub

/**
 * A helper clreplaced to provide a one-stop lookup of services for components not built by Spring
 */
public clreplaced ServiceLocator {

    private GenericApplicationContext applicationContext;

    private String compAdminEmail;

    private String projectFinanceEmail;

    public ServiceLocator(GenericApplicationContext applicationContext, String compAdminEmail, String projectFinanceEmail) {
        this.applicationContext = applicationContext;
        this.compAdminEmail = compAdminEmail;
        this.projectFinanceEmail = projectFinanceEmail;
    }

    public <T> T getBean(Clreplaced<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public String getCompAdminEmail() {
        return compAdminEmail;
    }

    public String getProjectFinanceEmail() {
        return projectFinanceEmail;
    }
}

19 Source : SpringBootPlugin.java
with Apache License 2.0
from hank-cp

public static void releaseRegisteredResources(PluginWrapper plugin, GenericApplicationContext mainAppCtx) {
    try {
        // unregister Extension beans
        Set<String> extensionClreplacedNames = plugin.getPluginManager().getExtensionClreplacedNames(plugin.getPluginId());
        for (String extensionClreplacedName : extensionClreplacedNames) {
            Clreplaced<?> extensionClreplaced = plugin.getPluginClreplacedLoader().loadClreplaced(extensionClreplacedName);
            SpringExtensionFactory extensionFactory = (SpringExtensionFactory) plugin.getPluginManager().getExtensionFactory();
            String beanName = extensionFactory.getExtensionBeanName(extensionClreplaced);
            if (StringUtils.isEmpty(beanName))
                continue;
            unregisterBeanFromMainContext(mainAppCtx, beanName);
        }
        // unregister Controller beans
        PluginRequestMappingHandlerMapping requestMapping = (PluginRequestMappingHandlerMapping) mainAppCtx.getBean("requestMappingHandlerMapping");
        Stream.concat(mainAppCtx.getBeansWithAnnotation(Controller.clreplaced).values().stream(), mainAppCtx.getBeansWithAnnotation(RestController.clreplaced).values().stream()).filter(bean -> bean.getClreplaced().getClreplacedLoader() == plugin.getPluginClreplacedLoader()).forEach(bean -> {
            requestMapping.unregisterController(mainAppCtx, bean);
        });
    } catch (Exception e) {
        log.trace("Release registered resources failed. " + e.getMessage(), e);
    }
}

19 Source : AbstractSingleSpringContextTests.java
with Apache License 2.0
from eclipse

/**
 * Factory method for creating new {@link BeanDefinitionReader}s for
 * loading bean definitions into the supplied
 * {@link GenericApplicationContext context}.
 * <p>The default implementation creates a new {@link XmlBeanDefinitionReader}.
 * Can be overridden in subclreplacedes to provide a different
 * BeanDefinitionReader implementation.
 * @param context the context for which the BeanDefinitionReader should be created
 * @return a BeanDefinitionReader for the supplied context
 * @see #createApplicationContext(String[])
 * @see BeanDefinitionReader
 * @see XmlBeanDefinitionReader
 */
protected BeanDefinitionReader createBeanDefinitionReader(GenericApplicationContext context) {
    return new XmlBeanDefinitionReader(context);
}

19 Source : AbstractSingleSpringContextTests.java
with Apache License 2.0
from eclipse

/**
 * Prepare the GenericApplicationContext used by this test.
 * Called before bean definitions are read.
 * <p>The default implementation is empty. Can be overridden in subclreplacedes to
 * customize GenericApplicationContext's standard settings.
 * @param context the context for which the BeanDefinitionReader should be created
 * @see #createApplicationContext
 * @see org.springframework.context.support.GenericApplicationContext#setResourceLoader
 * @see org.springframework.context.support.GenericApplicationContext#setId
 */
protected void prepareApplicationContext(GenericApplicationContext context) {
}

19 Source : OsgiSingleReferenceParserWithInvalidFilesTest.java
with Apache License 2.0
from eclipse

/**
 * @author Costin Leau
 */
public clreplaced OsgiSingleReferenceParserWithInvalidFilesTest extends TestCase {

    private GenericApplicationContext appContext;

    protected void setUp() throws Exception {
        BundleContext bundleContext = new MockBundleContext() {

            // service reference already registered
            public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
                return new ServiceReference[0];
            }
        };
        appContext = new GenericApplicationContext();
        appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
        appContext.setClreplacedLoader(getClreplaced().getClreplacedLoader());
    }

    protected void tearDown() throws Exception {
        appContext.close();
        appContext = null;
    }

    private void readCtxFromResource(String resourceName) {
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
        reader.loadBeanDefinitions(new ClreplacedPathResource(resourceName, getClreplaced()));
        appContext.refresh();
    }

    private void expectException(String resourceName) {
        try {
            readCtxFromResource(resourceName);
            fail("should have thrown parsing exception, invalid resource " + resourceName);
        } catch (FatalBeanException ex) {
        // expected
        }
    }

    public void testInlineInterfaceAndNestedInterfaces() throws Exception {
        expectException("osgiSingleReferenceInvalidInterface.xml");
    }

    public void testListenerWithNestedDefinitionAndInlinedRefVariant1() throws Exception {
        expectException("osgiSingleReferenceWithInvalidListener1.xml");
    }

    public void testListenerWithNestedDefinitionAndInlinedRefVariant2() throws Exception {
        expectException("osgiSingleReferenceWithInvalidListener2.xml");
    }
}

19 Source : OsgiReferenceNamespaceHandlerTest.java
with Apache License 2.0
from eclipse

/**
 * Integration test for osgi:reference namespace handler.
 *
 * @author Costin Leau
 */
public clreplaced OsgiReferenceNamespaceHandlerTest extends TestCase {

    private GenericApplicationContext appContext;

    protected void setUp() throws Exception {
        // reset counter just to be sure
        DummyListener.BIND_CALLS = 0;
        DummyListener.UNBIND_CALLS = 0;
        DummyListenerServiceSignature.BIND_CALLS = 0;
        DummyListenerServiceSignature.UNBIND_CALLS = 0;
        DummyListenerServiceSignature2.BIND_CALLS = 0;
        DummyListenerServiceSignature2.UNBIND_CALLS = 0;
        BundleContext bundleContext = new MockBundleContext() {

            // service reference already registered
            public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
                return new ServiceReference[] { new MockServiceReference(new String[] { Cloneable.clreplaced.getName() }) };
            }
        };
        appContext = new GenericApplicationContext();
        appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
        appContext.setClreplacedLoader(getClreplaced().getClreplacedLoader());
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
        // reader.setEventListener(this.listener);
        reader.loadBeanDefinitions(new ClreplacedPathResource("osgiReferenceNamespaceHandlerTests.xml", getClreplaced()));
        appContext.refresh();
    }

    protected void tearDown() throws Exception {
        appContext.close();
    }

    public void testSimpleReference() throws Exception {
        Object factoryBean = appContext.getBean("&serializable");
        replacedertTrue(factoryBean instanceof OsgiServiceProxyFactoryBean);
        OsgiServiceProxyFactoryBean proxyFactory = (OsgiServiceProxyFactoryBean) factoryBean;
        Clreplaced<?>[] intfs = (Clreplaced[]) TestUtils.getFieldValue(proxyFactory, "interfaces");
        replacedertEquals(1, intfs.length);
        replacedertSame(Serializable.clreplaced, intfs[0]);
        // get the factory product
        Object bean = appContext.getBean("serializable");
        replacedertTrue(bean instanceof Serializable);
        replacedertTrue(Proxy.isProxyClreplaced(bean.getClreplaced()));
    }

    public void testFullReference() throws Exception {
        OsgiServiceProxyFactoryBean factory = (OsgiServiceProxyFactoryBean) appContext.getBean("&full-options");
        // required to initialise proxy and hook
        factory.getObject();
        // listeners into the binding process
        OsgiServiceLifecycleListener[] listeners = (OsgiServiceLifecycleListener[]) TestUtils.getFieldValue(factory, "listeners");
        replacedertNotNull(listeners);
        replacedertEquals(5, listeners.length);
        replacedertEquals("already registered service should have been discovered", 4, DummyListener.BIND_CALLS);
        replacedertEquals(0, DummyListener.UNBIND_CALLS);
        listeners[1].bind(null, null);
        replacedertEquals(6, DummyListener.BIND_CALLS);
        listeners[1].unbind(null, null);
        replacedertEquals(2, DummyListener.UNBIND_CALLS);
        replacedertEquals(1, DummyListenerServiceSignature.BIND_CALLS);
        listeners[4].bind(null, null);
        replacedertEquals(2, DummyListenerServiceSignature.BIND_CALLS);
        replacedertEquals(0, DummyListenerServiceSignature.UNBIND_CALLS);
        listeners[4].unbind(null, null);
        replacedertEquals(1, DummyListenerServiceSignature.UNBIND_CALLS);
        replacedertEquals(1, DummyListenerServiceSignature2.BIND_CALLS);
        listeners[3].bind(null, null);
        replacedertEquals(2, DummyListenerServiceSignature2.BIND_CALLS);
        replacedertEquals(0, DummyListenerServiceSignature2.UNBIND_CALLS);
        listeners[3].unbind(null, null);
        replacedertEquals(1, DummyListenerServiceSignature2.UNBIND_CALLS);
    }

    public void testMultipleInterfaces() throws Exception {
        OsgiServiceProxyFactoryBean factory = (OsgiServiceProxyFactoryBean) appContext.getBean("&multi-interfaces");
        Clreplaced<?>[] intfs = (Clreplaced[]) TestUtils.getFieldValue(factory, "interfaces");
        replacedertNotNull(intfs);
        replacedertEquals(2, intfs.length);
        replacedertTrue(Arrays.equals(new Clreplaced<?>[] { Serializable.clreplaced, Externalizable.clreplaced }, intfs));
    }

    public void testBeanNameAttrToServiceBeanNameProperty() throws Exception {
        OsgiServiceProxyFactoryBean factory = (OsgiServiceProxyFactoryBean) appContext.getBean("&importerWithBeanName");
        Object obj = TestUtils.getFieldValue(factory, "serviceBeanName");
        replacedertEquals("bean-name attr hasn't been properly parsed", "someBean", obj);
    }
}

19 Source : OsgiReferenceCollectionNamespaceHandlerTest.java
with Apache License 2.0
from eclipse

/**
 * @author Costin Leau
 */
public clreplaced OsgiReferenceCollectionNamespaceHandlerTest extends TestCase {

    private GenericApplicationContext appContext;

    protected void setUp() throws Exception {
        // reset counter just to be sure
        DummyListener.BIND_CALLS = 0;
        DummyListener.UNBIND_CALLS = 0;
        DummyListenerServiceSignature.BIND_CALLS = 0;
        DummyListenerServiceSignature.UNBIND_CALLS = 0;
        DummyListenerServiceSignature2.BIND_CALLS = 0;
        DummyListenerServiceSignature2.UNBIND_CALLS = 0;
        BundleContext bundleContext = new MockBundleContext() {

            // service reference already registered
            public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
                return new ServiceReference[0];
            }
        };
        appContext = new GenericApplicationContext();
        appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
        appContext.setClreplacedLoader(getClreplaced().getClreplacedLoader());
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
        // reader.setEventListener(this.listener);
        reader.loadBeanDefinitions(new ClreplacedPathResource("osgiReferenceCollectionNamespaceHandlerTests.xml", getClreplaced()));
        appContext.refresh();
    }

    protected void tearDown() throws Exception {
        appContext.close();
    }

    public void testSimpleList() {
        Object factoryBean = appContext.getBean("&simpleList");
        replacedertTrue(factoryBean instanceof OsgiServiceCollectionProxyFactoryBean);
        // get the factory product
        Object bean = appContext.getBean("simpleList");
        replacedertFalse(bean instanceof OsgiServiceList);
        replacedertTrue(bean instanceof List);
    }

    public void testSimpleSet() {
        Object factoryBean = appContext.getBean("&simpleSet");
        replacedertTrue(factoryBean instanceof OsgiServiceCollectionProxyFactoryBean);
        // get the factory product
        Object bean = appContext.getBean("simpleSet");
        replacedertFalse(bean instanceof OsgiServiceSet);
        replacedertTrue(bean instanceof Set);
    }

    public void testSimpleListWithGreedyProxyingOn() throws Exception {
        Object factoryBean = appContext.getBean("&simpleListWithGreedyProxying");
        replacedertTrue(factoryBean instanceof OsgiServiceCollectionProxyFactoryBean);
        replacedertEquals(Boolean.TRUE, (Boolean) TestUtils.getFieldValue(factoryBean, "greedyProxying"));
        // get the factory product
        Object bean = appContext.getBean("simpleListWithGreedyProxying");
        replacedertFalse(bean instanceof OsgiServiceList);
        replacedertTrue(bean instanceof List);
    }

    public void testSimpleListWithDefaultProxying() throws Exception {
        Object factoryBean = appContext.getBean("&simpleSet");
        replacedertTrue(factoryBean instanceof OsgiServiceCollectionProxyFactoryBean);
        replacedertEquals(Boolean.FALSE, (Boolean) TestUtils.getFieldValue(factoryBean, "greedyProxying"));
    }

    public void testImplicitSortedList() {
        Object factoryBean = appContext.getBean("&implicitSortedList");
        replacedertTrue(factoryBean instanceof OsgiServiceCollectionProxyFactoryBean);
        // get the factory product
        Object bean = appContext.getBean("implicitSortedList");
        replacedertFalse(bean instanceof OsgiServiceSortedList);
        replacedertTrue(bean instanceof List);
        OsgiServiceSortedList exposedProxy = (OsgiServiceSortedList) TestUtils.getFieldValue(factoryBean, "exposedProxy");
        replacedertSame(appContext.getBean("defaultComparator"), exposedProxy.comparator());
    }

    public void testImplicitSortedSet() {
        Object factoryBean = appContext.getBean("&implicitSortedSet");
        replacedertTrue(factoryBean instanceof OsgiServiceCollectionProxyFactoryBean);
        Object bean = appContext.getBean("implicitSortedSet");
        replacedertFalse(bean instanceof OsgiServiceSortedSet);
        replacedertTrue(bean instanceof SortedSet);
        replacedertSame(appContext.getBean("defaultComparator"), ((SortedSet) bean).comparator());
    }

    public void testSimpleSortedList() {
        Object factoryBean = appContext.getBean("&implicitSortedList");
        replacedertTrue(factoryBean instanceof OsgiServiceCollectionProxyFactoryBean);
        Object bean = appContext.getBean("implicitSortedList");
        replacedertFalse(bean instanceof OsgiServiceSortedList);
        replacedertTrue(bean instanceof List);
        Clreplaced<?>[] intfs = getInterfaces(factoryBean);
        replacedertTrue(Arrays.equals(new Clreplaced<?>[] { Serializable.clreplaced }, intfs));
    }

    public void testSimpleSortedSet() {
        Object factoryBean = appContext.getBean("&implicitSortedSet");
        replacedertTrue(factoryBean instanceof OsgiServiceCollectionProxyFactoryBean);
        Object bean = appContext.getBean("implicitSortedSet");
        replacedertFalse(bean instanceof OsgiServiceSortedSet);
        replacedertTrue(bean instanceof SortedSet);
        Clreplaced<?>[] intfs = getInterfaces(factoryBean);
        replacedertTrue(Arrays.equals(new Clreplaced<?>[] { Externalizable.clreplaced }, intfs));
    }

    public void testSortedSetWithNaturalOrderingOnRefs() throws Exception {
        Object factoryBean = appContext.getBean("&sortedSetWithNaturalOrderingOnRefs");
        replacedertTrue(factoryBean instanceof OsgiServiceCollectionProxyFactoryBean);
        Comparator comp = getComparator(factoryBean);
        replacedertNotNull(comp);
        replacedertSame(ServiceReferenceComparator.clreplaced, comp.getClreplaced());
        Clreplaced<?>[] intfs = getInterfaces(factoryBean);
        replacedertTrue(Arrays.equals(new Clreplaced<?>[] { Externalizable.clreplaced }, intfs));
        OsgiServiceLifecycleListener[] listeners = getListeners(factoryBean);
        replacedertEquals(2, listeners.length);
        Object bean = appContext.getBean("sortedSetWithNaturalOrderingOnRefs");
        replacedertFalse(bean instanceof OsgiServiceSortedSet);
        replacedertTrue(bean instanceof SortedSet);
    }

    public void testSortedListWithNaturalOrderingOnServs() throws Exception {
        Object factoryBean = appContext.getBean("&sortedListWithNaturalOrderingOnServs");
        replacedertTrue(factoryBean instanceof OsgiServiceCollectionProxyFactoryBean);
        replacedertNull(getComparator(factoryBean));
        Object bean = appContext.getBean("sortedListWithNaturalOrderingOnServs");
        replacedertFalse(bean instanceof OsgiServiceSortedList);
        replacedertTrue(bean instanceof List);
        Clreplaced<?>[] intfs = getInterfaces(factoryBean);
        replacedertTrue(Arrays.equals(new Clreplaced<?>[] { Externalizable.clreplaced }, intfs));
    }

    private Clreplaced<?>[] getInterfaces(Object proxy) {
        return (Clreplaced[]) TestUtils.getFieldValue(proxy, "interfaces");
    }

    private Comparator getComparator(Object proxy) {
        return (Comparator) TestUtils.getFieldValue(proxy, "comparator");
    }

    private OsgiServiceLifecycleListener[] getListeners(Object proxy) {
        return (OsgiServiceLifecycleListener[]) TestUtils.getFieldValue(proxy, "listeners");
    }
}

19 Source : OsgiDefaultsTests.java
with Apache License 2.0
from eclipse

/**
 * @author Costin Leau
 */
public clreplaced OsgiDefaultsTests extends TestCase {

    private GenericApplicationContext appContext;

    protected void setUp() throws Exception {
        BundleContext bundleContext = new MockBundleContext() {

            // service reference already registered
            public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
                return new ServiceReference[] { new MockServiceReference(new String[] { Serializable.clreplaced.getName() }) };
            }
        };
        appContext = new GenericApplicationContext();
        appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
        appContext.setClreplacedLoader(getClreplaced().getClreplacedLoader());
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
        reader.loadBeanDefinitions(new ClreplacedPathResource("osgiDefaults.xml", getClreplaced()));
        appContext.refresh();
    }

    protected void tearDown() throws Exception {
        appContext.close();
        appContext = null;
    }

    public void testLocalDefinitionForTimeout() throws Exception {
        OsgiServiceProxyFactoryBean fb = (OsgiServiceProxyFactoryBean) appContext.getBean("&refWLocalConfig");
        replacedertEquals(55, getTimeout(fb));
    }

    public void testLocalDefinitionForCardinalityOnMultiImporter() throws Exception {
        OsgiServiceCollectionProxyFactoryBean fb = (OsgiServiceCollectionProxyFactoryBean) appContext.getBean("&colWLocalConfig");
        replacedertEquals(Availability.MANDATORY, getCardinality(fb));
    }

    public void testLocalDefinitionForCardinalityOnSingleImporter() throws Exception {
        OsgiServiceProxyFactoryBean fb = (OsgiServiceProxyFactoryBean) appContext.getBean("&refWLocalConfig");
        replacedertEquals(Availability.MANDATORY, getCardinality(fb));
    }

    public void testTimeoutDefault() throws Exception {
        OsgiServiceProxyFactoryBean fb = (OsgiServiceProxyFactoryBean) appContext.getBean("&refWDefaults");
        replacedertEquals("default osgi timeout not applied", 10, getTimeout(fb));
    }

    public void testCardinalityDefaultOnSingleImporter() throws Exception {
        OsgiServiceProxyFactoryBean fb = (OsgiServiceProxyFactoryBean) appContext.getBean("&refWDefaults");
        replacedertEquals(Availability.OPTIONAL, getCardinality(fb));
    }

    public void testCardinalityDefaultOnMultiImporter() throws Exception {
        OsgiServiceCollectionProxyFactoryBean fb = (OsgiServiceCollectionProxyFactoryBean) appContext.getBean("&colWDefaults");
        replacedertEquals(Availability.OPTIONAL, getCardinality(fb));
    }

    public void testNormalBeanInjection() throws Exception {
        appContext.getBean("nestedURLValue");
    }

    private Availability getCardinality(Object obj) {
        return (Availability) TestUtils.getFieldValue(obj, "availability");
    }

    private long getTimeout(Object obj) {
        return ((RetryTemplate) TestUtils.getFieldValue(obj, "retryTemplate")).getWaitTime();
    }
}

19 Source : NestedReferencesTest.java
with Apache License 2.0
from eclipse

/**
 * @author Costin Leau
 */
public clreplaced NestedReferencesTest extends TestCase {

    public static clreplaced Holder {

        private Object data;

        public Object getData() {
            return data;
        }

        public void setData(Object data) {
            this.data = data;
        }
    }

    private GenericApplicationContext appContext;

    protected void setUp() throws Exception {
        BundleContext bundleContext = new MockBundleContext() {

            // service reference already registered
            public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
                return new ServiceReference[0];
            }
        };
        appContext = new GenericApplicationContext();
        appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
        appContext.setClreplacedLoader(getClreplaced().getClreplacedLoader());
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
        // reader.setEventListener(this.listener);
        reader.loadBeanDefinitions(new ClreplacedPathResource("osgiReferenceNestedBeans.xml", getClreplaced()));
        appContext.refresh();
    }

    protected void tearDown() throws Exception {
        appContext.close();
    }

    public void testNestedBeansMadeTopLevel() throws Exception {
        // 5 top-level plus 4 promoted beans
        replacedertEquals(5 + 4, appContext.getBeanDefinitionCount());
    }

    public void testNestedReferenceWithName() {
        Object bean = appContext.getBean("satriani#org.eclipse.gemini.blueprint.service.importer.support.OsgiServiceProxyFactoryBean#0");
        Holder holder = (Holder) appContext.getBean("nestedNamedReference", Holder.clreplaced);
        replacedertSame(bean, holder.data);
    }

    public void testNestedReferenceWithoutName() throws Exception {
        Object bean = appContext.getBean("org.eclipse.gemini.blueprint.service.importer.support.OsgiServiceProxyFactoryBean#0");
        Holder holder = (Holder) appContext.getBean("nestedAnonymousReference", Holder.clreplaced);
        replacedertSame(bean, holder.data);
    }

    public void testNestedCollectionWithName() throws Exception {
        Object bean = appContext.getBean("dire-straits#org.eclipse.gemini.blueprint.service.importer.support.OsgiServiceCollectionProxyFactoryBean#0");
        Holder holder = (Holder) appContext.getBean("nestedNamedCollection", Holder.clreplaced);
        replacedertSame(bean, holder.data);
    }

    public void testNesteCollectionWithoutName() throws Exception {
        Object bean = appContext.getBean("org.eclipse.gemini.blueprint.service.importer.support.OsgiServiceCollectionProxyFactoryBean#0");
        Holder holder = (Holder) appContext.getBean("nestedAnonymousCollection", Holder.clreplaced);
        replacedertSame(bean, holder.data);
    }
}

19 Source : InvalidOsgiDefaultsTest.java
with Apache License 2.0
from eclipse

public clreplaced InvalidOsgiDefaultsTest extends TestCase {

    private GenericApplicationContext appContext;

    protected void setUp() throws Exception {
        BundleContext bundleContext = new MockBundleContext() {

            // service reference already registered
            public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
                return new ServiceReference[] { new MockServiceReference(new String[] { Serializable.clreplaced.getName() }) };
            }
        };
        appContext = new GenericApplicationContext();
        appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
        appContext.setClreplacedLoader(getClreplaced().getClreplacedLoader());
    }

    protected void tearDown() throws Exception {
        appContext.close();
        appContext = null;
    }

    public void testInvalidDefaultsCheck() throws Exception {
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
        try {
            reader.loadBeanDefinitions(new ClreplacedPathResource("osgiInvalidDefaults.xml", getClreplaced()));
            fail("should have failed since osgi:defaults cannot be used outside the root element");
        } catch (BeanDefinitionParsingException ex) {
        // expected
        }
    }
}

19 Source : ManagedServiceFactoryTest.java
with Apache License 2.0
from eclipse

/**
 * Parsing test for ManagedServiceFactory/<managed-service-factory/>
 *
 * @author Costin Leau
 */
public clreplaced ManagedServiceFactoryTest extends TestCase {

    private GenericApplicationContext appContext;

    protected void setUp() throws Exception {
        final Configuration cfg = createMock(Configuration.clreplaced);
        expect(cfg.getProperties()).andReturn(new Hashtable<String, Object>());
        replay(cfg);
        BundleContext bundleContext = new MockBundleContext() {

            // always return a ConfigurationAdmin
            public Object getService(ServiceReference reference) {
                return new MockConfigurationAdmin() {

                    public Configuration getConfiguration(String pid) throws IOException {
                        return cfg;
                    }
                };
            }
        };
        appContext = new GenericApplicationContext();
        appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
        appContext.setClreplacedLoader(getClreplaced().getClreplacedLoader());
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
        reader.loadBeanDefinitions(new ClreplacedPathResource("managedServiceFactory.xml", getClreplaced()));
        appContext.refresh();
    }

    protected void tearDown() throws Exception {
        appContext.close();
        appContext = null;
    }

    public void testBasicParsing() throws Exception {
        Object factory = appContext.getBean("&simple");
        replacedertTrue(factory instanceof ManagedServiceFactoryFactoryBean);
    }

    public void testBasicExportAttributes() throws Exception {
        Object factory = appContext.getBean("&simple");
        Object intfs = TestUtils.getFieldValue(factory, "interfaces");
        replacedertTrue(Arrays.equals((Object[]) intfs, new Clreplaced<?>[] { Object.clreplaced }));
        Object autoExport = TestUtils.getFieldValue(factory, "detector");
        replacedertEquals(DefaultInterfaceDetector.ALL_CLreplacedES, autoExport);
    }

    public void testNestedInterfaceElement() throws Exception {
        Object factory = appContext.getBean("&ccl");
        Object intfs = TestUtils.getFieldValue(factory, "interfaces");
        replacedertTrue(Arrays.equals((Object[]) intfs, new Clreplaced<?>[] { Map.clreplaced, Serializable.clreplaced }));
    }

    public void testCCLAttribute() throws Exception {
        Object factory = appContext.getBean("&ccl");
        Object ccl = TestUtils.getFieldValue(factory, "ccl");
        replacedertEquals(ExportContextClreplacedLoaderEnum.SERVICE_PROVIDER, ccl);
    }

    public void testContainerUpdateAttr() throws Exception {
        Object factory = appContext.getBean("&container-update");
        Object strategy = TestUtils.getFieldValue(factory, "autowireOnUpdate");
        replacedertEquals(true, strategy);
    }

    public void testBeanManagedUpdateAttr() throws Exception {
        Object factory = appContext.getBean("&bean-update");
        Object strategy = TestUtils.getFieldValue(factory, "autowireOnUpdate");
        Object method = TestUtils.getFieldValue(factory, "updateMethod");
        replacedertEquals(false, strategy);
        replacedertEquals("update", method);
    }
}

19 Source : ManagedPropertiesTest.java
with Apache License 2.0
from eclipse

/**
 * @author Costin Leau
 */
public clreplaced ManagedPropertiesTest extends TestCase {

    private GenericApplicationContext appContext;

    private int unregistrationCounter;

    private int registrationCounter;

    protected void setUp() throws Exception {
        final Configuration cfg = createNiceMock(Configuration.clreplaced);
        expect(cfg.getProperties()).andReturn(new Hashtable<String, Object>());
        replay(cfg);
        registrationCounter = 0;
        unregistrationCounter = 0;
        BundleContext bundleContext = new MockBundleContext() {

            // always return a ConfigurationAdmin
            public Object getService(ServiceReference reference) {
                return new MockConfigurationAdmin() {

                    public Configuration getConfiguration(String pid) throws IOException {
                        return cfg;
                    }
                };
            }

            public ServiceRegistration registerService(String[] clazzes, Object service, Dictionary properties) {
                if (service instanceof ManagedService) {
                    registrationCounter++;
                    return new MockServiceRegistration(clazzes, properties) {

                        public void unregister() {
                            super.unregister();
                            unregistrationCounter++;
                        }
                    };
                }
                return super.registerService(clazzes, service, properties);
            }
        };
        appContext = new GenericApplicationContext();
        appContext.getBeanFactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
        appContext.setClreplacedLoader(getClreplaced().getClreplacedLoader());
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
        reader.loadBeanDefinitions(new ClreplacedPathResource("managedService.xml", getClreplaced()));
        appContext.refresh();
    }

    protected void tearDown() throws Exception {
        appContext.close();
        appContext = null;
    }

    private ManagedServiceInstanceTrackerPostProcessor getTrackerForBean(String beanName) {
        return (ManagedServiceInstanceTrackerPostProcessor) appContext.getBean(ManagedServiceInstanceTrackerPostProcessor.clreplaced.getName() + "#0#" + beanName);
    }

    public void testSimpleBeanTrackingBpp() throws Exception {
        ManagedServiceInstanceTrackerPostProcessor bpp = getTrackerForBean("simple");
        replacedertEquals("simple", TestUtils.getFieldValue(bpp, "pid"));
        replacedertNull(TestUtils.getFieldValue(bpp, "updateMethod"));
        replacedertNull(TestUtils.getFieldValue(bpp, "updateStrategy"));
    }

    public void testSimpleBeanWithNoNameTrackingBpp() throws Exception {
        ManagedServiceInstanceTrackerPostProcessor bpp = getTrackerForBean("org.eclipse.gemini.blueprint.compendium.OneSetter#0");
        replacedertEquals("non-name", TestUtils.getFieldValue(bpp, "pid"));
        replacedertNull(TestUtils.getFieldValue(bpp, "updateMethod"));
        replacedertNull(TestUtils.getFieldValue(bpp, "updateStrategy"));
    }

    public void testSimpleWUpdateBeanTrackingBpp() throws Exception {
        ManagedServiceInstanceTrackerPostProcessor bpp = getTrackerForBean("simpleWUpdate");
        replacedertEquals("simple", TestUtils.getFieldValue(bpp, "pid"));
        replacedertNull(TestUtils.getFieldValue(bpp, "updateMethod"));
    }

    public void testMultipleWUpdateBeanTrackingBpp() throws Exception {
        ManagedServiceInstanceTrackerPostProcessor bpp = getTrackerForBean("multipleWUpdate");
        replacedertEquals("multiple", TestUtils.getFieldValue(bpp, "pid"));
        replacedertNull(TestUtils.getFieldValue(bpp, "updateMethod"));
        replacedertEquals(true, TestUtils.getFieldValue(bpp, "autowireOnUpdate"));
    }

    public void testBeanManagedTrackingBpp() throws Exception {
        ManagedServiceInstanceTrackerPostProcessor bpp = getTrackerForBean("beanManaged");
        replacedertEquals("bean-managed", TestUtils.getFieldValue(bpp, "pid"));
        replacedertEquals("update", TestUtils.getFieldValue(bpp, "updateMethod"));
        replacedertEquals(false, TestUtils.getFieldValue(bpp, "autowireOnUpdate"));
    }

    public void testMixedManagedTrackingBpp() throws Exception {
        ManagedServiceInstanceTrackerPostProcessor bpp = getTrackerForBean("mixedManaged");
        replacedertEquals("bean-managed", TestUtils.getFieldValue(bpp, "pid"));
        replacedertEquals("update", TestUtils.getFieldValue(bpp, "updateMethod"));
        replacedertEquals(true, TestUtils.getFieldValue(bpp, "autowireOnUpdate"));
    }

    public void testTrackingCleanup() throws Exception {
        replacedertEquals(6, registrationCounter);
        replacedertEquals(0, unregistrationCounter);
        appContext.close();
        replacedertEquals(6, unregistrationCounter);
    }
}

18 Source : ClassLoaderFilesResourcePatternResolverTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void customProtocolResolverIsUsedInNonWebApplication() {
    GenericApplicationContext context = new GenericApplicationContext();
    Resource resource = mock(Resource.clreplaced);
    ProtocolResolver resolver = mockProtocolResolver("foo:some-file.txt", resource);
    context.addProtocolResolver(resolver);
    this.resolver = new ClreplacedLoaderFilesResourcePatternResolver(context, this.files);
    Resource actual = this.resolver.getResource("foo:some-file.txt");
    replacedertThat(actual).isSameAs(resource);
    verify(resolver).resolve(eq("foo:some-file.txt"), any(ResourceLoader.clreplaced));
}

18 Source : MustacheViewTests.java
with Apache License 2.0
from yuanmabiji

/**
 * Tests for {@link MustacheView}.
 *
 * @author Brian Clozel
 */
public clreplaced MustacheViewTests {

    private final String templateUrl = "clreplacedpath:/" + getClreplaced().getPackage().getName().replace(".", "/") + "/template.html";

    private GenericApplicationContext context = new GenericApplicationContext();

    private MockServerWebExchange exchange;

    @Before
    public void init() {
        this.context.refresh();
    }

    @Test
    public void viewResolvesHandlebars() {
        this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/test").build());
        MustacheView view = new MustacheView();
        view.setCompiler(Mustache.compiler());
        view.setUrl(this.templateUrl);
        view.setCharset(StandardCharsets.UTF_8.displayName());
        view.setApplicationContext(this.context);
        view.render(Collections.singletonMap("World", "Spring"), MediaType.TEXT_HTML, this.exchange).block();
        replacedertThat(this.exchange.getResponse().getBodyreplacedtring().block()).isEqualTo("Hello Spring");
    }
}

18 Source : HybridContextLoader.java
with MIT License
from Vip-Augus

@Override
protected BeanDefinitionReader createBeanDefinitionReader(GenericApplicationContext context) {
    throw new UnsupportedOperationException(getClreplaced().getSimpleName() + " doesn't support this");
}

See More Examples