Java Code Examples for org.springframework.beans.factory.config.BeanDefinition

The following are top voted examples for showing how to use org.springframework.beans.factory.config.BeanDefinition. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: springmock   File: BeanDefinitionFinderTest.java   View source code 6 votes vote down vote up
@Test
public void should_ignore_existing_spies_when_searching_for_bean_by_class() {
	//given
	final String spyName = "spy";
	final DoubleRegistry doubleRegistry = new DoubleRegistry(
			emptyList(),
			singletonList(doubleDefinition(String.class, spyName)));
	final ApplicationContext appCtx = buildAppContext(Stream.of(
			bean(spyName, spyName + " - bean")
	));
	final BeanDefinitionFinder definitionFinder = new BeanDefinitionFinder(appCtx, doubleRegistry);

	//when
	final Optional<BeanDefinition> definition = definitionFinder.tryToFindBeanDefinition("any bean name", String.class);

	//then
	assertFalse(definition.isPresent());
}
 
Example 2
Project: gemini.blueprint   File: MetadataUtils.java   View source code 6 votes vote down vote up
static List<BeanProperty> getBeanProperties(BeanDefinition definition) {
	List<BeanProperty> temp;

	List<PropertyValue> pvs = definition.getPropertyValues().getPropertyValueList();

	if (pvs.isEmpty()) {
		return Collections.<BeanProperty> emptyList();
	} else {
		temp = new ArrayList<BeanProperty>(pvs.size());
	}

	for (PropertyValue propertyValue : pvs) {
		temp.add(new SimpleBeanProperty(propertyValue));
	}

	return Collections.unmodifiableList(temp);
}
 
Example 3
Project: springboot-analysis   File: ConsumerRegistrar.java   View source code 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AnnotationTypeFilter(Consumer.class));
    provider.addIncludeFilter(new AssignableTypeFilter(IConsumer.class));
    Set<BeanDefinition> beanDefinitionSet = provider.findCandidateComponents("spring.study.componentprovider.bean");

    for(BeanDefinition beanDefinition : beanDefinitionSet) {
        String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry);
        if(!registry.containsBeanDefinition(beanName)) {
            registry.registerBeanDefinition(beanName, beanDefinition);
            registry.registerBeanDefinition("11", beanDefinition);
        }
    }

}
 
Example 4
Project: parabuild-ci   File: DwrNamespaceHandler.java   View source code 6 votes vote down vote up
private BeanDefinition findParentDefinition(String parentName, BeanDefinitionRegistry registry)
{   
    if (registry != null) 
    {
        if (registry.containsBeanDefinition(parentName)) 
        {
            return registry.getBeanDefinition(parentName);
        } 
        else if (registry instanceof HierarchicalBeanFactory) 
        {
            // Try to get parent definition from the parent BeanFactory. This could return null
            BeanFactory parentBeanFactory = ((HierarchicalBeanFactory)registry).getParentBeanFactory();
            return findParentDefinition(parentName, (BeanDefinitionRegistry)parentBeanFactory);
        } 
    }
    
    // we've exhausted all possibilities        
    return null;
}
 
Example 5
Project: cassandra-client   File: CassandraClientUIConfiguration.java   View source code 6 votes vote down vote up
@Bean
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public Menu fileMenu() {
    Menu file = new Menu(localeService.getMessage("ui.menu.file"));
    file.setMnemonicParsing(false);

    MenuItem connect = new MenuItem(localeService.getMessage("ui.menu.file.connect"));
    connect.setMnemonicParsing(false);
    connect.setOnAction(event -> newConnectionBox(getMainView().getPrimaryStage(),
            (data) -> getMainController().loadTables(data)));

    MenuItem manager = new MenuItem(localeService.getMessage("ui.menu.file.manager"));
    manager.setMnemonicParsing(false);
    manager.setOnAction(event -> connectionManager());
    file.getItems().addAll(connect, manager);
    return file;
}
 
Example 6
Project: holon-jdbc   File: DataSourcesTransactionManagerAutoConfigurationRegistrar.java   View source code 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

	if (beanFactory instanceof ListableBeanFactory) {

		String[] dataSourceBeanNames = ((ListableBeanFactory) beanFactory).getBeanNamesForType(DataSource.class,
				false, true);
		if (dataSourceBeanNames != null) {
			for (String dataSourceBeanName : dataSourceBeanNames) {
				BeanDefinition bd = registry.getBeanDefinition(dataSourceBeanName);
				if (bd instanceof DataContextBoundBeanDefinition) {
					DataSourceRegistrar.registerDataSourceTransactionManager(registry, dataSourceBeanName,
							((DataContextBoundBeanDefinition) bd).getDataContextId().orElse(null),
							PrimaryMode.AUTO);
				}
			}
		}

	}

}
 
