Java Code Examples for org.springframework.beans.factory.support.BeanDefinitionBuilder#setLazyInit()

The following examples show how to use org.springframework.beans.factory.support.BeanDefinitionBuilder#setLazyInit() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TaskTrackerAnnotationFactoryBean.java    From light-task-scheduler with Apache License 2.0 6 votes vote down vote up
/**
 * 将 JobRunner 生成Bean放入spring容器中管理
 * 采用原型 scope, 所以可以在JobRunner中使用@Autowired
 */
private void registerRunnerBeanDefinition() {
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)
            ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
    jobRunnerBeanName = "LTS_".concat(jobRunnerClass.getSimpleName());
    if (!beanFactory.containsBean(jobRunnerBeanName)) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(jobRunnerClass);
        if (jobRunnerClass == JobDispatcher.class) {
            builder.setScope(BeanDefinition.SCOPE_SINGLETON);
            builder.setLazyInit(false);
            builder.getBeanDefinition().getPropertyValues().addPropertyValue("shardField", shardField);
        } else {
            builder.setScope(BeanDefinition.SCOPE_PROTOTYPE);
        }
        beanFactory.registerBeanDefinition(jobRunnerBeanName, builder.getBeanDefinition());
    }
}
 
Example 2
Source File: SequenceGeneratorFactoryBean.java    From cloud-config with MIT License 6 votes vote down vote up
@Override
protected void buildResourceBeanDefinition(String resPath, String seqBeanId) throws Exception {
    if(getBeanFactory().containsBeanDefinition(seqBeanId)) {
        return;
    }

    if( isNestedRoutingNeeded(resPath) ) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(SequenceGeneratorFactoryBean.class);
        builder.addPropertyValue("path", resPath);
        builder.addPropertyValue("client", this.client);
        builder.addPropertyValue("resolver", ((NestedRoutingKeyResolver)this.resolver).next());
        builder.addPropertyValue("sequenceFormatter", sequenceFormatter);
        builder.setLazyInit(true);
        getBeanFactory().registerBeanDefinition(seqBeanId, builder.getBeanDefinition());
    } else {
        buildGeneratorBeanDefinition(resPath, seqBeanId, true);
    }
}
 
Example 3
Source File: AbstractJndiLocatingBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected void postProcess(BeanDefinitionBuilder definitionBuilder, Element element) {
	Object envValue = DomUtils.getChildElementValueByTagName(element, ENVIRONMENT);
	if (envValue != null) {
		// Specific environment settings defined, overriding any shared properties.
		definitionBuilder.addPropertyValue(JNDI_ENVIRONMENT, envValue);
	}
	else {
		// Check whether there is a reference to shared environment properties...
		String envRef = element.getAttribute(ENVIRONMENT_REF);
		if (StringUtils.hasLength(envRef)) {
			definitionBuilder.addPropertyValue(JNDI_ENVIRONMENT, new RuntimeBeanReference(envRef));
		}
	}

	String lazyInit = element.getAttribute(LAZY_INIT_ATTRIBUTE);
	if (StringUtils.hasText(lazyInit) && !DEFAULT_VALUE.equals(lazyInit)) {
		definitionBuilder.setLazyInit(TRUE_VALUE.equals(lazyInit));
	}
}
 