Example 7
Project: taboola-cronyx   File: ConfigUtil.java   View source code 6 votes vote down vote up
public static <T> List<Pair<Class, T>> cronyxQuartzConverterPairs(Class<T> tClass) {

        List<Pair<Class, T>> results = new ArrayList<>();

        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AssignableTypeFilter(tClass));

        Set<BeanDefinition> components = provider.findCandidateComponents(PACKAGE);
        for (BeanDefinition component : components) {
            try {
                Class cls = Class.forName(component.getBeanClassName());
                Class<?> typeArgument = GenericTypeResolver.resolveTypeArgument(cls, tClass);
                results.add(new ImmutablePair<>(typeArgument, (T) cls.newInstance()));

            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                throw new CronyxException("Could not instantiate cronyxToQuartzConverters", e);
            }
        }
        return results;
    }
 
Example 8
Project: ocmall   File: FullPackageBeanNameGenerator.java   View source code 6 votes vote down vote up
@Override
protected String buildDefaultBeanName(BeanDefinition definition) {
    if(this.packageDepth < 1){
        return super.buildDefaultBeanName(definition);
    }

    String fullName = definition.getBeanClassName(); //e.g.: com.mobanker.tkj.api.action.UserAction
    char delimiter = dotReplacement > 0 ? dotReplacement : DEFAULT_DOT_REPLACEMENT;
    String[] names = fullName.split("\\.");
    StringBuilder beanName = new StringBuilder("");

    //add package name
    if(names.length > 1){
        for(int i = 0; i < this.packageDepth; i++){
            String name = names[names.length - 2 - i];
            beanName.insert(0, delimiter);
            beanName.insert(0, name);
        }
    }

    //add Class name
    beanName.append(names[names.length - 1]);

    return beanName.toString();
}
 
Example 9
Project: lams   File: DefaultListableBeanFactory.java   View source code 6 votes vote down vote up
/**
 * Find a {@link Annotation} of {@code annotationType} on the specified
 * bean, traversing its interfaces and super classes if no annotation can be
 * found on the given class itself, as well as checking its raw bean class
 * if not found on the exposed bean reference (e.g. in case of a proxy).
 */
@Override
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
		throws NoSuchBeanDefinitionException{

	A ann = null;
	Class<?> beanType = getType(beanName);
	if (beanType != null) {
		ann = AnnotationUtils.findAnnotation(beanType, annotationType);
	}
	if (ann == null && containsBeanDefinition(beanName)) {
		BeanDefinition bd = getMergedBeanDefinition(beanName);
		if (bd instanceof AbstractBeanDefinition) {
			AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
			if (abd.hasBeanClass()) {
				ann = AnnotationUtils.findAnnotation(abd.getBeanClass(), annotationType);
			}
		}
	}
	return ann;
}
 
Example 10
Project: alfresco-repository   File: AJExtensionsCompileTest.java   View source code 6 votes vote down vote up
@Test
public void testCompileExtendedServices() throws Exception
{
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
    provider.addIncludeFilter(new AssignableTypeFilter(Extensible.class));

    Set<BeanDefinition> components = provider.findCandidateComponents("org/alfresco/*");
    Set<Class<? extends Extensible>> extensibles = new HashSet<>();
    for (BeanDefinition component : components)
    {
        @SuppressWarnings("unchecked")
        Class<? extends Extensible> extensibleClass = (Class<? extends Extensible>) Class.forName(component
                    .getBeanClassName());
        extensibles.add(extensibleClass);

    }
    compile(extensibles);
}
 
Example 11
Project: lams   File: AbstractAutowireCapableBeanFactory.java   View source code 6 votes vote down vote up
@Override
public Object configureBean(Object existingBean, String beanName) throws BeansException {
	markBeanAsCreated(beanName);
	BeanDefinition mbd = getMergedBeanDefinition(beanName);
	RootBeanDefinition bd = null;
	if (mbd instanceof RootBeanDefinition) {
		RootBeanDefinition rbd = (RootBeanDefinition) mbd;
		bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
	}
	if (!mbd.isPrototype()) {
		if (bd == null) {
			bd = new RootBeanDefinition(mbd);
		}
		bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
		bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader());
	}
	BeanWrapper bw = new BeanWrapperImpl(existingBean);
	initBeanWrapper(bw);
	populateBean(beanName, bd, bw);
	return initializeBean(beanName, existingBean, bd);
}
 
Example 12
Project: tasfe-framework   File: FullPackageBeanNameGenerator.java   View source code 6 votes vote down vote up
@Override
protected String buildDefaultBeanName(BeanDefinition definition) {
	if(this.packageDepth < 1){
		return super.buildDefaultBeanName(definition);
	}
	
	String fullName = definition.getBeanClassName(); //e.g.: com.tasfe.tkj.api.action.UserAction
	char delimiter = dotReplacement > 0 ? dotReplacement : DEFAULT_DOT_REPLACEMENT;
	String[] names = fullName.split("\\.");
	StringBuilder beanName = new StringBuilder("");

	//add package name
	if(names.length > 1){
		for(int i = 0; i < this.packageDepth; i++){
			String name = names[names.length - 2 - i];
			beanName.insert(0, delimiter);
			beanName.insert(0, name);
		}
	}
	
	//add Class name
	beanName.append(names[names.length - 1]);
	
	return beanName.toString();
}
 
Example 13
Project: lams   File: BeanComponentDefinition.java   View source code 6 votes vote down vote up
private void findInnerBeanDefinitionsAndBeanReferences(BeanDefinition beanDefinition) {
	List<BeanDefinition> innerBeans = new ArrayList<BeanDefinition>();
	List<BeanReference> references = new ArrayList<BeanReference>();
	PropertyValues propertyValues = beanDefinition.getPropertyValues();
	for (int i = 0; i < propertyValues.getPropertyValues().length; i++) {
		PropertyValue propertyValue = propertyValues.getPropertyValues()[i];
		Object value = propertyValue.getValue();
		if (value instanceof BeanDefinitionHolder) {
			innerBeans.add(((BeanDefinitionHolder) value).getBeanDefinition());
		}
		else if (value instanceof BeanDefinition) {
			innerBeans.add((BeanDefinition) value);
		}
		else if (value instanceof BeanReference) {
			references.add((BeanReference) value);
		}
	}
	this.innerBeanDefinitions = innerBeans.toArray(new BeanDefinition[innerBeans.size()]);
	this.beanReferences = references.toArray(new BeanReference[references.size()]);
}
 
Example 14
Project: jsf-sdk   File: JSFParameterDefinitionParser.java   View source code 6 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    RootBeanDefinition beanDefinition = new RootBeanDefinition();
    beanDefinition.setBeanClass(beanClass);
    beanDefinition.setLazyInit(false);

    String key = element.getAttribute("key");
    String value = element.getAttribute("value");
    String hide = element.getAttribute("hide");
    if(CommonUtils.isTrue(hide)){
        JSFContext.putGlobalVal(Constants.HIDE_KEY_PREFIX + key, value);
    } else {
        JSFContext.putGlobalVal(key, value);
    }

    beanDefinition.getPropertyValues().addPropertyValue("key", key);
    beanDefinition.getPropertyValues().addPropertyValue("value", value);
    beanDefinition.getPropertyValues().addPropertyValue("hide", Boolean.valueOf(hide));

    return beanDefinition;
}
 
Example 15
Project: lams   File: AspectJAutoProxyBeanDefinitionParser.java   View source code 6 votes vote down vote up
private void addIncludePatterns(Element element, ParserContext parserContext, BeanDefinition beanDef) {
	ManagedList<TypedStringValue> includePatterns = new ManagedList<TypedStringValue>();
	NodeList childNodes = element.getChildNodes();
	for (int i = 0; i < childNodes.getLength(); i++) {
		Node node = childNodes.item(i);
		if (node instanceof Element) {
			Element includeElement = (Element) node;
			TypedStringValue valueHolder = new TypedStringValue(includeElement.getAttribute("name"));
			valueHolder.setSource(parserContext.extractSource(includeElement));
			includePatterns.add(valueHolder);
		}
	}
	if (!includePatterns.isEmpty()) {
		includePatterns.setSource(parserContext.extractSource(element));
		beanDef.getPropertyValues().add("includePatterns", includePatterns);
	}
}
 