Example 4
Source File: AbstractRoutingResourceFactoryBean.java    From cloud-config with MIT License 6 votes vote down vote up
protected void buildResourceBeanDefinition(String dsPath, String dsBeanId) throws Exception {
    if(getBeanFactory().containsBeanDefinition(dsBeanId)) {
        return;
    }

    // build datasource bean based on config bean
    final BeanDefinitionBuilder dsBuilder;
    if( isNestedRoutingNeeded(dsPath) ) {
        dsBuilder = BeanDefinitionBuilder.rootBeanDefinition(getClass());
        dsBuilder.addPropertyValue("path", dsPath);
        dsBuilder.addPropertyValue("client", this.client);
        dsBuilder.addPropertyValue("fallbackResource", this.fallbackResource);
        dsBuilder.addPropertyValue("fallbackResourcePath", this.fallbackResourcePath);
        dsBuilder.addPropertyValue("resourceFactoryBeanClass", this.resourceFactoryBeanClass);
        dsBuilder.addPropertyValue("resolver", ((NestedRoutingKeyResolver)this.resolver).next());
    } else {
        dsBuilder = BeanDefinitionBuilder.rootBeanDefinition(resourceFactoryBeanClass);
        dsBuilder.addPropertyValue("configPath", dsPath);
    }
    dsBuilder.addPropertyValue("autoReload", isAutoReload());
    dsBuilder.addPropertyValue("validator", validator);
    dsBuilder.setLazyInit(true);
    getBeanFactory().registerBeanDefinition(dsBeanId, dsBuilder.getBeanDefinition());
    logger.info("Bean definition of resource '{}' is created as '{}'.", dsPath, dsBeanId);
}
 
Example 5
Source File: AbstractJndiLocatingBeanDefinitionParser.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void postProcess(BeanDefinitionBuilder definitionBuilder, Element element) {
	Object envValue = DomUtils.getChildElementValueByTagName(element, ENVIRONMENT);
	if (envValue != null) {
		// Specific environment settings defined, overriding any shared properties.
		definitionBuilder.addPropertyValue(JNDI_ENVIRONMENT, envValue);
	}
	else {
		// Check whether there is a reference to shared environment properties...
		String envRef = element.getAttribute(ENVIRONMENT_REF);
		if (StringUtils.hasLength(envRef)) {
			definitionBuilder.addPropertyValue(JNDI_ENVIRONMENT, new RuntimeBeanReference(envRef));
		}
	}

	String lazyInit = element.getAttribute(LAZY_INIT_ATTRIBUTE);
	if (StringUtils.hasText(lazyInit) && !DEFAULT_VALUE.equals(lazyInit)) {
		definitionBuilder.setLazyInit(TRUE_VALUE.equals(lazyInit));
	}
}
 