Example 16
Project: gemini.blueprint   File: AbstractReferenceDefinitionParser.java   View source code 6 votes vote down vote up
protected String generateBeanName(String prefix, BeanDefinition def, ParserContext parserContext) {
	BeanDefinitionRegistry registry = parserContext.getRegistry();
	String name = prefix + BeanDefinitionReaderUtils.generateBeanName(def, registry);
	String generated = name;
	int counter = 0;

	while (registry.containsBeanDefinition(generated)) {
		generated = name + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR + counter;
		if (parserContext.isNested()) {
			generated = generated.concat("#generated");
		}
		counter++;
	}

	return generated;
}
 
Example 17
Project: holon-jaxrs   File: JerseyResourcesPostProcessor.java   View source code 6 votes vote down vote up
@Override
public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException {
	LOGGER.debug(() -> "Lookup @Path and @Provider JAX-RS resource in bean factory [" + beanFactory + "]");

	resources = new ArrayList<>();

	for (String name : beanFactory.getBeanDefinitionNames()) {
		try {
			BeanDefinition definition = beanFactory.getBeanDefinition(name);
			if (!definition.isAbstract()) {
				Class<?> beanClass = BeanRegistryUtils.getBeanClass(name, definition, beanFactory, classLoader);
				if (beanClass != null) {
					if (isJaxrsResourceClass(definition, beanClass)) {
						resources.add(new WeakReference<>(beanClass));
						LOGGER.debug(() -> "Found JAX-RS resource class: [" + beanClass.getName() + "]");
					}
				}
			}
		} catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException e) {
			// ignore
		}
	}
}
 
Example 18
Project: lams   File: ScriptFactoryPostProcessor.java   View source code 6 votes vote down vote up
/**
 * Get the refresh check delay for the given {@link ScriptFactory} {@link BeanDefinition}.
 * If the {@link BeanDefinition} has a
 * {@link org.springframework.core.AttributeAccessor metadata attribute}
 * under the key {@link #REFRESH_CHECK_DELAY_ATTRIBUTE} which is a valid {@link Number}
 * type, then this value is used. Otherwise, the the {@link #defaultRefreshCheckDelay}
 * value is used.
 * @param beanDefinition the BeanDefinition to check
 * @return the refresh check delay
 */
protected long resolveRefreshCheckDelay(BeanDefinition beanDefinition) {
	long refreshCheckDelay = this.defaultRefreshCheckDelay;
	Object attributeValue = beanDefinition.getAttribute(REFRESH_CHECK_DELAY_ATTRIBUTE);
	if (attributeValue instanceof Number) {
		refreshCheckDelay = ((Number) attributeValue).longValue();
	}
	else if (attributeValue instanceof String) {
		refreshCheckDelay = Long.parseLong((String) attributeValue);
	}
	else if (attributeValue != null) {
		throw new BeanDefinitionStoreException("Invalid refresh check delay attribute [" +
				REFRESH_CHECK_DELAY_ATTRIBUTE + "] with value '" + attributeValue +
				"': needs to be of type Number or String");
	}
	return refreshCheckDelay;
}
 
Example 19
Project: gemini.blueprint   File: BeanDefinitionFactory.java   View source code 6 votes vote down vote up
BeanDefinition buildBeanDefinitionFor(ComponentMetadata metadata) {
	// shortcut (to avoid re-rewrapping)
	if (metadata instanceof SimpleComponentMetadata) {
		return ((SimpleComponentMetadata) metadata).getBeanDefinition();
	}

	AbstractBeanDefinition definition = buildBeanDefinition(metadata);
	// add common properties
	definition.setAttribute(MetadataConstants.COMPONENT_METADATA_ATTRIBUTE, metadata);
	definition.setAttribute(MetadataConstants.COMPONENT_NAME, metadata.getId());

	// Set<String> dependencies = metadata.;
	// definition.setDependsOn(dependencies.toArray(new String[dependencies.size()]));
	throw new UnsupportedOperationException("move depends on for BeanMetadata");

	// return definition;
}
 
Example 20
Project: lams   File: AnnotationDrivenCacheBeanDefinitionParser.java   View source code 5 votes vote down vote up
/**
 * Parses the '{@code <cache:annotation-driven>}' tag. Will
 * {@link AopNamespaceUtils#registerAutoProxyCreatorIfNecessary
 * register an AutoProxyCreator} with the container as necessary.
 */
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
	String mode = element.getAttribute("mode");
	if ("aspectj".equals(mode)) {
		// mode="aspectj"
		registerCacheAspect(element, parserContext);
	}
	else {
		// mode="proxy"
		AopAutoProxyConfigurer.configureAutoProxyCreator(element, parserContext);
	}

	return null;
}
 
Example 21
Project: jaffa-framework   File: JaffaRulesConfig.java   View source code 5 votes vote down vote up
/**
 * Configure the PrimaryKey Validator
 *
 * @return PrimaryKey Validator
 */
@Bean(name = "primary-key")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public PrimaryKeyValidator primaryKeyValidator() {
    PrimaryKeyValidator validator = new PrimaryKeyValidator();
    validator.setRuleEvaluator(ruleHelper());
    return validator;
}
 
Example 22
Project: configx   File: ConfigurationBeanFactoryMetaData.java   View source code 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    this.beanFactory = beanFactory;
    for (String name : beanFactory.getBeanDefinitionNames()) {
        BeanDefinition definition = beanFactory.getBeanDefinition(name);
        String method = definition.getFactoryMethodName();
        String bean = definition.getFactoryBeanName();
        if (method != null && bean != null) {
            this.beans.put(name, new MetaData(bean, method));
        }
    }
}
 
Example 23
Project: springmock   File: BeanDefinitionFinderTest.java   View source code 5 votes vote down vote up
@Test
public void should_find_bean_definition_by_name() {
	//given
	final String beanName = "object";
	final ApplicationContext appContext = buildAppContext(Stream.of(
			bean(beanName, new Object())));
	final BeanDefinitionFinder definitionFinder = new BeanDefinitionFinder(appContext, emptyDoubleRegistry());

	//when
	final Optional<BeanDefinition> definition = definitionFinder.tryToFindBeanDefinition(beanName);

	//then
	assertTrue(definition.isPresent());
}
 
Example 24
Project: lams   File: Jsr330ScopeMetadataResolver.java   View source code 5 votes vote down vote up
@Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
	ScopeMetadata metadata = new ScopeMetadata();
	metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
	if (definition instanceof AnnotatedBeanDefinition) {
		AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
		Set<String> annTypes = annDef.getMetadata().getAnnotationTypes();
		String found = null;
		for (String annType : annTypes) {
			Set<String> metaAnns = annDef.getMetadata().getMetaAnnotationTypes(annType);
			if (metaAnns.contains("javax.inject.Scope")) {
				if (found != null) {
					throw new IllegalStateException("Found ambiguous scope annotations on bean class [" +
							definition.getBeanClassName() + "]: " + found + ", " + annType);
				}
				found = annType;
				String scopeName = resolveScopeName(annType);
				if (scopeName == null) {
					throw new IllegalStateException(
							"Unsupported scope annotation - not mapped onto Spring scope name: " + annType);
				}
				metadata.setScopeName(scopeName);
			}
		}
	}
	return metadata;
}
 
Example 25
Project: common-dao   File: CrudTest.java   View source code 5 votes vote down vote up
private void printMetadata(BeanDefinition beanDef) {
    try {
        Class<?> cl = Class.forName(beanDef.getBeanClassName());
        Entity findable = cl.getAnnotation(Entity.class);
        System.out.printf("Found class: %s, with meta name: %s%n",
                cl.getSimpleName(), findable.name());
    } catch (Exception e) {
        System.err.println("Got exception: " + e.getMessage());
    }
}
 
Example 26
Project: alfresco-repository   File: ContextDependencyLister.java   View source code 5 votes vote down vote up
public void componentRegistered(
      ComponentDefinition paramComponentDefinition) {
   String name = paramComponentDefinition.getName();
   
   for(BeanDefinition bd : paramComponentDefinition.getBeanDefinitions()) {
      processBeanDefinition(name, bd);
   }
}
 
Example 27
Project: lams   File: SpringConfiguredBeanDefinitionParser.java   View source code 5 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
	if (!parserContext.getRegistry().containsBeanDefinition(BEAN_CONFIGURER_ASPECT_BEAN_NAME)) {
		RootBeanDefinition def = new RootBeanDefinition();
		def.setBeanClassName(BEAN_CONFIGURER_ASPECT_CLASS_NAME);
		def.setFactoryMethodName("aspectOf");
		def.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		def.setSource(parserContext.extractSource(element));
		parserContext.registerBeanComponent(new BeanComponentDefinition(def, BEAN_CONFIGURER_ASPECT_BEAN_NAME));
	}
	return null;
}
 