Example 6
Source File: KualiBeanDefinitionParserBase.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a {@link BeanDefinitionBuilder} instance for the
 * {@link #getBeanClass bean Class} and passes it to the
 * {@link #doParse} strategy method.
 * @param element the element that is to be parsed into a single BeanDefinition
 * @param parserContext the object encapsulating the current state of the parsing process
 * @return the BeanDefinition resulting from the parsing of the supplied {@link Element}
 * @throws IllegalStateException if the bean {@link Class} returned from
 * {@link #getBeanClass(org.w3c.dom.Element)} is <code>null</code>
 * @see #doParse
 */
@SuppressWarnings("unchecked")
protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
    BeanDefinitionBuilder builder = null;
    
    String parent = element.getAttribute("parent");
    String beanClass = element.getAttribute("class");
    if ( StringUtils.hasText(beanClass) ) {
        try {
            builder = BeanDefinitionBuilder.rootBeanDefinition(Class.forName(beanClass));
        } catch (Exception ex) {
            LOG.fatal( "Unable to resolve class given in class element of a " + element.getLocalName() + " element with id " + element.getAttribute("id"), ex );
            throw new RuntimeException(ex);
        }
    } else  if ( StringUtils.hasText(parent)) {
        builder = BeanDefinitionBuilder.childBeanDefinition(parent);
    } else if ( getBeanClass(element) != null ) {
        builder = BeanDefinitionBuilder.rootBeanDefinition(getBeanClass(element));
    } else {
        builder = BeanDefinitionBuilder.childBeanDefinition(getBaseBeanTypeParent(element)); 
    }
    builder.setSource(parserContext.extractSource(element));
    if (parserContext.isNested()) {
        // Inner bean definition must receive same singleton status as containing bean.
        builder.setSingleton(parserContext.getContainingBeanDefinition().isSingleton());
    }
    if (parserContext.isDefaultLazyInit()) {
        // Default-lazy-init applies to custom bean definitions as well.
        builder.setLazyInit(true);
    }
    doParse(element, parserContext, builder);
    return builder.getBeanDefinition();
}
 
Example 7
Source File: NativeQueryBeanDefinition.java    From spring-native-query with MIT License 5 votes vote down vote up
static AbstractBeanDefinition of(Class<? extends NativeQuery> classe, Object source) {
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(classe.getName());
    builder.getRawBeanDefinition().setSource(source);
    builder.setLazyInit(false);
    builder.setScope(BeanDefinition.SCOPE_SINGLETON);
    AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
    beanDefinition.setInstanceSupplier(() -> source);
    beanDefinition.setAttribute("factoryBeanObjectType", classe.getName());
    return beanDefinition;
}
 
Example 8
Source File: Parsers.java    From krpc with Apache License 2.0 5 votes vote down vote up
void registerReferer(String id, String interfaceName, ParserContext parserContext) {
    String beanName = generateBeanName(id, interfaceName);
    //log.info("register referer "+interfaceName+", beanName="+beanName);
    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(RefererFactory.class);
    beanDefinitionBuilder.addConstructorArgValue(beanName);
    beanDefinitionBuilder.addConstructorArgValue(interfaceName);
    beanDefinitionBuilder.addDependsOn("rpcApp");
    beanDefinitionBuilder.setLazyInit(true);
    parserContext.getRegistry().registerBeanDefinition(beanName, beanDefinitionBuilder.getRawBeanDefinition());

    registerAsyncReferer(beanName + "Async", interfaceName + "Async", parserContext);
}
 
Example 9
Source File: Parsers.java    From krpc with Apache License 2.0 5 votes vote down vote up
void registerAsyncReferer(String beanName, String interfaceName, ParserContext parserContext) {
    //log.info("register referer "+interfaceName+", beanName="+beanName);
    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(RefererFactory.class);
    beanDefinitionBuilder.addConstructorArgValue(beanName);
    beanDefinitionBuilder.addConstructorArgValue(interfaceName);
    beanDefinitionBuilder.addDependsOn("rpcApp");
    beanDefinitionBuilder.setLazyInit(true);
    parserContext.getRegistry().registerBeanDefinition(beanName, beanDefinitionBuilder.getRawBeanDefinition());
}
 
Example 10
Source File: AutoConfiguration.java    From krpc with Apache License 2.0 5 votes vote down vote up
void registerReferer(String id, String interfaceName, DefaultListableBeanFactory beanFactory) {
    String beanName = generateBeanName(id, interfaceName);
    //log.info("register referer "+interfaceName+", beanName="+beanName);
    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(RefererFactory.class);
    beanDefinitionBuilder.addConstructorArgValue(beanName);
    beanDefinitionBuilder.addConstructorArgValue(interfaceName);
    beanDefinitionBuilder.addDependsOn("rpcApp");
    beanDefinitionBuilder.setLazyInit(true);
    beanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getRawBeanDefinition());

    registerAsyncReferer(beanName + "Async", interfaceName + "Async", beanFactory);
}
 
Example 11
Source File: TaskTrackerAutoConfiguration.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
private void registerRunnerBeanDefinition() {
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)
            ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
    if (!beanFactory.containsBean(JOB_RUNNER_BEAN_NAME)) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(JobDispatcher.class);
        builder.setScope(BeanDefinition.SCOPE_SINGLETON);
        builder.setLazyInit(false);
        builder.getBeanDefinition().getPropertyValues().addPropertyValue("shardField", properties.getDispatchRunner().getShardValue());
        beanFactory.registerBeanDefinition(JOB_RUNNER_BEAN_NAME, builder.getBeanDefinition());
    }
}
 