Example 28
Project: jaffa-framework   File: JaffaRulesConfig.java   View source code 5 votes vote down vote up
/**
 * Configure the Mandatory Validator
 *
 * @return Mandatory Validator
 */
@Bean(name = "mandatory")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public MandatoryValidator mandatoryValidator() {
    MandatoryValidator validator = new MandatoryValidator();
    validator.setRuleEvaluator(ruleHelper());
    return validator;
}
 
Example 29
Project: spring-data-generator   File: AbstractTemplateProvider.java   View source code 5 votes vote down vote up
private Tuple<Boolean, Integer> createFileFromTemplate(String path, String repositoryPAckage, String simpleClassName, String postfix, BeanDefinition beanDefinition){
    Tuple<String, Integer> content = getContentFromTemplate(repositoryPAckage, simpleClassName, postfix, beanDefinition);
    if (content.left() == null) {
        return new Tuple<>(false, content.right());
    }

    try (BufferedWriter bw = new BufferedWriter(new FileWriter(path))) {
        bw.write(content.left());
        return new Tuple<>(true, 0);
    } catch (IOException e) {
        return new Tuple<>(false, SDLogger.addError("Error occurred while persisting file: " + e.getMessage()));
    }
}
 
Example 30
Project: gemini.blueprint   File: ComponentMetadataFactory.java   View source code 5 votes vote down vote up
private static boolean checkBeanDefinitionClassCompatibility(BeanDefinition definition, Class<?> clazz) {
	if (definition instanceof AbstractBeanDefinition) {
		AbstractBeanDefinition abstractDefinition = (AbstractBeanDefinition) definition;
		if (abstractDefinition.hasBeanClass()) {
			Class<?> beanClass = abstractDefinition.getBeanClass();
			return clazz.isAssignableFrom(beanClass);
		}
	}
	return (clazz.getName().equals(definition.getBeanClassName()));
}
 
Example 31
Project: kalinka   File: ContextConfiguration.java   View source code 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Bean(destroyMethod = "stop")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public KafkaMessageConsumer kafkaMessageConsumer(final String topic) {

	return new KafkaMessageConsumer<>(this.kafkaConsumerConfig(), topic, this.senderProvider(), this.messagePublisherProvider());
}
 
Example 32
Project: jaffa-framework   File: PropertyPlaceholderConfig.java   View source code 5 votes vote down vote up
/**
 * Load the properties files used in application contexts here
 *
 * @return the initialized instance of the PropertyPlaceholderConfigurer class
 */
@Bean(name="properties")
@Scope(BeanDefinition.SCOPE_SINGLETON)
public PropertyPlaceholderConfigurer conversionService() {
    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    Resource resource1 = new ClassPathResource("application_file_1.properties");
    Resource resource2 = new ClassPathResource("application_file_2.properties");
    configurer.setLocations(resource1, resource2);
    return configurer;
}
 
Example 33
Project: bdf2   File: OverrideInternalBeanParser.java   View source code 5 votes vote down vote up
public BeanDefinition parse(Element element, ParserContext parserContext) {
	String nodeName=parserContext.getDelegate().getLocalName(element);
	String refBeanId=element.getAttribute("ref");
	RuntimeBeanReference runtimeBean=new RuntimeBeanReference(refBeanId);
	RootBeanDefinition beanDefinition=new RootBeanDefinition(OverrideInternalBeanFactoryBean.class);
	beanDefinition.getPropertyValues().addPropertyValue("referenceBean", runtimeBean);
	beanDefinition.getPropertyValues().addPropertyValue("targetBeanClass", classMap.get(nodeName));
	beanDefinition.getPropertyValues().addPropertyValue("referenceBeanId", refBeanId);
	String id=beanIdMap.get(nodeName);
	parserContext.registerBeanComponent(new BeanComponentDefinition(beanDefinition,id));
	return beanDefinition;
}
 
Example 34
Project: gemini.blueprint   File: SpringBlueprintContainer.java   View source code 5 votes vote down vote up
public ComponentMetadata getComponentMetadata(String name) throws NoSuchComponentException {
	if (getBeanFactory().containsBeanDefinition(name)) {
		BeanDefinition beanDefinition = getBeanFactory().getBeanDefinition(name);
		return MetadataFactory.buildComponentMetadataFor(name, beanDefinition);
	} else {
		throw new NoSuchComponentException(name);
	}
}
 
Example 35
Project: lams   File: AopNamespaceUtils.java   View source code 5 votes vote down vote up
public static void registerAspectJAnnotationAutoProxyCreatorIfNecessary(
		ParserContext parserContext, Element sourceElement) {

	BeanDefinition beanDefinition = AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(
			parserContext.getRegistry(), parserContext.extractSource(sourceElement));
	useClassProxyingIfNecessary(parserContext.getRegistry(), sourceElement);
	registerComponentIfNecessary(beanDefinition, parserContext);
}
 
Example 36
Project: spring-boot-autoconfigure   File: BeanTypeRegistry.java   View source code 5 votes vote down vote up
private Method getFactoryMethod(ConfigurableListableBeanFactory beanFactory,
                                BeanDefinition definition) throws Exception {
    if (definition instanceof AnnotatedBeanDefinition) {
        MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) definition).getFactoryMethodMetadata();
        if (factoryMethodMetadata instanceof StandardMethodMetadata) {
            return ((StandardMethodMetadata) factoryMethodMetadata).getIntrospectedMethod();
        }
    }
    BeanDefinition factoryDefinition = beanFactory.getBeanDefinition(definition.getFactoryBeanName());
    Class<?> factoryClass = ClassUtils.forName(factoryDefinition.getBeanClassName(), beanFactory.getBeanClassLoader());
    return getFactoryMethod(definition, factoryClass);
}
 
Example 37
Project: lams   File: BeanDefinitionParserDelegate.java   View source code 5 votes vote down vote up
/**
 * Parse a set element.
 */
public Set<Object> parseSetElement(Element collectionEle, BeanDefinition bd) {
	String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
	NodeList nl = collectionEle.getChildNodes();
	ManagedSet<Object> target = new ManagedSet<Object>(nl.getLength());
	target.setSource(extractSource(collectionEle));
	target.setElementTypeName(defaultElementType);
	target.setMergeEnabled(parseMergeAttribute(collectionEle));
	parseCollectionElements(nl, target, bd, defaultElementType);
	return target;
}
 
Example 38
Project: alfresco-data-model   File: NoAutoStartClassPathXmlApplicationContext.java   View source code 5 votes vote down vote up
@Override  
public void parsePropertyElement(Element ele, BeanDefinition bd) {
   String propertyName = ele.getAttribute("name");
   if("autoStart".equals(propertyName)) {
      if("abstractPropertyBackedBean".equals(bd.getParentName())) {
         String id = ele.getParentNode().getAttributes().getNamedItem("id").getTextContent();
         System.out.println("Preventing the autostart of Subsystem " + id);
         return;
      }
   }
   
   super.parsePropertyElement(ele, bd);
}
 
Example 39
Project: saluki   File: TestController.java   View source code 5 votes vote down vote up
private Collection<Object> getTypedBeansWithAnnotation(Class<? extends Annotation> annotationType)
    throws Exception {
  return Stream.of(applicationContext.getBeanNamesForAnnotation(annotationType)).filter(name -> {
    BeanDefinition beanDefinition = applicationContext.getBeanFactory().getBeanDefinition(name);
    if (beanDefinition.getSource() instanceof StandardMethodMetadata) {
      StandardMethodMetadata metadata = (StandardMethodMetadata) beanDefinition.getSource();
      return metadata.isAnnotated(annotationType.getName());
    }
    return null != applicationContext.getBeanFactory().findAnnotationOnBean(name, annotationType);
  }).map(name -> applicationContext.getBeanFactory().getBean(name)).collect(Collectors.toList());

}
 
Example 40
Project: gemini.blueprint   File: BogusHandler.java   View source code 5 votes vote down vote up
public BeanDefinition parse(Element element, ParserContext parserContext) {
	BeanDefinitionRegistry registry = parserContext.getRegistry();
	
	registry.registerBeanDefinition("nsDate", BeanDefinitionBuilder.genericBeanDefinition("java.util.Date").getBeanDefinition());
	registry.registerBeanDefinition("nsBean", BeanDefinitionBuilder.genericBeanDefinition("java.awt.Rectangle").getBeanDefinition());
	return null;
}