Example 12
Source File: AbstractSingleBeanDefinitionParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a {@link BeanDefinitionBuilder} instance for the
 * {@link #getBeanClass bean Class} and passes it to the
 * {@link #doParse} strategy method.
 * @param element the element that is to be parsed into a single BeanDefinition
 * @param parserContext the object encapsulating the current state of the parsing process
 * @return the BeanDefinition resulting from the parsing of the supplied {@link Element}
 * @throws IllegalStateException if the bean {@link Class} returned from
 * {@link #getBeanClass(org.w3c.dom.Element)} is {@code null}
 * @see #doParse
 */
@Override
protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
	String parentName = getParentName(element);
	if (parentName != null) {
		builder.getRawBeanDefinition().setParentName(parentName);
	}
	Class<?> beanClass = getBeanClass(element);
	if (beanClass != null) {
		builder.getRawBeanDefinition().setBeanClass(beanClass);
	}
	else {
		String beanClassName = getBeanClassName(element);
		if (beanClassName != null) {
			builder.getRawBeanDefinition().setBeanClassName(beanClassName);
		}
	}
	builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
	if (parserContext.isNested()) {
		// Inner bean definition must receive same scope as containing bean.
		builder.setScope(parserContext.getContainingBeanDefinition().getScope());
	}
	if (parserContext.isDefaultLazyInit()) {
		// Default-lazy-init applies to custom bean definitions as well.
		builder.setLazyInit(true);
	}
	doParse(element, parserContext, builder);
	return builder.getBeanDefinition();
}
 
Example 13
Source File: ServerFactoryBeanDefinitionParser.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void doParse(Element element, ParserContext ctx, BeanDefinitionBuilder bean) {
    super.doParse(element, ctx, bean);

    bean.setInitMethodName("create");
    bean.setDestroyMethodName("destroy");

    // We don't really want to delay the registration of our Server
    bean.setLazyInit(false);
}
 
Example 14
Source File: AbstractSingleBeanDefinitionParser.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link BeanDefinitionBuilder} instance for the
 * {@link #getBeanClass bean Class} and passes it to the
 * {@link #doParse} strategy method.
 * @param element the element that is to be parsed into a single BeanDefinition
 * @param parserContext the object encapsulating the current state of the parsing process
 * @return the BeanDefinition resulting from the parsing of the supplied {@link Element}
 * @throws IllegalStateException if the bean {@link Class} returned from
 * {@link #getBeanClass(Element)} is {@code null}
 * @see #doParse
 */
@Override
protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
	String parentName = getParentName(element);
	if (parentName != null) {
		builder.getRawBeanDefinition().setParentName(parentName);
	}
	Class<?> beanClass = getBeanClass(element);
	if (beanClass != null) {
		builder.getRawBeanDefinition().setBeanClass(beanClass);
	}
	else {
		String beanClassName = getBeanClassName(element);
		if (beanClassName != null) {
			builder.getRawBeanDefinition().setBeanClassName(beanClassName);
		}
	}
	builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
	if (parserContext.isNested()) {
		// Inner bean definition must receive same scope as containing bean.
		builder.setScope(parserContext.getContainingBeanDefinition().getScope());
	}
	if (parserContext.isDefaultLazyInit()) {
		// Default-lazy-init applies to custom bean definitions as well.
		builder.setLazyInit(true);
	}
	doParse(element, parserContext, builder);
	return builder.getBeanDefinition();
}
 
Example 15
Source File: RedissonNamespaceParserSupport.java    From redisson with Apache License 2.0 5 votes vote down vote up
public BeanDefinitionBuilder createBeanDefinitionBuilder(Element element, ParserContext parserContext, Class<?> cls) {
    BeanDefinitionBuilder builder
            = BeanDefinitionBuilder.genericBeanDefinition();
    builder.getRawBeanDefinition().setBeanClass(cls);
    builder.getRawBeanDefinition()
            .setSource(parserContext.extractSource(element));
    if (parserContext.isNested()) {
        builder.setScope(parserContext.getContainingBeanDefinition()
                .getScope());
    }
    if (parserContext.isDefaultLazyInit()) {
        builder.setLazyInit(true);
    }
    return builder;
}
 
Example 16
Source File: BeanDefinitionParser.java    From hasor with Apache License 2.0 5 votes vote down vote up
@Override
protected AbstractBeanDefinition parse(Element element, NamedNodeMap attributes, ParserContext parserContext) {
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
    builder.getRawBeanDefinition().setBeanClass(TargetFactoryBean.class);
    //
    String factoryID = revertProperty(attributes, "hasorID");
    String refID = revertProperty(attributes, "refID");
    String refType = revertProperty(attributes, "refType");
    String refName = revertProperty(attributes, "refName");
    String lazy = revertProperty(attributes, "lazy");
    builder.setLazyInit((Boolean) ConverterUtils.convert(lazy, Boolean.TYPE));
    //
    if (StringUtils.isBlank(factoryID)) {
        factoryID = AppContext.class.getName();
    }
    if (StringUtils.isNotBlank(refID) || StringUtils.isNotBlank(refType)) {
        builder.addPropertyReference("factory", factoryID);
        builder.addPropertyValue("refID", refID);
        //
        builder.addPropertyValue("refName", refName);
        if (StringUtils.isNotBlank(refType)) {
            try {
                ClassLoader classLoader = parserContext.getReaderContext().getBeanClassLoader();
                Class<?> refTypeClass = ClassUtils.forName(refType, classLoader);
                builder.addPropertyValue("refType", refTypeClass);
            } catch (ClassNotFoundException ex) {
                parserContext.getReaderContext().error("Bean class [" + refType + "] not found", element, ex);
            }
        }
    } else {
        parserContext.getReaderContext().error("Bean class [" + refType + "] refID and refType ,both undefined.", element);
    }
    return builder.getBeanDefinition();
}
 
Example 17
Source File: ScheduledTasksBeanDefinitionParser.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
	builder.setLazyInit(false); // lazy scheduled tasks are a contradiction in terms -> force to false
	ManagedList<RuntimeBeanReference> cronTaskList = new ManagedList<>();
	ManagedList<RuntimeBeanReference> fixedDelayTaskList = new ManagedList<>();
	ManagedList<RuntimeBeanReference> fixedRateTaskList = new ManagedList<>();
	ManagedList<RuntimeBeanReference> triggerTaskList = new ManagedList<>();
	NodeList childNodes = element.getChildNodes();
	for (int i = 0; i < childNodes.getLength(); i++) {
		Node child = childNodes.item(i);
		if (!isScheduledElement(child, parserContext)) {
			continue;
		}
		Element taskElement = (Element) child;
		String ref = taskElement.getAttribute("ref");
		String method = taskElement.getAttribute("method");

		// Check that 'ref' and 'method' are specified
		if (!StringUtils.hasText(ref) || !StringUtils.hasText(method)) {
			parserContext.getReaderContext().error("Both 'ref' and 'method' are required", taskElement);
			// Continue with the possible next task element
			continue;
		}

		String cronAttribute = taskElement.getAttribute("cron");
		String fixedDelayAttribute = taskElement.getAttribute("fixed-delay");
		String fixedRateAttribute = taskElement.getAttribute("fixed-rate");
		String triggerAttribute = taskElement.getAttribute("trigger");
		String initialDelayAttribute = taskElement.getAttribute("initial-delay");

		boolean hasCronAttribute = StringUtils.hasText(cronAttribute);
		boolean hasFixedDelayAttribute = StringUtils.hasText(fixedDelayAttribute);
		boolean hasFixedRateAttribute = StringUtils.hasText(fixedRateAttribute);
		boolean hasTriggerAttribute = StringUtils.hasText(triggerAttribute);
		boolean hasInitialDelayAttribute = StringUtils.hasText(initialDelayAttribute);

		if (!(hasCronAttribute || hasFixedDelayAttribute || hasFixedRateAttribute || hasTriggerAttribute)) {
			parserContext.getReaderContext().error(
					"one of the 'cron', 'fixed-delay', 'fixed-rate', or 'trigger' attributes is required", taskElement);
			continue; // with the possible next task element
		}

		if (hasInitialDelayAttribute && (hasCronAttribute || hasTriggerAttribute)) {
			parserContext.getReaderContext().error(
					"the 'initial-delay' attribute may not be used with cron and trigger tasks", taskElement);
			continue; // with the possible next task element
		}

		String runnableName =
				runnableReference(ref, method, taskElement, parserContext).getBeanName();

		if (hasFixedDelayAttribute) {
			fixedDelayTaskList.add(intervalTaskReference(runnableName,
					initialDelayAttribute, fixedDelayAttribute, taskElement, parserContext));
		}
		if (hasFixedRateAttribute) {
			fixedRateTaskList.add(intervalTaskReference(runnableName,
					initialDelayAttribute, fixedRateAttribute, taskElement, parserContext));
		}
		if (hasCronAttribute) {
			cronTaskList.add(cronTaskReference(runnableName, cronAttribute,
					taskElement, parserContext));
		}
		if (hasTriggerAttribute) {
			String triggerName = new RuntimeBeanReference(triggerAttribute).getBeanName();
			triggerTaskList.add(triggerTaskReference(runnableName, triggerName,
					taskElement, parserContext));
		}
	}
	String schedulerRef = element.getAttribute("scheduler");
	if (StringUtils.hasText(schedulerRef)) {
		builder.addPropertyReference("taskScheduler", schedulerRef);
	}
	builder.addPropertyValue("cronTasksList", cronTaskList);
	builder.addPropertyValue("fixedDelayTasksList", fixedDelayTaskList);
	builder.addPropertyValue("fixedRateTasksList", fixedRateTaskList);
	builder.addPropertyValue("triggerTasksList", triggerTaskList);
}
 
Example 18
Source File: ScheduledTasksBeanDefinitionParser.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
	builder.setLazyInit(false); // lazy scheduled tasks are a contradiction in terms -> force to false
	ManagedList<RuntimeBeanReference> cronTaskList = new ManagedList<>();
	ManagedList<RuntimeBeanReference> fixedDelayTaskList = new ManagedList<>();
	ManagedList<RuntimeBeanReference> fixedRateTaskList = new ManagedList<>();
	ManagedList<RuntimeBeanReference> triggerTaskList = new ManagedList<>();
	NodeList childNodes = element.getChildNodes();
	for (int i = 0; i < childNodes.getLength(); i++) {
		Node child = childNodes.item(i);
		if (!isScheduledElement(child, parserContext)) {
			continue;
		}
		Element taskElement = (Element) child;
		String ref = taskElement.getAttribute("ref");
		String method = taskElement.getAttribute("method");

		// Check that 'ref' and 'method' are specified
		if (!StringUtils.hasText(ref) || !StringUtils.hasText(method)) {
			parserContext.getReaderContext().error("Both 'ref' and 'method' are required", taskElement);
			// Continue with the possible next task element
			continue;
		}

		String cronAttribute = taskElement.getAttribute("cron");
		String fixedDelayAttribute = taskElement.getAttribute("fixed-delay");
		String fixedRateAttribute = taskElement.getAttribute("fixed-rate");
		String triggerAttribute = taskElement.getAttribute("trigger");
		String initialDelayAttribute = taskElement.getAttribute("initial-delay");

		boolean hasCronAttribute = StringUtils.hasText(cronAttribute);
		boolean hasFixedDelayAttribute = StringUtils.hasText(fixedDelayAttribute);
		boolean hasFixedRateAttribute = StringUtils.hasText(fixedRateAttribute);
		boolean hasTriggerAttribute = StringUtils.hasText(triggerAttribute);
		boolean hasInitialDelayAttribute = StringUtils.hasText(initialDelayAttribute);

		if (!(hasCronAttribute || hasFixedDelayAttribute || hasFixedRateAttribute || hasTriggerAttribute)) {
			parserContext.getReaderContext().error(
					"one of the 'cron', 'fixed-delay', 'fixed-rate', or 'trigger' attributes is required", taskElement);
			continue; // with the possible next task element
		}

		if (hasInitialDelayAttribute && (hasCronAttribute || hasTriggerAttribute)) {
			parserContext.getReaderContext().error(
					"the 'initial-delay' attribute may not be used with cron and trigger tasks", taskElement);
			continue; // with the possible next task element
		}

		String runnableName =
				runnableReference(ref, method, taskElement, parserContext).getBeanName();

		if (hasFixedDelayAttribute) {
			fixedDelayTaskList.add(intervalTaskReference(runnableName,
					initialDelayAttribute, fixedDelayAttribute, taskElement, parserContext));
		}
		if (hasFixedRateAttribute) {
			fixedRateTaskList.add(intervalTaskReference(runnableName,
					initialDelayAttribute, fixedRateAttribute, taskElement, parserContext));
		}
		if (hasCronAttribute) {
			cronTaskList.add(cronTaskReference(runnableName, cronAttribute,
					taskElement, parserContext));
		}
		if (hasTriggerAttribute) {
			String triggerName = new RuntimeBeanReference(triggerAttribute).getBeanName();
			triggerTaskList.add(triggerTaskReference(runnableName, triggerName,
					taskElement, parserContext));
		}
	}
	String schedulerRef = element.getAttribute("scheduler");
	if (StringUtils.hasText(schedulerRef)) {
		builder.addPropertyReference("taskScheduler", schedulerRef);
	}
	builder.addPropertyValue("cronTasksList", cronTaskList);
	builder.addPropertyValue("fixedDelayTasksList", fixedDelayTaskList);
	builder.addPropertyValue("fixedRateTasksList", fixedRateTaskList);
	builder.addPropertyValue("triggerTasksList", triggerTaskList);
}
 
Example 19
Source File: ScheduledTasksBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
	builder.setLazyInit(false); // lazy scheduled tasks are a contradiction in terms -> force to false
	ManagedList<RuntimeBeanReference> cronTaskList = new ManagedList<RuntimeBeanReference>();
	ManagedList<RuntimeBeanReference> fixedDelayTaskList = new ManagedList<RuntimeBeanReference>();
	ManagedList<RuntimeBeanReference> fixedRateTaskList = new ManagedList<RuntimeBeanReference>();
	ManagedList<RuntimeBeanReference> triggerTaskList = new ManagedList<RuntimeBeanReference>();
	NodeList childNodes = element.getChildNodes();
	for (int i = 0; i < childNodes.getLength(); i++) {
		Node child = childNodes.item(i);
		if (!isScheduledElement(child, parserContext)) {
			continue;
		}
		Element taskElement = (Element) child;
		String ref = taskElement.getAttribute("ref");
		String method = taskElement.getAttribute("method");

		// Check that 'ref' and 'method' are specified
		if (!StringUtils.hasText(ref) || !StringUtils.hasText(method)) {
			parserContext.getReaderContext().error("Both 'ref' and 'method' are required", taskElement);
			// Continue with the possible next task element
			continue;
		}

		String cronAttribute = taskElement.getAttribute("cron");
		String fixedDelayAttribute = taskElement.getAttribute("fixed-delay");
		String fixedRateAttribute = taskElement.getAttribute("fixed-rate");
		String triggerAttribute = taskElement.getAttribute("trigger");
		String initialDelayAttribute = taskElement.getAttribute("initial-delay");

		boolean hasCronAttribute = StringUtils.hasText(cronAttribute);
		boolean hasFixedDelayAttribute = StringUtils.hasText(fixedDelayAttribute);
		boolean hasFixedRateAttribute = StringUtils.hasText(fixedRateAttribute);
		boolean hasTriggerAttribute = StringUtils.hasText(triggerAttribute);
		boolean hasInitialDelayAttribute = StringUtils.hasText(initialDelayAttribute);

		if (!(hasCronAttribute || hasFixedDelayAttribute || hasFixedRateAttribute || hasTriggerAttribute)) {
			parserContext.getReaderContext().error(
					"one of the 'cron', 'fixed-delay', 'fixed-rate', or 'trigger' attributes is required", taskElement);
			continue; // with the possible next task element
		}

		if (hasInitialDelayAttribute && (hasCronAttribute || hasTriggerAttribute)) {
			parserContext.getReaderContext().error(
					"the 'initial-delay' attribute may not be used with cron and trigger tasks", taskElement);
			continue; // with the possible next task element
		}

		String runnableName =
				runnableReference(ref, method, taskElement, parserContext).getBeanName();

		if (hasFixedDelayAttribute) {
			fixedDelayTaskList.add(intervalTaskReference(runnableName,
					initialDelayAttribute, fixedDelayAttribute, taskElement, parserContext));
		}
		if (hasFixedRateAttribute) {
			fixedRateTaskList.add(intervalTaskReference(runnableName,
					initialDelayAttribute, fixedRateAttribute, taskElement, parserContext));
		}
		if (hasCronAttribute) {
			cronTaskList.add(cronTaskReference(runnableName, cronAttribute,
					taskElement, parserContext));
		}
		if (hasTriggerAttribute) {
			String triggerName = new RuntimeBeanReference(triggerAttribute).getBeanName();
			triggerTaskList.add(triggerTaskReference(runnableName, triggerName,
					taskElement, parserContext));
		}
	}
	String schedulerRef = element.getAttribute("scheduler");
	if (StringUtils.hasText(schedulerRef)) {
		builder.addPropertyReference("taskScheduler", schedulerRef);
	}
	builder.addPropertyValue("cronTasksList", cronTaskList);
	builder.addPropertyValue("fixedDelayTasksList", fixedDelayTaskList);
	builder.addPropertyValue("fixedRateTasksList", fixedRateTaskList);
	builder.addPropertyValue("triggerTasksList", triggerTaskList);
}
 
Example 20
Source File: UndertowHTTPServerEngineBeanDefinitionParser.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void doParse(Element element, ParserContext ctx, BeanDefinitionBuilder bean) {

        String portStr = element.getAttribute("port");
        bean.addPropertyValue("port", portStr);

        String hostStr = element.getAttribute("host");
        if (hostStr != null && !"".equals(hostStr.trim())) {
            bean.addPropertyValue("host", hostStr);
        }

        String continuationsStr = element.getAttribute("continuationsEnabled");
        if (continuationsStr != null && continuationsStr.length() > 0) {
            bean.addPropertyValue("continuationsEnabled", continuationsStr);
        }

        String maxIdleTimeStr = element.getAttribute("maxIdleTime");
        if (maxIdleTimeStr != null && !"".equals(maxIdleTimeStr.trim())) {
            bean.addPropertyValue("maxIdleTime", maxIdleTimeStr);
        }


        ValueHolder busValue = ctx.getContainingBeanDefinition()
            .getConstructorArgumentValues().getArgumentValue(0, Bus.class);
        bean.addPropertyValue("bus", busValue.getValue());
        try {
            Element elem = DOMUtils.getFirstElement(element);
            while (elem != null) {
                String name = elem.getLocalName();
                if ("tlsServerParameters".equals(name)) {
                    mapTLSServerParameters(elem, bean);
                } else if ("threadingParameters".equals(name)) {
                    mapElementToJaxbPropertyFactory(elem,
                                                    bean,
                                                    "threadingParameters",
                                                    ThreadingParametersType.class,
                                                    UndertowHTTPServerEngineBeanDefinitionParser.class,
                                                    "createThreadingParameters");
                } else if ("tlsServerParametersRef".equals(name)) {
                    mapElementToJaxbPropertyFactory(elem,
                                                    bean,
                                                    "tlsServerParametersRef",
                                                    TLSServerParametersIdentifiedType.class,
                                                    UndertowHTTPServerEngineBeanDefinitionParser.class,
                                                    "createTLSServerParametersConfigRef");
                } else if ("threadingParametersRef".equals(name)) {
                    mapElementToJaxbPropertyFactory(elem,
                                                    bean,
                                                    "threadingParametersRef",
                                                    ThreadingParametersIdentifiedType.class,
                                                    UndertowHTTPServerEngineBeanDefinitionParser.class,
                                                    "createThreadingParametersRef"
                                                    );
                } else if ("handlers".equals(name)) {
                    List<?> handlers =
                        ctx.getDelegate().parseListElement(elem, bean.getBeanDefinition());
                    bean.addPropertyValue("handlers", handlers);
                }
                elem = org.apache.cxf.helpers.DOMUtils.getNextElement(elem);
            }
        } catch (Exception e) {
            throw new RuntimeException("Could not process configuration.", e);
        }

        bean.setLazyInit(false);
    }