proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/Entity.java
|
Entity
|
equals
|
class Entity implements Serializable {
private Long id;
private volatile Integer version;
/**
* Default constructor for {@link Entity}.
* <p>
* The ID defaults to zero.
*/
public Entity() {
super();
}
/**
* The constructor for the {@link Entity} where the ID is established.
* @param id The ID for the entity.
*/
public Entity(Long id) {
super();
// Commented out because StepExecutions are still created in a disconnected
// manner. The Repository should create them, then this can be uncommented.
// Assert.notNull(id, "Entity id must not be null.");
this.id = id;
}
/**
* @return The ID associated with the {@link Entity}.
*/
public Long getId() {
return id;
}
/**
* @param id The ID for the {@link Entity}.
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the version.
*/
public Integer getVersion() {
return version;
}
/**
* Public setter for the version. Needed only by repository methods.
* @param version The version to set.
*/
public void setVersion(Integer version) {
this.version = version;
}
/**
* Increment the version number.
*/
public void incrementVersion() {
if (version == null) {
version = 0;
}
else {
version = version + 1;
}
}
/**
* Creates a string representation of the {@code Entity}, including the {@code id},
* {@code version}, and class name.
*/
@Override
public String toString() {
return String.format("%s: id=%d, version=%d", ClassUtils.getShortName(getClass()), id, version);
}
/**
* Attempt to establish identity based on {@code id} if both exist. If either
* {@code id} does not exist, use {@code Object.equals()}.
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object other) {<FILL_FUNCTION_BODY>}
/**
* Use {@code id}, if it exists, to establish a hash code. Otherwise fall back to
* {@code Object.hashCode()}. It is based on the same information as {@code equals},
* so, if that changes, this will. Note that this follows the contract of
* {@code Object.hashCode()} but will cause problems for anyone adding an unsaved
* {@link Entity} to a {@code Set} because {@code Set.contains()} almost certainly
* returns false for the {@link Entity} after it is saved. Spring Batch does not store
* any of its entities in sets as a matter of course, so this is internally
* consistent. Clients should not be exposed to unsaved entities.
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
if (id == null) {
return super.hashCode();
}
return 39 + 87 * id.hashCode();
}
}
|
if (other == this) {
return true;
}
if (other == null) {
return false;
}
if (!(other instanceof Entity entity)) {
return false;
}
if (id == null || entity.getId() == null) {
return false;
}
return id.equals(entity.getId());
| 814
| 92
| 906
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/JobInstance.java
|
JobInstance
|
toString
|
class JobInstance extends Entity {
private final String jobName;
/**
* Constructor for {@link JobInstance}.
* @param id The instance ID.
* @param jobName The name associated with the {@link JobInstance}.
*/
public JobInstance(Long id, String jobName) {
super(id);
Assert.hasLength(jobName, "A jobName is required");
this.jobName = jobName;
}
/**
* @return the job name. (Equivalent to {@code getJob().getName()}).
*/
public String getJobName() {
return jobName;
}
/**
* Adds the job name to the string representation of the super class ({@link Entity}).
*/
@Override
public String toString() {<FILL_FUNCTION_BODY>}
/**
* @return The current instance ID.
*/
public long getInstanceId() {
return super.getId();
}
}
|
return super.toString() + ", Job=[" + jobName + "]";
| 240
| 22
| 262
|
<methods>public void <init>() ,public void <init>(java.lang.Long) ,public boolean equals(java.lang.Object) ,public java.lang.Long getId() ,public java.lang.Integer getVersion() ,public int hashCode() ,public void incrementVersion() ,public void setId(java.lang.Long) ,public void setVersion(java.lang.Integer) ,public java.lang.String toString() <variables>private java.lang.Long id,private volatile java.lang.Integer version
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/JobParameter.java
|
JobParameter
|
equals
|
class JobParameter<T> implements Serializable {
private final T value;
private final Class<T> type;
private final boolean identifying;
/**
* Create a new {@link JobParameter}.
* @param value the value of the parameter. Must not be {@code null}.
* @param type the type of the parameter. Must not be {@code null}.
* @param identifying true if the parameter is identifying. false otherwise.
*/
public JobParameter(@NonNull T value, @NonNull Class<T> type, boolean identifying) {
Assert.notNull(value, "value must not be null");
Assert.notNull(type, "type must not be null");
this.value = value;
this.type = type;
this.identifying = identifying;
}
/**
* Create a new identifying {@link JobParameter}.
* @param value the value of the parameter. Must not be {@code null}.
* @param type the type of the parameter. Must not be {@code null}.
*/
public JobParameter(@NonNull T value, @NonNull Class<T> type) {
this(value, type, true);
}
/**
* @return The identifying flag. It is set to {@code true} if the job parameter is
* identifying.
*/
public boolean isIdentifying() {
return identifying;
}
/**
* @return the value contained within this {@code JobParameter}.
*/
public T getValue() {
return value;
}
/**
* Return the type of the parameter.
* @return the type of the parameter
*/
public Class<T> getType() {
return type;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "{" + "value=" + value + ", type=" + type + ", identifying=" + identifying + '}';
}
@Override
public int hashCode() {
return 7 + 21 * value.hashCode();
}
}
|
if (!(obj instanceof JobParameter rhs)) {
return false;
}
if (this == obj) {
return true;
}
return type == rhs.type && value.equals(rhs.value);
| 502
| 62
| 564
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/SpringBatchVersion.java
|
SpringBatchVersion
|
getVersion
|
class SpringBatchVersion {
/**
* The key to use in the execution context for batch version.
*/
public static final String BATCH_VERSION_KEY = "batch.version";
private SpringBatchVersion() {
}
/**
* Return the full version string of the present Spring Batch codebase, or
* {@code "N/A"} if it cannot be determined.
* @see Package#getImplementationVersion()
*/
@Nullable
public static String getVersion() {<FILL_FUNCTION_BODY>}
}
|
Package pkg = SpringBatchVersion.class.getPackage();
if (pkg != null && pkg.getImplementationVersion() != null) {
return pkg.getImplementationVersion();
}
return "N/A";
| 132
| 63
| 195
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/StepContribution.java
|
StepContribution
|
toString
|
class StepContribution implements Serializable {
private volatile long readCount = 0;
private volatile long writeCount = 0;
private volatile long filterCount = 0;
private final long parentSkipCount;
private volatile long readSkipCount;
private volatile long writeSkipCount;
private volatile long processSkipCount;
private ExitStatus exitStatus = ExitStatus.EXECUTING;
private final StepExecution stepExecution;
/**
* @param execution {@link StepExecution} the stepExecution used to initialize
* {@code skipCount}.
*/
public StepContribution(StepExecution execution) {
this.stepExecution = execution;
this.parentSkipCount = execution.getSkipCount();
}
/**
* Set the {@link ExitStatus} for this contribution.
* @param status {@link ExitStatus} instance to be used to set the exit status.
*/
public void setExitStatus(ExitStatus status) {
this.exitStatus = status;
}
/**
* Public getter for the {@code ExitStatus}.
* @return the {@link ExitStatus} for this contribution
*/
public ExitStatus getExitStatus() {
return exitStatus;
}
/**
* Increment the counter for the number of items processed.
* @param count The {@code long} amount to increment by.
*/
public void incrementFilterCount(long count) {
filterCount += count;
}
/**
* Increment the counter for the number of items read.
*/
public void incrementReadCount() {
readCount++;
}
/**
* Increment the counter for the number of items written.
* @param count The {@code long} amount to increment by.
*/
public void incrementWriteCount(long count) {
writeCount += count;
}
/**
* Public access to the read counter.
* @return the read item counter.
*/
public long getReadCount() {
return readCount;
}
/**
* Public access to the write counter.
* @return the write item counter.
*/
public long getWriteCount() {
return writeCount;
}
/**
* Public getter for the filter counter.
* @return the filter counter.
*/
public long getFilterCount() {
return filterCount;
}
/**
* @return the sum of skips accumulated in the parent {@link StepExecution} and this
* <code>StepContribution</code>.
*/
public long getStepSkipCount() {
return readSkipCount + writeSkipCount + processSkipCount + parentSkipCount;
}
/**
* @return the number of skips collected in this <code>StepContribution</code> (not
* including skips accumulated in the parent {@link StepExecution}).
*/
public long getSkipCount() {
return readSkipCount + writeSkipCount + processSkipCount;
}
/**
* Increment the read skip count for this contribution.
*/
public void incrementReadSkipCount() {
readSkipCount++;
}
/**
* Increment the read skip count for this contribution.
* @param count The {@code long} amount to increment by.
*/
public void incrementReadSkipCount(long count) {
readSkipCount += count;
}
/**
* Increment the write skip count for this contribution.
*/
public void incrementWriteSkipCount() {
writeSkipCount++;
}
/**
*
*/
public void incrementProcessSkipCount() {
processSkipCount++;
}
/**
* Public getter for the read skip count.
* @return the read skip count.
*/
public long getReadSkipCount() {
return readSkipCount;
}
/**
* Public getter for the write skip count.
* @return the write skip count.
*/
public long getWriteSkipCount() {
return writeSkipCount;
}
/**
* Public getter for the process skip count.
* @return the process skip count.
*/
public long getProcessSkipCount() {
return processSkipCount;
}
/**
* Public getter for the parent step execution of this contribution.
* @return parent step execution of this contribution
*/
public StepExecution getStepExecution() {
return stepExecution;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof StepContribution other)) {
return false;
}
return toString().equals(other.toString());
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return 11 + toString().hashCode() * 43;
}
}
|
return "[StepContribution: read=" + readCount + ", written=" + writeCount + ", filtered=" + filterCount
+ ", readSkips=" + readSkipCount + ", writeSkips=" + writeSkipCount + ", processSkips="
+ processSkipCount + ", exitStatus=" + exitStatus.getExitCode() + "]";
| 1,206
| 88
| 1,294
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/aot/CoreRuntimeHints.java
|
CoreRuntimeHints
|
registerHints
|
class CoreRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {<FILL_FUNCTION_BODY>}
}
|
Set<String> jdkTypes = Set.of("java.time.Ser", "java.util.Collections$SynchronizedSet",
"java.util.Collections$SynchronizedCollection", "java.util.concurrent.locks.ReentrantLock$Sync",
"java.util.concurrent.locks.ReentrantLock$FairSync",
"java.util.concurrent.locks.ReentrantLock$NonfairSync",
"java.util.concurrent.ConcurrentHashMap$Segment");
// resource hints
hints.resources().registerPattern("org/springframework/batch/core/schema-h2.sql");
hints.resources().registerPattern("org/springframework/batch/core/schema-derby.sql");
hints.resources().registerPattern("org/springframework/batch/core/schema-hsqldb.sql");
hints.resources().registerPattern("org/springframework/batch/core/schema-sqlite.sql");
hints.resources().registerPattern("org/springframework/batch/core/schema-db2.sql");
hints.resources().registerPattern("org/springframework/batch/core/schema-hana.sql");
hints.resources().registerPattern("org/springframework/batch/core/schema-mysql.sql");
hints.resources().registerPattern("org/springframework/batch/core/schema-mariadb.sql");
hints.resources().registerPattern("org/springframework/batch/core/schema-oracle.sql");
hints.resources().registerPattern("org/springframework/batch/core/schema-postgresql.sql");
hints.resources().registerPattern("org/springframework/batch/core/schema-sqlserver.sql");
hints.resources().registerPattern("org/springframework/batch/core/schema-sybase.sql");
// proxy hints
hints.proxies()
.registerJdkProxy(builder -> builder
.proxiedInterfaces(TypeReference.of("org.springframework.batch.core.repository.JobRepository"))
.proxiedInterfaces(SpringProxy.class, Advised.class, DecoratingProxy.class))
.registerJdkProxy(builder -> builder
.proxiedInterfaces(TypeReference.of("org.springframework.batch.core.explore.JobExplorer"))
.proxiedInterfaces(SpringProxy.class, Advised.class, DecoratingProxy.class))
.registerJdkProxy(builder -> builder
.proxiedInterfaces(TypeReference.of("org.springframework.batch.core.launch.JobOperator"))
.proxiedInterfaces(SpringProxy.class, Advised.class, DecoratingProxy.class));
// reflection hints
hints.reflection().registerType(Types.class, MemberCategory.DECLARED_FIELDS);
hints.reflection().registerType(JobContext.class, MemberCategory.INVOKE_PUBLIC_METHODS);
hints.reflection().registerType(StepContext.class, MemberCategory.INVOKE_PUBLIC_METHODS);
hints.reflection().registerType(JobParameter.class, MemberCategory.values());
hints.reflection().registerType(JobParameters.class, MemberCategory.values());
hints.reflection().registerType(ExitStatus.class, MemberCategory.values());
hints.reflection().registerType(JobInstance.class, MemberCategory.values());
hints.reflection().registerType(JobExecution.class, MemberCategory.values());
hints.reflection().registerType(StepExecution.class, MemberCategory.values());
hints.reflection().registerType(StepContribution.class, MemberCategory.values());
hints.reflection().registerType(Entity.class, MemberCategory.values());
hints.reflection().registerType(ExecutionContext.class, MemberCategory.values());
hints.reflection().registerType(Chunk.class, MemberCategory.values());
jdkTypes.stream()
.map(TypeReference::of)
.forEach(type -> hints.reflection().registerType(type, MemberCategory.values()));
// serialization hints
SerializationHints serializationHints = hints.serialization();
Stream.of(LinkedHashSet.class, LinkedHashMap.class, HashSet.class, ReentrantLock.class, ConcurrentHashMap.class,
AbstractOwnableSynchronizer.class, AbstractQueuedSynchronizer.class, Number.class, Byte.class,
Short.class, Integer.class, Long.class, Double.class, Float.class, Character.class, String.class,
Boolean.class, Date.class, Calendar.class, LocalDate.class, LocalTime.class, LocalDateTime.class,
OffsetTime.class, OffsetDateTime.class, ZonedDateTime.class, Instant.class, Duration.class,
Period.class, HashMap.class, Hashtable.class, ArrayList.class, JobParameter.class, JobParameters.class,
ExitStatus.class, JobInstance.class, JobExecution.class, StepExecution.class, StepContribution.class,
Entity.class, ExecutionContext.class, Chunk.class, Properties.class, Exception.class, UUID.class)
.forEach(serializationHints::registerType);
jdkTypes.stream().map(TypeReference::of).forEach(serializationHints::registerType);
| 51
| 1,330
| 1,381
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/AutomaticJobRegistrarBeanPostProcessor.java
|
AutomaticJobRegistrarBeanPostProcessor
|
postProcessAfterInitialization
|
class AutomaticJobRegistrarBeanPostProcessor implements BeanFactoryPostProcessor, BeanPostProcessor {
private ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>}
}
|
if (bean instanceof AutomaticJobRegistrar automaticJobRegistrar) {
automaticJobRegistrar.setJobLoader(new DefaultJobLoader(this.beanFactory.getBean(JobRegistry.class)));
for (ApplicationContextFactory factory : this.beanFactory.getBeansOfType(ApplicationContextFactory.class)
.values()) {
automaticJobRegistrar.addApplicationContextFactory(factory);
}
return automaticJobRegistrar;
}
return bean;
| 113
| 123
| 236
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/BatchObservabilityBeanPostProcessor.java
|
BatchObservabilityBeanPostProcessor
|
postProcessAfterInitialization
|
class BatchObservabilityBeanPostProcessor implements BeanFactoryPostProcessor, BeanPostProcessor {
private static final Log LOGGER = LogFactory.getLog(BatchObservabilityBeanPostProcessor.class);
private ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>}
}
|
try {
if (bean instanceof AbstractJob || bean instanceof AbstractStep) {
ObservationRegistry observationRegistry = this.beanFactory.getBean(ObservationRegistry.class);
if (bean instanceof AbstractJob) {
((AbstractJob) bean).setObservationRegistry(observationRegistry);
}
if (bean instanceof AbstractStep) {
((AbstractStep) bean).setObservationRegistry(observationRegistry);
}
}
}
catch (NoSuchBeanDefinitionException e) {
LOGGER.info("No Micrometer observation registry found, defaulting to ObservationRegistry.NOOP");
}
return bean;
| 135
| 162
| 297
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrar.java
|
AutomaticJobRegistrar
|
start
|
class AutomaticJobRegistrar implements Ordered, SmartLifecycle, ApplicationContextAware, InitializingBean {
private final Collection<ApplicationContextFactory> applicationContextFactories = new ArrayList<>();
private JobLoader jobLoader;
private ApplicationContext applicationContext;
private volatile boolean running = false;
private int phase = Integer.MIN_VALUE + 1000;
private boolean autoStartup = true;
private final Object lifecycleMonitor = new Object();
private int order = Ordered.LOWEST_PRECEDENCE;
/**
* The enclosing application context, which you can use to check whether
* {@link ApplicationContextEvent events} come from the expected source.
* @param applicationContext the enclosing application context, if there is one
* @see ApplicationContextAware#setApplicationContext(ApplicationContext)
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* Add a single {@link ApplicationContextFactory} to the set that is used to load
* contexts and jobs.
* @param applicationContextFactory the {@link ApplicationContextFactory} values to
* use
*/
public void addApplicationContextFactory(ApplicationContextFactory applicationContextFactory) {
if (applicationContextFactory instanceof ApplicationContextAware) {
((ApplicationContextAware) applicationContextFactory).setApplicationContext(applicationContext);
}
this.applicationContextFactories.add(applicationContextFactory);
}
/**
* Add an array of {@link ApplicationContextFactory} instances to the set that is used
* to load contexts and jobs.
* @param applicationContextFactories the {@link ApplicationContextFactory} values to
* use
*/
public void setApplicationContextFactories(ApplicationContextFactory[] applicationContextFactories) {
this.applicationContextFactories.addAll(Arrays.asList(applicationContextFactories));
}
/**
* The job loader that is used to load and manage jobs.
* @param jobLoader the {@link JobLoader} to set
*/
public void setJobLoader(JobLoader jobLoader) {
this.jobLoader = jobLoader;
}
@Override
public int getOrder() {
return order;
}
/**
* The order in which to start up and shutdown.
* @param order the order (default {@link Ordered#LOWEST_PRECEDENCE}).
* @see Ordered
*/
public void setOrder(int order) {
this.order = order;
}
/**
*/
@Override
public void afterPropertiesSet() {
Assert.state(jobLoader != null, "A JobLoader must be provided");
}
/**
* Delegates to {@link JobLoader#clear()}.
*
* @see Lifecycle#stop()
*/
@Override
public void stop() {
synchronized (this.lifecycleMonitor) {
jobLoader.clear();
running = false;
}
}
/**
* Take all the contexts from the factories provided and pass them to the
* {@link JobLoader}.
*
* @see Lifecycle#start()
*/
@Override
public void start() {<FILL_FUNCTION_BODY>}
/**
* Check whether this component has been started.
* @return {@code true} if started successfully and not stopped.
* @see Lifecycle#isRunning()
*/
@Override
public boolean isRunning() {
synchronized (this.lifecycleMonitor) {
return running;
}
}
@Override
public boolean isAutoStartup() {
return autoStartup;
}
/**
* @param autoStartup {@code true} for auto start.
* @see #isAutoStartup()
*/
public void setAutoStartup(boolean autoStartup) {
this.autoStartup = autoStartup;
}
@Override
public int getPhase() {
return phase;
}
/**
* @param phase the phase.
* @see #getPhase()
*/
public void setPhase(int phase) {
this.phase = phase;
}
@Override
public void stop(Runnable callback) {
stop();
callback.run();
}
}
|
synchronized (this.lifecycleMonitor) {
if (running) {
return;
}
for (ApplicationContextFactory factory : applicationContextFactories) {
try {
jobLoader.load(factory);
}
catch (DuplicateJobException e) {
throw new IllegalStateException(e);
}
}
running = true;
}
| 1,055
| 104
| 1,159
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/ClasspathXmlApplicationContextsFactoryBean.java
|
ClasspathXmlApplicationContextsFactoryBean
|
getObject
|
class ClasspathXmlApplicationContextsFactoryBean
implements FactoryBean<ApplicationContextFactory[]>, ApplicationContextAware {
private List<Resource> resources = new ArrayList<>();
private boolean copyConfiguration = true;
private Class<? extends BeanFactoryPostProcessor>[] beanFactoryPostProcessorClasses;
private Class<?>[] beanPostProcessorExcludeClasses;
private ApplicationContext applicationContext;
/**
* A set of resources to load by using a {@link GenericApplicationContextFactory}.
* Each resource should be a Spring configuration file that is loaded into an
* application context whose parent is the current context. In a configuration file,
* the resources can be given as a pattern (for example,
* <code>classpath*:/config/*-context.xml</code>).
* @param resources array of resources to use
*/
public void setResources(Resource[] resources) {
this.resources = Arrays.asList(resources);
}
/**
* Flag to indicate that configuration, such as bean post processors and custom
* editors, should be copied from the parent context. Defaults to {@code true}.
* @param copyConfiguration the flag value to set
*/
public void setCopyConfiguration(boolean copyConfiguration) {
this.copyConfiguration = copyConfiguration;
}
/**
* Determines which bean factory post processors (such as property placeholders)
* should be copied from the parent context. Defaults to
* {@link PropertySourcesPlaceholderConfigurer} and {@link CustomEditorConfigurer}.
* @param beanFactoryPostProcessorClasses post processor types to be copied
*/
public void setBeanFactoryPostProcessorClasses(
Class<? extends BeanFactoryPostProcessor>[] beanFactoryPostProcessorClasses) {
this.beanFactoryPostProcessorClasses = beanFactoryPostProcessorClasses;
}
/**
* Determines, by exclusion, which bean post processors should be copied from the
* parent context. Defaults to {@link BeanFactoryAware} (so any post processors that
* have a reference to the parent bean factory are not copied into the child). Note
* that these classes do not themselves have to be {@link BeanPostProcessor}
* implementations or sub-interfaces.
* @param beanPostProcessorExcludeClasses the classes to set
*/
public void setBeanPostProcessorExcludeClasses(Class<?>[] beanPostProcessorExcludeClasses) {
this.beanPostProcessorExcludeClasses = beanPostProcessorExcludeClasses;
}
/**
* Create an {@link ApplicationContextFactory} from each resource provided in
* {@link #setResources(Resource[])}.
* @return an array of {@link ApplicationContextFactory}
* @see org.springframework.beans.factory.FactoryBean#getObject()
*/
@Override
public ApplicationContextFactory[] getObject() throws Exception {<FILL_FUNCTION_BODY>}
/**
* The type of object returned by this factory as an array of
* {@link ApplicationContextFactory}.
* @return array of {@link ApplicationContextFactory}
* @see FactoryBean#getObjectType()
*/
@Override
public Class<?> getObjectType() {
return ApplicationContextFactory[].class;
}
/**
* Optimization hint for bean factory.
* @return {@code true}
* @see FactoryBean#isSingleton()
*/
@Override
public boolean isSingleton() {
return true;
}
/**
* An application context that can be used as a parent context for all the factories.
* @param applicationContext the {@link ApplicationContext} to set
* @see ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
|
if (resources == null) {
return new ApplicationContextFactory[0];
}
List<ApplicationContextFactory> applicationContextFactories = new ArrayList<>();
for (Resource resource : resources) {
GenericApplicationContextFactory factory = new GenericApplicationContextFactory(resource);
factory.setCopyConfiguration(copyConfiguration);
if (beanFactoryPostProcessorClasses != null) {
factory.setBeanFactoryPostProcessorClasses(beanFactoryPostProcessorClasses);
}
if (beanPostProcessorExcludeClasses != null) {
factory.setBeanPostProcessorExcludeClasses(beanPostProcessorExcludeClasses);
}
factory.setApplicationContext(applicationContext);
applicationContextFactories.add(factory);
}
return applicationContextFactories.toArray(new ApplicationContextFactory[applicationContextFactories.size()]);
| 917
| 209
| 1,126
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/GenericApplicationContextFactory.java
|
GenericApplicationContextFactory
|
createApplicationContext
|
class GenericApplicationContextFactory extends AbstractApplicationContextFactory {
/**
* Create an application context factory for the specified resource. The resource can
* be an actual {@link Resource} (in which case, it is interpreted as an XML file), or
* it can be a @Configuration class or a package name. All types must be the same
* (mixing XML with a Java package, for example, is not allowed and results in an
* {@link java.lang.IllegalArgumentException}).
* @param resources some resources (XML configuration files, @Configuration
* classes, or Java packages to scan)
*/
public GenericApplicationContextFactory(Object... resources) {
super(resources);
}
/**
* @see AbstractApplicationContextFactory#createApplicationContext(ConfigurableApplicationContext,
* Object...)
*/
@Override
protected ConfigurableApplicationContext createApplicationContext(ConfigurableApplicationContext parent,
Object... resources) {<FILL_FUNCTION_BODY>}
private boolean allObjectsOfType(Object[] objects, Class<?> type) {
for (Object object : objects) {
if (!type.isInstance(object)) {
return false;
}
}
return true;
}
private abstract class ApplicationContextHelper {
private final DefaultListableBeanFactory parentBeanFactory;
private final ConfigurableApplicationContext parent;
public ApplicationContextHelper(ConfigurableApplicationContext parent, GenericApplicationContext context,
Object... config) {
this.parent = parent;
if (parent != null) {
Assert.isTrue(parent.getBeanFactory() instanceof DefaultListableBeanFactory,
"The parent application context must have a bean factory of type DefaultListableBeanFactory");
parentBeanFactory = (DefaultListableBeanFactory) parent.getBeanFactory();
}
else {
parentBeanFactory = null;
}
context.setParent(parent);
context.setId(generateId(config));
loadConfiguration(config);
prepareContext(parent, context);
}
protected abstract String generateId(Object... configs);
protected abstract void loadConfiguration(Object... configs);
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
if (parentBeanFactory != null) {
GenericApplicationContextFactory.this.prepareBeanFactory(parentBeanFactory, beanFactory);
for (Class<? extends BeanFactoryPostProcessor> cls : getBeanFactoryPostProcessorClasses()) {
for (String name : parent.getBeanNamesForType(cls)) {
beanFactory.registerSingleton(name, (parent.getBean(name)));
}
}
}
}
}
private final class ResourceXmlApplicationContext extends GenericXmlApplicationContext {
private final ApplicationContextHelper helper;
public ResourceXmlApplicationContext(ConfigurableApplicationContext parent, Object... resources) {
class ResourceXmlApplicationContextHelper extends ApplicationContextHelper {
ResourceXmlApplicationContextHelper(ConfigurableApplicationContext parent,
GenericApplicationContext context, Object... config) {
super(parent, context, config);
}
@Override
protected String generateId(Object... configs) {
Resource[] resources = Arrays.copyOfRange(configs, 0, configs.length, Resource[].class);
try {
List<String> uris = new ArrayList<>();
for (Resource resource : resources) {
uris.add(resource.getURI().toString());
}
return StringUtils.collectionToCommaDelimitedString(uris);
}
catch (IOException e) {
return Arrays.toString(resources);
}
}
@Override
protected void loadConfiguration(Object... configs) {
Resource[] resources = Arrays.copyOfRange(configs, 0, configs.length, Resource[].class);
load(resources);
}
}
helper = new ResourceXmlApplicationContextHelper(parent, this, resources);
refresh();
}
@Override
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.prepareBeanFactory(beanFactory);
helper.prepareBeanFactory(beanFactory);
}
@Override
public String toString() {
return "ResourceXmlApplicationContext:" + getId();
}
}
private final class ResourceAnnotationApplicationContext extends AnnotationConfigApplicationContext {
private final ApplicationContextHelper helper;
public ResourceAnnotationApplicationContext(ConfigurableApplicationContext parent, Object... resources) {
class ResourceAnnotationApplicationContextHelper extends ApplicationContextHelper {
public ResourceAnnotationApplicationContextHelper(ConfigurableApplicationContext parent,
GenericApplicationContext context, Object... config) {
super(parent, context, config);
}
@Override
protected String generateId(Object... configs) {
if (allObjectsOfType(configs, Class.class)) {
Class<?>[] types = Arrays.copyOfRange(configs, 0, configs.length, Class[].class);
List<String> names = new ArrayList<>();
for (Class<?> type : types) {
names.add(type.getName());
}
return StringUtils.collectionToCommaDelimitedString(names);
}
else {
return Arrays.toString(configs);
}
}
@Override
protected void loadConfiguration(Object... configs) {
if (allObjectsOfType(configs, Class.class)) {
Class<?>[] types = Arrays.copyOfRange(configs, 0, configs.length, Class[].class);
register(types);
}
else {
String[] pkgs = Arrays.copyOfRange(configs, 0, configs.length, String[].class);
scan(pkgs);
}
}
}
helper = new ResourceAnnotationApplicationContextHelper(parent, this, resources);
refresh();
}
@Override
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.prepareBeanFactory(beanFactory);
helper.prepareBeanFactory(beanFactory);
}
@Override
public String toString() {
return "ResourceAnnotationApplicationContext:" + getId();
}
}
}
|
ConfigurableApplicationContext context;
if (allObjectsOfType(resources, Resource.class)) {
context = new ResourceXmlApplicationContext(parent, resources);
}
else if (allObjectsOfType(resources, Class.class)) {
context = new ResourceAnnotationApplicationContext(parent, resources);
}
else if (allObjectsOfType(resources, String.class)) {
context = new ResourceAnnotationApplicationContext(parent, resources);
}
else {
List<Class<?>> types = new ArrayList<>();
for (Object resource : resources) {
types.add(resource.getClass());
}
throw new IllegalArgumentException(
"No application context could be created for resource types: " + Arrays.toString(types.toArray()));
}
return context;
| 1,585
| 203
| 1,788
|
<methods>public transient void <init>(java.lang.Object[]) ,public org.springframework.context.ConfigurableApplicationContext createApplicationContext() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public void setApplicationContext(org.springframework.context.ApplicationContext) throws org.springframework.beans.BeansException,public void setBeanFactoryPostProcessorClasses(Class<? extends org.springframework.beans.factory.config.BeanFactoryPostProcessor>[]) ,public void setBeanPostProcessorExcludeClasses(Class<?>[]) ,public void setCopyConfiguration(boolean) ,public java.lang.String toString() <variables>private Collection<Class<? extends org.springframework.beans.factory.config.BeanFactoryPostProcessor>> beanFactoryPostProcessorClasses,private Collection<Class<?>> beanPostProcessorExcludeClasses,private boolean copyConfiguration,private static final org.apache.commons.logging.Log logger,private org.springframework.context.ConfigurableApplicationContext parent,private final non-sealed java.lang.Object[] resources
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/GroupAwareJob.java
|
GroupAwareJob
|
equals
|
class GroupAwareJob implements Job {
/**
* The separator between group and delegate job names in the final name given to this
* job.
*/
private static final String SEPARATOR = ".";
private final Job delegate;
private final String groupName;
/**
* Create a new {@link Job} with the delegate and no group name.
* @param delegate a delegate for the features of a regular Job
*/
public GroupAwareJob(Job delegate) {
this(null, delegate);
}
/**
* Create a new {@link Job} with the given group name and delegate.
* @param groupName the group name to prepend (can be {@code null})
* @param delegate a delegate for the features of a regular Job
*/
public GroupAwareJob(@Nullable String groupName, Job delegate) {
super();
this.groupName = groupName;
this.delegate = delegate;
}
@Override
public void execute(JobExecution execution) {
delegate.execute(execution);
}
/**
* Concatenates the group name and the delegate job name (joining with a ".").
*
* @see org.springframework.batch.core.Job#getName()
*/
@Override
public String getName() {
return groupName == null ? delegate.getName() : groupName + SEPARATOR + delegate.getName();
}
@Override
public boolean isRestartable() {
return delegate.isRestartable();
}
@Override
@Nullable
public JobParametersIncrementer getJobParametersIncrementer() {
return delegate.getJobParametersIncrementer();
}
@Override
public JobParametersValidator getJobParametersValidator() {
return delegate.getJobParametersValidator();
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public String toString() {
return ClassUtils.getShortName(delegate.getClass()) + ": [name=" + getName() + "]";
}
}
|
if (obj instanceof GroupAwareJob) {
return ((GroupAwareJob) obj).delegate.equals(delegate);
}
return false;
| 525
| 44
| 569
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/JobFactoryRegistrationListener.java
|
JobFactoryRegistrationListener
|
unbind
|
class JobFactoryRegistrationListener {
private final Log logger = LogFactory.getLog(getClass());
private JobRegistry jobRegistry;
/**
* Public setter for a {@link JobRegistry} to use for all the bind and unbind events.
* @param jobRegistry {@link JobRegistry}
*/
public void setJobRegistry(JobRegistry jobRegistry) {
this.jobRegistry = jobRegistry;
}
/**
* Take the {@link JobFactory} provided and register it with the {@link JobRegistry}.
* @param jobFactory a {@link JobFactory}
* @param params not needed by this listener.
* @throws Exception if there is a problem
*/
public void bind(JobFactory jobFactory, Map<String, ?> params) throws Exception {
if (logger.isInfoEnabled()) {
logger.info("Binding JobFactory: " + jobFactory.getJobName());
}
jobRegistry.register(jobFactory);
}
/**
* Take the provided {@link JobFactory} and unregister it with the
* {@link JobRegistry}.
* @param jobFactory a {@link JobFactory}
* @param params not needed by this listener.
* @throws Exception if there is a problem
*/
public void unbind(JobFactory jobFactory, Map<String, ?> params) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (logger.isInfoEnabled()) {
logger.info("Unbinding JobFactory: " + jobFactory.getJobName());
}
jobRegistry.unregister(jobFactory.getJobName());
| 334
| 54
| 388
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/JobRegistryBeanPostProcessor.java
|
JobRegistryBeanPostProcessor
|
destroy
|
class JobRegistryBeanPostProcessor
implements BeanPostProcessor, BeanFactoryAware, InitializingBean, DisposableBean {
private static final Log logger = LogFactory.getLog(JobRegistryBeanPostProcessor.class);
// It doesn't make sense for this to have a default value...
private JobRegistry jobRegistry = null;
private final Collection<String> jobNames = new HashSet<>();
private String groupName = null;
private DefaultListableBeanFactory beanFactory;
/**
* The group name for jobs registered by this component. Optional (defaults to null,
* which means that jobs are registered with their bean names). Useful where there is
* a hierarchy of application contexts all contributing to the same
* {@link JobRegistry}: child contexts can then define an instance with a unique group
* name to avoid clashes between job names.
* @param groupName the groupName to set
*/
public void setGroupName(String groupName) {
this.groupName = groupName;
}
/**
* Injection setter for {@link JobRegistry}.
* @param jobRegistry the jobConfigurationRegistry to set
*/
public void setJobRegistry(JobRegistry jobRegistry) {
this.jobRegistry = jobRegistry;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
if (beanFactory instanceof DefaultListableBeanFactory) {
this.beanFactory = (DefaultListableBeanFactory) beanFactory;
}
}
/**
* Make sure the registry is set before use.
*
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(jobRegistry != null, "JobRegistry must not be null");
}
/**
* Unregister all the {@link Job} instances that were registered by this post
* processor.
* @see org.springframework.beans.factory.DisposableBean#destroy()
*/
@Override
public void destroy() throws Exception {<FILL_FUNCTION_BODY>}
/**
* If the bean is an instance of {@link Job}, then register it.
* @throws FatalBeanException if there is a {@link DuplicateJobException}.
*
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object,
* java.lang.String)
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Job job) {
try {
String groupName = this.groupName;
if (beanFactory != null && beanFactory.containsBean(beanName)) {
groupName = getGroupName(beanFactory.getBeanDefinition(beanName), job);
}
job = groupName == null ? job : new GroupAwareJob(groupName, job);
ReferenceJobFactory jobFactory = new ReferenceJobFactory(job);
String name = jobFactory.getJobName();
if (logger.isDebugEnabled()) {
logger.debug("Registering job: " + name);
}
jobRegistry.register(jobFactory);
jobNames.add(name);
}
catch (DuplicateJobException e) {
throw new FatalBeanException("Cannot register job configuration", e);
}
return job;
}
return bean;
}
/**
* Determine a group name for the job to be registered. The default implementation
* returns the {@link #setGroupName(String) groupName} configured. Provides an
* extension point for specialised subclasses.
* @param beanDefinition the bean definition for the job
* @param job the job
* @return a group name for the job (or null if not needed)
*/
protected String getGroupName(BeanDefinition beanDefinition, Job job) {
return groupName;
}
/**
* Do nothing.
*
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object,
* java.lang.String)
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
|
for (String name : jobNames) {
if (logger.isDebugEnabled()) {
logger.debug("Unregistering job: " + name);
}
jobRegistry.unregister(name);
}
jobNames.clear();
| 1,043
| 66
| 1,109
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/JobRegistrySmartInitializingSingleton.java
|
JobRegistrySmartInitializingSingleton
|
destroy
|
class JobRegistrySmartInitializingSingleton
implements SmartInitializingSingleton, BeanFactoryAware, InitializingBean, DisposableBean {
private static final Log logger = LogFactory.getLog(JobRegistrySmartInitializingSingleton.class);
// It doesn't make sense for this to have a default value...
private JobRegistry jobRegistry = null;
private final Collection<String> jobNames = new HashSet<>();
private String groupName = null;
private ListableBeanFactory beanFactory;
/**
* Default constructor.
*/
public JobRegistrySmartInitializingSingleton() {
}
/**
* Convenience constructor for setting the {@link JobRegistry}.
* @param jobRegistry the {@link JobRegistry} to register the {@link Job}s with
*/
public JobRegistrySmartInitializingSingleton(JobRegistry jobRegistry) {
this.jobRegistry = jobRegistry;
}
/**
* The group name for jobs registered by this component. Optional (defaults to null,
* which means that jobs are registered with their bean names). Useful where there is
* a hierarchy of application contexts all contributing to the same
* {@link JobRegistry}: child contexts can then define an instance with a unique group
* name to avoid clashes between job names.
* @param groupName the groupName to set
*/
public void setGroupName(String groupName) {
this.groupName = groupName;
}
/**
* Injection setter for {@link JobRegistry}.
* @param jobRegistry the {@link JobRegistry} to register the {@link Job}s with
*/
public void setJobRegistry(JobRegistry jobRegistry) {
this.jobRegistry = jobRegistry;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
if (beanFactory instanceof ListableBeanFactory listableBeanFactory) {
this.beanFactory = listableBeanFactory;
}
}
/**
* Make sure the registry is set before use.
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(jobRegistry != null, "JobRegistry must not be null");
}
/**
* Unregister all the {@link Job} instances that were registered by this smart
* initializing singleton.
*/
@Override
public void destroy() throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void afterSingletonsInstantiated() {
if (beanFactory == null) {
return;
}
Map<String, Job> jobs = beanFactory.getBeansOfType(Job.class, false, false);
for (var entry : jobs.entrySet()) {
postProcessAfterInitialization(entry.getValue(), entry.getKey());
}
}
private void postProcessAfterInitialization(Job job, String beanName) {
try {
String groupName = this.groupName;
if (beanFactory instanceof DefaultListableBeanFactory defaultListableBeanFactory
&& beanFactory.containsBean(beanName)) {
groupName = getGroupName(defaultListableBeanFactory.getBeanDefinition(beanName), job);
}
job = groupName == null ? job : new GroupAwareJob(groupName, job);
ReferenceJobFactory jobFactory = new ReferenceJobFactory(job);
String name = jobFactory.getJobName();
if (logger.isDebugEnabled()) {
logger.debug("Registering job: " + name);
}
jobRegistry.register(jobFactory);
jobNames.add(name);
}
catch (DuplicateJobException e) {
throw new FatalBeanException("Cannot register job configuration", e);
}
}
/**
* Determine a group name for the job to be registered. The default implementation
* returns the {@link #setGroupName(String) groupName} configured. Provides an
* extension point for specialised subclasses.
* @param beanDefinition the bean definition for the job
* @param job the job
* @return a group name for the job (or null if not needed)
*/
protected String getGroupName(BeanDefinition beanDefinition, Job job) {
return groupName;
}
}
|
for (String name : jobNames) {
if (logger.isDebugEnabled()) {
logger.debug("Unregistering job: " + name);
}
jobRegistry.unregister(name);
}
jobNames.clear();
| 1,021
| 66
| 1,087
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/MapJobRegistry.java
|
MapJobRegistry
|
register
|
class MapJobRegistry implements JobRegistry {
/**
* The map holding the registered job factories.
*/
// The "final" ensures that it is visible and initialized when the constructor
// resolves.
private final ConcurrentMap<String, JobFactory> map = new ConcurrentHashMap<>();
@Override
public void register(JobFactory jobFactory) throws DuplicateJobException {<FILL_FUNCTION_BODY>}
@Override
public void unregister(String name) {
Assert.notNull(name, "Job configuration must have a name.");
map.remove(name);
}
@Override
public Job getJob(@Nullable String name) throws NoSuchJobException {
JobFactory factory = map.get(name);
if (factory == null) {
throw new NoSuchJobException("No job configuration with the name [" + name + "] was registered");
}
else {
return factory.createJob();
}
}
/**
* Provides an unmodifiable view of the job names.
*/
@Override
public Set<String> getJobNames() {
return Collections.unmodifiableSet(map.keySet());
}
}
|
Assert.notNull(jobFactory, "jobFactory is null");
String name = jobFactory.getJobName();
Assert.notNull(name, "Job configuration must have a name.");
JobFactory previousValue = map.putIfAbsent(name, jobFactory);
if (previousValue != null) {
throw new DuplicateJobException("A job configuration with this name [" + name + "] was already registered");
}
| 287
| 110
| 397
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/MapStepRegistry.java
|
MapStepRegistry
|
getStep
|
class MapStepRegistry implements StepRegistry {
private final ConcurrentMap<String, Map<String, Step>> map = new ConcurrentHashMap<>();
@Override
public void register(String jobName, Collection<Step> steps) throws DuplicateJobException {
Assert.notNull(jobName, "The job name cannot be null.");
Assert.notNull(steps, "The job steps cannot be null.");
final Map<String, Step> jobSteps = new HashMap<>();
for (Step step : steps) {
jobSteps.put(step.getName(), step);
}
final Object previousValue = map.putIfAbsent(jobName, jobSteps);
if (previousValue != null) {
throw new DuplicateJobException(
"A job configuration with this name [" + jobName + "] was already registered");
}
}
@Override
public void unregisterStepsFromJob(String jobName) {
Assert.notNull(jobName, "Job configuration must have a name.");
map.remove(jobName);
}
@Override
public Step getStep(String jobName, String stepName) throws NoSuchJobException {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(jobName, "The job name cannot be null.");
Assert.notNull(stepName, "The step name cannot be null.");
if (!map.containsKey(jobName)) {
throw new NoSuchJobException("No job configuration with the name [" + jobName + "] was registered");
}
else {
final Map<String, Step> jobSteps = map.get(jobName);
if (jobSteps.containsKey(stepName)) {
return jobSteps.get(stepName);
}
else {
throw new NoSuchStepException(
"The step called [" + stepName + "] does not exist in the job [" + jobName + "]");
}
}
| 301
| 185
| 486
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/AbstractListenerParser.java
|
AbstractListenerParser
|
parseListenerElement
|
class AbstractListenerParser {
private static final String ID_ATTR = "id";
private static final String REF_ATTR = "ref";
private static final String BEAN_ELE = "bean";
private static final String REF_ELE = "ref";
public AbstractBeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(getBeanClass());
doParse(element, parserContext, builder);
return builder.getBeanDefinition();
}
public void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
builder.addPropertyValue("delegate",
parseListenerElement(element, parserContext, builder.getRawBeanDefinition()));
ManagedMap<String, String> metaDataMap = new ManagedMap<>();
for (String metaDataPropertyName : getMethodNameAttributes()) {
String listenerMethod = element.getAttribute(metaDataPropertyName);
if (StringUtils.hasText(listenerMethod)) {
metaDataMap.put(metaDataPropertyName, listenerMethod);
}
}
builder.addPropertyValue("metaDataMap", metaDataMap);
}
public static BeanMetadataElement parseListenerElement(Element element, ParserContext parserContext,
BeanDefinition enclosing) {<FILL_FUNCTION_BODY>}
private static void verifyListenerAttributesAndSubelements(String listenerRef, List<Element> beanElements,
List<Element> refElements, Element element, ParserContext parserContext) {
int total = (StringUtils.hasText(listenerRef) ? 1 : 0) + beanElements.size() + refElements.size();
if (total != 1) {
StringBuilder found = new StringBuilder();
if (total == 0) {
found.append("None");
}
else {
if (StringUtils.hasText(listenerRef)) {
found.append("'" + REF_ATTR + "' attribute, ");
}
if (beanElements.size() == 1) {
found.append("<" + BEAN_ELE + "/> element, ");
}
else if (beanElements.size() > 1) {
found.append(beanElements.size()).append(" <").append(BEAN_ELE).append("/> elements, ");
}
if (refElements.size() == 1) {
found.append("<" + REF_ELE + "/> element, ");
}
else if (refElements.size() > 1) {
found.append(refElements.size()).append(" <").append(REF_ELE).append("/> elements, ");
}
found.delete(found.length() - 2, found.length());
}
String id = element.getAttribute(ID_ATTR);
parserContext.getReaderContext()
.error("The <" + element.getTagName() + (StringUtils.hasText(id) ? " id=\"" + id + "\"" : "")
+ "/> element must have exactly one of: '" + REF_ATTR + "' attribute, <" + BEAN_ELE
+ "/> attribute, or <" + REF_ELE + "/> element. Found: " + found + ".", element);
}
}
private List<String> getMethodNameAttributes() {
List<String> methodNameAttributes = new ArrayList<>();
for (ListenerMetaData metaData : getMetaDataValues()) {
methodNameAttributes.add(metaData.getPropertyName());
}
return methodNameAttributes;
}
/**
* Gets the bean class.
* @return The {@link Class} for the implementation of
* {@link AbstractListenerFactoryBean}.
*/
protected abstract Class<? extends AbstractListenerFactoryBean<?>> getBeanClass();
/**
* Gets the metadata values.
* @return The array of {@link ListenerMetaData}.
*/
protected abstract ListenerMetaData[] getMetaDataValues();
}
|
String listenerRef = element.getAttribute(REF_ATTR);
List<Element> beanElements = DomUtils.getChildElementsByTagName(element, BEAN_ELE);
List<Element> refElements = DomUtils.getChildElementsByTagName(element, REF_ELE);
verifyListenerAttributesAndSubelements(listenerRef, beanElements, refElements, element, parserContext);
if (StringUtils.hasText(listenerRef)) {
return new RuntimeBeanReference(listenerRef);
}
else if (beanElements.size() == 1) {
Element beanElement = beanElements.get(0);
BeanDefinitionHolder beanDefinitionHolder = parserContext.getDelegate()
.parseBeanDefinitionElement(beanElement, enclosing);
parserContext.getDelegate().decorateBeanDefinitionIfRequired(beanElement, beanDefinitionHolder);
return beanDefinitionHolder;
}
else {
return (BeanMetadataElement) parserContext.getDelegate().parsePropertySubElement(refElements.get(0), null);
}
| 989
| 259
| 1,248
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/CoreNamespaceHandler.java
|
CoreNamespaceHandler
|
init
|
class CoreNamespaceHandler extends NamespaceHandlerSupport {
/**
* @see NamespaceHandler#init()
*/
@Override
public void init() {<FILL_FUNCTION_BODY>}
}
|
this.registerBeanDefinitionParser("job", new JobParser());
this.registerBeanDefinitionParser("flow", new TopLevelFlowParser());
this.registerBeanDefinitionParser("step", new TopLevelStepParser());
this.registerBeanDefinitionParser("job-repository", new JobRepositoryParser());
this.registerBeanDefinitionParser("job-listener", new TopLevelJobListenerParser());
this.registerBeanDefinitionParser("step-listener", new TopLevelStepListenerParser());
| 52
| 112
| 164
|
<methods>public void <init>() ,public org.springframework.beans.factory.config.BeanDefinitionHolder decorate(org.w3c.dom.Node, org.springframework.beans.factory.config.BeanDefinitionHolder, org.springframework.beans.factory.xml.ParserContext) ,public org.springframework.beans.factory.config.BeanDefinition parse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext) <variables>private final Map<java.lang.String,org.springframework.beans.factory.xml.BeanDefinitionDecorator> attributeDecorators,private final Map<java.lang.String,org.springframework.beans.factory.xml.BeanDefinitionDecorator> decorators,private final Map<java.lang.String,org.springframework.beans.factory.xml.BeanDefinitionParser> parsers
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/CoreNamespacePostProcessor.java
|
CoreNamespacePostProcessor
|
overrideStepClass
|
class CoreNamespacePostProcessor
implements BeanPostProcessor, BeanFactoryPostProcessor, ApplicationContextAware {
private static final String DEFAULT_JOB_REPOSITORY_NAME = "jobRepository";
private static final String DEFAULT_TRANSACTION_MANAGER_NAME = "transactionManager";
private static final String JOB_FACTORY_PROPERTY_NAME = "jobParserJobFactoryBeanRef";
private static final String JOB_REPOSITORY_PROPERTY_NAME = "jobRepository";
private ApplicationContext applicationContext;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
for (String beanName : beanFactory.getBeanDefinitionNames()) {
injectJobRepositoryIntoSteps(beanName, beanFactory);
overrideStepClass(beanName, beanFactory);
}
}
/**
* Automatically inject job-repository from a job into its steps. Only inject if the
* step is an AbstractStep or StepParserStepFactoryBean.
* @param beanName the bean name
* @param beanFactory the bean factory
*/
private void injectJobRepositoryIntoSteps(String beanName, ConfigurableListableBeanFactory beanFactory) {
BeanDefinition bd = beanFactory.getBeanDefinition(beanName);
if (bd.hasAttribute(JOB_FACTORY_PROPERTY_NAME)) {
MutablePropertyValues pvs = bd.getPropertyValues();
if (beanFactory.isTypeMatch(beanName, AbstractStep.class)) {
String jobName = (String) bd.getAttribute(JOB_FACTORY_PROPERTY_NAME);
PropertyValue jobRepository = BeanDefinitionUtils.getPropertyValue(jobName,
JOB_REPOSITORY_PROPERTY_NAME, beanFactory);
if (jobRepository != null) {
// Set the job's JobRepository onto the step
pvs.addPropertyValue(jobRepository);
}
else {
// No JobRepository found, so inject the default
RuntimeBeanReference jobRepositoryBeanRef = new RuntimeBeanReference(DEFAULT_JOB_REPOSITORY_NAME);
pvs.addPropertyValue(JOB_REPOSITORY_PROPERTY_NAME, jobRepositoryBeanRef);
}
}
}
}
/**
* If any of the beans in the parent hierarchy is a <step/> with a
* <tasklet/>, then the bean class must be {@link StepParserStepFactoryBean}.
* @param beanName the bean name
* @param beanFactory the bean factory
*/
private void overrideStepClass(String beanName, ConfigurableListableBeanFactory beanFactory) {<FILL_FUNCTION_BODY>}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return injectDefaults(bean);
}
/**
* Inject defaults into factory beans.
* <ul>
* <li>Inject "jobRepository" into any {@link JobParserJobFactoryBean} without a
* jobRepository.
* <li>Inject "transactionManager" into any {@link StepParserStepFactoryBean} without
* a transactionManager.
* </ul>
* @param bean the bean object
* @return the bean with default collaborators injected into it
*/
private Object injectDefaults(Object bean) {
if (bean instanceof JobParserJobFactoryBean) {
JobParserJobFactoryBean fb = (JobParserJobFactoryBean) bean;
JobRepository jobRepository = fb.getJobRepository();
if (jobRepository == null) {
fb.setJobRepository((JobRepository) applicationContext.getBean(DEFAULT_JOB_REPOSITORY_NAME));
}
}
else if (bean instanceof StepParserStepFactoryBean) {
StepParserStepFactoryBean<?, ?> fb = (StepParserStepFactoryBean<?, ?>) bean;
JobRepository jobRepository = fb.getJobRepository();
if (jobRepository == null) {
fb.setJobRepository((JobRepository) applicationContext.getBean(DEFAULT_JOB_REPOSITORY_NAME));
}
PlatformTransactionManager transactionManager = fb.getTransactionManager();
if (transactionManager == null && fb.requiresTransactionManager()) {
fb.setTransactionManager(
(PlatformTransactionManager) applicationContext.getBean(DEFAULT_TRANSACTION_MANAGER_NAME));
}
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
|
BeanDefinition bd = beanFactory.getBeanDefinition(beanName);
Object isNamespaceStep = BeanDefinitionUtils.getAttribute(beanName, "isNamespaceStep", beanFactory);
if (isNamespaceStep != null && (Boolean) isNamespaceStep) {
((AbstractBeanDefinition) bd).setBeanClass(StepParserStepFactoryBean.class);
}
| 1,175
| 93
| 1,268
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/DecisionParser.java
|
DecisionParser
|
parse
|
class DecisionParser {
/**
* Parse the decision and turn it into a list of transitions.
* @param element the <decision/gt; element to parse
* @param parserContext the parser context for the bean factory
* @return a collection of bean definitions for
* {@link org.springframework.batch.core.job.flow.support.StateTransition} instances
* objects
*/
public Collection<BeanDefinition> parse(Element element, ParserContext parserContext) {<FILL_FUNCTION_BODY>}
}
|
String refAttribute = element.getAttribute("decider");
String idAttribute = element.getAttribute("id");
BeanDefinitionBuilder stateBuilder = BeanDefinitionBuilder
.genericBeanDefinition("org.springframework.batch.core.job.flow.support.state.DecisionState");
stateBuilder.addConstructorArgValue(new RuntimeBeanReference(refAttribute));
stateBuilder.addConstructorArgValue(idAttribute);
return InlineFlowParser.getNextElements(parserContext, stateBuilder.getBeanDefinition(), element);
| 133
| 130
| 263
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/ExceptionElementParser.java
|
ExceptionElementParser
|
parse
|
class ExceptionElementParser {
public ManagedMap<TypedStringValue, Boolean> parse(Element element, ParserContext parserContext,
String exceptionListName) {<FILL_FUNCTION_BODY>}
private void addExceptionClasses(String elementName, boolean include, Element exceptionClassesElement,
ManagedMap<TypedStringValue, Boolean> map, ParserContext parserContext) {
for (Element child : DomUtils.getChildElementsByTagName(exceptionClassesElement, elementName)) {
String className = child.getAttribute("class");
map.put(new TypedStringValue(className, Class.class), include);
}
}
}
|
List<Element> children = DomUtils.getChildElementsByTagName(element, exceptionListName);
if (children.size() == 1) {
ManagedMap<TypedStringValue, Boolean> map = new ManagedMap<>();
Element exceptionClassesElement = children.get(0);
addExceptionClasses("include", true, exceptionClassesElement, map, parserContext);
addExceptionClasses("exclude", false, exceptionClassesElement, map, parserContext);
map.put(new TypedStringValue(ForceRollbackForWriteSkipException.class.getName(), Class.class), true);
return map;
}
else if (children.size() > 1) {
parserContext.getReaderContext()
.error("The <" + exceptionListName + "/> element may not appear more than once in a single <"
+ element.getNodeName() + "/>.", element);
}
return null;
| 160
| 230
| 390
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/FlowElementParser.java
|
FlowElementParser
|
parse
|
class FlowElementParser {
private static final String ID_ATTR = "id";
private static final String REF_ATTR = "parent";
/**
* Parse the flow and turn it into a list of transitions.
* @param element The <flow/gt; element to parse.
* @param parserContext The parser context for the bean factory.
* @return a collection of bean definitions for
* {@link org.springframework.batch.core.job.flow.support.StateTransition} instances
* objects.
*/
public Collection<BeanDefinition> parse(Element element, ParserContext parserContext) {<FILL_FUNCTION_BODY>}
}
|
String refAttribute = element.getAttribute(REF_ATTR);
String idAttribute = element.getAttribute(ID_ATTR);
BeanDefinitionBuilder stateBuilder = BeanDefinitionBuilder
.genericBeanDefinition("org.springframework.batch.core.job.flow.support.state.FlowState");
AbstractBeanDefinition flowDefinition = new GenericBeanDefinition();
flowDefinition.setParentName(refAttribute);
MutablePropertyValues propertyValues = flowDefinition.getPropertyValues();
propertyValues.addPropertyValue("name", idAttribute);
stateBuilder.addConstructorArgValue(flowDefinition);
stateBuilder.addConstructorArgValue(idAttribute);
return InlineFlowParser.getNextElements(parserContext, stateBuilder.getBeanDefinition(), element);
| 162
| 188
| 350
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/InlineFlowParser.java
|
InlineFlowParser
|
doParse
|
class InlineFlowParser extends AbstractFlowParser {
private final String flowName;
/**
* Construct a {@link InlineFlowParser} with the specified name and using the provided
* job repository reference.
* @param flowName The name of the flow.
* @param jobFactoryRef The reference to the {@link JobParserJobFactoryBean} from the
* enclosing tag.
*/
public InlineFlowParser(String flowName, String jobFactoryRef) {
this.flowName = flowName;
setJobFactoryRef(jobFactoryRef);
}
@Override
protected boolean shouldGenerateId() {
return true;
}
/**
* Does the parsing.
* @param element The top level element containing a flow definition.
* @param parserContext The {@link ParserContext}.
*/
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {<FILL_FUNCTION_BODY>}
}
|
builder.getRawBeanDefinition().setAttribute("flowName", flowName);
builder.addPropertyValue("name", flowName);
builder.addPropertyValue("stateTransitionComparator",
new RuntimeBeanReference(DefaultStateTransitionComparator.STATE_TRANSITION_COMPARATOR));
super.doParse(element, parserContext, builder);
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
parserContext.popAndRegisterContainingComponent();
| 242
| 129
| 371
|
<methods>public non-sealed void <init>() ,public static Collection<org.springframework.beans.factory.config.BeanDefinition> getNextElements(org.springframework.beans.factory.xml.ParserContext, org.springframework.beans.factory.config.BeanDefinition, org.w3c.dom.Element) ,public static Collection<org.springframework.beans.factory.config.BeanDefinition> getNextElements(org.springframework.beans.factory.xml.ParserContext, java.lang.String, org.springframework.beans.factory.config.BeanDefinition, org.w3c.dom.Element) ,public static org.springframework.beans.factory.config.BeanDefinition getStateTransitionReference(org.springframework.beans.factory.xml.ParserContext, org.springframework.beans.factory.config.BeanDefinition, java.lang.String, java.lang.String) <variables>protected static final java.lang.String DECISION_ELE,protected static final java.lang.String END_ELE,protected static final java.lang.String EXIT_CODE_ATTR,protected static final java.lang.String FAIL_ELE,protected static final java.lang.String FLOW_ELE,protected static final java.lang.String ID_ATTR,protected static final java.lang.String NEXT_ATTR,protected static final java.lang.String NEXT_ELE,protected static final java.lang.String ON_ATTR,protected static final java.lang.String RESTART_ATTR,protected static final java.lang.String SPLIT_ELE,protected static final java.lang.String STEP_ELE,protected static final java.lang.String STOP_ELE,protected static final java.lang.String TO_ATTR,private static final org.springframework.batch.core.configuration.xml.DecisionParser decisionParser,protected static int endCounter,private static final org.springframework.batch.core.configuration.xml.FlowElementParser flowParser,private java.lang.String jobFactoryRef,private static final org.springframework.batch.core.configuration.xml.InlineStepParser stepParser
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/InlineStepParser.java
|
InlineStepParser
|
parse
|
class InlineStepParser extends AbstractStepParser {
/**
* Parse the step and turn it into a list of transitions.
* @param element The <step/gt; element to parse.
* @param parserContext The parser context for the bean factory.
* @param jobFactoryRef The reference to the {@link JobParserJobFactoryBean} from the
* enclosing tag.
* @return a collection of bean definitions for
* {@link org.springframework.batch.core.job.flow.support.StateTransition} instances
* objects.
*/
public Collection<BeanDefinition> parse(Element element, ParserContext parserContext, String jobFactoryRef) {<FILL_FUNCTION_BODY>}
}
|
BeanDefinitionBuilder stateBuilder = BeanDefinitionBuilder.genericBeanDefinition(StepState.class);
String stepId = element.getAttribute(ID_ATTR);
AbstractBeanDefinition bd = parseStep(element, parserContext, jobFactoryRef);
parserContext.registerBeanComponent(new BeanComponentDefinition(bd, stepId));
stateBuilder.addConstructorArgReference(stepId);
return InlineFlowParser.getNextElements(parserContext, stepId, stateBuilder.getBeanDefinition(), element);
| 175
| 128
| 303
|
<methods>public non-sealed void <init>() <variables>private static final java.lang.String AGGREGATOR_ATTR,private static final java.lang.String ALLOW_START_ATTR,private static final java.lang.String FLOW_ELE,private static final java.lang.String GRID_SIZE_ATTR,private static final java.lang.String HANDLER_ATTR,private static final java.lang.String HANDLER_ELE,protected static final java.lang.String ID_ATTR,private static final java.lang.String JOB_ELE,private static final java.lang.String JOB_LAUNCHER_ATTR,private static final java.lang.String JOB_PARAMS_EXTRACTOR_ATTR,private static final java.lang.String JOB_REPO_ATTR,private static final java.lang.String PARENT_ATTR,private static final java.lang.String PARTITIONER_ATTR,private static final java.lang.String PARTITION_ELE,private static final java.lang.String REF_ATTR,private static final java.lang.String STEP_ATTR,private static final java.lang.String STEP_ELE,private static final java.lang.String TASKLET_ELE,private static final java.lang.String TASK_EXECUTOR_ATTR,private static final org.springframework.batch.core.configuration.xml.StepListenerParser stepListenerParser
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/JobParser.java
|
JobParser
|
doParse
|
class JobParser extends AbstractSingleBeanDefinitionParser {
private static final String MERGE_ATTR = "merge";
private static final String REF_ATTR = "ref";
private static final String BEAN_ELE = "bean";
private static final String REF_ELE = "ref";
private static final JobExecutionListenerParser jobListenerParser = new JobExecutionListenerParser();
@Override
protected Class<JobParserJobFactoryBean> getBeanClass(Element element) {
return JobParserJobFactoryBean.class;
}
/**
* Create a bean definition for a
* {@link org.springframework.batch.core.job.flow.FlowJob}. Nested step elements are
* delegated to an {@link InlineStepParser}.
*
* @see AbstractSingleBeanDefinitionParser#doParse(Element, ParserContext,
* BeanDefinitionBuilder)
*/
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {<FILL_FUNCTION_BODY>}
/**
* Parse the element to retrieve {@link BeanMetadataElement}.
* @param element The {@link Element} to be parsed.
* @param parserContext The {@link ParserContext}.
* @return the {@link BeanMetadataElement} extracted from the element parameter.
*/
public BeanMetadataElement parseBeanElement(Element element, ParserContext parserContext) {
String refAttribute = element.getAttribute(REF_ATTR);
Element beanElement = DomUtils.getChildElementByTagName(element, BEAN_ELE);
Element refElement = DomUtils.getChildElementByTagName(element, REF_ELE);
if (StringUtils.hasText(refAttribute)) {
return new RuntimeBeanReference(refAttribute);
}
else if (beanElement != null) {
BeanDefinitionHolder beanDefinitionHolder = parserContext.getDelegate()
.parseBeanDefinitionElement(beanElement);
parserContext.getDelegate().decorateBeanDefinitionIfRequired(beanElement, beanDefinitionHolder);
return beanDefinitionHolder;
}
else if (refElement != null) {
return (BeanMetadataElement) parserContext.getDelegate().parsePropertySubElement(refElement, null);
}
parserContext.getReaderContext()
.error("One of ref attribute or a nested bean definition or ref element must be specified", element);
return null;
}
}
|
if (!CoreNamespaceUtils.namespaceMatchesVersion(element)) {
parserContext.getReaderContext()
.error("You are using a version of the spring-batch XSD that is not compatible with Spring Batch 3.0."
+ " Please upgrade your schema declarations (or use the spring-batch.xsd alias if you are "
+ "feeling lucky).", element);
return;
}
CoreNamespaceUtils.autoregisterBeansForNamespace(parserContext, parserContext.extractSource(element));
String jobName = element.getAttribute("id");
builder.addConstructorArgValue(jobName);
boolean isAbstract = CoreNamespaceUtils.isAbstract(element);
builder.setAbstract(isAbstract);
String parentRef = element.getAttribute("parent");
if (StringUtils.hasText(parentRef)) {
builder.setParentName(parentRef);
}
String repositoryAttribute = element.getAttribute("job-repository");
if (StringUtils.hasText(repositoryAttribute)) {
builder.addPropertyReference("jobRepository", repositoryAttribute);
}
Element validator = DomUtils.getChildElementByTagName(element, "validator");
if (validator != null) {
builder.addPropertyValue("jobParametersValidator", parseBeanElement(validator, parserContext));
}
String restartableAttribute = element.getAttribute("restartable");
if (StringUtils.hasText(restartableAttribute)) {
builder.addPropertyValue("restartable", restartableAttribute);
}
String incrementer = (element.getAttribute("incrementer"));
if (StringUtils.hasText(incrementer)) {
builder.addPropertyReference("jobParametersIncrementer", incrementer);
}
if (isAbstract) {
for (String tagName : Arrays.asList("step", "decision", "split")) {
if (!DomUtils.getChildElementsByTagName(element, tagName).isEmpty()) {
parserContext.getReaderContext()
.error("The <" + tagName + "/> element may not appear on a <job/> with abstract=\"true\" ["
+ jobName + "]", element);
}
}
}
else {
InlineFlowParser flowParser = new InlineFlowParser(jobName, jobName);
BeanDefinition flowDef = flowParser.parse(element, parserContext);
builder.addPropertyValue("flow", flowDef);
}
Element description = DomUtils.getChildElementByTagName(element, "description");
if (description != null) {
builder.getBeanDefinition().setDescription(description.getTextContent());
}
List<Element> listenersElements = DomUtils.getChildElementsByTagName(element, "listeners");
if (listenersElements.size() == 1) {
Element listenersElement = listenersElements.get(0);
CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(listenersElement.getTagName(),
parserContext.extractSource(element));
parserContext.pushContainingComponent(compositeDef);
ManagedList<BeanDefinition> listeners = new ManagedList<>();
listeners.setMergeEnabled(listenersElement.hasAttribute(MERGE_ATTR)
&& Boolean.parseBoolean(listenersElement.getAttribute(MERGE_ATTR)));
List<Element> listenerElements = DomUtils.getChildElementsByTagName(listenersElement, "listener");
for (Element listenerElement : listenerElements) {
listeners.add(jobListenerParser.parse(listenerElement, parserContext));
}
builder.addPropertyValue("jobExecutionListeners", listeners);
parserContext.popAndRegisterContainingComponent();
}
else if (listenersElements.size() > 1) {
parserContext.getReaderContext()
.error("The '<listeners/>' element may not appear more than once in a single <job/>.", element);
}
| 587
| 999
| 1,586
|
<methods>public void <init>() <variables>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/JobParserJobFactoryBean.java
|
JobParserJobFactoryBean
|
getObject
|
class JobParserJobFactoryBean implements SmartFactoryBean<FlowJob> {
private final String name;
private Boolean restartable;
private JobRepository jobRepository;
private JobParametersValidator jobParametersValidator;
private JobExecutionListener[] jobExecutionListeners;
private JobParametersIncrementer jobParametersIncrementer;
private Flow flow;
/**
* Constructor for the factory bean that initializes the name.
* @param name The name to be used by the factory bean.
*/
public JobParserJobFactoryBean(String name) {
this.name = name;
}
@Override
public final FlowJob getObject() throws Exception {<FILL_FUNCTION_BODY>}
/**
* Set the restartable flag for the factory bean.
* @param restartable The restartable flag to be used by the factory bean.
*/
public void setRestartable(Boolean restartable) {
this.restartable = restartable;
}
/**
* Set the {@link JobRepository} for the factory bean.
* @param jobRepository The {@link JobRepository} to be used by the factory bean.
*/
public void setJobRepository(JobRepository jobRepository) {
this.jobRepository = jobRepository;
}
/**
* Set the {@link JobParametersValidator} for the factory bean.
* @param jobParametersValidator The {@link JobParametersValidator} to be used by the
* factory bean.
*/
public void setJobParametersValidator(JobParametersValidator jobParametersValidator) {
this.jobParametersValidator = jobParametersValidator;
}
/**
* @return The {@link JobRepository} used by the factory bean.
*/
public JobRepository getJobRepository() {
return this.jobRepository;
}
public void setJobExecutionListeners(JobExecutionListener[] jobExecutionListeners) {
this.jobExecutionListeners = jobExecutionListeners;
}
/**
* Set the {@link JobParametersIncrementer} for the factory bean.
* @param jobParametersIncrementer The {@link JobParametersIncrementer} to be used by
* the factory bean.
*/
public void setJobParametersIncrementer(JobParametersIncrementer jobParametersIncrementer) {
this.jobParametersIncrementer = jobParametersIncrementer;
}
/**
* Set the flow for the factory bean.
* @param flow The {@link Flow} to be used by the factory bean.
*/
public void setFlow(Flow flow) {
this.flow = flow;
}
@Override
public Class<FlowJob> getObjectType() {
return FlowJob.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public boolean isEagerInit() {
return true;
}
@Override
public boolean isPrototype() {
return false;
}
}
|
Assert.isTrue(StringUtils.hasText(name), "The job must have an id.");
FlowJob flowJob = new FlowJob(name);
if (restartable != null) {
flowJob.setRestartable(restartable);
}
if (jobRepository != null) {
flowJob.setJobRepository(jobRepository);
}
if (jobParametersValidator != null) {
flowJob.setJobParametersValidator(jobParametersValidator);
}
if (jobExecutionListeners != null) {
flowJob.setJobExecutionListeners(jobExecutionListeners);
}
if (jobParametersIncrementer != null) {
flowJob.setJobParametersIncrementer(jobParametersIncrementer);
}
if (flow != null) {
flowJob.setFlow(flow);
}
flowJob.afterPropertiesSet();
return flowJob;
| 700
| 247
| 947
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/JobRepositoryParser.java
|
JobRepositoryParser
|
doParse
|
class JobRepositoryParser extends AbstractSingleBeanDefinitionParser {
@Override
protected String getBeanClassName(Element element) {
return "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean";
}
@Override
protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext)
throws BeanDefinitionStoreException {
String id = element.getAttribute(ID_ATTRIBUTE);
if (!StringUtils.hasText(id)) {
id = "jobRepository";
}
return id;
}
/**
* Parse and create a bean definition for a
* {@link org.springframework.batch.core.repository.support.JobRepositoryFactoryBean}
* .
*/
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {<FILL_FUNCTION_BODY>}
}
|
CoreNamespaceUtils.autoregisterBeansForNamespace(parserContext, element);
String dataSource = element.getAttribute("data-source");
String jdbcOperations = element.getAttribute("jdbc-operations");
String transactionManager = element.getAttribute("transaction-manager");
String isolationLevelForCreate = element.getAttribute("isolation-level-for-create");
String tablePrefix = element.getAttribute("table-prefix");
String maxVarCharLength = element.getAttribute("max-varchar-length");
String lobHandler = element.getAttribute("lob-handler");
String serializer = element.getAttribute("serializer");
String conversionService = element.getAttribute("conversion-service");
RuntimeBeanReference ds = new RuntimeBeanReference(dataSource);
builder.addPropertyValue("dataSource", ds);
RuntimeBeanReference tx = new RuntimeBeanReference(transactionManager);
builder.addPropertyValue("transactionManager", tx);
if (StringUtils.hasText(jdbcOperations)) {
builder.addPropertyReference("jdbcOperations", jdbcOperations);
}
if (StringUtils.hasText(isolationLevelForCreate)) {
builder.addPropertyValue("isolationLevelForCreate",
DefaultTransactionDefinition.PREFIX_ISOLATION + isolationLevelForCreate);
}
if (StringUtils.hasText(tablePrefix)) {
builder.addPropertyValue("tablePrefix", tablePrefix);
}
if (StringUtils.hasText(lobHandler)) {
builder.addPropertyReference("lobHandler", lobHandler);
}
if (StringUtils.hasText(maxVarCharLength)) {
builder.addPropertyValue("maxVarCharLength", maxVarCharLength);
}
if (StringUtils.hasText(serializer)) {
builder.addPropertyReference("serializer", serializer);
}
if (StringUtils.hasText(conversionService)) {
builder.addPropertyReference("conversionService", conversionService);
}
builder.setRole(BeanDefinition.ROLE_SUPPORT);
| 223
| 528
| 751
|
<methods>public void <init>() <variables>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/SimpleFlowFactoryBean.java
|
SimpleFlowFactoryBean
|
getObject
|
class SimpleFlowFactoryBean implements FactoryBean<SimpleFlow>, InitializingBean {
private String name;
private List<StateTransition> stateTransitions;
private String prefix;
private Comparator<StateTransition> stateTransitionComparator;
private Class<SimpleFlow> flowType;
/**
* @param stateTransitionComparator {@link Comparator} implementation that addresses
* the ordering of state evaluation.
*/
public void setStateTransitionComparator(Comparator<StateTransition> stateTransitionComparator) {
this.stateTransitionComparator = stateTransitionComparator;
}
/**
* @param flowType Used to inject the type of flow (regular Spring Batch or JSR-352).
*/
public void setFlowType(Class<SimpleFlow> flowType) {
this.flowType = flowType;
}
/**
* The name of the flow that is created by this factory.
* @param name the value of the name
*/
public void setName(String name) {
this.name = name;
this.prefix = name + ".";
}
/**
* The raw state transitions for the flow. They are transformed into proxies that have
* the same behavior but unique names prefixed with the flow name.
* @param stateTransitions the list of transitions
*/
public void setStateTransitions(List<StateTransition> stateTransitions) {
this.stateTransitions = stateTransitions;
}
/**
* Check mandatory properties (name).
* @throws Exception thrown if error occurs.
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(StringUtils.hasText(name), "The flow must have a name");
if (flowType == null) {
flowType = SimpleFlow.class;
}
}
@Override
public SimpleFlow getObject() throws Exception {<FILL_FUNCTION_BODY>}
private String getNext(String next) {
if (next == null) {
return null;
}
return (next.startsWith(this.prefix) ? "" : this.prefix) + next;
}
/**
* Convenience method to get a state that proxies the input but with a different name,
* appropriate to this flow. If the state is a {@link StepState}, the step name is
* also changed.
* @param state the state to proxy
* @return the proxy state
*/
private State getProxyState(State state) {
String oldName = state.getName();
if (oldName.startsWith(prefix)) {
return state;
}
String stateName = prefix + oldName;
if (state instanceof StepState) {
return createNewStepState(state, oldName, stateName);
}
return new DelegateState(stateName, state);
}
/**
* Provides an extension point to provide alternative {@link StepState}
* implementations within a {@link SimpleFlow}.
* @param state The state that is used to create the {@code StepState}.
* @param oldName The name to be replaced.
* @param stateName The name for the new State.
* @return a state for the requested data.
*/
protected State createNewStepState(State state, String oldName, String stateName) {
return new StepState(stateName, ((StepState) state).getStep(oldName));
}
@Override
public Class<?> getObjectType() {
return SimpleFlow.class;
}
@Override
public boolean isSingleton() {
return true;
}
/**
* A State that proxies a delegate and changes its name but leaves its behavior
* unchanged.
*
* @author Dave Syer
*
*/
public static class DelegateState extends AbstractState implements FlowHolder {
private final State state;
private DelegateState(String name, State state) {
super(name);
this.state = state;
}
/**
* Gets the current state.
* @return The {@link State} being used by the factory bean.
*/
public State getState() {
return this.state;
}
@Override
public boolean isEndState() {
return state.isEndState();
}
@Override
public FlowExecutionStatus handle(FlowExecutor executor) throws Exception {
return state.handle(executor);
}
@Override
public Collection<Flow> getFlows() {
return (state instanceof FlowHolder) ? ((FlowHolder) state).getFlows() : Collections.<Flow>emptyList();
}
}
}
|
SimpleFlow flow = flowType.getConstructor(String.class).newInstance(name);
flow.setStateTransitionComparator(stateTransitionComparator);
List<StateTransition> updatedTransitions = new ArrayList<>();
for (StateTransition stateTransition : stateTransitions) {
State state = getProxyState(stateTransition.getState());
updatedTransitions.add(StateTransition.switchOriginAndDestination(stateTransition, state,
getNext(stateTransition.getNext())));
}
flow.setStateTransitions(updatedTransitions);
flow.afterPropertiesSet();
return flow;
| 1,156
| 169
| 1,325
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/SplitParser.java
|
SplitParser
|
parse
|
class SplitParser {
private static final String PARENT_ATTR = "parent";
private final String jobFactoryRef;
/**
* Construct a {@link InlineFlowParser} by using the provided job repository
* reference.
* @param jobFactoryRef The reference to the {@link JobParserJobFactoryBean} from the
* enclosing tag.
*/
public SplitParser(String jobFactoryRef) {
this.jobFactoryRef = jobFactoryRef;
}
/**
* Parse the split and turn it into a list of transitions.
* @param element The <split/gt; element to parse
* @param parserContext The parser context for the bean factory
* @return a collection of bean definitions for
* {@link org.springframework.batch.core.job.flow.support.StateTransition} instances
* objects
*/
public Collection<BeanDefinition> parse(Element element, ParserContext parserContext) {<FILL_FUNCTION_BODY>}
}
|
String idAttribute = element.getAttribute("id");
BeanDefinitionBuilder stateBuilder = BeanDefinitionBuilder
.genericBeanDefinition("org.springframework.batch.core.job.flow.support.state.SplitState");
String taskExecutorBeanId = element.getAttribute("task-executor");
if (StringUtils.hasText(taskExecutorBeanId)) {
RuntimeBeanReference taskExecutorRef = new RuntimeBeanReference(taskExecutorBeanId);
stateBuilder.addPropertyValue("taskExecutor", taskExecutorRef);
}
List<Element> flowElements = DomUtils.getChildElementsByTagName(element, "flow");
if (flowElements.size() < 2) {
parserContext.getReaderContext().error("A <split/> must contain at least two 'flow' elements.", element);
}
Collection<BeanDefinition> flows = new ManagedList<>();
int i = 0;
String prefix = idAttribute;
for (Element nextElement : flowElements) {
String ref = nextElement.getAttribute(PARENT_ATTR);
if (StringUtils.hasText(ref)) {
if (nextElement.getElementsByTagName("*").getLength() > 0) {
parserContext.getReaderContext()
.error("A <flow/> in a <split/> must have ref= or nested <flow/>, but not both.", nextElement);
}
AbstractBeanDefinition flowDefinition = new GenericBeanDefinition();
flowDefinition.setParentName(ref);
MutablePropertyValues propertyValues = flowDefinition.getPropertyValues();
propertyValues.addPropertyValue("name", prefix + "." + i);
flows.add(flowDefinition);
}
else {
InlineFlowParser flowParser = new InlineFlowParser(prefix + "." + i, jobFactoryRef);
flows.add(flowParser.parse(nextElement, parserContext));
}
i++;
}
stateBuilder.addConstructorArgValue(flows);
stateBuilder.addConstructorArgValue(prefix);
return InlineFlowParser.getNextElements(parserContext, stateBuilder.getBeanDefinition(), element);
| 240
| 539
| 779
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/StepListenerParser.java
|
StepListenerParser
|
handleListenersElement
|
class StepListenerParser extends AbstractListenerParser {
private static final String LISTENERS_ELE = "listeners";
private static final String MERGE_ATTR = "merge";
private final ListenerMetaData[] listenerMetaData;
public StepListenerParser() {
this(StepListenerMetaData.values());
}
public StepListenerParser(ListenerMetaData[] listenerMetaData) {
this.listenerMetaData = listenerMetaData;
}
@Override
protected Class<? extends AbstractListenerFactoryBean<?>> getBeanClass() {
return StepListenerFactoryBean.class;
}
@Override
protected ListenerMetaData[] getMetaDataValues() {
return listenerMetaData;
}
@SuppressWarnings("unchecked")
public void handleListenersElement(Element stepElement, BeanDefinition beanDefinition,
ParserContext parserContext) {<FILL_FUNCTION_BODY>}
}
|
MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
List<Element> listenersElements = DomUtils.getChildElementsByTagName(stepElement, LISTENERS_ELE);
if (listenersElements.size() == 1) {
Element listenersElement = listenersElements.get(0);
CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(listenersElement.getTagName(),
parserContext.extractSource(stepElement));
parserContext.pushContainingComponent(compositeDef);
ManagedList<BeanDefinition> listenerBeans = new ManagedList<>();
if (propertyValues.contains("listeners")) {
listenerBeans = (ManagedList<BeanDefinition>) propertyValues.getPropertyValue("listeners").getValue();
}
listenerBeans.setMergeEnabled(listenersElement.hasAttribute(MERGE_ATTR)
&& Boolean.parseBoolean(listenersElement.getAttribute(MERGE_ATTR)));
List<Element> listenerElements = DomUtils.getChildElementsByTagName(listenersElement, "listener");
if (listenerElements != null) {
for (Element listenerElement : listenerElements) {
listenerBeans.add(parse(listenerElement, parserContext));
}
}
propertyValues.addPropertyValue("listeners", listenerBeans);
parserContext.popAndRegisterContainingComponent();
}
| 224
| 353
| 577
|
<methods>public non-sealed void <init>() ,public void doParse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext, org.springframework.beans.factory.support.BeanDefinitionBuilder) ,public org.springframework.beans.factory.support.AbstractBeanDefinition parse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext) ,public static org.springframework.beans.BeanMetadataElement parseListenerElement(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext, org.springframework.beans.factory.config.BeanDefinition) <variables>private static final java.lang.String BEAN_ELE,private static final java.lang.String ID_ATTR,private static final java.lang.String REF_ATTR,private static final java.lang.String REF_ELE
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/TopLevelFlowParser.java
|
TopLevelFlowParser
|
doParse
|
class TopLevelFlowParser extends AbstractFlowParser {
private static final String ABSTRACT_ATTR = "abstract";
/**
* Parse the flow.
* @param element the top level element containing a flow definition
* @param parserContext the {@link ParserContext}
*/
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {<FILL_FUNCTION_BODY>}
}
|
CoreNamespaceUtils.autoregisterBeansForNamespace(parserContext, element);
String flowName = element.getAttribute(ID_ATTR);
builder.getRawBeanDefinition().setAttribute("flowName", flowName);
builder.addPropertyValue("name", flowName);
builder.addPropertyValue("stateTransitionComparator",
new RuntimeBeanReference(DefaultStateTransitionComparator.STATE_TRANSITION_COMPARATOR));
String abstractAttr = element.getAttribute(ABSTRACT_ATTR);
if (StringUtils.hasText(abstractAttr)) {
builder.setAbstract(abstractAttr.equals("true"));
}
super.doParse(element, parserContext, builder);
| 110
| 179
| 289
|
<methods>public non-sealed void <init>() ,public static Collection<org.springframework.beans.factory.config.BeanDefinition> getNextElements(org.springframework.beans.factory.xml.ParserContext, org.springframework.beans.factory.config.BeanDefinition, org.w3c.dom.Element) ,public static Collection<org.springframework.beans.factory.config.BeanDefinition> getNextElements(org.springframework.beans.factory.xml.ParserContext, java.lang.String, org.springframework.beans.factory.config.BeanDefinition, org.w3c.dom.Element) ,public static org.springframework.beans.factory.config.BeanDefinition getStateTransitionReference(org.springframework.beans.factory.xml.ParserContext, org.springframework.beans.factory.config.BeanDefinition, java.lang.String, java.lang.String) <variables>protected static final java.lang.String DECISION_ELE,protected static final java.lang.String END_ELE,protected static final java.lang.String EXIT_CODE_ATTR,protected static final java.lang.String FAIL_ELE,protected static final java.lang.String FLOW_ELE,protected static final java.lang.String ID_ATTR,protected static final java.lang.String NEXT_ATTR,protected static final java.lang.String NEXT_ELE,protected static final java.lang.String ON_ATTR,protected static final java.lang.String RESTART_ATTR,protected static final java.lang.String SPLIT_ELE,protected static final java.lang.String STEP_ELE,protected static final java.lang.String STOP_ELE,protected static final java.lang.String TO_ATTR,private static final org.springframework.batch.core.configuration.xml.DecisionParser decisionParser,protected static int endCounter,private static final org.springframework.batch.core.configuration.xml.FlowElementParser flowParser,private java.lang.String jobFactoryRef,private static final org.springframework.batch.core.configuration.xml.InlineStepParser stepParser
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/converter/DefaultJobParametersConverter.java
|
DefaultJobParametersConverter
|
parseType
|
class DefaultJobParametersConverter implements JobParametersConverter {
protected ConfigurableConversionService conversionService;
public DefaultJobParametersConverter() {
DefaultConversionService conversionService = new DefaultConversionService();
conversionService.addConverter(new DateToStringConverter());
conversionService.addConverter(new StringToDateConverter());
conversionService.addConverter(new LocalDateToStringConverter());
conversionService.addConverter(new StringToLocalDateConverter());
conversionService.addConverter(new LocalTimeToStringConverter());
conversionService.addConverter(new StringToLocalTimeConverter());
conversionService.addConverter(new LocalDateTimeToStringConverter());
conversionService.addConverter(new StringToLocalDateTimeConverter());
this.conversionService = conversionService;
}
/**
* @see org.springframework.batch.core.converter.JobParametersConverter#getJobParameters(java.util.Properties)
*/
@Override
public JobParameters getJobParameters(@Nullable Properties properties) {
if (properties == null || properties.isEmpty()) {
return new JobParameters();
}
JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
for (Entry<Object, Object> entry : properties.entrySet()) {
String parameterName = (String) entry.getKey();
String encodedJobParameter = (String) entry.getValue();
JobParameter<?> jobParameter = decode(encodedJobParameter);
jobParametersBuilder.addJobParameter(parameterName, jobParameter);
}
return jobParametersBuilder.toJobParameters();
}
/**
* @see org.springframework.batch.core.converter.JobParametersConverter#getProperties(org.springframework.batch.core.JobParameters)
*/
@Override
public Properties getProperties(@Nullable JobParameters jobParameters) {
if (jobParameters == null || jobParameters.isEmpty()) {
return new Properties();
}
Map<String, JobParameter<?>> parameters = jobParameters.getParameters();
Properties properties = new Properties();
for (Entry<String, JobParameter<?>> entry : parameters.entrySet()) {
String parameterName = entry.getKey();
JobParameter<?> jobParameter = entry.getValue();
properties.setProperty(parameterName, encode(jobParameter));
}
return properties;
}
/**
* Set the conversion service to use.
* @param conversionService the conversion service to use. Must not be {@code null}.
* @since 5.0
*/
public void setConversionService(@NonNull ConfigurableConversionService conversionService) {
Assert.notNull(conversionService, "The conversionService must not be null");
this.conversionService = conversionService;
}
/**
* Encode a job parameter to a string.
* @param jobParameter the parameter to encode
* @return the encoded job parameter
*/
protected String encode(JobParameter<?> jobParameter) {
Class<?> parameterType = jobParameter.getType();
boolean parameterIdentifying = jobParameter.isIdentifying();
Object parameterTypedValue = jobParameter.getValue();
String parameterStringValue = this.conversionService.convert(parameterTypedValue, String.class);
return String.join(",", parameterStringValue, parameterType.getName(), Boolean.toString(parameterIdentifying));
}
/**
* Decode a job parameter from a string.
* @param encodedJobParameter the encoded job parameter
* @return the decoded job parameter
*/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
protected JobParameter<?> decode(String encodedJobParameter) {
String parameterStringValue = parseValue(encodedJobParameter);
Class<?> parameterType = parseType(encodedJobParameter);
boolean parameterIdentifying = parseIdentifying(encodedJobParameter);
try {
Object typedValue = this.conversionService.convert(parameterStringValue, parameterType);
return new JobParameter(typedValue, parameterType, parameterIdentifying);
}
catch (Exception e) {
throw new JobParametersConversionException(
"Unable to convert job parameter " + parameterStringValue + " to type " + parameterType, e);
}
}
private String parseValue(String encodedJobParameter) {
String[] tokens = StringUtils.commaDelimitedListToStringArray(encodedJobParameter);
if (tokens.length == 0) {
return "";
}
return tokens[0];
}
private Class<?> parseType(String encodedJobParameter) {<FILL_FUNCTION_BODY>}
private boolean parseIdentifying(String encodedJobParameter) {
String[] tokens = StringUtils.commaDelimitedListToStringArray(encodedJobParameter);
if (tokens.length <= 2) {
return true;
}
return Boolean.parseBoolean(tokens[2]);
}
}
|
String[] tokens = StringUtils.commaDelimitedListToStringArray(encodedJobParameter);
if (tokens.length <= 1) {
return String.class;
}
try {
Class<?> type = Class.forName(tokens[1]);
return type;
}
catch (ClassNotFoundException e) {
throw new JobParametersConversionException("Unable to parse job parameter " + encodedJobParameter, e);
}
| 1,200
| 119
| 1,319
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/converter/JsonJobParametersConverter.java
|
JsonJobParametersConverter
|
decode
|
class JsonJobParametersConverter extends DefaultJobParametersConverter {
private final ObjectMapper objectMapper;
/**
* Create a new {@link JsonJobParametersConverter} with a default
* {@link ObjectMapper}.
*/
public JsonJobParametersConverter() {
this(new ObjectMapper());
}
/**
* Create a new {@link JsonJobParametersConverter} with a custom {@link ObjectMapper}.
* @param objectMapper the object mapper to use
*/
public JsonJobParametersConverter(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
protected String encode(JobParameter<?> jobParameter) {
Class<?> parameterType = jobParameter.getType();
Object parameterTypedValue = jobParameter.getValue();
boolean parameterIdentifying = jobParameter.isIdentifying();
String parameterStringValue = this.conversionService.convert(parameterTypedValue, String.class);
try {
return this.objectMapper.writeValueAsString(new JobParameterDefinition(parameterStringValue,
parameterType.getName(), Boolean.toString(parameterIdentifying)));
}
catch (JsonProcessingException e) {
throw new JobParametersConversionException("Unable to encode job parameter " + jobParameter, e);
}
}
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Override
protected JobParameter decode(String encodedJobParameter) {<FILL_FUNCTION_BODY>}
public record JobParameterDefinition(String value, String type, String identifying) {
}
}
|
try {
JobParameterDefinition jobParameterDefinition = this.objectMapper.readValue(encodedJobParameter,
JobParameterDefinition.class);
Class<?> parameterType = String.class;
if (jobParameterDefinition.type() != null) {
parameterType = Class.forName(jobParameterDefinition.type());
}
boolean parameterIdentifying = true;
if (jobParameterDefinition.identifying() != null && !jobParameterDefinition.identifying().isEmpty()) {
parameterIdentifying = Boolean.parseBoolean(jobParameterDefinition.identifying());
}
Object parameterTypedValue = this.conversionService.convert(jobParameterDefinition.value(), parameterType);
return new JobParameter(parameterTypedValue, parameterType, parameterIdentifying);
}
catch (JsonProcessingException | ClassNotFoundException e) {
throw new JobParametersConversionException("Unable to decode job parameter " + encodedJobParameter, e);
}
| 382
| 240
| 622
|
<methods>public void <init>() ,public org.springframework.batch.core.JobParameters getJobParameters(java.util.Properties) ,public java.util.Properties getProperties(org.springframework.batch.core.JobParameters) ,public void setConversionService(org.springframework.core.convert.support.ConfigurableConversionService) <variables>protected org.springframework.core.convert.support.ConfigurableConversionService conversionService
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/explore/support/AbstractJobExplorerFactoryBean.java
|
AbstractJobExplorerFactoryBean
|
afterPropertiesSet
|
class AbstractJobExplorerFactoryBean implements FactoryBean<JobExplorer>, InitializingBean {
private static final String TRANSACTION_ISOLATION_LEVEL_PREFIX = "ISOLATION_";
private static final String TRANSACTION_PROPAGATION_PREFIX = "PROPAGATION_";
private PlatformTransactionManager transactionManager;
private TransactionAttributeSource transactionAttributeSource;
private final ProxyFactory proxyFactory = new ProxyFactory();
/**
* Creates a job instance data access object (DAO).
* @return a fully configured {@link JobInstanceDao} implementation.
* @throws Exception thrown if error occurs during JobInstanceDao creation.
*/
protected abstract JobInstanceDao createJobInstanceDao() throws Exception;
/**
* Creates a job execution data access object (DAO).
* @return a fully configured {@link JobExecutionDao} implementation.
* @throws Exception thrown if error occurs during JobExecutionDao creation.
*/
protected abstract JobExecutionDao createJobExecutionDao() throws Exception;
/**
* Creates a step execution data access object (DAO).
* @return a fully configured {@link StepExecutionDao} implementation.
* @throws Exception thrown if error occurs during StepExecutionDao creation.
*/
protected abstract StepExecutionDao createStepExecutionDao() throws Exception;
/**
* Creates an execution context instance data access object (DAO).
* @return fully configured {@link ExecutionContextDao} implementation.
* @throws Exception thrown if error occurs during ExecutionContextDao creation.
*/
protected abstract ExecutionContextDao createExecutionContextDao() throws Exception;
/**
* Public setter for the {@link PlatformTransactionManager}.
* @param transactionManager the transactionManager to set
* @since 5.0
*/
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
/**
* The transaction manager used in this factory. Useful to inject into steps and jobs,
* to ensure that they are using the same instance.
* @return the transactionManager
* @since 5.0
*/
public PlatformTransactionManager getTransactionManager() {
return this.transactionManager;
}
/**
* Set the transaction attributes source to use in the created proxy.
* @param transactionAttributeSource the transaction attributes source to use in the
* created proxy.
* @since 5.0
*/
public void setTransactionAttributeSource(TransactionAttributeSource transactionAttributeSource) {
Assert.notNull(transactionAttributeSource, "transactionAttributeSource must not be null.");
this.transactionAttributeSource = transactionAttributeSource;
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
/**
* Returns the type of object to be returned from {@link #getObject()}.
* @return {@code JobExplorer.class}
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
*/
@Override
public Class<JobExplorer> getObjectType() {
return JobExplorer.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public JobExplorer getObject() throws Exception {
TransactionInterceptor advice = new TransactionInterceptor((TransactionManager) this.transactionManager,
this.transactionAttributeSource);
proxyFactory.addAdvice(advice);
proxyFactory.setProxyTargetClass(false);
proxyFactory.addInterface(JobExplorer.class);
proxyFactory.setTarget(getTarget());
return (JobExplorer) proxyFactory.getProxy(getClass().getClassLoader());
}
private JobExplorer getTarget() throws Exception {
return new SimpleJobExplorer(createJobInstanceDao(), createJobExecutionDao(), createStepExecutionDao(),
createExecutionContextDao());
}
}
|
Assert.notNull(this.transactionManager, "TransactionManager must not be null.");
if (this.transactionAttributeSource == null) {
Properties transactionAttributes = new Properties();
String transactionProperties = String.join(",", TRANSACTION_PROPAGATION_PREFIX + Propagation.SUPPORTS,
TRANSACTION_ISOLATION_LEVEL_PREFIX + Isolation.DEFAULT);
transactionAttributes.setProperty("get*", transactionProperties);
transactionAttributes.setProperty("find*", transactionProperties);
this.transactionAttributeSource = new NameMatchTransactionAttributeSource();
((NameMatchTransactionAttributeSource) this.transactionAttributeSource)
.setProperties(transactionAttributes);
}
| 950
| 177
| 1,127
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/explore/support/JobExplorerFactoryBean.java
|
JobExplorerFactoryBean
|
afterPropertiesSet
|
class JobExplorerFactoryBean extends AbstractJobExplorerFactoryBean implements InitializingBean {
private DataSource dataSource;
private JdbcOperations jdbcOperations;
private String tablePrefix = AbstractJdbcBatchMetadataDao.DEFAULT_TABLE_PREFIX;
private final DataFieldMaxValueIncrementer incrementer = new AbstractDataFieldMaxValueIncrementer() {
@Override
protected long getNextKey() {
throw new IllegalStateException("JobExplorer is read only.");
}
};
private JobKeyGenerator jobKeyGenerator;
private LobHandler lobHandler;
private ExecutionContextSerializer serializer;
private Charset charset = StandardCharsets.UTF_8;
private ConfigurableConversionService conversionService;
/**
* A custom implementation of {@link ExecutionContextSerializer}. The default, if not
* injected, is the {@link DefaultExecutionContextSerializer}.
* @param serializer The serializer used to serialize or deserialize an
* {@link org.springframework.batch.item.ExecutionContext}.
* @see ExecutionContextSerializer
*/
public void setSerializer(ExecutionContextSerializer serializer) {
this.serializer = serializer;
}
/**
* Sets the data source.
* <p>
* Public setter for the {@link DataSource}.
* @param dataSource A {@code DataSource}.
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* Public setter for the {@link JdbcOperations}. If this property is not explicitly
* set, a new {@link JdbcTemplate} is created, by default, for the configured
* {@link DataSource}.
* @param jdbcOperations a {@link JdbcOperations}
*/
public void setJdbcOperations(JdbcOperations jdbcOperations) {
this.jdbcOperations = jdbcOperations;
}
/**
* Sets the table prefix for all the batch metadata tables.
* @param tablePrefix The table prefix for the batch metadata tables.
*/
public void setTablePrefix(String tablePrefix) {
this.tablePrefix = tablePrefix;
}
/**
* * Sets the generator for creating the key used in identifying unique {link
* JobInstance} objects
* @param jobKeyGenerator a {@link JobKeyGenerator}
* @since 5.1
*/
public void setJobKeyGenerator(JobKeyGenerator jobKeyGenerator) {
this.jobKeyGenerator = jobKeyGenerator;
}
/**
* The lob handler to use when saving {@link ExecutionContext} instances. Defaults to
* {@code null}, which works for most databases.
* @param lobHandler Large object handler for saving an
* {@link org.springframework.batch.item.ExecutionContext}.
*/
public void setLobHandler(LobHandler lobHandler) {
this.lobHandler = lobHandler;
}
/**
* Sets the {@link Charset} to use when deserializing the execution context. Defaults
* to "UTF-8". Must not be {@code null}.
* @param charset The character set to use when deserializing the execution context.
* @see JdbcExecutionContextDao#setCharset(Charset)
* @since 5.0
*/
public void setCharset(@NonNull Charset charset) {
Assert.notNull(charset, "Charset must not be null");
this.charset = charset;
}
/**
* Set the conversion service to use in the job explorer. This service is used to
* convert job parameters from String literal to typed values and vice versa.
* @param conversionService the conversion service to use
* @since 5.0
*/
public void setConversionService(@NonNull ConfigurableConversionService conversionService) {
Assert.notNull(conversionService, "ConversionService must not be null");
this.conversionService = conversionService;
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
@Override
protected ExecutionContextDao createExecutionContextDao() throws Exception {
JdbcExecutionContextDao dao = new JdbcExecutionContextDao();
dao.setJdbcTemplate(jdbcOperations);
dao.setLobHandler(lobHandler);
dao.setTablePrefix(tablePrefix);
dao.setSerializer(serializer);
dao.setCharset(charset);
dao.afterPropertiesSet();
return dao;
}
@Override
protected JobInstanceDao createJobInstanceDao() throws Exception {
JdbcJobInstanceDao dao = new JdbcJobInstanceDao();
dao.setJdbcTemplate(jdbcOperations);
dao.setJobInstanceIncrementer(incrementer);
dao.setJobKeyGenerator(jobKeyGenerator);
dao.setTablePrefix(tablePrefix);
dao.afterPropertiesSet();
return dao;
}
@Override
protected JobExecutionDao createJobExecutionDao() throws Exception {
JdbcJobExecutionDao dao = new JdbcJobExecutionDao();
dao.setJdbcTemplate(jdbcOperations);
dao.setJobExecutionIncrementer(incrementer);
dao.setTablePrefix(tablePrefix);
dao.setConversionService(this.conversionService);
dao.afterPropertiesSet();
return dao;
}
@Override
protected StepExecutionDao createStepExecutionDao() throws Exception {
JdbcStepExecutionDao dao = new JdbcStepExecutionDao();
dao.setJdbcTemplate(jdbcOperations);
dao.setStepExecutionIncrementer(incrementer);
dao.setTablePrefix(tablePrefix);
dao.afterPropertiesSet();
return dao;
}
}
|
Assert.state(dataSource != null, "DataSource must not be null.");
if (jdbcOperations == null) {
jdbcOperations = new JdbcTemplate(dataSource);
}
if (jobKeyGenerator == null) {
jobKeyGenerator = new DefaultJobKeyGenerator();
}
if (serializer == null) {
serializer = new DefaultExecutionContextSerializer();
}
if (this.conversionService == null) {
DefaultConversionService conversionService = new DefaultConversionService();
conversionService.addConverter(new DateToStringConverter());
conversionService.addConverter(new StringToDateConverter());
conversionService.addConverter(new LocalDateToStringConverter());
conversionService.addConverter(new StringToLocalDateConverter());
conversionService.addConverter(new LocalTimeToStringConverter());
conversionService.addConverter(new StringToLocalTimeConverter());
conversionService.addConverter(new LocalDateTimeToStringConverter());
conversionService.addConverter(new StringToLocalDateTimeConverter());
this.conversionService = conversionService;
}
super.afterPropertiesSet();
| 1,464
| 295
| 1,759
|
<methods>public non-sealed void <init>() ,public void afterPropertiesSet() throws java.lang.Exception,public org.springframework.batch.core.explore.JobExplorer getObject() throws java.lang.Exception,public Class<org.springframework.batch.core.explore.JobExplorer> getObjectType() ,public org.springframework.transaction.PlatformTransactionManager getTransactionManager() ,public boolean isSingleton() ,public void setTransactionAttributeSource(org.springframework.transaction.interceptor.TransactionAttributeSource) ,public void setTransactionManager(org.springframework.transaction.PlatformTransactionManager) <variables>private static final java.lang.String TRANSACTION_ISOLATION_LEVEL_PREFIX,private static final java.lang.String TRANSACTION_PROPAGATION_PREFIX,private final org.springframework.aop.framework.ProxyFactory proxyFactory,private org.springframework.transaction.interceptor.TransactionAttributeSource transactionAttributeSource,private org.springframework.transaction.PlatformTransactionManager transactionManager
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/explore/support/SimpleJobExplorer.java
|
SimpleJobExplorer
|
getStepExecution
|
class SimpleJobExplorer implements JobExplorer {
private JobInstanceDao jobInstanceDao;
private JobExecutionDao jobExecutionDao;
private StepExecutionDao stepExecutionDao;
private ExecutionContextDao ecDao;
/**
* Provides a default constructor with low visibility in case you want to use
* aop:proxy-target-class="true" for the AOP interceptor.
*/
SimpleJobExplorer() {
}
/**
* Constructor to initialize the job {@link SimpleJobExplorer}.
* @param jobInstanceDao The {@link JobInstanceDao} to be used by the repository.
* @param jobExecutionDao The {@link JobExecutionDao} to be used by the repository.
* @param stepExecutionDao The {@link StepExecutionDao} to be used by the repository.
* @param ecDao The {@link ExecutionContextDao} to be used by the repository.
*/
public SimpleJobExplorer(JobInstanceDao jobInstanceDao, JobExecutionDao jobExecutionDao,
StepExecutionDao stepExecutionDao, ExecutionContextDao ecDao) {
super();
this.jobInstanceDao = jobInstanceDao;
this.jobExecutionDao = jobExecutionDao;
this.stepExecutionDao = stepExecutionDao;
this.ecDao = ecDao;
}
@Override
public List<JobExecution> getJobExecutions(JobInstance jobInstance) {
List<JobExecution> executions = jobExecutionDao.findJobExecutions(jobInstance);
for (JobExecution jobExecution : executions) {
getJobExecutionDependencies(jobExecution);
for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
getStepExecutionDependencies(stepExecution);
}
}
return executions;
}
@Nullable
@Override
public JobExecution getLastJobExecution(JobInstance jobInstance) {
JobExecution lastJobExecution = jobExecutionDao.getLastJobExecution(jobInstance);
if (lastJobExecution != null) {
getJobExecutionDependencies(lastJobExecution);
for (StepExecution stepExecution : lastJobExecution.getStepExecutions()) {
getStepExecutionDependencies(stepExecution);
}
}
return lastJobExecution;
}
@Override
public Set<JobExecution> findRunningJobExecutions(@Nullable String jobName) {
Set<JobExecution> executions = jobExecutionDao.findRunningJobExecutions(jobName);
for (JobExecution jobExecution : executions) {
getJobExecutionDependencies(jobExecution);
for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
getStepExecutionDependencies(stepExecution);
}
}
return executions;
}
@Nullable
@Override
public JobExecution getJobExecution(@Nullable Long executionId) {
if (executionId == null) {
return null;
}
JobExecution jobExecution = jobExecutionDao.getJobExecution(executionId);
if (jobExecution == null) {
return null;
}
getJobExecutionDependencies(jobExecution);
for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
getStepExecutionDependencies(stepExecution);
}
return jobExecution;
}
@Nullable
@Override
public StepExecution getStepExecution(@Nullable Long jobExecutionId, @Nullable Long executionId) {<FILL_FUNCTION_BODY>}
@Nullable
@Override
public JobInstance getJobInstance(@Nullable Long instanceId) {
return jobInstanceDao.getJobInstance(instanceId);
}
@Nullable
@Override
public JobInstance getJobInstance(String jobName, JobParameters jobParameters) {
return jobInstanceDao.getJobInstance(jobName, jobParameters);
}
@Nullable
@Override
public JobInstance getLastJobInstance(String jobName) {
return jobInstanceDao.getLastJobInstance(jobName);
}
@Override
public List<JobInstance> getJobInstances(String jobName, int start, int count) {
return jobInstanceDao.getJobInstances(jobName, start, count);
}
@Override
public List<String> getJobNames() {
return jobInstanceDao.getJobNames();
}
@Override
public long getJobInstanceCount(@Nullable String jobName) throws NoSuchJobException {
return jobInstanceDao.getJobInstanceCount(jobName);
}
/**
* @return instance of {@link JobInstanceDao}.
* @since 5.1
*/
protected JobInstanceDao getJobInstanceDao() {
return jobInstanceDao;
}
/**
* @return instance of {@link JobExecutionDao}.
* @since 5.1
*/
protected JobExecutionDao getJobExecutionDao() {
return jobExecutionDao;
}
/**
* @return instance of {@link StepExecutionDao}.
* @since 5.1
*/
protected StepExecutionDao getStepExecutionDao() {
return stepExecutionDao;
}
/**
* @return instance of {@link ExecutionContextDao}.
* @since 5.1
*/
protected ExecutionContextDao getEcDao() {
return ecDao;
}
/*
* Find all dependencies for a JobExecution, including JobInstance (which requires
* JobParameters) plus StepExecutions
*/
private void getJobExecutionDependencies(JobExecution jobExecution) {
JobInstance jobInstance = jobInstanceDao.getJobInstance(jobExecution);
stepExecutionDao.addStepExecutions(jobExecution);
jobExecution.setJobInstance(jobInstance);
jobExecution.setExecutionContext(ecDao.getExecutionContext(jobExecution));
}
private void getStepExecutionDependencies(StepExecution stepExecution) {
if (stepExecution != null) {
stepExecution.setExecutionContext(ecDao.getExecutionContext(stepExecution));
}
}
@Override
public List<JobInstance> findJobInstancesByJobName(String jobName, int start, int count) {
return jobInstanceDao.findJobInstancesByName(jobName, start, count);
}
}
|
JobExecution jobExecution = jobExecutionDao.getJobExecution(jobExecutionId);
if (jobExecution == null) {
return null;
}
getJobExecutionDependencies(jobExecution);
StepExecution stepExecution = stepExecutionDao.getStepExecution(jobExecution, executionId);
getStepExecutionDependencies(stepExecution);
return stepExecution;
| 1,543
| 95
| 1,638
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/CompositeJobParametersValidator.java
|
CompositeJobParametersValidator
|
afterPropertiesSet
|
class CompositeJobParametersValidator implements JobParametersValidator, InitializingBean {
private List<JobParametersValidator> validators;
/**
* Validates the JobParameters according to the injected JobParameterValidators
* Validation stops and exception is thrown on first validation error
* @param parameters some {@link JobParameters}
* @throws JobParametersInvalidException if the parameters are invalid
*/
@Override
public void validate(@Nullable JobParameters parameters) throws JobParametersInvalidException {
for (JobParametersValidator validator : validators) {
validator.validate(parameters);
}
}
/**
* Public setter for the validators
* @param validators list of validators to be used by the
* CompositeJobParametersValidator.
*/
public void setValidators(List<JobParametersValidator> validators) {
this.validators = validators;
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
}
|
Assert.state(validators != null, "The 'validators' may not be null");
Assert.state(!validators.isEmpty(), "The 'validators' may not be empty");
| 238
| 50
| 288
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/DefaultJobParametersValidator.java
|
DefaultJobParametersValidator
|
validate
|
class DefaultJobParametersValidator implements JobParametersValidator, InitializingBean {
private static final Log logger = LogFactory.getLog(DefaultJobParametersValidator.class);
private Collection<String> requiredKeys;
private Collection<String> optionalKeys;
/**
* Convenient default constructor for unconstrained validation.
*/
public DefaultJobParametersValidator() {
this(new String[0], new String[0]);
}
/**
* Create a new validator with the required and optional job parameter keys provided.
*
* @see DefaultJobParametersValidator#setOptionalKeys(String[])
* @see DefaultJobParametersValidator#setRequiredKeys(String[])
* @param requiredKeys the required keys
* @param optionalKeys the optional keys
*/
public DefaultJobParametersValidator(String[] requiredKeys, String[] optionalKeys) {
super();
setRequiredKeys(requiredKeys);
setOptionalKeys(optionalKeys);
}
/**
* Check that there are no overlaps between required and optional keys.
* @throws IllegalStateException if there is an overlap
*/
@Override
public void afterPropertiesSet() throws IllegalStateException {
for (String key : requiredKeys) {
Assert.state(!optionalKeys.contains(key), "Optional keys cannot be required: " + key);
}
}
/**
* Check the parameters meet the specification provided. If optional keys are
* explicitly specified then all keys must be in that list, or in the required list.
* Otherwise all keys that are specified as required must be present.
*
* @see JobParametersValidator#validate(JobParameters)
* @throws JobParametersInvalidException if the parameters are not valid
*/
@Override
public void validate(@Nullable JobParameters parameters) throws JobParametersInvalidException {<FILL_FUNCTION_BODY>}
/**
* The keys that are required in the parameters. The default is empty, meaning that
* all parameters are optional, unless optional keys are explicitly specified.
* @param requiredKeys the required key values
*
* @see #setOptionalKeys(String[])
*/
public final void setRequiredKeys(String[] requiredKeys) {
this.requiredKeys = new HashSet<>(Arrays.asList(requiredKeys));
}
/**
* The keys that are optional in the parameters. If any keys are explicitly optional,
* then to be valid all other keys must be explicitly required. The default is empty,
* meaning that all parameters that are not required are optional.
* @param optionalKeys the optional key values
*
* @see #setRequiredKeys(String[])
*/
public final void setOptionalKeys(String[] optionalKeys) {
this.optionalKeys = new HashSet<>(Arrays.asList(optionalKeys));
}
}
|
if (parameters == null) {
throw new JobParametersInvalidException("The JobParameters can not be null");
}
Set<String> keys = parameters.getParameters().keySet();
// If there are explicit optional keys then all keys must be in that
// group, or in the required group.
if (!optionalKeys.isEmpty()) {
Collection<String> missingKeys = new HashSet<>();
for (String key : keys) {
if (!optionalKeys.contains(key) && !requiredKeys.contains(key)) {
missingKeys.add(key);
}
}
if (!missingKeys.isEmpty()) {
logger.warn(
"The JobParameters contains keys that are not explicitly optional or required: " + missingKeys);
}
}
Collection<String> missingKeys = new HashSet<>();
for (String key : requiredKeys) {
if (!keys.contains(key)) {
missingKeys.add(key);
}
}
if (!missingKeys.isEmpty()) {
throw new JobParametersInvalidException("The JobParameters do not contain required keys: " + missingKeys);
}
| 666
| 294
| 960
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/SimpleJob.java
|
SimpleJob
|
doExecute
|
class SimpleJob extends AbstractJob {
private final List<Step> steps = new ArrayList<>();
/**
* Default constructor for job with null name
*/
public SimpleJob() {
this(null);
}
/**
* @param name the job name.
*/
public SimpleJob(String name) {
super(name);
}
/**
* Public setter for the steps in this job. Overrides any calls to
* {@link #addStep(Step)}.
* @param steps the steps to execute
*/
public void setSteps(List<Step> steps) {
this.steps.clear();
this.steps.addAll(steps);
}
/**
* Convenience method for clients to inspect the steps for this job.
* @return the step names for this job
*/
@Override
public Collection<String> getStepNames() {
List<String> names = new ArrayList<>();
for (Step step : steps) {
names.add(step.getName());
if (step instanceof StepLocator) {
names.addAll(((StepLocator) step).getStepNames());
}
}
return names;
}
/**
* Convenience method for adding a single step to the job.
* @param step a {@link Step} to add
*/
public void addStep(Step step) {
this.steps.add(step);
}
@Override
public Step getStep(String stepName) {
for (Step step : this.steps) {
if (step.getName().equals(stepName)) {
return step;
}
else if (step instanceof StepLocator) {
Step result = ((StepLocator) step).getStep(stepName);
if (result != null) {
return result;
}
}
}
return null;
}
/**
* Handler of steps sequentially as provided, checking each one for success before
* moving to the next. Returns the last {@link StepExecution} successfully processed
* if it exists, and null if none were processed.
* @param execution the current {@link JobExecution}
*
* @see AbstractJob#handleStep(Step, JobExecution)
*/
@Override
protected void doExecute(JobExecution execution)
throws JobInterruptedException, JobRestartException, StartLimitExceededException {<FILL_FUNCTION_BODY>}
}
|
StepExecution stepExecution = null;
for (Step step : steps) {
stepExecution = handleStep(step, execution);
if (stepExecution.getStatus() != BatchStatus.COMPLETED) {
//
// Terminate the job if a step fails
//
break;
}
}
//
// Update the job status to be the same as the last step
//
if (stepExecution != null) {
if (logger.isDebugEnabled()) {
logger.debug("Upgrading JobExecution status: " + stepExecution);
}
execution.upgradeStatus(stepExecution.getStatus());
execution.setExitStatus(stepExecution.getExitStatus());
}
| 599
| 184
| 783
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void afterPropertiesSet() throws java.lang.Exception,public final void execute(org.springframework.batch.core.JobExecution) ,public org.springframework.batch.core.JobParametersIncrementer getJobParametersIncrementer() ,public org.springframework.batch.core.JobParametersValidator getJobParametersValidator() ,public java.lang.String getName() ,public abstract org.springframework.batch.core.Step getStep(java.lang.String) ,public abstract Collection<java.lang.String> getStepNames() ,public boolean isRestartable() ,public void registerJobExecutionListener(org.springframework.batch.core.JobExecutionListener) ,public void setBeanName(java.lang.String) ,public void setJobExecutionListeners(org.springframework.batch.core.JobExecutionListener[]) ,public void setJobParametersIncrementer(org.springframework.batch.core.JobParametersIncrementer) ,public void setJobParametersValidator(org.springframework.batch.core.JobParametersValidator) ,public void setJobRepository(org.springframework.batch.core.repository.JobRepository) ,public void setMeterRegistry(io.micrometer.core.instrument.MeterRegistry) ,public void setName(java.lang.String) ,public void setObservationConvention(org.springframework.batch.core.observability.BatchJobObservationConvention) ,public void setObservationRegistry(io.micrometer.observation.ObservationRegistry) ,public void setRestartable(boolean) ,public java.lang.String toString() <variables>private org.springframework.batch.core.JobParametersIncrementer jobParametersIncrementer,private org.springframework.batch.core.JobParametersValidator jobParametersValidator,private org.springframework.batch.core.repository.JobRepository jobRepository,private final org.springframework.batch.core.listener.CompositeJobExecutionListener listener,protected static final org.apache.commons.logging.Log logger,private io.micrometer.core.instrument.MeterRegistry meterRegistry,private java.lang.String name,private org.springframework.batch.core.observability.BatchJobObservationConvention observationConvention,private io.micrometer.observation.ObservationRegistry observationRegistry,private boolean restartable,private org.springframework.batch.core.job.StepHandler stepHandler
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/SimpleStepHandler.java
|
SimpleStepHandler
|
shouldStart
|
class SimpleStepHandler implements StepHandler, InitializingBean {
private static final Log logger = LogFactory.getLog(SimpleStepHandler.class);
private JobRepository jobRepository;
private ExecutionContext executionContext;
/**
* Convenient default constructor for configuration usage.
*/
public SimpleStepHandler() {
this(null);
}
/**
* @param jobRepository a
* {@link org.springframework.batch.core.repository.JobRepository}
*/
public SimpleStepHandler(JobRepository jobRepository) {
this(jobRepository, new ExecutionContext());
}
/**
* @param jobRepository a
* {@link org.springframework.batch.core.repository.JobRepository}
* @param executionContext the {@link org.springframework.batch.item.ExecutionContext}
* for the current Step
*/
public SimpleStepHandler(JobRepository jobRepository, ExecutionContext executionContext) {
this.jobRepository = jobRepository;
this.executionContext = executionContext;
}
/**
* Check mandatory properties (jobRepository).
*
* @see InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(jobRepository != null, "A JobRepository must be provided");
}
/**
* @return the used jobRepository
*/
protected JobRepository getJobRepository() {
return this.jobRepository;
}
/**
* @param jobRepository the jobRepository to set
*/
public void setJobRepository(JobRepository jobRepository) {
this.jobRepository = jobRepository;
}
/**
* A context containing values to be added to the step execution before it is handled.
* @param executionContext the execution context to set
*/
public void setExecutionContext(ExecutionContext executionContext) {
this.executionContext = executionContext;
}
@Override
public StepExecution handleStep(Step step, JobExecution execution)
throws JobInterruptedException, JobRestartException, StartLimitExceededException {
if (execution.isStopping()) {
throw new JobInterruptedException("JobExecution interrupted.");
}
JobInstance jobInstance = execution.getJobInstance();
StepExecution lastStepExecution = jobRepository.getLastStepExecution(jobInstance, step.getName());
if (stepExecutionPartOfExistingJobExecution(execution, lastStepExecution)) {
// If the last execution of this step was in the same job, it's
// probably intentional so we want to run it again...
if (logger.isInfoEnabled()) {
logger.info(String.format(
"Duplicate step [%s] detected in execution of job=[%s]. "
+ "If either step fails, both will be executed again on restart.",
step.getName(), jobInstance.getJobName()));
}
lastStepExecution = null;
}
StepExecution currentStepExecution = lastStepExecution;
if (shouldStart(lastStepExecution, execution, step)) {
currentStepExecution = execution.createStepExecution(step.getName());
boolean isRestart = (lastStepExecution != null
&& !lastStepExecution.getStatus().equals(BatchStatus.COMPLETED));
if (isRestart) {
currentStepExecution.setExecutionContext(lastStepExecution.getExecutionContext());
if (lastStepExecution.getExecutionContext().containsKey("batch.executed")) {
currentStepExecution.getExecutionContext().remove("batch.executed");
}
}
else {
currentStepExecution.setExecutionContext(new ExecutionContext(executionContext));
}
jobRepository.add(currentStepExecution);
if (logger.isInfoEnabled()) {
logger.info("Executing step: [" + step.getName() + "]");
}
try {
step.execute(currentStepExecution);
currentStepExecution.getExecutionContext().put("batch.executed", true);
}
catch (JobInterruptedException e) {
// Ensure that the job gets the message that it is stopping
// and can pass it on to other steps that are executing
// concurrently.
execution.setStatus(BatchStatus.STOPPING);
throw e;
}
jobRepository.updateExecutionContext(execution);
if (currentStepExecution.getStatus() == BatchStatus.STOPPING
|| currentStepExecution.getStatus() == BatchStatus.STOPPED) {
// Ensure that the job gets the message that it is stopping
execution.setStatus(BatchStatus.STOPPING);
throw new JobInterruptedException("Job interrupted by step execution");
}
}
return currentStepExecution;
}
/**
* Detect whether a step execution belongs to this job execution.
* @param jobExecution the current job execution
* @param stepExecution an existing step execution
* @return true if the {@link org.springframework.batch.core.StepExecution} is part of
* the {@link org.springframework.batch.core.JobExecution}
*/
private boolean stepExecutionPartOfExistingJobExecution(JobExecution jobExecution, StepExecution stepExecution) {
return stepExecution != null && stepExecution.getJobExecutionId() != null
&& stepExecution.getJobExecutionId().equals(jobExecution.getId());
}
/**
* Given a step and configuration, return true if the step should start, false if it
* should not, and throw an exception if the job should finish.
* @param lastStepExecution the last step execution
* @param jobExecution the {@link JobExecution} instance to be evaluated.
* @param step the {@link Step} instance to be evaluated.
* @return true if step should start, false if it should not.
* @throws StartLimitExceededException if the start limit has been exceeded for this
* step
* @throws JobRestartException if the job is in an inconsistent state from an earlier
* failure
*/
protected boolean shouldStart(StepExecution lastStepExecution, JobExecution jobExecution, Step step)
throws JobRestartException, StartLimitExceededException {<FILL_FUNCTION_BODY>}
}
|
BatchStatus stepStatus;
if (lastStepExecution == null) {
stepStatus = BatchStatus.STARTING;
}
else {
stepStatus = lastStepExecution.getStatus();
}
if (stepStatus == BatchStatus.UNKNOWN) {
throw new JobRestartException("Cannot restart step from UNKNOWN status. "
+ "The last execution ended with a failure that could not be rolled back, "
+ "so it may be dangerous to proceed. Manual intervention is probably necessary.");
}
if ((stepStatus == BatchStatus.COMPLETED && !step.isAllowStartIfComplete())
|| stepStatus == BatchStatus.ABANDONED) {
// step is complete, false should be returned, indicating that the
// step should not be started
if (logger.isInfoEnabled()) {
logger.info("Step already complete or not restartable, so no action to execute: " + lastStepExecution);
}
return false;
}
if (jobRepository.getStepExecutionCount(jobExecution.getJobInstance(), step.getName()) < step.getStartLimit()) {
// step start count is less than start max, return true
return true;
}
else {
// start max has been exceeded, throw an exception.
throw new StartLimitExceededException(
"Maximum start limit exceeded for step: " + step.getName() + "StartMax: " + step.getStartLimit());
}
| 1,517
| 369
| 1,886
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/FlowJobBuilder.java
|
FlowJobBuilder
|
build
|
class FlowJobBuilder extends JobBuilderHelper<FlowJobBuilder> {
private Flow flow;
/**
* Create a new builder initialized with any properties in the parent. The parent is
* copied, so it can be re-used.
* @param parent a parent helper containing common job properties
*/
public FlowJobBuilder(JobBuilderHelper<?> parent) {
super(parent);
}
/**
* Start a job with this flow, but expect to transition from there to other flows or
* steps.
* @param flow the flow to start with
* @return a builder to enable fluent chaining
*/
public JobFlowBuilder start(Flow flow) {
return new JobFlowBuilder(this, flow);
}
/**
* Start a job with this step, but expect to transition from there to other flows or
* steps.
* @param step the step to start with
* @return a builder to enable fluent chaining
*/
public JobFlowBuilder start(Step step) {
return new JobFlowBuilder(this, step);
}
/**
* Start a job with this decider, but expect to transition from there to other flows
* or steps.
* @param decider the decider to start with
* @return a builder to enable fluent chaining
* @since 5.1
*/
public JobFlowBuilder start(JobExecutionDecider decider) {
return new JobFlowBuilder(this, decider);
}
/**
* Provide a single flow to execute as the job.
* @param flow the flow to execute
* @return this for fluent chaining
*/
protected FlowJobBuilder flow(Flow flow) {
this.flow = flow;
return this;
}
/**
* Build a job that executes the flow provided, normally composed of other steps.
* @return a flow job
*/
public Job build() {<FILL_FUNCTION_BODY>}
}
|
FlowJob job = new FlowJob();
job.setName(getName());
job.setFlow(flow);
super.enhance(job);
try {
job.afterPropertiesSet();
}
catch (Exception e) {
throw new StepBuilderException(e);
}
return job;
| 474
| 90
| 564
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, org.springframework.batch.core.repository.JobRepository) ,public org.springframework.batch.core.job.builder.FlowJobBuilder incrementer(org.springframework.batch.core.JobParametersIncrementer) ,public org.springframework.batch.core.job.builder.FlowJobBuilder listener(java.lang.Object) ,public org.springframework.batch.core.job.builder.FlowJobBuilder listener(org.springframework.batch.core.JobExecutionListener) ,public org.springframework.batch.core.job.builder.FlowJobBuilder meterRegistry(io.micrometer.core.instrument.MeterRegistry) ,public org.springframework.batch.core.job.builder.FlowJobBuilder observationConvention(org.springframework.batch.core.observability.BatchJobObservationConvention) ,public org.springframework.batch.core.job.builder.FlowJobBuilder observationRegistry(io.micrometer.observation.ObservationRegistry) ,public org.springframework.batch.core.job.builder.FlowJobBuilder preventRestart() ,public org.springframework.batch.core.job.builder.FlowJobBuilder repository(org.springframework.batch.core.repository.JobRepository) ,public org.springframework.batch.core.job.builder.FlowJobBuilder validator(org.springframework.batch.core.JobParametersValidator) <variables>protected final org.apache.commons.logging.Log logger,private final non-sealed org.springframework.batch.core.job.builder.JobBuilderHelper.CommonJobProperties properties
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/JobFlowBuilder.java
|
JobFlowBuilder
|
build
|
class JobFlowBuilder extends FlowBuilder<FlowJobBuilder> {
private final FlowJobBuilder parent;
public JobFlowBuilder(FlowJobBuilder parent) {
super(parent.getName());
this.parent = parent;
}
public JobFlowBuilder(FlowJobBuilder parent, Step step) {
super(parent.getName());
this.parent = parent;
start(step);
}
public JobFlowBuilder(FlowJobBuilder parent, JobExecutionDecider decider) {
super(parent.getName());
this.parent = parent;
start(decider);
}
public JobFlowBuilder(FlowJobBuilder parent, Flow flow) {
super(parent.getName());
this.parent = parent;
start(flow);
}
/**
* Build a flow and inject it into the parent builder. The parent builder is then
* returned so it can be enhanced before building an actual job. Normally called
* explicitly via {@link #end()}.
*
* @see org.springframework.batch.core.job.builder.FlowBuilder#build()
*/
@Override
public FlowJobBuilder build() {<FILL_FUNCTION_BODY>}
}
|
Flow flow = flow();
if (flow instanceof InitializingBean) {
try {
((InitializingBean) flow).afterPropertiesSet();
}
catch (Exception e) {
throw new FlowBuilderException(e);
}
}
parent.flow(flow);
return parent;
| 291
| 86
| 377
|
<methods>public void <init>(java.lang.String) ,public org.springframework.batch.core.job.builder.FlowJobBuilder build() ,public final org.springframework.batch.core.job.builder.FlowJobBuilder end() ,public FlowBuilder<org.springframework.batch.core.job.builder.FlowJobBuilder> from(org.springframework.batch.core.Step) ,public UnterminatedFlowBuilder<org.springframework.batch.core.job.builder.FlowJobBuilder> from(org.springframework.batch.core.job.flow.JobExecutionDecider) ,public FlowBuilder<org.springframework.batch.core.job.builder.FlowJobBuilder> from(org.springframework.batch.core.job.flow.Flow) ,public FlowBuilder<org.springframework.batch.core.job.builder.FlowJobBuilder> next(org.springframework.batch.core.Step) ,public UnterminatedFlowBuilder<org.springframework.batch.core.job.builder.FlowJobBuilder> next(org.springframework.batch.core.job.flow.JobExecutionDecider) ,public FlowBuilder<org.springframework.batch.core.job.builder.FlowJobBuilder> next(org.springframework.batch.core.job.flow.Flow) ,public TransitionBuilder<org.springframework.batch.core.job.builder.FlowJobBuilder> on(java.lang.String) ,public SplitBuilder<org.springframework.batch.core.job.builder.FlowJobBuilder> split(org.springframework.core.task.TaskExecutor) ,public FlowBuilder<org.springframework.batch.core.job.builder.FlowJobBuilder> start(org.springframework.batch.core.Step) ,public UnterminatedFlowBuilder<org.springframework.batch.core.job.builder.FlowJobBuilder> start(org.springframework.batch.core.job.flow.JobExecutionDecider) ,public FlowBuilder<org.springframework.batch.core.job.builder.FlowJobBuilder> start(org.springframework.batch.core.job.flow.Flow) <variables>private final non-sealed org.springframework.batch.core.job.flow.support.state.EndState completedState,private org.springframework.batch.core.job.flow.State currentState,private int decisionCounter,private boolean dirty,private int endCounter,private final non-sealed org.springframework.batch.core.job.flow.support.state.EndState failedState,private org.springframework.batch.core.job.flow.support.SimpleFlow flow,private int flowCounter,private final non-sealed java.lang.String name,private final non-sealed java.lang.String prefix,private int splitCounter,private final Map<java.lang.Object,org.springframework.batch.core.job.flow.State> states,private int stepCounter,private final non-sealed org.springframework.batch.core.job.flow.support.state.EndState stoppedState,private final Map<java.lang.String,org.springframework.batch.core.job.flow.State> tos,private final List<org.springframework.batch.core.job.flow.support.StateTransition> transitions
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/SimpleJobBuilder.java
|
SimpleJobBuilder
|
on
|
class SimpleJobBuilder extends JobBuilderHelper<SimpleJobBuilder> {
private final List<Step> steps = new ArrayList<>();
private JobFlowBuilder builder;
/**
* Create a new builder initialized with any properties in the parent. The parent is
* copied, so it can be re-used.
* @param parent the parent to use
*/
public SimpleJobBuilder(JobBuilderHelper<?> parent) {
super(parent);
}
public Job build() {
if (builder != null) {
return builder.end().build();
}
SimpleJob job = new SimpleJob(getName());
super.enhance(job);
job.setSteps(steps);
try {
job.afterPropertiesSet();
}
catch (Exception e) {
throw new JobBuilderException(e);
}
return job;
}
/**
* Start the job with this step.
* @param step a step to start with
* @return this for fluent chaining
*/
public SimpleJobBuilder start(Step step) {
if (steps.isEmpty()) {
steps.add(step);
}
else {
steps.set(0, step);
}
return this;
}
/**
* Branch into a flow conditional on the outcome of the current step.
* @param pattern a pattern for the exit status of the current step
* @return a builder for fluent chaining
*/
public FlowBuilder.TransitionBuilder<FlowJobBuilder> on(String pattern) {<FILL_FUNCTION_BODY>}
/**
* Start with this decider. Returns a flow builder and when the flow is ended a job
* builder will be returned to continue the job configuration if needed.
* @param decider a decider to execute first
* @return builder for fluent chaining
*/
public JobFlowBuilder start(JobExecutionDecider decider) {
if (builder == null) {
builder = new JobFlowBuilder(new FlowJobBuilder(this), decider);
}
else {
builder.start(decider);
}
if (!steps.isEmpty()) {
steps.remove(0);
}
for (Step step : steps) {
builder.next(step);
}
return builder;
}
/**
* Continue with this decider if the previous step was successful. Returns a flow
* builder and when the flow is ended a job builder will be returned to continue the
* job configuration if needed.
* @param decider a decider to execute next
* @return builder for fluent chaining
*/
public JobFlowBuilder next(JobExecutionDecider decider) {
for (Step step : steps) {
if (builder == null) {
builder = new JobFlowBuilder(new FlowJobBuilder(this), step);
}
else {
builder.next(step);
}
}
if (builder == null) {
builder = new JobFlowBuilder(new FlowJobBuilder(this), decider);
}
else {
builder.next(decider);
}
return builder;
}
/**
* Continue or end a job with this step if the previous step was successful.
* @param step a step to execute next
* @return this for fluent chaining
*/
public SimpleJobBuilder next(Step step) {
steps.add(step);
return this;
}
/**
* @param executor instance of {@link TaskExecutor} to be used.
* @return builder for fluent chaining
*/
public JobFlowBuilder.SplitBuilder<FlowJobBuilder> split(TaskExecutor executor) {
for (Step step : steps) {
if (builder == null) {
builder = new JobFlowBuilder(new FlowJobBuilder(this), step);
}
else {
builder.next(step);
}
}
if (builder == null) {
builder = new JobFlowBuilder(new FlowJobBuilder(this));
}
return builder.split(executor);
}
}
|
Assert.state(steps.size() > 0, "You have to start a job with a step");
for (Step step : steps) {
if (builder == null) {
builder = new JobFlowBuilder(new FlowJobBuilder(this), step);
}
else {
builder.next(step);
}
}
return builder.on(pattern);
| 1,017
| 97
| 1,114
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, org.springframework.batch.core.repository.JobRepository) ,public org.springframework.batch.core.job.builder.SimpleJobBuilder incrementer(org.springframework.batch.core.JobParametersIncrementer) ,public org.springframework.batch.core.job.builder.SimpleJobBuilder listener(java.lang.Object) ,public org.springframework.batch.core.job.builder.SimpleJobBuilder listener(org.springframework.batch.core.JobExecutionListener) ,public org.springframework.batch.core.job.builder.SimpleJobBuilder meterRegistry(io.micrometer.core.instrument.MeterRegistry) ,public org.springframework.batch.core.job.builder.SimpleJobBuilder observationConvention(org.springframework.batch.core.observability.BatchJobObservationConvention) ,public org.springframework.batch.core.job.builder.SimpleJobBuilder observationRegistry(io.micrometer.observation.ObservationRegistry) ,public org.springframework.batch.core.job.builder.SimpleJobBuilder preventRestart() ,public org.springframework.batch.core.job.builder.SimpleJobBuilder repository(org.springframework.batch.core.repository.JobRepository) ,public org.springframework.batch.core.job.builder.SimpleJobBuilder validator(org.springframework.batch.core.JobParametersValidator) <variables>protected final org.apache.commons.logging.Log logger,private final non-sealed org.springframework.batch.core.job.builder.JobBuilderHelper.CommonJobProperties properties
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/FlowExecutionStatus.java
|
FlowExecutionStatus
|
compareTo
|
class FlowExecutionStatus implements Comparable<FlowExecutionStatus> {
/**
* Special well-known status value.
*/
public static final FlowExecutionStatus COMPLETED = new FlowExecutionStatus(Status.COMPLETED.toString());
/**
* Special well-known status value.
*/
public static final FlowExecutionStatus STOPPED = new FlowExecutionStatus(Status.STOPPED.toString());
/**
* Special well-known status value.
*/
public static final FlowExecutionStatus FAILED = new FlowExecutionStatus(Status.FAILED.toString());
/**
* Special well-known status value.
*/
public static final FlowExecutionStatus UNKNOWN = new FlowExecutionStatus(Status.UNKNOWN.toString());
private final String name;
private enum Status {
COMPLETED, STOPPED, FAILED, UNKNOWN;
static Status match(String value) {
for (int i = 0; i < values().length; i++) {
Status status = values()[i];
if (value.startsWith(status.toString())) {
return status;
}
}
// Default match should be the lowest priority
return COMPLETED;
}
}
/**
* @param status String status value.
*/
public FlowExecutionStatus(String status) {
this.name = status;
}
/**
* @return true if the status starts with "STOPPED"
*/
public boolean isStop() {
return name.startsWith(STOPPED.getName());
}
/**
* @return true if the status starts with "FAILED"
*/
public boolean isFail() {
return name.startsWith(FAILED.getName());
}
/**
* @return true if this status represents the end of a flow
*/
public boolean isEnd() {
return isStop() || isFail() || isComplete();
}
/**
* @return true if the status starts with "COMPLETED"
*/
private boolean isComplete() {
return name.startsWith(COMPLETED.getName());
}
/**
* Create an ordering on {@link FlowExecutionStatus} instances by comparing their
* statuses.
*
* @see Comparable#compareTo(Object)
* @param other instance of {@link FlowExecutionStatus} to compare this instance with.
* @return negative, zero or positive as per the contract
*/
@Override
public int compareTo(FlowExecutionStatus other) {<FILL_FUNCTION_BODY>}
/**
* Check the equality of the statuses.
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof FlowExecutionStatus other)) {
return false;
}
return name.equals(other.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
/**
* @see Object#toString()
*/
@Override
public String toString() {
return name;
}
/**
* @return the name of this status
*/
public String getName() {
return name;
}
}
|
Status one = Status.match(this.name);
Status two = Status.match(other.name);
int comparison = one.compareTo(two);
if (comparison == 0) {
return this.name.compareTo(other.name);
}
return comparison;
| 822
| 75
| 897
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/FlowJob.java
|
FlowJob
|
doExecute
|
class FlowJob extends AbstractJob {
protected Flow flow;
private final Map<String, Step> stepMap = new ConcurrentHashMap<>();
private volatile boolean initialized = false;
/**
* Create a {@link FlowJob} with null name and no flow (invalid state).
*/
public FlowJob() {
super();
}
/**
* Create a {@link FlowJob} with provided name and no flow (invalid state).
* @param name the name to be associated with the FlowJob.
*/
public FlowJob(String name) {
super(name);
}
/**
* Public setter for the flow.
* @param flow the flow to set
*/
public void setFlow(Flow flow) {
this.flow = flow;
}
/**
* {@inheritDoc}
*/
@Override
public Step getStep(String stepName) {
if (!initialized) {
init();
}
return stepMap.get(stepName);
}
/**
* Initialize the step names
*/
private void init() {
findSteps(flow, stepMap);
initialized = true;
}
private void findSteps(Flow flow, Map<String, Step> map) {
for (State state : flow.getStates()) {
if (state instanceof StepLocator locator) {
for (String name : locator.getStepNames()) {
map.put(name, locator.getStep(name));
}
}
else if (state instanceof StepHolder) {
Step step = ((StepHolder) state).getStep();
String name = step.getName();
stepMap.put(name, step);
}
else if (state instanceof FlowHolder) {
for (Flow subflow : ((FlowHolder) state).getFlows()) {
findSteps(subflow, map);
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public Collection<String> getStepNames() {
if (!initialized) {
init();
}
return stepMap.keySet();
}
/**
* @see AbstractJob#doExecute(JobExecution)
*/
@Override
protected void doExecute(final JobExecution execution) throws JobExecutionException {<FILL_FUNCTION_BODY>}
}
|
try {
JobFlowExecutor executor = new JobFlowExecutor(getJobRepository(),
new SimpleStepHandler(getJobRepository()), execution);
executor.updateJobExecutionStatus(flow.start(executor).getStatus());
}
catch (FlowExecutionException e) {
if (e.getCause() instanceof JobExecutionException) {
throw (JobExecutionException) e.getCause();
}
throw new JobExecutionException("Flow execution ended unexpectedly", e);
}
| 586
| 129
| 715
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void afterPropertiesSet() throws java.lang.Exception,public final void execute(org.springframework.batch.core.JobExecution) ,public org.springframework.batch.core.JobParametersIncrementer getJobParametersIncrementer() ,public org.springframework.batch.core.JobParametersValidator getJobParametersValidator() ,public java.lang.String getName() ,public abstract org.springframework.batch.core.Step getStep(java.lang.String) ,public abstract Collection<java.lang.String> getStepNames() ,public boolean isRestartable() ,public void registerJobExecutionListener(org.springframework.batch.core.JobExecutionListener) ,public void setBeanName(java.lang.String) ,public void setJobExecutionListeners(org.springframework.batch.core.JobExecutionListener[]) ,public void setJobParametersIncrementer(org.springframework.batch.core.JobParametersIncrementer) ,public void setJobParametersValidator(org.springframework.batch.core.JobParametersValidator) ,public void setJobRepository(org.springframework.batch.core.repository.JobRepository) ,public void setMeterRegistry(io.micrometer.core.instrument.MeterRegistry) ,public void setName(java.lang.String) ,public void setObservationConvention(org.springframework.batch.core.observability.BatchJobObservationConvention) ,public void setObservationRegistry(io.micrometer.observation.ObservationRegistry) ,public void setRestartable(boolean) ,public java.lang.String toString() <variables>private org.springframework.batch.core.JobParametersIncrementer jobParametersIncrementer,private org.springframework.batch.core.JobParametersValidator jobParametersValidator,private org.springframework.batch.core.repository.JobRepository jobRepository,private final org.springframework.batch.core.listener.CompositeJobExecutionListener listener,protected static final org.apache.commons.logging.Log logger,private io.micrometer.core.instrument.MeterRegistry meterRegistry,private java.lang.String name,private org.springframework.batch.core.observability.BatchJobObservationConvention observationConvention,private io.micrometer.observation.ObservationRegistry observationRegistry,private boolean restartable,private org.springframework.batch.core.job.StepHandler stepHandler
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/FlowStep.java
|
FlowStep
|
doExecute
|
class FlowStep extends AbstractStep {
private Flow flow;
/**
* Default constructor convenient for configuration purposes.
*/
public FlowStep() {
super(null);
}
/**
* Constructor for a {@link FlowStep} that sets the flow and of the step explicitly.
* @param flow the {@link Flow} instance to be associated with this step.
*/
public FlowStep(Flow flow) {
super(flow.getName());
}
/**
* Public setter for the flow.
* @param flow the flow to set
*/
public void setFlow(Flow flow) {
this.flow = flow;
}
/**
* Ensure that the flow is set.
* @see AbstractStep#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(flow != null, "A Flow must be provided");
if (getName() == null) {
setName(flow.getName());
}
super.afterPropertiesSet();
}
/**
* Delegate to the flow provided for the execution of the step.
*
* @see AbstractStep#doExecute(StepExecution)
*/
@Override
protected void doExecute(StepExecution stepExecution) throws Exception {<FILL_FUNCTION_BODY>}
}
|
try {
stepExecution.getExecutionContext().put(STEP_TYPE_KEY, this.getClass().getName());
StepHandler stepHandler = new SimpleStepHandler(getJobRepository(), stepExecution.getExecutionContext());
FlowExecutor executor = new JobFlowExecutor(getJobRepository(), stepHandler,
stepExecution.getJobExecution());
executor.updateJobExecutionStatus(flow.start(executor).getStatus());
stepExecution.upgradeStatus(executor.getJobExecution().getStatus());
stepExecution.setExitStatus(executor.getJobExecution().getExitStatus());
}
catch (FlowExecutionException e) {
if (e.getCause() instanceof JobExecutionException) {
throw (JobExecutionException) e.getCause();
}
throw new JobExecutionException("Flow execution ended unexpectedly", e);
}
| 326
| 217
| 543
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void afterPropertiesSet() throws java.lang.Exception,public final void execute(org.springframework.batch.core.StepExecution) throws org.springframework.batch.core.JobInterruptedException, org.springframework.batch.core.UnexpectedJobExecutionException,public java.lang.String getName() ,public int getStartLimit() ,public boolean isAllowStartIfComplete() ,public void registerStepExecutionListener(org.springframework.batch.core.StepExecutionListener) ,public void setAllowStartIfComplete(boolean) ,public void setBeanName(java.lang.String) ,public void setJobRepository(org.springframework.batch.core.repository.JobRepository) ,public void setMeterRegistry(io.micrometer.core.instrument.MeterRegistry) ,public void setName(java.lang.String) ,public void setObservationConvention(org.springframework.batch.core.observability.BatchStepObservationConvention) ,public void setObservationRegistry(io.micrometer.observation.ObservationRegistry) ,public void setStartLimit(int) ,public void setStepExecutionListeners(org.springframework.batch.core.StepExecutionListener[]) ,public java.lang.String toString() <variables>private boolean allowStartIfComplete,private org.springframework.batch.core.repository.JobRepository jobRepository,private static final org.apache.commons.logging.Log logger,private io.micrometer.core.instrument.MeterRegistry meterRegistry,private java.lang.String name,private org.springframework.batch.core.observability.BatchStepObservationConvention observationConvention,private io.micrometer.observation.ObservationRegistry observationRegistry,private int startLimit,private final org.springframework.batch.core.listener.CompositeStepExecutionListener stepExecutionListener
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/JobFlowExecutor.java
|
JobFlowExecutor
|
executeStep
|
class JobFlowExecutor implements FlowExecutor {
private final ThreadLocal<StepExecution> stepExecutionHolder = new ThreadLocal<>();
private final JobExecution execution;
protected ExitStatus exitStatus = ExitStatus.EXECUTING;
private final StepHandler stepHandler;
private final JobRepository jobRepository;
/**
* @param jobRepository instance of {@link JobRepository}.
* @param stepHandler instance of {@link StepHandler}.
* @param execution instance of {@link JobExecution}.
*/
public JobFlowExecutor(JobRepository jobRepository, StepHandler stepHandler, JobExecution execution) {
this.jobRepository = jobRepository;
this.stepHandler = stepHandler;
this.execution = execution;
stepExecutionHolder.set(null);
}
@Override
public String executeStep(Step step)
throws JobInterruptedException, JobRestartException, StartLimitExceededException {<FILL_FUNCTION_BODY>}
private boolean isStepRestart(Step step) {
long count = jobRepository.getStepExecutionCount(execution.getJobInstance(), step.getName());
return count > 0;
}
@Override
public void abandonStepExecution() {
StepExecution lastStepExecution = stepExecutionHolder.get();
if (lastStepExecution != null && lastStepExecution.getStatus().isGreaterThan(BatchStatus.STOPPING)) {
lastStepExecution.upgradeStatus(BatchStatus.ABANDONED);
jobRepository.update(lastStepExecution);
}
}
@Override
public void updateJobExecutionStatus(FlowExecutionStatus status) {
execution.setStatus(findBatchStatus(status));
exitStatus = exitStatus.and(new ExitStatus(status.getName()));
execution.setExitStatus(exitStatus);
}
@Override
public JobExecution getJobExecution() {
return execution;
}
@Override
@Nullable
public StepExecution getStepExecution() {
return stepExecutionHolder.get();
}
@Override
public void close(FlowExecution result) {
stepExecutionHolder.set(null);
}
@Override
public boolean isRestart() {
if (getStepExecution() != null && getStepExecution().getStatus() == BatchStatus.ABANDONED) {
/*
* This is assumed to be the last step execution and it was marked abandoned,
* so we are in a restart of a stopped step.
*/
// TODO: mark the step execution in some more definitive way?
return true;
}
return execution.getStepExecutions().isEmpty();
}
@Override
public void addExitStatus(String code) {
exitStatus = exitStatus.and(new ExitStatus(code));
}
/**
* @param status {@link FlowExecutionStatus} to convert.
* @return A {@link BatchStatus} appropriate for the {@link FlowExecutionStatus}
* provided
*/
protected BatchStatus findBatchStatus(FlowExecutionStatus status) {
for (BatchStatus batchStatus : BatchStatus.values()) {
if (status.getName().startsWith(batchStatus.toString())) {
return batchStatus;
}
}
return BatchStatus.UNKNOWN;
}
}
|
boolean isRerun = isStepRestart(step);
StepExecution stepExecution = stepHandler.handleStep(step, execution);
stepExecutionHolder.set(stepExecution);
if (stepExecution == null) {
return ExitStatus.COMPLETED.getExitCode();
}
if (stepExecution.isTerminateOnly()) {
throw new JobInterruptedException("Step requested termination: " + stepExecution,
stepExecution.getStatus());
}
if (isRerun) {
stepExecution.getExecutionContext().put("batch.restart", true);
}
return stepExecution.getExitStatus().getExitCode();
| 788
| 170
| 958
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/DefaultStateTransitionComparator.java
|
DefaultStateTransitionComparator
|
compare
|
class DefaultStateTransitionComparator implements Comparator<StateTransition> {
public static final String STATE_TRANSITION_COMPARATOR = "batch_state_transition_comparator";
@Override
public int compare(StateTransition arg0, StateTransition arg1) {<FILL_FUNCTION_BODY>}
}
|
String arg0Pattern = arg0.getPattern();
String arg1Pattern = arg1.getPattern();
if (arg0.getPattern().equals(arg1Pattern)) {
return 0;
}
int arg0AsteriskCount = StringUtils.countOccurrencesOf(arg0Pattern, "*");
int arg1AsteriskCount = StringUtils.countOccurrencesOf(arg1Pattern, "*");
if (arg0AsteriskCount > 0 && arg1AsteriskCount == 0) {
return -1;
}
if (arg0AsteriskCount == 0 && arg1AsteriskCount > 0) {
return 1;
}
if (arg0AsteriskCount > 0 && arg1AsteriskCount > 0) {
if (arg0AsteriskCount < arg1AsteriskCount) {
return -1;
}
if (arg0AsteriskCount > arg1AsteriskCount) {
return 1;
}
}
int arg0WildcardCount = StringUtils.countOccurrencesOf(arg0Pattern, "?");
int arg1WildcardCount = StringUtils.countOccurrencesOf(arg1Pattern, "?");
if (arg0WildcardCount > arg1WildcardCount) {
return -1;
}
if (arg0WildcardCount < arg1WildcardCount) {
return 1;
}
if (arg0Pattern.length() != arg1Pattern.length() && (arg0AsteriskCount > 0 || arg0WildcardCount > 0)) {
return Integer.compare(arg0Pattern.length(), arg1Pattern.length());
}
return arg1.getPattern().compareTo(arg0Pattern);
| 84
| 442
| 526
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/StateTransition.java
|
StateTransition
|
toString
|
class StateTransition {
private final State state;
private final String pattern;
private final String next;
/**
* @return the pattern the {@link ExitStatus#getExitCode()} will be compared against.
*/
public String getPattern() {
return this.pattern;
}
/**
* Create a new end state {@link StateTransition} specification. This transition
* explicitly goes unconditionally to an end state (i.e. no more executions).
* @param state the {@link State} used to generate the outcome for this transition
* @return {@link StateTransition} that was created.
*/
public static StateTransition createEndStateTransition(State state) {
return createStateTransition(state, null, null);
}
/**
* Create a new end state {@link StateTransition} specification. This transition
* explicitly goes to an end state (i.e. no more processing) if the outcome matches
* the pattern.
* @param state the {@link State} used to generate the outcome for this transition
* @param pattern the pattern to match in the exit status of the {@link State}
* @return {@link StateTransition} that was created.
*/
public static StateTransition createEndStateTransition(State state, String pattern) {
return createStateTransition(state, pattern, null);
}
/**
* Convenience method to switch the origin and destination of a transition, creating a
* new instance.
* @param stateTransition an existing state transition
* @param state the new state for the origin
* @param next the new name for the destination
* @return {@link StateTransition} that was created.
*/
public static StateTransition switchOriginAndDestination(StateTransition stateTransition, State state,
String next) {
return createStateTransition(state, stateTransition.pattern, next);
}
/**
* Create a new state {@link StateTransition} specification with a wildcard pattern
* that matches all outcomes.
* @param state the {@link State} used to generate the outcome for this transition
* @param next the name of the next {@link State} to execute
* @return {@link StateTransition} that was created.
*/
public static StateTransition createStateTransition(State state, String next) {
return createStateTransition(state, null, next);
}
/**
* Create a new {@link StateTransition} specification from one {@link State} to
* another (by name).
* @param state the {@link State} used to generate the outcome for this transition
* @param pattern the pattern to match in the exit status of the {@link State} (can be
* {@code null})
* @param next the name of the next {@link State} to execute (can be {@code null})
* @return {@link StateTransition} that was created.
*/
public static StateTransition createStateTransition(State state, @Nullable String pattern, @Nullable String next) {
return new StateTransition(state, pattern, next);
}
private StateTransition(State state, @Nullable String pattern, @Nullable String next) {
super();
if (!StringUtils.hasText(pattern)) {
this.pattern = "*";
}
else {
this.pattern = pattern;
}
Assert.notNull(state, "A state is required for a StateTransition");
if (state.isEndState() && StringUtils.hasText(next)) {
throw new IllegalStateException("End state cannot have next: " + state);
}
this.next = next;
this.state = state;
}
/**
* Public getter for the State.
* @return the State
*/
public State getState() {
return state;
}
/**
* Public getter for the next State name.
* @return the next
*/
public String getNext() {
return next;
}
/**
* Check if the provided status matches the pattern, signalling that the next State
* should be executed.
* @param status the status to compare
* @return true if the pattern matches this status
*/
public boolean matches(String status) {
return PatternMatcher.match(pattern, status);
}
/**
* Check for a special next State signalling the end of a job.
* @return true if this transition goes nowhere (there is no next)
*/
public boolean isEnd() {
return next == null;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return String.format("StateTransition: [state=%s, pattern=%s, next=%s]", state == null ? null : state.getName(),
pattern, next);
| 1,122
| 48
| 1,170
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/AbstractState.java
|
AbstractState
|
toString
|
class AbstractState implements State {
private final String name;
/**
* @param name of the state.
*/
public AbstractState(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public abstract FlowExecutionStatus handle(FlowExecutor executor) throws Exception;
}
|
return getClass().getSimpleName() + ": name=[" + name + "]";
| 113
| 25
| 138
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/EndState.java
|
EndState
|
handle
|
class EndState extends AbstractState {
private final FlowExecutionStatus status;
private final boolean abandon;
private final String code;
/**
* @param status The {@link FlowExecutionStatus} to end with
* @param name The name of the state
*/
public EndState(FlowExecutionStatus status, String name) {
this(status, status.getName(), name);
}
/**
* @param status The {@link FlowExecutionStatus} to end with
* @param name The name of the state
* @param code The exit status to save
*/
public EndState(FlowExecutionStatus status, String code, String name) {
this(status, code, name, false);
}
/**
* @param status The {@link FlowExecutionStatus} to end with
* @param name The name of the state
* @param code The exit status to save
* @param abandon flag to indicate that previous step execution can be marked as
* abandoned (if there is one)
*
*/
public EndState(FlowExecutionStatus status, String code, String name, boolean abandon) {
super(name);
this.status = status;
this.code = code;
this.abandon = abandon;
}
protected FlowExecutionStatus getStatus() {
return this.status;
}
protected boolean isAbandon() {
return this.abandon;
}
protected String getCode() {
return this.code;
}
/**
* Return the {@link FlowExecutionStatus} stored.
*
* @see State#handle(FlowExecutor)
*/
@Override
public FlowExecutionStatus handle(FlowExecutor executor) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Performs any logic to update the exit status for the current flow.
* @param executor {@link FlowExecutor} for the current flow
* @param code The exit status to save
*/
protected void setExitStatus(FlowExecutor executor, String code) {
executor.addExitStatus(code);
}
@Override
public boolean isEndState() {
return !status.isStop();
}
@Override
public String toString() {
return super.toString() + " status=[" + status + "]";
}
}
|
synchronized (executor) {
// Special case. If the last step execution could not complete we
// are in an unknown state (possibly unrecoverable).
StepExecution stepExecution = executor.getStepExecution();
if (stepExecution != null && executor.getStepExecution().getStatus() == BatchStatus.UNKNOWN) {
return FlowExecutionStatus.UNKNOWN;
}
if (status.isStop()) {
if (!executor.isRestart()) {
/*
* If there are step executions, then we are not at the beginning of a
* restart.
*/
if (abandon) {
/*
* Only if instructed to do so, upgrade the status of last step
* execution so it is not replayed on a restart...
*/
executor.abandonStepExecution();
}
}
else {
/*
* If we are a stop state and we got this far then it must be a
* restart, so return COMPLETED.
*/
return FlowExecutionStatus.COMPLETED;
}
}
setExitStatus(executor, code);
return status;
}
| 556
| 304
| 860
|
<methods>public void <init>(java.lang.String) ,public java.lang.String getName() ,public abstract org.springframework.batch.core.job.flow.FlowExecutionStatus handle(org.springframework.batch.core.job.flow.FlowExecutor) throws java.lang.Exception,public java.lang.String toString() <variables>private final non-sealed java.lang.String name
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/MaxValueFlowExecutionAggregator.java
|
MaxValueFlowExecutionAggregator
|
aggregate
|
class MaxValueFlowExecutionAggregator implements FlowExecutionAggregator {
/**
* Aggregate all of the {@link FlowExecutionStatus}es of the {@link FlowExecution}s
* into one status. The aggregate status will be the status with the highest
* precedence.
*
* @see FlowExecutionAggregator#aggregate(Collection)
*/
@Override
public FlowExecutionStatus aggregate(Collection<FlowExecution> executions) {<FILL_FUNCTION_BODY>}
}
|
if (executions == null || executions.size() == 0) {
return FlowExecutionStatus.UNKNOWN;
}
return Collections.max(executions).getStatus();
| 120
| 50
| 170
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/SplitState.java
|
SplitState
|
handle
|
class SplitState extends AbstractState implements FlowHolder {
private final Collection<Flow> flows;
private final SplitState parentSplit;
private TaskExecutor taskExecutor = new SyncTaskExecutor();
private final FlowExecutionAggregator aggregator = new MaxValueFlowExecutionAggregator();
/**
* @param flows collection of {@link Flow} instances.
* @param name the name of the state.
*/
public SplitState(Collection<Flow> flows, String name) {
this(flows, name, null);
}
/**
* @param flows collection of {@link Flow} instances.
* @param name the name of the state.
* @param parentSplit the parent {@link SplitState}.
*/
public SplitState(Collection<Flow> flows, String name, @Nullable SplitState parentSplit) {
super(name);
this.flows = flows;
this.parentSplit = parentSplit;
}
/**
* Public setter for the taskExecutor.
* @param taskExecutor the taskExecutor to set
*/
public void setTaskExecutor(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* @return the flows
*/
@Override
public Collection<Flow> getFlows() {
return flows;
}
/**
* Execute the flows in parallel by passing them to the {@link TaskExecutor} and wait
* for all of them to finish before proceeding.
*
* @see State#handle(FlowExecutor)
*/
@Override
public FlowExecutionStatus handle(final FlowExecutor executor) throws Exception {<FILL_FUNCTION_BODY>}
protected FlowExecutionStatus doAggregation(Collection<FlowExecution> results, FlowExecutor executor) {
return aggregator.aggregate(results);
}
@Override
public boolean isEndState() {
return false;
}
}
|
// TODO: collect the last StepExecution from the flows as well, so they
// can be abandoned if necessary
Collection<Future<FlowExecution>> tasks = new ArrayList<>();
for (final Flow flow : flows) {
final FutureTask<FlowExecution> task = new FutureTask<>(() -> flow.start(executor));
tasks.add(task);
try {
taskExecutor.execute(task);
}
catch (TaskRejectedException e) {
throw new FlowExecutionException("TaskExecutor rejected task for flow=" + flow.getName());
}
}
FlowExecutionStatus parentSplitStatus = parentSplit == null ? null : parentSplit.handle(executor);
Collection<FlowExecution> results = new ArrayList<>();
// Could use a CompletionService here?
for (Future<FlowExecution> task : tasks) {
try {
results.add(task.get());
}
catch (ExecutionException e) {
// Unwrap the expected exceptions
Throwable cause = e.getCause();
if (cause instanceof Exception) {
throw (Exception) cause;
}
else {
throw e;
}
}
}
FlowExecutionStatus flowExecutionStatus = doAggregation(results, executor);
if (parentSplitStatus != null) {
return Collections.max(Arrays.asList(flowExecutionStatus, parentSplitStatus));
}
return flowExecutionStatus;
| 458
| 376
| 834
|
<methods>public void <init>(java.lang.String) ,public java.lang.String getName() ,public abstract org.springframework.batch.core.job.flow.FlowExecutionStatus handle(org.springframework.batch.core.job.flow.FlowExecutor) throws java.lang.Exception,public java.lang.String toString() <variables>private final non-sealed java.lang.String name
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/StepState.java
|
StepState
|
handle
|
class StepState extends AbstractState implements StepLocator, StepHolder {
private final Step step;
/**
* @param step the step that will be executed
*/
public StepState(Step step) {
super(step.getName());
this.step = step;
}
/**
* @param name for the step that will be executed
* @param step the step that will be executed
*/
public StepState(String name, Step step) {
super(name);
this.step = step;
}
@Override
public FlowExecutionStatus handle(FlowExecutor executor) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public Step getStep() {
return step;
}
@Override
public boolean isEndState() {
return false;
}
@Override
public Collection<String> getStepNames() {
List<String> names = new ArrayList<>();
names.add(step.getName());
if (step instanceof StepLocator) {
names.addAll(((StepLocator) step).getStepNames());
}
return names;
}
@Override
public Step getStep(String stepName) throws NoSuchStepException {
Step result = null;
if (step.getName().equals(stepName)) {
result = step;
}
else if (step instanceof StepLocator) {
result = ((StepLocator) step).getStep(stepName);
}
return result;
}
}
|
/*
* On starting a new step, possibly upgrade the last execution to make sure it is
* abandoned on restart if it failed.
*/
executor.abandonStepExecution();
return new FlowExecutionStatus(executor.executeStep(step));
| 375
| 65
| 440
|
<methods>public void <init>(java.lang.String) ,public java.lang.String getName() ,public abstract org.springframework.batch.core.job.flow.FlowExecutionStatus handle(org.springframework.batch.core.job.flow.FlowExecutor) throws java.lang.Exception,public java.lang.String toString() <variables>private final non-sealed java.lang.String name
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/JobOperatorFactoryBean.java
|
JobOperatorFactoryBean
|
afterPropertiesSet
|
class JobOperatorFactoryBean implements FactoryBean<JobOperator>, InitializingBean {
private static final String TRANSACTION_ISOLATION_LEVEL_PREFIX = "ISOLATION_";
private static final String TRANSACTION_PROPAGATION_PREFIX = "PROPAGATION_";
private PlatformTransactionManager transactionManager;
private TransactionAttributeSource transactionAttributeSource;
private JobRegistry jobRegistry;
private JobLauncher jobLauncher;
private JobRepository jobRepository;
private JobExplorer jobExplorer;
private JobParametersConverter jobParametersConverter = new DefaultJobParametersConverter();
private final ProxyFactory proxyFactory = new ProxyFactory();
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
/**
* Setter for the job registry.
* @param jobRegistry the job registry to set
*/
public void setJobRegistry(JobRegistry jobRegistry) {
this.jobRegistry = jobRegistry;
}
/**
* Setter for the job launcher.
* @param jobLauncher the job launcher to set
*/
public void setJobLauncher(JobLauncher jobLauncher) {
this.jobLauncher = jobLauncher;
}
/**
* Setter for the job repository.
* @param jobRepository the job repository to set
*/
public void setJobRepository(JobRepository jobRepository) {
this.jobRepository = jobRepository;
}
/**
* Setter for the job explorer.
* @param jobExplorer the job explorer to set
*/
public void setJobExplorer(JobExplorer jobExplorer) {
this.jobExplorer = jobExplorer;
}
/**
* Setter for the job parameters converter.
* @param jobParametersConverter the job parameters converter to set
*/
public void setJobParametersConverter(JobParametersConverter jobParametersConverter) {
this.jobParametersConverter = jobParametersConverter;
}
/**
* Setter for the transaction manager.
* @param transactionManager the transaction manager to set
*/
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
/**
* Set the transaction attributes source to use in the created proxy.
* @param transactionAttributeSource the transaction attributes source to use in the
* created proxy.
*/
public void setTransactionAttributeSource(TransactionAttributeSource transactionAttributeSource) {
Assert.notNull(transactionAttributeSource, "transactionAttributeSource must not be null.");
this.transactionAttributeSource = transactionAttributeSource;
}
@Override
public Class<?> getObjectType() {
return JobOperator.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public JobOperator getObject() throws Exception {
TransactionInterceptor advice = new TransactionInterceptor((TransactionManager) this.transactionManager,
this.transactionAttributeSource);
this.proxyFactory.addAdvice(advice);
this.proxyFactory.setProxyTargetClass(false);
this.proxyFactory.addInterface(JobOperator.class);
this.proxyFactory.setTarget(getTarget());
return (JobOperator) this.proxyFactory.getProxy(getClass().getClassLoader());
}
private SimpleJobOperator getTarget() throws Exception {
SimpleJobOperator simpleJobOperator = new SimpleJobOperator();
simpleJobOperator.setJobRegistry(this.jobRegistry);
simpleJobOperator.setJobExplorer(this.jobExplorer);
simpleJobOperator.setJobRepository(this.jobRepository);
simpleJobOperator.setJobLauncher(this.jobLauncher);
simpleJobOperator.setJobParametersConverter(this.jobParametersConverter);
simpleJobOperator.afterPropertiesSet();
return simpleJobOperator;
}
}
|
Assert.notNull(this.transactionManager, "TransactionManager must not be null");
Assert.notNull(this.jobLauncher, "JobLauncher must not be null");
Assert.notNull(this.jobRegistry, "JobRegistry must not be null");
Assert.notNull(this.jobExplorer, "JobExplorer must not be null");
Assert.notNull(this.jobRepository, "JobRepository must not be null");
if (this.transactionAttributeSource == null) {
Properties transactionAttributes = new Properties();
String transactionProperties = String.join(",", TRANSACTION_PROPAGATION_PREFIX + Propagation.REQUIRED,
TRANSACTION_ISOLATION_LEVEL_PREFIX + Isolation.DEFAULT);
transactionAttributes.setProperty("stop*", transactionProperties);
this.transactionAttributeSource = new NameMatchTransactionAttributeSource();
((NameMatchTransactionAttributeSource) transactionAttributeSource).setProperties(transactionAttributes);
}
| 923
| 243
| 1,166
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/JobRegistryBackgroundJobRunner.java
|
JobRegistryBackgroundJobRunner
|
main
|
class JobRegistryBackgroundJobRunner {
/**
* System property key that switches the runner to "embedded" mode (returning
* immediately from the main method). Useful for testing purposes.
*/
public static final String EMBEDDED = JobRegistryBackgroundJobRunner.class.getSimpleName() + ".EMBEDDED";
private static final Log logger = LogFactory.getLog(JobRegistryBackgroundJobRunner.class);
private JobLoader jobLoader;
private ApplicationContext parentContext = null;
public static boolean testing = false;
final private String parentContextPath;
private JobRegistry jobRegistry;
private static final List<Exception> errors = Collections.synchronizedList(new ArrayList<>());
/**
* @param parentContextPath the parentContextPath to be used by the
* JobRegistryBackgroundJobRunner.
*/
public JobRegistryBackgroundJobRunner(String parentContextPath) {
super();
this.parentContextPath = parentContextPath;
}
/**
* A loader for the jobs that are going to be registered.
* @param jobLoader the {@link JobLoader} to set
*/
public void setJobLoader(JobLoader jobLoader) {
this.jobLoader = jobLoader;
}
/**
* A job registry that can be used to create a job loader (if none is provided).
* @param jobRegistry the {@link JobRegistry} to set
*/
public void setJobRegistry(JobRegistry jobRegistry) {
this.jobRegistry = jobRegistry;
}
/**
* Public getter for the startup errors encountered during parent context creation.
* @return the errors
*/
public static List<Exception> getErrors() {
synchronized (errors) {
return new ArrayList<>(errors);
}
}
private void register(String[] paths) throws DuplicateJobException, IOException {
maybeCreateJobLoader();
for (String s : paths) {
Resource[] resources = parentContext.getResources(s);
for (Resource path : resources) {
if (logger.isInfoEnabled()) {
logger.info("Registering Job definitions from " + Arrays.toString(resources));
}
GenericApplicationContextFactory factory = new GenericApplicationContextFactory(path);
factory.setApplicationContext(parentContext);
jobLoader.load(factory);
}
}
}
/**
* If there is no {@link JobLoader} then try and create one from existing bean
* definitions.
*/
private void maybeCreateJobLoader() {
if (jobLoader != null) {
return;
}
String[] names = parentContext.getBeanNamesForType(JobLoader.class);
if (names.length == 0) {
if (parentContext.containsBean("jobLoader")) {
jobLoader = parentContext.getBean("jobLoader", JobLoader.class);
return;
}
if (jobRegistry != null) {
jobLoader = new DefaultJobLoader(jobRegistry);
return;
}
}
jobLoader = parentContext.getBean(names[0], JobLoader.class);
}
/**
* Supply a list of application context locations, starting with the parent context,
* and followed by the children. The parent must contain a {@link JobRegistry} and the
* child contexts are expected to contain {@link Job} definitions, each of which will
* be registered wit the registry.
* <p>
* Example usage:
*
* <pre>
* $ java -classpath ... JobRegistryBackgroundJobRunner job-registry-context.xml job1.xml job2.xml ...
* </pre>
*
* The child contexts are created only when needed though the {@link JobFactory}
* interface (but the XML is validated on startup by using it to create a
* {@link BeanFactory} which is then discarded).
* <p>
* The parent context is created in a separate thread, and the program will pause for
* input in an infinite loop until the user hits any key.
* @param args the context locations to use (first one is for parent)
* @throws Exception if anything goes wrong with the context creation
*/
public static void main(String... args) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Unregister all the {@link Job} instances that were registered by this post
* processor.
* @see org.springframework.beans.factory.DisposableBean#destroy()
*/
private void destroy() throws Exception {
jobLoader.clear();
}
private void run() {
final ApplicationContext parent = new ClassPathXmlApplicationContext(parentContextPath);
parent.getAutowireCapableBeanFactory()
.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
parent.getAutowireCapableBeanFactory().initializeBean(this, getClass().getSimpleName());
this.parentContext = parent;
}
/**
* If embedded in a JVM, call this method to terminate the main method.
*/
public static void stop() {
synchronized (JobRegistryBackgroundJobRunner.class) {
JobRegistryBackgroundJobRunner.class.notify();
}
}
}
|
Assert.state(args.length >= 1, "At least one argument (the parent context path) must be provided.");
final JobRegistryBackgroundJobRunner launcher = new JobRegistryBackgroundJobRunner(args[0]);
errors.clear();
if (logger.isInfoEnabled()) {
logger.info("Starting job registry in parent context from XML at: [" + args[0] + "]");
}
new Thread(() -> {
try {
launcher.run();
}
catch (RuntimeException e) {
errors.add(e);
throw e;
}
}).start();
logger.info("Waiting for parent context to start.");
while (launcher.parentContext == null && errors.isEmpty()) {
Thread.sleep(100L);
}
synchronized (errors) {
if (!errors.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info(errors.size() + " errors detected on startup of parent context. Rethrowing.");
}
throw errors.get(0);
}
}
errors.clear();
// Paths to individual job configurations.
final String[] paths = new String[args.length - 1];
System.arraycopy(args, 1, paths, 0, paths.length);
if (logger.isInfoEnabled()) {
logger.info("Parent context started. Registering jobs from paths: " + Arrays.asList(paths));
}
launcher.register(paths);
if (System.getProperty(EMBEDDED) != null) {
launcher.destroy();
return;
}
synchronized (JobRegistryBackgroundJobRunner.class) {
System.out.println(
"Started application. Interrupt (CTRL-C) or call JobRegistryBackgroundJobRunner.stop() to exit.");
JobRegistryBackgroundJobRunner.class.wait();
}
launcher.destroy();
| 1,298
| 515
| 1,813
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/RunIdIncrementer.java
|
RunIdIncrementer
|
getNext
|
class RunIdIncrementer implements JobParametersIncrementer {
private static final String RUN_ID_KEY = "run.id";
private String key = RUN_ID_KEY;
/**
* The name of the run id in the job parameters. Defaults to "run.id".
* @param key the key to set
*/
public void setKey(String key) {
this.key = key;
}
/**
* Increment the run.id parameter (starting with 1).
* @param parameters the previous job parameters
* @return the next job parameters with an incremented (or initialized) run.id
* @throws IllegalArgumentException if the previous value of run.id is invalid
*/
@Override
public JobParameters getNext(@Nullable JobParameters parameters) {<FILL_FUNCTION_BODY>}
}
|
JobParameters params = (parameters == null) ? new JobParameters() : parameters;
JobParameter<?> runIdParameter = params.getParameters().get(this.key);
long id = 1;
if (runIdParameter != null) {
try {
id = Long.parseLong(runIdParameter.getValue().toString()) + 1;
}
catch (NumberFormatException exception) {
throw new IllegalArgumentException("Invalid value for parameter " + this.key, exception);
}
}
return new JobParametersBuilder(params).addLong(this.key, id).toJobParameters();
| 206
| 156
| 362
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/RuntimeExceptionTranslator.java
|
RuntimeExceptionTranslator
|
invoke
|
class RuntimeExceptionTranslator implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
try {
return invocation.proceed();
}
catch (Exception e) {
if (e.getClass().getName().startsWith("java")) {
throw e;
}
throw new RuntimeException(e.getClass().getSimpleName() + ": " + e.getMessage());
}
| 48
| 85
| 133
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/SimpleJobLauncher.java
|
SimpleJobLauncher
|
run
|
class SimpleJobLauncher implements JobLauncher, InitializingBean {
protected static final Log logger = LogFactory.getLog(SimpleJobLauncher.class);
private JobRepository jobRepository;
private TaskExecutor taskExecutor;
private MeterRegistry meterRegistry = Metrics.globalRegistry;
private Counter jobLaunchCount; // NoopCounter is still incubating
/**
* Run the provided job with the given {@link JobParameters}. The
* {@link JobParameters} will be used to determine if this is an execution of an
* existing job instance, or if a new one should be created.
* @param job the job to be run.
* @param jobParameters the {@link JobParameters} for this particular execution.
* @return the {@link JobExecution} if it returns synchronously. If the implementation
* is asynchronous, the status might well be unknown.
* @throws JobExecutionAlreadyRunningException if the JobInstance already exists and
* has an execution already running.
* @throws JobRestartException if the execution would be a re-start, but a re-start is
* either not allowed or not needed.
* @throws JobInstanceAlreadyCompleteException if this instance has already completed
* successfully
* @throws JobParametersInvalidException thrown if jobParameters is invalid.
*/
@Override
public JobExecution run(final Job job, final JobParameters jobParameters)
throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException,
JobParametersInvalidException {<FILL_FUNCTION_BODY>}
/**
* Set the JobRepository.
* @param jobRepository instance of {@link JobRepository}.
*/
public void setJobRepository(JobRepository jobRepository) {
this.jobRepository = jobRepository;
}
/**
* Set the TaskExecutor. (Optional)
* @param taskExecutor instance of {@link TaskExecutor}.
*/
public void setTaskExecutor(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* Set the meter registry to use for metrics. Defaults to
* {@link Metrics#globalRegistry}.
* @param meterRegistry the meter registry
* @since 5.0
*/
public void setMeterRegistry(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}
/**
* Ensure the required dependencies of a {@link JobRepository} have been set.
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(jobRepository != null, "A JobRepository has not been set.");
if (taskExecutor == null) {
logger.info("No TaskExecutor has been set, defaulting to synchronous executor.");
taskExecutor = new SyncTaskExecutor();
}
this.jobLaunchCount = BatchMetrics.createCounter(this.meterRegistry, "job.launch.count", "Job launch count");
}
}
|
Assert.notNull(job, "The Job must not be null.");
Assert.notNull(jobParameters, "The JobParameters must not be null.");
if (this.jobLaunchCount != null) {
this.jobLaunchCount.increment();
}
final JobExecution jobExecution;
JobExecution lastExecution = jobRepository.getLastJobExecution(job.getName(), jobParameters);
if (lastExecution != null) {
if (!job.isRestartable()) {
throw new JobRestartException("JobInstance already exists and is not restartable");
}
/*
* validate here if it has stepExecutions that are UNKNOWN, STARTING, STARTED
* and STOPPING retrieve the previous execution and check
*/
for (StepExecution execution : lastExecution.getStepExecutions()) {
BatchStatus status = execution.getStatus();
if (status.isRunning()) {
throw new JobExecutionAlreadyRunningException(
"A job execution for this job is already running: " + lastExecution);
}
else if (status == BatchStatus.UNKNOWN) {
throw new JobRestartException(
"Cannot restart step [" + execution.getStepName() + "] from UNKNOWN status. "
+ "The last execution ended with a failure that could not be rolled back, "
+ "so it may be dangerous to proceed. Manual intervention is probably necessary.");
}
}
}
// Check the validity of the parameters before doing creating anything
// in the repository...
job.getJobParametersValidator().validate(jobParameters);
/*
* There is a very small probability that a non-restartable job can be restarted,
* but only if another process or thread manages to launch <i>and</i> fail a job
* execution for this instance between the last assertion and the next method
* returning successfully.
*/
jobExecution = jobRepository.createJobExecution(job.getName(), jobParameters);
try {
taskExecutor.execute(new Runnable() {
@Override
public void run() {
try {
if (logger.isInfoEnabled()) {
logger.info("Job: [" + job + "] launched with the following parameters: [" + jobParameters
+ "]");
}
job.execute(jobExecution);
if (logger.isInfoEnabled()) {
Duration jobExecutionDuration = BatchMetrics.calculateDuration(jobExecution.getStartTime(),
jobExecution.getEndTime());
logger.info("Job: [" + job + "] completed with the following parameters: [" + jobParameters
+ "] and the following status: [" + jobExecution.getStatus() + "]"
+ (jobExecutionDuration == null ? ""
: " in " + BatchMetrics.formatDuration(jobExecutionDuration)));
}
}
catch (Throwable t) {
if (logger.isInfoEnabled()) {
logger.info("Job: [" + job
+ "] failed unexpectedly and fatally with the following parameters: ["
+ jobParameters + "]", t);
}
rethrow(t);
}
}
private void rethrow(Throwable t) {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
else if (t instanceof Error) {
throw (Error) t;
}
throw new IllegalStateException(t);
}
});
}
catch (TaskRejectedException e) {
jobExecution.upgradeStatus(BatchStatus.FAILED);
if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) {
jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e));
}
jobRepository.update(jobExecution);
}
return jobExecution;
| 702
| 974
| 1,676
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/SimpleJvmExitCodeMapper.java
|
SimpleJvmExitCodeMapper
|
intValue
|
class SimpleJvmExitCodeMapper implements ExitCodeMapper {
protected Log logger = LogFactory.getLog(getClass());
private final Map<String, Integer> mapping;
public SimpleJvmExitCodeMapper() {
mapping = new HashMap<>();
mapping.put(ExitStatus.COMPLETED.getExitCode(), JVM_EXITCODE_COMPLETED);
mapping.put(ExitStatus.FAILED.getExitCode(), JVM_EXITCODE_GENERIC_ERROR);
mapping.put(ExitCodeMapper.JOB_NOT_PROVIDED, JVM_EXITCODE_JOB_ERROR);
mapping.put(ExitCodeMapper.NO_SUCH_JOB, JVM_EXITCODE_JOB_ERROR);
}
public Map<String, Integer> getMapping() {
return mapping;
}
/**
* Supply the ExitCodeMappings
* @param exitCodeMap A set of mappings between environment specific exit codes and
* batch framework internal exit codes
*/
public void setMapping(Map<String, Integer> exitCodeMap) {
mapping.putAll(exitCodeMap);
}
/**
* Get the operating system exit status that matches a certain Batch Framework exit
* code
* @param exitCode The exit code of the Batch Job as known by the Batch Framework
* @return The exitCode of the Batch Job as known by the JVM
*/
@Override
public int intValue(String exitCode) {<FILL_FUNCTION_BODY>}
}
|
Integer statusCode = null;
try {
statusCode = mapping.get(exitCode);
}
catch (RuntimeException ex) {
// We still need to return an exit code, even if there is an issue
// with
// the mapper.
logger.fatal("Error mapping exit code, generic exit status returned.", ex);
}
return (statusCode != null) ? statusCode : JVM_EXITCODE_GENERIC_ERROR;
| 382
| 125
| 507
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/AbstractListenerFactoryBean.java
|
AbstractListenerFactoryBean
|
getObject
|
class AbstractListenerFactoryBean<T> implements FactoryBean<Object>, InitializingBean {
private static final Log logger = LogFactory.getLog(AbstractListenerFactoryBean.class);
private Object delegate;
private Map<String, String> metaDataMap;
@Override
public Object getObject() {<FILL_FUNCTION_BODY>}
protected abstract ListenerMetaData getMetaDataFromPropertyName(String propertyName);
protected abstract ListenerMetaData[] getMetaDataValues();
protected abstract Class<?> getDefaultListenerClass();
protected MethodInvoker getMethodInvokerByName(String methodName, Object candidate, Class<?>... params) {
if (methodName != null) {
return MethodInvokerUtils.getMethodInvokerByName(candidate, methodName, false, params);
}
else {
return null;
}
}
@Override
public boolean isSingleton() {
return true;
}
public void setDelegate(Object delegate) {
this.delegate = delegate;
}
public void setMetaDataMap(Map<String, String> metaDataMap) {
this.metaDataMap = metaDataMap;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(delegate != null, "Delegate must not be null");
}
/**
* Convenience method to check whether the given object is or can be made into a
* listener.
* @param target the object to check
* @param listenerType the class of the listener.
* @param metaDataValues array of {@link ListenerMetaData}.
* @return true if the delegate is an instance of any of the listener interface, or
* contains the marker annotations
*/
public static boolean isListener(Object target, Class<?> listenerType, ListenerMetaData[] metaDataValues) {
if (target == null) {
return false;
}
if (listenerType.isInstance(target)) {
return true;
}
if (target instanceof Advised) {
TargetSource targetSource = ((Advised) target).getTargetSource();
if (targetSource != null && targetSource.getTargetClass() != null
&& listenerType.isAssignableFrom(targetSource.getTargetClass())) {
return true;
}
if (targetSource != null && targetSource.getTargetClass() != null
&& targetSource.getTargetClass().isInterface()) {
logger.warn(String.format(
"%s is an interface. The implementing class will not be queried for annotation based listener configurations. If using @StepScope on a @Bean method, be sure to return the implementing class so listener annotations can be used.",
targetSource.getTargetClass().getName()));
}
}
for (ListenerMetaData metaData : metaDataValues) {
if (MethodInvokerUtils.getMethodInvokerByAnnotation(metaData.getAnnotation(), target) != null) {
return true;
}
}
return false;
}
}
|
if (metaDataMap == null) {
metaDataMap = new HashMap<>();
}
// Because all annotations and interfaces should be checked for, make
// sure that each meta data
// entry is represented.
for (ListenerMetaData metaData : this.getMetaDataValues()) {
if (!metaDataMap.containsKey(metaData.getPropertyName())) {
// put null so that the annotation and interface is checked
metaDataMap.put(metaData.getPropertyName(), null);
}
}
Set<Class<?>> listenerInterfaces = new HashSet<>();
// For every entry in the map, try and find a method by interface, name,
// or annotation. If the same
Map<String, Set<MethodInvoker>> invokerMap = new HashMap<>();
boolean synthetic = false;
for (Entry<String, String> entry : metaDataMap.entrySet()) {
final ListenerMetaData metaData = this.getMetaDataFromPropertyName(entry.getKey());
Set<MethodInvoker> invokers = new HashSet<>();
MethodInvoker invoker;
invoker = MethodInvokerUtils.getMethodInvokerForInterface(metaData.getListenerInterface(),
metaData.getMethodName(), delegate, metaData.getParamTypes());
if (invoker != null) {
invokers.add(invoker);
}
invoker = getMethodInvokerByName(entry.getValue(), delegate, metaData.getParamTypes());
if (invoker != null) {
invokers.add(invoker);
synthetic = true;
}
if (metaData.getAnnotation() != null) {
invoker = MethodInvokerUtils.getMethodInvokerByAnnotation(metaData.getAnnotation(), delegate,
metaData.getParamTypes());
if (invoker != null) {
invokers.add(invoker);
synthetic = true;
}
}
if (!invokers.isEmpty()) {
invokerMap.put(metaData.getMethodName(), invokers);
listenerInterfaces.add(metaData.getListenerInterface());
}
}
if (listenerInterfaces.isEmpty()) {
listenerInterfaces.add(this.getDefaultListenerClass());
}
if (!synthetic) {
int count = 0;
for (Class<?> listenerInterface : listenerInterfaces) {
if (listenerInterface.isInstance(delegate)) {
count++;
}
}
// All listeners can be supplied by the delegate itself
if (count == listenerInterfaces.size()) {
return delegate;
}
}
boolean ordered = false;
if (delegate instanceof Ordered) {
ordered = true;
listenerInterfaces.add(Ordered.class);
}
// create a proxy listener for only the interfaces that have methods to
// be called
ProxyFactory proxyFactory = new ProxyFactory();
if (delegate instanceof Advised) {
proxyFactory.setTargetSource(((Advised) delegate).getTargetSource());
}
else {
proxyFactory.setTarget(delegate);
}
@SuppressWarnings("rawtypes")
Class[] a = new Class[0];
proxyFactory.setInterfaces(listenerInterfaces.toArray(a));
proxyFactory.addAdvisor(new DefaultPointcutAdvisor(new MethodInvokerMethodInterceptor(invokerMap, ordered)));
return proxyFactory.getProxy();
| 747
| 915
| 1,662
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/CompositeChunkListener.java
|
CompositeChunkListener
|
afterChunk
|
class CompositeChunkListener implements ChunkListener {
private final OrderedComposite<ChunkListener> listeners = new OrderedComposite<>();
/**
* Default constructor
*/
public CompositeChunkListener() {
}
/**
* Convenience constructor for setting the {@link ChunkListener}s.
* @param listeners list of {@link ChunkListener}.
*/
public CompositeChunkListener(List<? extends ChunkListener> listeners) {
setListeners(listeners);
}
/**
* Convenience constructor for setting the {@link ChunkListener}s.
* @param listeners array of {@link ChunkListener}.
*/
public CompositeChunkListener(ChunkListener... listeners) {
this(Arrays.asList(listeners));
}
/**
* Public setter for the listeners.
* @param listeners list of {@link ChunkListener}.
*/
public void setListeners(List<? extends ChunkListener> listeners) {
this.listeners.setItems(listeners);
}
/**
* Register additional listener.
* @param chunkListener instance of {@link ChunkListener}.
*/
public void register(ChunkListener chunkListener) {
listeners.add(chunkListener);
}
/**
* Call the registered listeners in reverse order.
*
* @see org.springframework.batch.core.ChunkListener#afterChunk(ChunkContext context)
*/
@Override
public void afterChunk(ChunkContext context) {<FILL_FUNCTION_BODY>}
/**
* Call the registered listeners in order, respecting and prioritizing those that
* implement {@link Ordered}.
*
* @see org.springframework.batch.core.ChunkListener#beforeChunk(ChunkContext context)
*/
@Override
public void beforeChunk(ChunkContext context) {
for (Iterator<ChunkListener> iterator = listeners.iterator(); iterator.hasNext();) {
ChunkListener listener = iterator.next();
listener.beforeChunk(context);
}
}
/**
* Call the registered listeners in reverse order.
*
* @see org.springframework.batch.core.ChunkListener#afterChunkError(ChunkContext
* context)
*/
@Override
public void afterChunkError(ChunkContext context) {
for (Iterator<ChunkListener> iterator = listeners.reverse(); iterator.hasNext();) {
ChunkListener listener = iterator.next();
listener.afterChunkError(context);
}
}
}
|
for (Iterator<ChunkListener> iterator = listeners.reverse(); iterator.hasNext();) {
ChunkListener listener = iterator.next();
listener.afterChunk(context);
}
| 645
| 57
| 702
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/CompositeItemProcessListener.java
|
CompositeItemProcessListener
|
afterProcess
|
class CompositeItemProcessListener<T, S> implements ItemProcessListener<T, S> {
private final OrderedComposite<ItemProcessListener<? super T, ? super S>> listeners = new OrderedComposite<>();
/**
* Public setter for the listeners.
* @param itemProcessorListeners list of {@link ItemProcessListener}s to be called
* when process events occur.
*/
public void setListeners(List<? extends ItemProcessListener<? super T, ? super S>> itemProcessorListeners) {
this.listeners.setItems(itemProcessorListeners);
}
/**
* Register additional listener.
* @param itemProcessorListener instance of {@link ItemProcessListener} to be
* registered.
*/
public void register(ItemProcessListener<? super T, ? super S> itemProcessorListener) {
listeners.add(itemProcessorListener);
}
/**
* Call the registered listeners in reverse order, respecting and prioritising those
* that implement {@link Ordered}.
* @see org.springframework.batch.core.ItemProcessListener#afterProcess(java.lang.Object,
* java.lang.Object)
*/
@Override
public void afterProcess(T item, @Nullable S result) {<FILL_FUNCTION_BODY>}
/**
* Call the registered listeners in order, respecting and prioritising those that
* implement {@link Ordered}.
* @see org.springframework.batch.core.ItemProcessListener#beforeProcess(java.lang.Object)
*/
@Override
public void beforeProcess(T item) {
for (Iterator<ItemProcessListener<? super T, ? super S>> iterator = listeners.iterator(); iterator.hasNext();) {
ItemProcessListener<? super T, ? super S> listener = iterator.next();
listener.beforeProcess(item);
}
}
/**
* Call the registered listeners in reverse order, respecting and prioritising those
* that implement {@link Ordered}.
* @see org.springframework.batch.core.ItemProcessListener#onProcessError(java.lang.Object,
* java.lang.Exception)
*/
@Override
public void onProcessError(T item, Exception e) {
for (Iterator<ItemProcessListener<? super T, ? super S>> iterator = listeners.reverse(); iterator.hasNext();) {
ItemProcessListener<? super T, ? super S> listener = iterator.next();
listener.onProcessError(item, e);
}
}
}
|
for (Iterator<ItemProcessListener<? super T, ? super S>> iterator = listeners.reverse(); iterator.hasNext();) {
ItemProcessListener<? super T, ? super S> listener = iterator.next();
listener.afterProcess(item, result);
}
| 622
| 75
| 697
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/CompositeItemReadListener.java
|
CompositeItemReadListener
|
beforeRead
|
class CompositeItemReadListener<T> implements ItemReadListener<T> {
private final OrderedComposite<ItemReadListener<? super T>> listeners = new OrderedComposite<>();
/**
* Public setter for the listeners.
* @param itemReadListeners list of {@link ItemReadListener}s to be called when read
* events occur.
*/
public void setListeners(List<? extends ItemReadListener<? super T>> itemReadListeners) {
this.listeners.setItems(itemReadListeners);
}
/**
* Register additional listener.
* @param itemReaderListener instance of {@link ItemReadListener} to be registered.
*/
public void register(ItemReadListener<? super T> itemReaderListener) {
listeners.add(itemReaderListener);
}
/**
* Call the registered listeners in reverse order, respecting and prioritising those
* that implement {@link Ordered}.
* @see org.springframework.batch.core.ItemReadListener#afterRead(java.lang.Object)
*/
@Override
public void afterRead(T item) {
for (Iterator<ItemReadListener<? super T>> iterator = listeners.reverse(); iterator.hasNext();) {
ItemReadListener<? super T> listener = iterator.next();
listener.afterRead(item);
}
}
/**
* Call the registered listeners in order, respecting and prioritising those that
* implement {@link Ordered}.
* @see org.springframework.batch.core.ItemReadListener#beforeRead()
*/
@Override
public void beforeRead() {<FILL_FUNCTION_BODY>}
/**
* Call the registered listeners in reverse order, respecting and prioritising those
* that implement {@link Ordered}.
* @see org.springframework.batch.core.ItemReadListener#onReadError(java.lang.Exception)
*/
@Override
public void onReadError(Exception ex) {
for (Iterator<ItemReadListener<? super T>> iterator = listeners.reverse(); iterator.hasNext();) {
ItemReadListener<? super T> listener = iterator.next();
listener.onReadError(ex);
}
}
}
|
for (Iterator<ItemReadListener<? super T>> iterator = listeners.iterator(); iterator.hasNext();) {
ItemReadListener<? super T> listener = iterator.next();
listener.beforeRead();
}
| 551
| 62
| 613
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/CompositeItemWriteListener.java
|
CompositeItemWriteListener
|
onWriteError
|
class CompositeItemWriteListener<S> implements ItemWriteListener<S> {
private final OrderedComposite<ItemWriteListener<? super S>> listeners = new OrderedComposite<>();
/**
* Public setter for the listeners.
* @param itemWriteListeners list of {@link ItemWriteListener}s to be called when
* write events occur.
*/
public void setListeners(List<? extends ItemWriteListener<? super S>> itemWriteListeners) {
this.listeners.setItems(itemWriteListeners);
}
/**
* Register additional listener.
* @param itemWriteListener list of {@link ItemWriteListener}s to be registered.
*/
public void register(ItemWriteListener<? super S> itemWriteListener) {
listeners.add(itemWriteListener);
}
/**
* Call the registered listeners in reverse order, respecting and prioritising those
* that implement {@link Ordered}.
* @see ItemWriteListener#afterWrite(Chunk)
*/
@Override
public void afterWrite(Chunk<? extends S> items) {
for (Iterator<ItemWriteListener<? super S>> iterator = listeners.reverse(); iterator.hasNext();) {
ItemWriteListener<? super S> listener = iterator.next();
listener.afterWrite(items);
}
}
/**
* Call the registered listeners in order, respecting and prioritising those that
* implement {@link Ordered}.
* @see ItemWriteListener#beforeWrite(Chunk)
*/
@Override
public void beforeWrite(Chunk<? extends S> items) {
for (Iterator<ItemWriteListener<? super S>> iterator = listeners.iterator(); iterator.hasNext();) {
ItemWriteListener<? super S> listener = iterator.next();
listener.beforeWrite(items);
}
}
/**
* Call the registered listeners in reverse order, respecting and prioritising those
* that implement {@link Ordered}.
* @see ItemWriteListener#onWriteError(Exception, Chunk)
*/
@Override
public void onWriteError(Exception ex, Chunk<? extends S> items) {<FILL_FUNCTION_BODY>}
}
|
for (Iterator<ItemWriteListener<? super S>> iterator = listeners.reverse(); iterator.hasNext();) {
ItemWriteListener<? super S> listener = iterator.next();
listener.onWriteError(ex, items);
}
| 549
| 68
| 617
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/CompositeJobExecutionListener.java
|
CompositeJobExecutionListener
|
afterJob
|
class CompositeJobExecutionListener implements JobExecutionListener {
private final OrderedComposite<JobExecutionListener> listeners = new OrderedComposite<>();
/**
* Public setter for the listeners.
* @param listeners list of {@link JobExecutionListener}s to be called when job
* execution events occur.
*/
public void setListeners(List<? extends JobExecutionListener> listeners) {
this.listeners.setItems(listeners);
}
/**
* Register additional listener.
* @param jobExecutionListener instance {@link JobExecutionListener} to be registered.
*/
public void register(JobExecutionListener jobExecutionListener) {
listeners.add(jobExecutionListener);
}
/**
* Call the registered listeners in reverse order, respecting and prioritising those
* that implement {@link Ordered}.
* @see org.springframework.batch.core.JobExecutionListener#afterJob(org.springframework.batch.core.JobExecution)
*/
@Override
public void afterJob(JobExecution jobExecution) {<FILL_FUNCTION_BODY>}
/**
* Call the registered listeners in order, respecting and prioritising those that
* implement {@link Ordered}.
* @see org.springframework.batch.core.JobExecutionListener#beforeJob(org.springframework.batch.core.JobExecution)
*/
@Override
public void beforeJob(JobExecution jobExecution) {
for (Iterator<JobExecutionListener> iterator = listeners.iterator(); iterator.hasNext();) {
JobExecutionListener listener = iterator.next();
listener.beforeJob(jobExecution);
}
}
}
|
for (Iterator<JobExecutionListener> iterator = listeners.reverse(); iterator.hasNext();) {
JobExecutionListener listener = iterator.next();
listener.afterJob(jobExecution);
}
| 398
| 57
| 455
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/CompositeSkipListener.java
|
CompositeSkipListener
|
onSkipInRead
|
class CompositeSkipListener<T, S> implements SkipListener<T, S> {
private final OrderedComposite<SkipListener<? super T, ? super S>> listeners = new OrderedComposite<>();
/**
* Public setter for the listeners.
* @param listeners list of {@link SkipListener}s to be called when skip events occur.
*/
public void setListeners(List<? extends SkipListener<? super T, ? super S>> listeners) {
this.listeners.setItems(listeners);
}
/**
* Register additional listener.
* @param listener instance of {@link SkipListener} to be registered.
*/
public void register(SkipListener<? super T, ? super S> listener) {
listeners.add(listener);
}
/**
* Call the registered listeners in order, respecting and prioritising those that
* implement {@link Ordered}.
* @see org.springframework.batch.core.SkipListener#onSkipInRead(java.lang.Throwable)
*/
@Override
public void onSkipInRead(Throwable t) {<FILL_FUNCTION_BODY>}
/**
* Call the registered listeners in order, respecting and prioritising those that
* implement {@link Ordered}.
* @see org.springframework.batch.core.SkipListener#onSkipInWrite(java.lang.Object,
* java.lang.Throwable)
*/
@Override
public void onSkipInWrite(S item, Throwable t) {
for (Iterator<SkipListener<? super T, ? super S>> iterator = listeners.iterator(); iterator.hasNext();) {
SkipListener<? super T, ? super S> listener = iterator.next();
listener.onSkipInWrite(item, t);
}
}
/**
* Call the registered listeners in order, respecting and prioritising those that
* implement {@link Ordered}.
* @see org.springframework.batch.core.SkipListener#onSkipInWrite(java.lang.Object,
* java.lang.Throwable)
*/
@Override
public void onSkipInProcess(T item, Throwable t) {
for (Iterator<SkipListener<? super T, ? super S>> iterator = listeners.iterator(); iterator.hasNext();) {
SkipListener<? super T, ? super S> listener = iterator.next();
listener.onSkipInProcess(item, t);
}
}
}
|
for (Iterator<SkipListener<? super T, ? super S>> iterator = listeners.iterator(); iterator.hasNext();) {
SkipListener<? super T, ? super S> listener = iterator.next();
listener.onSkipInRead(t);
}
| 611
| 72
| 683
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/CompositeStepExecutionListener.java
|
CompositeStepExecutionListener
|
afterStep
|
class CompositeStepExecutionListener implements StepExecutionListener {
private final OrderedComposite<StepExecutionListener> list = new OrderedComposite<>();
/**
* Public setter for the listeners.
* @param listeners list of {@link StepExecutionListener}s to be called when step
* execution events occur.
*/
public void setListeners(StepExecutionListener[] listeners) {
list.setItems(Arrays.asList(listeners));
}
/**
* Register additional listener.
* @param stepExecutionListener instance of {@link StepExecutionListener} to be
* registered.
*/
public void register(StepExecutionListener stepExecutionListener) {
list.add(stepExecutionListener);
}
/**
* Call the registered listeners in reverse order, respecting and prioritizing those
* that implement {@link Ordered}.
* @see org.springframework.batch.core.StepExecutionListener#afterStep(StepExecution)
*/
@Nullable
@Override
public ExitStatus afterStep(StepExecution stepExecution) {<FILL_FUNCTION_BODY>}
/**
* Call the registered listeners in order, respecting and prioritizing those that
* implement {@link Ordered}.
* @see org.springframework.batch.core.StepExecutionListener#beforeStep(StepExecution)
*/
@Override
public void beforeStep(StepExecution stepExecution) {
for (Iterator<StepExecutionListener> iterator = list.iterator(); iterator.hasNext();) {
StepExecutionListener listener = iterator.next();
listener.beforeStep(stepExecution);
}
}
}
|
for (Iterator<StepExecutionListener> iterator = list.reverse(); iterator.hasNext();) {
StepExecutionListener listener = iterator.next();
ExitStatus close = listener.afterStep(stepExecution);
stepExecution.setExitStatus(stepExecution.getExitStatus().and(close));
}
return stepExecution.getExitStatus();
| 390
| 91
| 481
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/ExecutionContextPromotionListener.java
|
ExecutionContextPromotionListener
|
afterPropertiesSet
|
class ExecutionContextPromotionListener implements StepExecutionListener, InitializingBean {
private String[] keys = null;
private String[] statuses = new String[] { ExitStatus.COMPLETED.getExitCode() };
private boolean strict = false;
@Nullable
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
ExecutionContext stepContext = stepExecution.getExecutionContext();
ExecutionContext jobContext = stepExecution.getJobExecution().getExecutionContext();
String exitCode = stepExecution.getExitStatus().getExitCode();
for (String statusPattern : statuses) {
if (PatternMatcher.match(statusPattern, exitCode)) {
for (String key : keys) {
if (stepContext.containsKey(key)) {
jobContext.put(key, stepContext.get(key));
}
else {
if (strict) {
throw new IllegalArgumentException(
"The key [" + key + "] was not found in the Step's ExecutionContext.");
}
}
}
break;
}
}
return null;
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
/**
* @param keys A list of keys corresponding to items in the {@link Step}
* {@link ExecutionContext} that must be promoted.
*/
public void setKeys(String[] keys) {
this.keys = keys;
}
/**
* @param statuses A list of statuses for which the promotion should occur. Statuses
* can may contain wildcards recognizable by a {@link PatternMatcher}.
*/
public void setStatuses(String[] statuses) {
this.statuses = statuses;
}
/**
* If set to TRUE, the listener will throw an exception if any 'key' is not found in
* the Step {@link ExecutionContext}. FALSE by default.
* @param strict boolean the value of the flag.
*/
public void setStrict(boolean strict) {
this.strict = strict;
}
}
|
Assert.state(this.keys != null, "The 'keys' property must be provided");
Assert.state(!ObjectUtils.isEmpty(this.keys), "The 'keys' property must not be empty");
Assert.state(this.statuses != null, "The 'statuses' property must be provided");
Assert.state(!ObjectUtils.isEmpty(this.statuses), "The 'statuses' property must not be empty");
| 511
| 109
| 620
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/JobListenerFactoryBean.java
|
JobListenerFactoryBean
|
getListener
|
class JobListenerFactoryBean extends AbstractListenerFactoryBean<JobExecutionListener> {
@Override
protected ListenerMetaData getMetaDataFromPropertyName(String propertyName) {
return JobListenerMetaData.fromPropertyName(propertyName);
}
@Override
protected ListenerMetaData[] getMetaDataValues() {
return JobListenerMetaData.values();
}
@Override
protected Class<?> getDefaultListenerClass() {
return JobExecutionListener.class;
}
@Override
public Class<?> getObjectType() {
return JobExecutionListener.class;
}
/**
* Convenience method to wrap any object and expose the appropriate
* {@link JobExecutionListener} interfaces.
* @param delegate a delegate object
* @return a JobListener instance constructed from the delegate
*/
public static JobExecutionListener getListener(Object delegate) {<FILL_FUNCTION_BODY>}
/**
* Convenience method to check whether the given object is or can be made into a
* {@link JobExecutionListener}.
* @param delegate the object to check
* @return true if the delegate is an instance of {@link JobExecutionListener}, or
* contains the marker annotations
*/
public static boolean isListener(Object delegate) {
return AbstractListenerFactoryBean.isListener(delegate, JobExecutionListener.class,
JobListenerMetaData.values());
}
}
|
JobListenerFactoryBean factory = new JobListenerFactoryBean();
factory.setDelegate(delegate);
return (JobExecutionListener) factory.getObject();
| 340
| 43
| 383
|
<methods>public non-sealed void <init>() ,public void afterPropertiesSet() throws java.lang.Exception,public java.lang.Object getObject() ,public static boolean isListener(java.lang.Object, Class<?>, org.springframework.batch.core.listener.ListenerMetaData[]) ,public boolean isSingleton() ,public void setDelegate(java.lang.Object) ,public void setMetaDataMap(Map<java.lang.String,java.lang.String>) <variables>private java.lang.Object delegate,private static final org.apache.commons.logging.Log logger,private Map<java.lang.String,java.lang.String> metaDataMap
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/JobParameterExecutionContextCopyListener.java
|
JobParameterExecutionContextCopyListener
|
beforeStep
|
class JobParameterExecutionContextCopyListener implements StepExecutionListener {
private Collection<String> keys = null;
/**
* @param keys A list of keys corresponding to items in the {@link JobParameters} that
* should be copied.
*/
public void setKeys(String[] keys) {
this.keys = Arrays.asList(keys);
}
/**
* Copy attributes from the {@link JobParameters} to the {@link Step}
* {@link ExecutionContext}, if not already present. The key is already present we
* assume that a restart is in operation and the previous value is needed. If the
* provided keys are empty defaults to copy all keys in the {@link JobParameters}.
*/
@Override
public void beforeStep(StepExecution stepExecution) {<FILL_FUNCTION_BODY>}
}
|
ExecutionContext stepContext = stepExecution.getExecutionContext();
JobParameters jobParameters = stepExecution.getJobParameters();
Collection<String> keys = this.keys;
if (keys == null) {
keys = jobParameters.getParameters().keySet();
}
for (String key : keys) {
if (!stepContext.containsKey(key)) {
stepContext.put(key, jobParameters.getParameters().get(key).getValue());
}
}
| 197
| 123
| 320
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MethodInvokerMethodInterceptor.java
|
MethodInvokerMethodInterceptor
|
invoke
|
class MethodInvokerMethodInterceptor implements MethodInterceptor {
private final Map<String, Set<MethodInvoker>> invokerMap;
private final boolean ordered;
public MethodInvokerMethodInterceptor(Map<String, Set<MethodInvoker>> invokerMap) {
this(invokerMap, false);
}
public MethodInvokerMethodInterceptor(Map<String, Set<MethodInvoker>> invokerMap, boolean ordered) {
this.ordered = ordered;
this.invokerMap = invokerMap;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof MethodInvokerMethodInterceptor other)) {
return false;
}
return invokerMap.equals(other.invokerMap);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return invokerMap.hashCode();
}
}
|
String methodName = invocation.getMethod().getName();
if (ordered && methodName.equals("getOrder")) {
return invocation.proceed();
}
Set<MethodInvoker> invokers = invokerMap.get(methodName);
if (invokers == null) {
return null;
}
ExitStatus status = null;
for (MethodInvoker invoker : invokers) {
Object retVal = invoker.invokeMethod(invocation.getArguments());
if (retVal instanceof ExitStatus) {
if (status != null) {
status = status.and((ExitStatus) retVal);
}
else {
status = (ExitStatus) retVal;
}
}
}
// The only possible return values are ExitStatus or int (from Ordered)
return status;
| 266
| 221
| 487
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/OrderedComposite.java
|
OrderedComposite
|
add
|
class OrderedComposite<S> {
private final List<S> unordered = new ArrayList<>();
private final List<S> ordered = new ArrayList<>();
private final Comparator<? super S> comparator = new AnnotationAwareOrderComparator();
private final List<S> list = new ArrayList<>();
/**
* Public setter for the listeners.
* @param items to set
*/
public void setItems(List<? extends S> items) {
unordered.clear();
ordered.clear();
for (S s : items) {
add(s);
}
}
/**
* Register additional item.
* @param item to add
*/
public void add(S item) {<FILL_FUNCTION_BODY>}
/**
* Public getter for the list of items. The {@link Ordered} items come first, followed
* by any unordered ones.
* @return an iterator over the list of items
*/
public Iterator<S> iterator() {
return Collections.unmodifiableList(list).iterator();
}
/**
* Public getter for the list of items in reverse. The {@link Ordered} items come
* last, after any unordered ones.
* @return an iterator over the list of items
*/
public Iterator<S> reverse() {
ArrayList<S> result = new ArrayList<>(list);
Collections.reverse(result);
return result.iterator();
}
}
|
if (item instanceof Ordered) {
if (!ordered.contains(item)) {
ordered.add(item);
}
}
else if (AnnotationUtils.isAnnotationDeclaredLocally(Order.class, item.getClass())) {
if (!ordered.contains(item)) {
ordered.add(item);
}
}
else if (!unordered.contains(item)) {
unordered.add(item);
}
ordered.sort(comparator);
list.clear();
list.addAll(ordered);
list.addAll(unordered);
| 374
| 155
| 529
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/listener/StepListenerFactoryBean.java
|
StepListenerFactoryBean
|
getListener
|
class StepListenerFactoryBean extends AbstractListenerFactoryBean<StepListener> {
@Override
protected ListenerMetaData getMetaDataFromPropertyName(String propertyName) {
return StepListenerMetaData.fromPropertyName(propertyName);
}
@Override
protected ListenerMetaData[] getMetaDataValues() {
return StepListenerMetaData.values();
}
@Override
protected Class<?> getDefaultListenerClass() {
return StepListener.class;
}
@Override
public Class<StepListener> getObjectType() {
return StepListener.class;
}
/**
* Convenience method to wrap any object and expose the appropriate
* {@link StepListener} interfaces.
* @param delegate a delegate object
* @return a StepListener instance constructed from the delegate
*/
public static StepListener getListener(Object delegate) {<FILL_FUNCTION_BODY>}
/**
* Convenience method to check whether the given object is or can be made into a
* {@link StepListener}.
* @param delegate the object to check
* @return true if the delegate is an instance of any of the {@link StepListener}
* interfaces, or contains the marker annotations
*/
public static boolean isListener(Object delegate) {
return AbstractListenerFactoryBean.isListener(delegate, StepListener.class, StepListenerMetaData.values());
}
}
|
StepListenerFactoryBean factory = new StepListenerFactoryBean();
factory.setDelegate(delegate);
return (StepListener) factory.getObject();
| 335
| 42
| 377
|
<methods>public non-sealed void <init>() ,public void afterPropertiesSet() throws java.lang.Exception,public java.lang.Object getObject() ,public static boolean isListener(java.lang.Object, Class<?>, org.springframework.batch.core.listener.ListenerMetaData[]) ,public boolean isSingleton() ,public void setDelegate(java.lang.Object) ,public void setMetaDataMap(Map<java.lang.String,java.lang.String>) <variables>private java.lang.Object delegate,private static final org.apache.commons.logging.Log logger,private Map<java.lang.String,java.lang.String> metaDataMap
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/observability/BatchMetrics.java
|
BatchMetrics
|
formatDuration
|
class BatchMetrics {
public static final String METRICS_PREFIX = "spring.batch.";
public static final String STATUS_SUCCESS = "SUCCESS";
public static final String STATUS_FAILURE = "FAILURE";
private BatchMetrics() {
}
/**
* Create a {@link Timer}.
* @param meterRegistry the meter registry to use
* @param name of the timer. Will be prefixed with
* {@link BatchMetrics#METRICS_PREFIX}.
* @param description of the timer
* @param tags of the timer
* @return a new timer instance
*/
public static Timer createTimer(MeterRegistry meterRegistry, String name, String description, Tag... tags) {
return Timer.builder(METRICS_PREFIX + name)
.description(description)
.tags(Arrays.asList(tags))
.register(meterRegistry);
}
/**
* Create a {@link Counter}.
* @param meterRegistry the meter registry to use
* @param name of the counter. Will be prefixed with
* {@link BatchMetrics#METRICS_PREFIX}.
* @param description of the counter
* @param tags of the counter
* @return a new timer instance
*/
public static Counter createCounter(MeterRegistry meterRegistry, String name, String description, Tag... tags) {
return Counter.builder(METRICS_PREFIX + name)
.description(description)
.tags(Arrays.asList(tags))
.register(meterRegistry);
}
/**
* Create a new {@link Observation}. It's not started, you must explicitly call
* {@link Observation#start()} to start it.
* <p>
* Remember to register the {@link DefaultMeterObservationHandler} via the
* {@code Metrics.globalRegistry.withTimerObservationHandler()} in the user code.
* Otherwise you won't observe any metrics.
* @param name of the observation
* @param context of the batch job observation
* @return a new observation instance
* @since 5.0
*/
public static Observation createObservation(String name, BatchJobContext context,
ObservationRegistry observationRegistry) {
return Observation.createNotStarted(name, context, observationRegistry);
}
/**
* Create a new {@link Observation}. It's not started, you must explicitly call
* {@link Observation#start()} to start it.
* <p>
* Remember to register the {@link DefaultMeterObservationHandler} via the
* {@code Metrics.globalRegistry.withTimerObservationHandler()} in the user code.
* Otherwise you won't observe any metrics.
* @param name of the observation
* @param context of the observation step context
* @return a new observation instance
* @since 5.0
*/
public static Observation createObservation(String name, BatchStepContext context,
ObservationRegistry observationRegistry) {
return Observation.createNotStarted(name, context, observationRegistry);
}
/**
* Create a new {@link Timer.Sample}.
* @param meterRegistry the meter registry to use
* @return a new timer sample instance
*/
public static Timer.Sample createTimerSample(MeterRegistry meterRegistry) {
return Timer.start(meterRegistry);
}
/**
* Create a new {@link LongTaskTimer}.
* @param meterRegistry the meter registry to use
* @param name of the long task timer. Will be prefixed with
* {@link BatchMetrics#METRICS_PREFIX}.
* @param description of the long task timer.
* @param tags of the timer
* @return a new long task timer instance
*/
public static LongTaskTimer createLongTaskTimer(MeterRegistry meterRegistry, String name, String description,
Tag... tags) {
return LongTaskTimer.builder(METRICS_PREFIX + name)
.description(description)
.tags(Arrays.asList(tags))
.register(meterRegistry);
}
/**
* Calculate the duration between two dates.
* @param startTime the start time
* @param endTime the end time
* @return the duration between start time and end time
*/
@Nullable
public static Duration calculateDuration(@Nullable LocalDateTime startTime, @Nullable LocalDateTime endTime) {
if (startTime == null || endTime == null) {
return null;
}
return Duration.between(startTime, endTime);
}
/**
* Format a duration in a human readable format like: 2h32m15s10ms.
* @param duration to format
* @return A human readable duration
*/
public static String formatDuration(@Nullable Duration duration) {<FILL_FUNCTION_BODY>}
}
|
if (duration == null || duration.isZero() || duration.isNegative()) {
return "";
}
StringBuilder formattedDuration = new StringBuilder();
long hours = duration.toHours();
long minutes = duration.toMinutes();
long seconds = duration.getSeconds();
long millis = duration.toMillis();
if (hours != 0) {
formattedDuration.append(hours).append("h");
}
if (minutes != 0) {
formattedDuration.append(minutes - TimeUnit.HOURS.toMinutes(hours)).append("m");
}
if (seconds != 0) {
formattedDuration.append(seconds - TimeUnit.MINUTES.toSeconds(minutes)).append("s");
}
if (millis != 0) {
formattedDuration.append(millis - TimeUnit.SECONDS.toMillis(seconds)).append("ms");
}
return formattedDuration.toString();
| 1,215
| 255
| 1,470
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/observability/DefaultBatchJobObservationConvention.java
|
DefaultBatchJobObservationConvention
|
getLowCardinalityKeyValues
|
class DefaultBatchJobObservationConvention implements BatchJobObservationConvention {
@Override
public KeyValues getLowCardinalityKeyValues(BatchJobContext context) {<FILL_FUNCTION_BODY>}
@Override
public KeyValues getHighCardinalityKeyValues(BatchJobContext context) {
JobExecution execution = context.getJobExecution();
return KeyValues.of(
BatchJobObservation.JobHighCardinalityTags.JOB_INSTANCE_ID
.withValue(String.valueOf(execution.getJobInstance().getInstanceId())),
BatchJobObservation.JobHighCardinalityTags.JOB_EXECUTION_ID
.withValue(String.valueOf(execution.getId())));
}
}
|
JobExecution execution = context.getJobExecution();
return KeyValues.of(
BatchJobObservation.JobLowCardinalityTags.JOB_NAME.withValue(execution.getJobInstance().getJobName()),
BatchJobObservation.JobLowCardinalityTags.JOB_STATUS
.withValue(execution.getExitStatus().getExitCode()));
| 183
| 92
| 275
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/observability/DefaultBatchStepObservationConvention.java
|
DefaultBatchStepObservationConvention
|
getLowCardinalityKeyValues
|
class DefaultBatchStepObservationConvention implements BatchStepObservationConvention {
@Override
public KeyValues getLowCardinalityKeyValues(BatchStepContext context) {<FILL_FUNCTION_BODY>}
@Override
public KeyValues getHighCardinalityKeyValues(BatchStepContext context) {
StepExecution execution = context.getStepExecution();
return KeyValues.of(BatchStepObservation.StepHighCardinalityTags.STEP_EXECUTION_ID
.withValue(String.valueOf(execution.getId())));
}
}
|
StepExecution execution = context.getStepExecution();
return KeyValues.of(BatchStepObservation.StepLowCardinalityTags.STEP_NAME.withValue(execution.getStepName()),
BatchStepObservation.StepLowCardinalityTags.JOB_NAME
.withValue(execution.getJobExecution().getJobInstance().getJobName()),
BatchStepObservation.StepLowCardinalityTags.STEP_STATUS
.withValue(execution.getExitStatus().getExitCode()));
| 137
| 124
| 261
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/AbstractPartitionHandler.java
|
AbstractPartitionHandler
|
handle
|
class AbstractPartitionHandler implements PartitionHandler {
protected int gridSize = 1;
/**
* Executes the specified {@link StepExecution} instances and returns an updated view
* of them. Throws an {@link Exception} if anything goes wrong.
* @param managerStepExecution the whole partition execution
* @param partitionStepExecutions the {@link StepExecution} instances to execute
* @return an updated view of these completed {@link StepExecution} instances
* @throws Exception if anything goes wrong. This allows implementations to be liberal
* and rely on the caller to translate an exception into a step failure as necessary.
*/
protected abstract Set<StepExecution> doHandle(StepExecution managerStepExecution,
Set<StepExecution> partitionStepExecutions) throws Exception;
/**
* @see PartitionHandler#handle(StepExecutionSplitter, StepExecution)
*/
@Override
public Collection<StepExecution> handle(final StepExecutionSplitter stepSplitter,
final StepExecution managerStepExecution) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Returns the number of step executions.
* @return the number of step executions
*/
public int getGridSize() {
return gridSize;
}
/**
* Passed to the {@link StepExecutionSplitter} in the
* {@link #handle(StepExecutionSplitter, StepExecution)} method, instructing it how
* many {@link StepExecution} instances are required, ideally. The
* {@link StepExecutionSplitter} is allowed to ignore the grid size in the case of a
* restart, since the input data partitions must be preserved.
* @param gridSize the number of step executions that will be created
*/
public void setGridSize(int gridSize) {
this.gridSize = gridSize;
}
}
|
final Set<StepExecution> stepExecutions = stepSplitter.split(managerStepExecution, gridSize);
return doHandle(managerStepExecution, stepExecutions);
| 437
| 44
| 481
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/DefaultStepExecutionAggregator.java
|
DefaultStepExecutionAggregator
|
aggregate
|
class DefaultStepExecutionAggregator implements StepExecutionAggregator {
/**
* Aggregates the input executions into the result {@link StepExecution}. The
* aggregated fields are
* <ul>
* <li>status - choosing the highest value using
* {@link BatchStatus#max(BatchStatus, BatchStatus)}</li>
* <li>exitStatus - using {@link ExitStatus#and(ExitStatus)}</li>
* <li>commitCount, rollbackCount, etc. - by arithmetic sum</li>
* </ul>
* @see StepExecutionAggregator #aggregate(StepExecution, Collection)
*/
@Override
public void aggregate(StepExecution result, Collection<StepExecution> executions) {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(result, "To aggregate into a result it must be non-null.");
if (executions == null) {
return;
}
for (StepExecution stepExecution : executions) {
BatchStatus status = stepExecution.getStatus();
result.setStatus(BatchStatus.max(result.getStatus(), status));
result.setExitStatus(result.getExitStatus().and(stepExecution.getExitStatus()));
result.setFilterCount(result.getFilterCount() + stepExecution.getFilterCount());
result.setProcessSkipCount(result.getProcessSkipCount() + stepExecution.getProcessSkipCount());
result.setCommitCount(result.getCommitCount() + stepExecution.getCommitCount());
result.setRollbackCount(result.getRollbackCount() + stepExecution.getRollbackCount());
result.setReadCount(result.getReadCount() + stepExecution.getReadCount());
result.setReadSkipCount(result.getReadSkipCount() + stepExecution.getReadSkipCount());
result.setWriteCount(result.getWriteCount() + stepExecution.getWriteCount());
result.setWriteSkipCount(result.getWriteSkipCount() + stepExecution.getWriteSkipCount());
}
| 197
| 318
| 515
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/MultiResourcePartitioner.java
|
MultiResourcePartitioner
|
partition
|
class MultiResourcePartitioner implements Partitioner {
private static final String DEFAULT_KEY_NAME = "fileName";
private static final String PARTITION_KEY = "partition";
private Resource[] resources = new Resource[0];
private String keyName = DEFAULT_KEY_NAME;
/**
* The resources to assign to each partition. In Spring configuration you can use a
* pattern to select multiple resources.
* @param resources the resources to use
*/
public void setResources(Resource[] resources) {
this.resources = resources;
}
/**
* The name of the key for the file name in each {@link ExecutionContext}. Defaults to
* "fileName".
* @param keyName the value of the key
*/
public void setKeyName(String keyName) {
this.keyName = keyName;
}
/**
* Assign the filename of each of the injected resources to an
* {@link ExecutionContext}.
*
* @see Partitioner#partition(int)
*/
@Override
public Map<String, ExecutionContext> partition(int gridSize) {<FILL_FUNCTION_BODY>}
}
|
Map<String, ExecutionContext> map = new HashMap<>(gridSize);
int i = 0;
for (Resource resource : resources) {
ExecutionContext context = new ExecutionContext();
Assert.state(resource.exists(), "Resource does not exist: " + resource);
try {
context.putString(keyName, resource.getURL().toExternalForm());
}
catch (IOException e) {
throw new IllegalArgumentException("File could not be located for: " + resource, e);
}
map.put(PARTITION_KEY + i, context);
i++;
}
return map;
| 284
| 165
| 449
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/PartitionStep.java
|
PartitionStep
|
doExecute
|
class PartitionStep extends AbstractStep {
private StepExecutionSplitter stepExecutionSplitter;
private PartitionHandler partitionHandler;
private StepExecutionAggregator stepExecutionAggregator = new DefaultStepExecutionAggregator();
/**
* A {@link PartitionHandler} which can send out step executions for remote processing
* and bring back the results.
* @param partitionHandler the {@link PartitionHandler} to set
*/
public void setPartitionHandler(PartitionHandler partitionHandler) {
this.partitionHandler = partitionHandler;
}
/**
* A {@link StepExecutionAggregator} that can aggregate step executions when they come
* back from the handler. Defaults to a {@link DefaultStepExecutionAggregator}.
* @param stepExecutionAggregator the {@link StepExecutionAggregator} to set
*/
public void setStepExecutionAggregator(StepExecutionAggregator stepExecutionAggregator) {
this.stepExecutionAggregator = stepExecutionAggregator;
}
/**
* Public setter for mandatory property {@link StepExecutionSplitter}.
* @param stepExecutionSplitter the {@link StepExecutionSplitter} to set
*/
public void setStepExecutionSplitter(StepExecutionSplitter stepExecutionSplitter) {
this.stepExecutionSplitter = stepExecutionSplitter;
}
/**
* Assert that mandatory properties are set (stepExecutionSplitter, partitionHandler)
* and delegate top superclass.
*
* @see AbstractStep#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(stepExecutionSplitter != null, "StepExecutionSplitter must be provided");
Assert.state(partitionHandler != null, "PartitionHandler must be provided");
super.afterPropertiesSet();
}
/**
* Delegate execution to the {@link PartitionHandler} provided. The
* {@link StepExecution} passed in here becomes the parent or manager execution for
* the partition, summarising the status on exit of the logical grouping of work
* carried out by the {@link PartitionHandler}. The individual step executions and
* their input parameters (through {@link ExecutionContext}) for the partition
* elements are provided by the {@link StepExecutionSplitter}.
* @param stepExecution the manager step execution for the partition
*
* @see Step#execute(StepExecution)
*/
@Override
protected void doExecute(StepExecution stepExecution) throws Exception {<FILL_FUNCTION_BODY>}
protected StepExecutionSplitter getStepExecutionSplitter() {
return stepExecutionSplitter;
}
protected PartitionHandler getPartitionHandler() {
return partitionHandler;
}
}
|
stepExecution.getExecutionContext().put(STEP_TYPE_KEY, this.getClass().getName());
// Wait for task completion and then aggregate the results
Collection<StepExecution> executions = partitionHandler.handle(stepExecutionSplitter, stepExecution);
stepExecution.upgradeStatus(BatchStatus.COMPLETED);
stepExecutionAggregator.aggregate(stepExecution, executions);
// If anything failed or had a problem we need to crap out
if (stepExecution.getStatus().isUnsuccessful()) {
throw new JobExecutionException("Partition handler returned an unsuccessful step");
}
| 636
| 154
| 790
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void afterPropertiesSet() throws java.lang.Exception,public final void execute(org.springframework.batch.core.StepExecution) throws org.springframework.batch.core.JobInterruptedException, org.springframework.batch.core.UnexpectedJobExecutionException,public java.lang.String getName() ,public int getStartLimit() ,public boolean isAllowStartIfComplete() ,public void registerStepExecutionListener(org.springframework.batch.core.StepExecutionListener) ,public void setAllowStartIfComplete(boolean) ,public void setBeanName(java.lang.String) ,public void setJobRepository(org.springframework.batch.core.repository.JobRepository) ,public void setMeterRegistry(io.micrometer.core.instrument.MeterRegistry) ,public void setName(java.lang.String) ,public void setObservationConvention(org.springframework.batch.core.observability.BatchStepObservationConvention) ,public void setObservationRegistry(io.micrometer.observation.ObservationRegistry) ,public void setStartLimit(int) ,public void setStepExecutionListeners(org.springframework.batch.core.StepExecutionListener[]) ,public java.lang.String toString() <variables>private boolean allowStartIfComplete,private org.springframework.batch.core.repository.JobRepository jobRepository,private static final org.apache.commons.logging.Log logger,private io.micrometer.core.instrument.MeterRegistry meterRegistry,private java.lang.String name,private org.springframework.batch.core.observability.BatchStepObservationConvention observationConvention,private io.micrometer.observation.ObservationRegistry observationRegistry,private int startLimit,private final org.springframework.batch.core.listener.CompositeStepExecutionListener stepExecutionListener
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/RemoteStepExecutionAggregator.java
|
RemoteStepExecutionAggregator
|
aggregate
|
class RemoteStepExecutionAggregator implements StepExecutionAggregator, InitializingBean {
private StepExecutionAggregator delegate = new DefaultStepExecutionAggregator();
private JobExplorer jobExplorer;
/**
* Create a new instance (useful for configuration purposes).
*/
public RemoteStepExecutionAggregator() {
}
/**
* Create a new instance with a job explorer that can be used to refresh the data when
* aggregating.
* @param jobExplorer the {@link JobExplorer} to use
*/
public RemoteStepExecutionAggregator(JobExplorer jobExplorer) {
super();
this.jobExplorer = jobExplorer;
}
/**
* @param jobExplorer the jobExplorer to set
*/
public void setJobExplorer(JobExplorer jobExplorer) {
this.jobExplorer = jobExplorer;
}
/**
* @param delegate the delegate to set
*/
public void setDelegate(StepExecutionAggregator delegate) {
this.delegate = delegate;
}
/**
* @throws Exception if the job explorer is not provided
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(jobExplorer != null, "A JobExplorer must be provided");
}
/**
* Aggregates the input executions into the result {@link StepExecution} delegating to
* the delegate aggregator once the input has been refreshed from the
* {@link JobExplorer}.
*
* @see StepExecutionAggregator #aggregate(StepExecution, Collection)
*/
@Override
public void aggregate(StepExecution result, Collection<StepExecution> executions) {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(result, "To aggregate into a result it must be non-null.");
if (executions == null) {
return;
}
Set<Long> stepExecutionIds = executions.stream().map(stepExecution -> {
Long id = stepExecution.getId();
Assert.state(id != null, "StepExecution has null id. It must be saved first: " + stepExecution);
return id;
}).collect(Collectors.toSet());
JobExecution jobExecution = jobExplorer.getJobExecution(result.getJobExecutionId());
Assert.state(jobExecution != null,
"Could not load JobExecution from JobRepository for id " + result.getJobExecutionId());
List<StepExecution> updates = jobExecution.getStepExecutions()
.stream()
.filter(stepExecution -> stepExecutionIds.contains(stepExecution.getId()))
.collect(Collectors.toList());
delegate.aggregate(result, updates);
| 418
| 251
| 669
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/SimplePartitioner.java
|
SimplePartitioner
|
partition
|
class SimplePartitioner implements Partitioner {
private static final String PARTITION_KEY = "partition";
@Override
public Map<String, ExecutionContext> partition(int gridSize) {<FILL_FUNCTION_BODY>}
}
|
Map<String, ExecutionContext> map = new HashMap<>(gridSize);
for (int i = 0; i < gridSize; i++) {
map.put(PARTITION_KEY + i, new ExecutionContext());
}
return map;
| 60
| 69
| 129
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandler.java
|
TaskExecutorPartitionHandler
|
doHandle
|
class TaskExecutorPartitionHandler extends AbstractPartitionHandler implements StepHolder, InitializingBean {
private TaskExecutor taskExecutor = new SyncTaskExecutor();
private Step step;
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(step != null, "A Step must be provided.");
}
/**
* Setter for the {@link TaskExecutor} that is used to farm out step executions to
* multiple threads.
* @param taskExecutor a {@link TaskExecutor}
*/
public void setTaskExecutor(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* Setter for the {@link Step} that will be used to execute the partitioned
* {@link StepExecution}. This is a regular Spring Batch step, with all the business
* logic required to complete an execution based on the input parameters in its
* {@link StepExecution} context.
* @param step the {@link Step} instance to use to execute business logic
*/
public void setStep(Step step) {
this.step = step;
}
/**
* The step instance that will be executed in parallel by this handler.
* @return the step instance that will be used
* @see StepHolder#getStep()
*/
@Override
public Step getStep() {
return this.step;
}
@Override
protected Set<StepExecution> doHandle(StepExecution managerStepExecution,
Set<StepExecution> partitionStepExecutions) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Creates the task executing the given step in the context of the given execution.
* @param step the step to execute
* @param stepExecution the given execution
* @return the task executing the given step
*/
protected FutureTask<StepExecution> createTask(final Step step, final StepExecution stepExecution) {
return new FutureTask<>(() -> {
step.execute(stepExecution);
return stepExecution;
});
}
}
|
Assert.notNull(step, "A Step must be provided.");
final Set<Future<StepExecution>> tasks = new HashSet<>(getGridSize());
final Set<StepExecution> result = new HashSet<>();
for (final StepExecution stepExecution : partitionStepExecutions) {
final FutureTask<StepExecution> task = createTask(step, stepExecution);
try {
taskExecutor.execute(task);
tasks.add(task);
}
catch (TaskRejectedException e) {
// couldn't execute one of the tasks
ExitStatus exitStatus = ExitStatus.FAILED
.addExitDescription("TaskExecutor rejected the task for this step.");
/*
* Set the status in case the caller is tracking it through the
* JobExecution.
*/
stepExecution.setStatus(BatchStatus.FAILED);
stepExecution.setExitStatus(exitStatus);
result.add(stepExecution);
}
}
for (Future<StepExecution> task : tasks) {
result.add(task.get());
}
return result;
| 483
| 285
| 768
|
<methods>public non-sealed void <init>() ,public int getGridSize() ,public Collection<org.springframework.batch.core.StepExecution> handle(org.springframework.batch.core.partition.StepExecutionSplitter, org.springframework.batch.core.StepExecution) throws java.lang.Exception,public void setGridSize(int) <variables>protected int gridSize
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/DefaultExecutionContextSerializer.java
|
DefaultExecutionContextSerializer
|
serialize
|
class DefaultExecutionContextSerializer implements ExecutionContextSerializer {
/**
* Serializes an execution context to the provided {@link OutputStream}. The stream is
* not closed prior to it's return.
* @param context {@link Map} contents of the {@code ExecutionContext}.
* @param out {@link OutputStream} where the serialized context information will be
* written.
*/
@Override
public void serialize(Map<String, Object> context, OutputStream out) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Deserializes an execution context from the provided {@link InputStream}.
* @param inputStream {@link InputStream} containing the information to be
* deserialized.
* @return the object serialized in the provided {@link InputStream}
*/
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> deserialize(InputStream inputStream) throws IOException {
var decodingStream = Base64.getDecoder().wrap(inputStream);
try {
var objectInputStream = new ObjectInputStream(decodingStream);
return (Map<String, Object>) objectInputStream.readObject();
}
catch (IOException ex) {
throw new IllegalArgumentException("Failed to deserialize object", ex);
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException("Failed to deserialize object type", ex);
}
}
}
|
Assert.notNull(context, "context is required");
Assert.notNull(out, "OutputStream is required");
for (Object value : context.values()) {
Assert.notNull(value, "A null value was found");
if (!(value instanceof Serializable)) {
throw new IllegalArgumentException(
"Value: [" + value + "] must be serializable. " + "Object of class: ["
+ value.getClass().getName() + "] must be an instance of " + Serializable.class);
}
}
var byteArrayOutputStream = new ByteArrayOutputStream(1024);
var encodingStream = Base64.getEncoder().wrap(byteArrayOutputStream);
try (var objectOutputStream = new ObjectOutputStream(encodingStream)) {
objectOutputStream.writeObject(context);
}
out.write(byteArrayOutputStream.toByteArray());
| 351
| 220
| 571
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/repository/support/AbstractJobRepositoryFactoryBean.java
|
AbstractJobRepositoryFactoryBean
|
afterPropertiesSet
|
class AbstractJobRepositoryFactoryBean implements FactoryBean<JobRepository>, InitializingBean {
private PlatformTransactionManager transactionManager;
private TransactionAttributeSource transactionAttributeSource;
private final ProxyFactory proxyFactory = new ProxyFactory();
private String isolationLevelForCreate = DEFAULT_ISOLATION_LEVEL;
private boolean validateTransactionState = true;
private static final String TRANSACTION_ISOLATION_LEVEL_PREFIX = "ISOLATION_";
private static final String TRANSACTION_PROPAGATION_PREFIX = "PROPAGATION_";
/**
* Default value for isolation level in create* method.
*/
private static final String DEFAULT_ISOLATION_LEVEL = TRANSACTION_ISOLATION_LEVEL_PREFIX + "SERIALIZABLE";
/**
* @return fully configured {@link JobInstanceDao} implementation.
* @throws Exception thrown if error occurs creating JobInstanceDao.
*/
protected abstract JobInstanceDao createJobInstanceDao() throws Exception;
/**
* @return fully configured {@link JobExecutionDao} implementation.
* @throws Exception thrown if error occurs creating JobExecutionDao.
*/
protected abstract JobExecutionDao createJobExecutionDao() throws Exception;
/**
* @return fully configured {@link StepExecutionDao} implementation.
* @throws Exception thrown if error occurs creating StepExecutionDao.
*/
protected abstract StepExecutionDao createStepExecutionDao() throws Exception;
/**
* @return fully configured {@link ExecutionContextDao} implementation.
* @throws Exception thrown if error occurs creating ExecutionContextDao.
*/
protected abstract ExecutionContextDao createExecutionContextDao() throws Exception;
/**
* The type of object to be returned from {@link #getObject()}.
* @return JobRepository.class
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
*/
@Override
public Class<JobRepository> getObjectType() {
return JobRepository.class;
}
@Override
public boolean isSingleton() {
return true;
}
/**
* Flag to determine whether to check for an existing transaction when a JobExecution
* is created. Defaults to true because it is usually a mistake, and leads to problems
* with restartability and also to deadlocks in multi-threaded steps.
* @param validateTransactionState the flag to set
*/
public void setValidateTransactionState(boolean validateTransactionState) {
this.validateTransactionState = validateTransactionState;
}
/**
* public setter for the isolation level to be used for the transaction when job
* execution entities are initially created. The default is ISOLATION_SERIALIZABLE,
* which prevents accidental concurrent execution of the same job
* (ISOLATION_REPEATABLE_READ would work as well).
* @param isolationLevelForCreate the isolation level name to set
*
* @see SimpleJobRepository#createJobExecution(String,
* org.springframework.batch.core.JobParameters)
*/
public void setIsolationLevelForCreate(String isolationLevelForCreate) {
this.isolationLevelForCreate = isolationLevelForCreate;
}
/**
* public setter for the isolation level to be used for the transaction when job
* execution entities are initially created. The default is ISOLATION_SERIALIZABLE,
* which prevents accidental concurrent execution of the same job
* (ISOLATION_REPEATABLE_READ would work as well).
* @param isolationLevelForCreate the isolation level to set
*
* @see SimpleJobRepository#createJobExecution(String,
* org.springframework.batch.core.JobParameters)
*/
public void setIsolationLevelForCreateEnum(Isolation isolationLevelForCreate) {
this.setIsolationLevelForCreate(TRANSACTION_ISOLATION_LEVEL_PREFIX + isolationLevelForCreate.name());
}
/**
* Public setter for the {@link PlatformTransactionManager}.
* @param transactionManager the transactionManager to set
*/
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
/**
* The transaction manager used in this factory. Useful to inject into steps and jobs,
* to ensure that they are using the same instance.
* @return the transactionManager
*/
public PlatformTransactionManager getTransactionManager() {
return transactionManager;
}
/**
* Set the transaction attributes source to use in the created proxy.
* @param transactionAttributeSource the transaction attributes source to use in the
* created proxy.
* @since 5.0
*/
public void setTransactionAttributeSource(TransactionAttributeSource transactionAttributeSource) {
Assert.notNull(transactionAttributeSource, "transactionAttributeSource must not be null.");
this.transactionAttributeSource = transactionAttributeSource;
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
@Override
public JobRepository getObject() throws Exception {
TransactionInterceptor advice = new TransactionInterceptor((TransactionManager) this.transactionManager,
this.transactionAttributeSource);
if (this.validateTransactionState) {
DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor((MethodInterceptor) invocation -> {
if (TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException("Existing transaction detected in JobRepository. "
+ "Please fix this and try again (e.g. remove @Transactional annotations from client).");
}
return invocation.proceed();
});
NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut();
pointcut.addMethodName("create*");
advisor.setPointcut(pointcut);
this.proxyFactory.addAdvisor(advisor);
}
this.proxyFactory.addAdvice(advice);
this.proxyFactory.setProxyTargetClass(false);
this.proxyFactory.addInterface(JobRepository.class);
this.proxyFactory.setTarget(getTarget());
return (JobRepository) this.proxyFactory.getProxy(getClass().getClassLoader());
}
private Object getTarget() throws Exception {
return new SimpleJobRepository(createJobInstanceDao(), createJobExecutionDao(), createStepExecutionDao(),
createExecutionContextDao());
}
}
|
Assert.state(transactionManager != null, "TransactionManager must not be null.");
if (this.transactionAttributeSource == null) {
Properties transactionAttributes = new Properties();
transactionAttributes.setProperty("create*",
TRANSACTION_PROPAGATION_PREFIX + Propagation.REQUIRES_NEW + "," + this.isolationLevelForCreate);
transactionAttributes.setProperty("getLastJobExecution*",
TRANSACTION_PROPAGATION_PREFIX + Propagation.REQUIRES_NEW + "," + this.isolationLevelForCreate);
transactionAttributes.setProperty("*", "PROPAGATION_REQUIRED");
this.transactionAttributeSource = new NameMatchTransactionAttributeSource();
((NameMatchTransactionAttributeSource) this.transactionAttributeSource)
.setProperties(transactionAttributes);
}
| 1,555
| 209
| 1,764
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/resource/StepExecutionSimpleCompletionPolicy.java
|
StepExecutionSimpleCompletionPolicy
|
start
|
class StepExecutionSimpleCompletionPolicy implements StepExecutionListener, CompletionPolicy {
private CompletionPolicy delegate;
private String keyName = "commit.interval";
/**
* Public setter for the key name of a Long value in the {@link JobParameters} that
* will contain a commit interval. Defaults to "commit.interval".
* @param keyName the keyName to set
*/
public void setKeyName(String keyName) {
this.keyName = keyName;
}
/**
* Set up a {@link SimpleCompletionPolicy} with a commit interval taken from the
* {@link JobParameters}. If there is a Long parameter with the given key name, the
* intValue of this parameter is used. If not an exception will be thrown.
*
* @see org.springframework.batch.core.StepExecutionListener#beforeStep(org.springframework.batch.core.StepExecution)
*/
@Override
public void beforeStep(StepExecution stepExecution) {
JobParameters jobParameters = stepExecution.getJobParameters();
Assert.state(jobParameters.getParameters().containsKey(keyName),
"JobParameters do not contain Long parameter with key=[" + keyName + "]");
delegate = new SimpleCompletionPolicy(jobParameters.getLong(keyName).intValue());
}
/**
* @return true if the commit interval has been reached or the result indicates
* completion
* @see CompletionPolicy#isComplete(RepeatContext, RepeatStatus)
*/
@Override
public boolean isComplete(RepeatContext context, RepeatStatus result) {
Assert.state(delegate != null, "The delegate resource has not been initialised. "
+ "Remember to register this object as a StepListener.");
return delegate.isComplete(context, result);
}
/**
* @return if the commit interval has been reached
* @see org.springframework.batch.repeat.CompletionPolicy#isComplete(org.springframework.batch.repeat.RepeatContext)
*/
@Override
public boolean isComplete(RepeatContext context) {
Assert.state(delegate != null, "The delegate resource has not been initialised. "
+ "Remember to register this object as a StepListener.");
return delegate.isComplete(context);
}
/**
* @return a new {@link RepeatContext}
* @see org.springframework.batch.repeat.CompletionPolicy#start(org.springframework.batch.repeat.RepeatContext)
*/
@Override
public RepeatContext start(RepeatContext parent) {<FILL_FUNCTION_BODY>}
/**
* @see org.springframework.batch.repeat.CompletionPolicy#update(org.springframework.batch.repeat.RepeatContext)
*/
@Override
public void update(RepeatContext context) {
Assert.state(delegate != null, "The delegate resource has not been initialised. "
+ "Remember to register this object as a StepListener.");
delegate.update(context);
}
/**
* Delegates to the wrapped {@link CompletionPolicy} if set, otherwise returns the
* value of {@link #setKeyName(String)}.
*/
@Override
public String toString() {
return (delegate == null) ? keyName : delegate.toString();
}
}
|
Assert.state(delegate != null, "The delegate resource has not been initialised. "
+ "Remember to register this object as a StepListener.");
return delegate.start(parent);
| 806
| 51
| 857
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/scope/BatchScopeSupport.java
|
BatchScopeSupport
|
postProcessBeanFactory
|
class BatchScopeSupport implements Scope, BeanFactoryPostProcessor, Ordered {
private boolean autoProxy = true;
private boolean proxyTargetClass = false;
private String name;
private int order = Ordered.LOWEST_PRECEDENCE;
/**
* @param order the order value to set priority of callback execution for the
* {@link BeanFactoryPostProcessor} part of this scope bean.
*/
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return order;
}
public String getName() {
return this.name;
}
/**
* Public setter for the name property. This can then be used as a bean definition
* attribute, e.g. scope="job".
* @param name the name to set for this scope.
*/
public void setName(String name) {
this.name = name;
}
/**
* Flag to indicate that proxies should use dynamic subclassing. This allows classes
* with no interface to be proxied. Defaults to false.
* @param proxyTargetClass set to true to have proxies created using dynamic
* subclasses
*/
public void setProxyTargetClass(boolean proxyTargetClass) {
this.proxyTargetClass = proxyTargetClass;
}
/**
* Flag to indicate that bean definitions need not be auto proxied. This gives control
* back to the declarer of the bean definition (e.g. in an @Configuration class).
* @param autoProxy the flag value to set (default true)
*/
public void setAutoProxy(boolean autoProxy) {
this.autoProxy = autoProxy;
}
public abstract String getTargetNamePrefix();
/**
* Register this scope with the enclosing BeanFactory.
*
* @see BeanFactoryPostProcessor#postProcessBeanFactory(ConfigurableListableBeanFactory)
* @param beanFactory the BeanFactory to register with
* @throws BeansException if there is a problem.
*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {<FILL_FUNCTION_BODY>}
/**
* Wrap a target bean definition in a proxy that defers initialization until after the
* {@link StepContext} is available. Amounts to adding <aop-auto-proxy/> to a
* step scoped bean.
* @param beanName the bean name to replace
* @param definition the bean definition to replace
* @param registry the enclosing {@link BeanDefinitionRegistry}
* @param proxyTargetClass true if we need to force use of dynamic subclasses
* @return a {@link BeanDefinitionHolder} for the new representation of the target.
* Caller should register it if needed to be visible at top level in bean factory.
*/
protected static BeanDefinitionHolder createScopedProxy(String beanName, BeanDefinition definition,
BeanDefinitionRegistry registry, boolean proxyTargetClass) {
BeanDefinitionHolder proxyHolder;
proxyHolder = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry,
proxyTargetClass);
registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
return proxyHolder;
}
/**
* Helper class to scan a bean definition hierarchy and force the use of auto-proxy
* for step scoped beans.
*
* @author Dave Syer
*
*/
protected static class Scopifier extends BeanDefinitionVisitor {
private final boolean proxyTargetClass;
private final BeanDefinitionRegistry registry;
private final String scope;
private final boolean scoped;
public Scopifier(BeanDefinitionRegistry registry, String scope, boolean proxyTargetClass, boolean scoped) {
super(value -> value);
this.registry = registry;
this.proxyTargetClass = proxyTargetClass;
this.scope = scope;
this.scoped = scoped;
}
@Override
protected Object resolveValue(Object value) {
BeanDefinition definition = null;
String beanName = null;
if (value instanceof BeanDefinition) {
definition = (BeanDefinition) value;
beanName = BeanDefinitionReaderUtils.generateBeanName(definition, registry);
}
else if (value instanceof BeanDefinitionHolder holder) {
definition = holder.getBeanDefinition();
beanName = holder.getBeanName();
}
if (definition != null) {
boolean nestedScoped = scope.equals(definition.getScope());
boolean scopeChangeRequiresProxy = !scoped && nestedScoped;
if (scopeChangeRequiresProxy) {
// Exit here so that nested inner bean definitions are not
// analysed
return createScopedProxy(beanName, definition, registry, proxyTargetClass);
}
}
// Nested inner bean definitions are recursively analysed here
value = super.resolveValue(value);
return value;
}
}
}
|
beanFactory.registerScope(name, this);
if (!autoProxy) {
return;
}
Assert.state(beanFactory instanceof BeanDefinitionRegistry,
"BeanFactory was not a BeanDefinitionRegistry, so JobScope cannot be used.");
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
for (String beanName : beanFactory.getBeanDefinitionNames()) {
if (!beanName.startsWith(getTargetNamePrefix())) {
BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
// Replace this or any of its inner beans with scoped proxy if it
// has this scope
boolean scoped = name.equals(definition.getScope());
Scopifier scopifier = new Scopifier(registry, name, proxyTargetClass, scoped);
scopifier.visitBeanDefinition(definition);
if (scoped && !definition.isAbstract()) {
createScopedProxy(beanName, definition, registry, proxyTargetClass);
}
}
}
| 1,264
| 262
| 1,526
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/scope/JobScope.java
|
JobScope
|
registerDestructionCallback
|
class JobScope extends BatchScopeSupport {
private static final String TARGET_NAME_PREFIX = "jobScopedTarget.";
private final Log logger = LogFactory.getLog(getClass());
private final Object mutex = new Object();
/**
* Context key for clients to use for conversation identifier.
*/
public static final String ID_KEY = "JOB_IDENTIFIER";
public JobScope() {
super();
setName("job");
}
/**
* This will be used to resolve expressions in job-scoped beans.
*/
@Override
public Object resolveContextualObject(String key) {
JobContext context = getContext();
// TODO: support for attributes as well maybe (setters not exposed yet
// so not urgent).
return new BeanWrapperImpl(context).getPropertyValue(key);
}
/**
* @see Scope#get(String, ObjectFactory)
*/
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
JobContext context = getContext();
Object scopedObject = context.getAttribute(name);
if (scopedObject == null) {
synchronized (mutex) {
scopedObject = context.getAttribute(name);
if (scopedObject == null) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Creating object in scope=%s, name=%s", this.getName(), name));
}
scopedObject = objectFactory.getObject();
context.setAttribute(name, scopedObject);
}
}
}
return scopedObject;
}
/**
* @see Scope#getConversationId()
*/
@Override
public String getConversationId() {
JobContext context = getContext();
return context.getId();
}
/**
* @see Scope#registerDestructionCallback(String, Runnable)
*/
@Override
public void registerDestructionCallback(String name, Runnable callback) {<FILL_FUNCTION_BODY>}
/**
* @see Scope#remove(String)
*/
@Override
public Object remove(String name) {
JobContext context = getContext();
if (logger.isDebugEnabled()) {
logger.debug(String.format("Removing from scope=%s, name=%s", this.getName(), name));
}
return context.removeAttribute(name);
}
/**
* Get an attribute accessor in the form of a {@link JobContext} that can be used to
* store scoped bean instances.
* @return the current job context which we can use as a scope storage medium
*/
private JobContext getContext() {
JobContext context = JobSynchronizationManager.getContext();
if (context == null) {
throw new IllegalStateException("No context holder available for job scope");
}
return context;
}
@Override
public String getTargetNamePrefix() {
return TARGET_NAME_PREFIX;
}
}
|
JobContext context = getContext();
if (logger.isDebugEnabled()) {
logger.debug(String.format("Registered destruction callback in scope=%s, name=%s", this.getName(), name));
}
context.registerDestructionCallback(name, callback);
| 767
| 73
| 840
|
<methods>public non-sealed void <init>() ,public java.lang.String getName() ,public int getOrder() ,public abstract java.lang.String getTargetNamePrefix() ,public void postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) throws org.springframework.beans.BeansException,public void setAutoProxy(boolean) ,public void setName(java.lang.String) ,public void setOrder(int) ,public void setProxyTargetClass(boolean) <variables>private boolean autoProxy,private java.lang.String name,private int order,private boolean proxyTargetClass
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/scope/StepScope.java
|
StepScope
|
registerDestructionCallback
|
class StepScope extends BatchScopeSupport {
private static final String TARGET_NAME_PREFIX = "scopedTarget.";
private final Log logger = LogFactory.getLog(getClass());
private final Object mutex = new Object();
/**
* Context key for clients to use for conversation identifier.
*/
public static final String ID_KEY = "STEP_IDENTIFIER";
public StepScope() {
super();
setName("step");
}
/**
* This will be used to resolve expressions in step-scoped beans.
*/
@Override
public Object resolveContextualObject(String key) {
StepContext context = getContext();
// TODO: support for attributes as well maybe (setters not exposed yet
// so not urgent).
return new BeanWrapperImpl(context).getPropertyValue(key);
}
/**
* @see Scope#get(String, ObjectFactory)
*/
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
StepContext context = getContext();
Object scopedObject = context.getAttribute(name);
if (scopedObject == null) {
synchronized (mutex) {
scopedObject = context.getAttribute(name);
if (scopedObject == null) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Creating object in scope=%s, name=%s", this.getName(), name));
}
scopedObject = objectFactory.getObject();
context.setAttribute(name, scopedObject);
}
}
}
return scopedObject;
}
/**
* @see Scope#getConversationId()
*/
@Override
public String getConversationId() {
StepContext context = getContext();
return context.getId();
}
/**
* @see Scope#registerDestructionCallback(String, Runnable)
*/
@Override
public void registerDestructionCallback(String name, Runnable callback) {<FILL_FUNCTION_BODY>}
/**
* @see Scope#remove(String)
*/
@Override
public Object remove(String name) {
StepContext context = getContext();
if (logger.isDebugEnabled()) {
logger.debug(String.format("Removing from scope=%s, name=%s", this.getName(), name));
}
return context.removeAttribute(name);
}
/**
* Get an attribute accessor in the form of a {@link StepContext} that can be used to
* store scoped bean instances.
* @return the current step context which we can use as a scope storage medium
*/
private StepContext getContext() {
StepContext context = StepSynchronizationManager.getContext();
if (context == null) {
throw new IllegalStateException("No context holder available for step scope");
}
return context;
}
@Override
public String getTargetNamePrefix() {
return TARGET_NAME_PREFIX;
}
}
|
StepContext context = getContext();
if (logger.isDebugEnabled()) {
logger.debug(String.format("Registered destruction callback in scope=%s, name=%s", this.getName(), name));
}
context.registerDestructionCallback(name, callback);
| 766
| 73
| 839
|
<methods>public non-sealed void <init>() ,public java.lang.String getName() ,public int getOrder() ,public abstract java.lang.String getTargetNamePrefix() ,public void postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) throws org.springframework.beans.BeansException,public void setAutoProxy(boolean) ,public void setName(java.lang.String) ,public void setOrder(int) ,public void setProxyTargetClass(boolean) <variables>private boolean autoProxy,private java.lang.String name,private int order,private boolean proxyTargetClass
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/JobContext.java
|
JobContext
|
toString
|
class JobContext extends SynchronizedAttributeAccessor {
private final JobExecution jobExecution;
private final Map<String, Set<Runnable>> callbacks = new HashMap<>();
public JobContext(JobExecution jobExecution) {
super();
Assert.notNull(jobExecution, "A JobContext must have a non-null JobExecution");
this.jobExecution = jobExecution;
}
/**
* Convenient accessor for current job name identifier.
* @return the job name identifier of the enclosing {@link JobInstance} associated
* with the current {@link JobExecution}
*/
public String getJobName() {
Assert.state(jobExecution.getJobInstance() != null, "JobExecution does not have a JobInstance");
return jobExecution.getJobInstance().getJobName();
}
/**
* Convenient accessor for System properties to make it easy to access them from
* placeholder expressions.
* @return the current System properties
*/
public Properties getSystemProperties() {
return System.getProperties();
}
/**
* @return a map containing the items from the job {@link ExecutionContext}
*/
public Map<String, Object> getJobExecutionContext() {
return jobExecution.getExecutionContext().toMap();
}
/**
* @return a map containing the items from the {@link JobParameters}
*/
public Map<String, Object> getJobParameters() {
Map<String, Object> result = new HashMap<>();
for (Entry<String, JobParameter<?>> entry : jobExecution.getJobParameters().getParameters().entrySet()) {
result.put(entry.getKey(), entry.getValue().getValue());
}
return Collections.unmodifiableMap(result);
}
/**
* Allow clients to register callbacks for clean up on close.
* @param name the callback id (unique attribute key in this context)
* @param callback a callback to execute on close
*/
public void registerDestructionCallback(String name, Runnable callback) {
synchronized (callbacks) {
Set<Runnable> set = callbacks.computeIfAbsent(name, k -> new HashSet<>());
set.add(callback);
}
}
private void unregisterDestructionCallbacks(String name) {
synchronized (callbacks) {
callbacks.remove(name);
}
}
/**
* Override base class behaviour to ensure destruction callbacks are unregistered as
* well as the default behaviour.
*
* @see SynchronizedAttributeAccessor#removeAttribute(String)
*/
@Override
@Nullable
public Object removeAttribute(String name) {
unregisterDestructionCallbacks(name);
return super.removeAttribute(name);
}
/**
* Clean up the context at the end of a step execution. Must be called once at the end
* of a step execution to honour the destruction callback contract from the
* {@link StepScope}.
*/
public void close() {
List<Exception> errors = new ArrayList<>();
Map<String, Set<Runnable>> copy = Collections.unmodifiableMap(callbacks);
for (Entry<String, Set<Runnable>> entry : copy.entrySet()) {
Set<Runnable> set = entry.getValue();
for (Runnable callback : set) {
if (callback != null) {
/*
* The documentation of the interface says that these callbacks must
* not throw exceptions, but we don't trust them necessarily...
*/
try {
callback.run();
}
catch (RuntimeException t) {
errors.add(t);
}
}
}
}
if (errors.isEmpty()) {
return;
}
Exception error = errors.get(0);
if (error instanceof RuntimeException) {
throw (RuntimeException) error;
}
else {
throw new UnexpectedJobExecutionException(
"Could not close step context, rethrowing first of " + errors.size() + " exceptions.", error);
}
}
/**
* The current {@link JobExecution} that is active in this context.
* @return the current {@link JobExecution}
*/
public JobExecution getJobExecution() {
return jobExecution;
}
/**
* @return unique identifier for this context based on the step execution
*/
public String getId() {
Assert.state(jobExecution.getId() != null,
"JobExecution has no id. " + "It must be saved before it can be used in job scope.");
return "jobExecution#" + jobExecution.getId();
}
/**
* Extend the base class method to include the job execution itself as a key (i.e. two
* contexts are only equal if their job executions are the same).
*/
@Override
public boolean equals(Object other) {
if (!(other instanceof JobContext context)) {
return false;
}
if (other == this) {
return true;
}
if (context.jobExecution == jobExecution) {
return true;
}
return jobExecution.equals(context.jobExecution);
}
/**
* Overrides the default behaviour to provide a hash code based only on the job
* execution.
*/
@Override
public int hashCode() {
return jobExecution.hashCode();
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return super.toString() + ", jobExecutionContext=" + getJobExecutionContext() + ", jobParameters="
+ getJobParameters();
| 1,367
| 36
| 1,403
|
<methods>public non-sealed void <init>() ,public java.lang.String[] attributeNames() ,public boolean equals(java.lang.Object) ,public java.lang.Object getAttribute(java.lang.String) ,public boolean hasAttribute(java.lang.String) ,public int hashCode() ,public java.lang.Object removeAttribute(java.lang.String) ,public void setAttribute(java.lang.String, java.lang.Object) ,public java.lang.Object setAttributeIfAbsent(java.lang.String, java.lang.Object) ,public java.lang.String toString() <variables>org.springframework.core.AttributeAccessorSupport support
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/JobScopeManager.java
|
JobScopeManager
|
execute
|
class JobScopeManager {
@Around("execution(void org.springframework.batch.core.Job+.execute(*)) && target(job) && args(jobExecution)")
public void execute(Job job, JobExecution jobExecution) {<FILL_FUNCTION_BODY>}
}
|
JobSynchronizationManager.register(jobExecution);
try {
job.execute(jobExecution);
}
finally {
JobSynchronizationManager.release();
}
| 70
| 55
| 125
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/StepContext.java
|
StepContext
|
getJobInstanceId
|
class StepContext extends SynchronizedAttributeAccessor {
private final StepExecution stepExecution;
private final Map<String, Set<Runnable>> callbacks = new HashMap<>();
/**
* Create a new instance of {@link StepContext} for this {@link StepExecution}.
* @param stepExecution a step execution
*/
public StepContext(StepExecution stepExecution) {
super();
Assert.notNull(stepExecution, "A StepContext must have a non-null StepExecution");
this.stepExecution = stepExecution;
}
/**
* Convenient accessor for current step name identifier. Usually this is the same as
* the bean name of the step that is executing (but might not be e.g. in a partition).
* @return the step name identifier of the current {@link StepExecution}
*/
public String getStepName() {
return stepExecution.getStepName();
}
/**
* Convenient accessor for current job name identifier.
* @return the job name identifier of the enclosing {@link JobInstance} associated
* with the current {@link StepExecution}
*/
public String getJobName() {
Assert.state(stepExecution.getJobExecution() != null, "StepExecution does not have a JobExecution");
Assert.state(stepExecution.getJobExecution().getJobInstance() != null,
"StepExecution does not have a JobInstance");
return stepExecution.getJobExecution().getJobInstance().getJobName();
}
/**
* Convenient accessor for current {@link JobInstance} identifier.
* @return the identifier of the enclosing {@link JobInstance} associated with the
* current {@link StepExecution}
*/
public Long getJobInstanceId() {<FILL_FUNCTION_BODY>}
/**
* Convenient accessor for System properties to make it easy to access them from
* placeholder expressions.
* @return the current System properties
*/
public Properties getSystemProperties() {
return System.getProperties();
}
/**
* @return a map containing the items from the step {@link ExecutionContext}
*/
public Map<String, Object> getStepExecutionContext() {
return stepExecution.getExecutionContext().toMap();
}
/**
* @return a map containing the items from the job {@link ExecutionContext}
*/
public Map<String, Object> getJobExecutionContext() {
return stepExecution.getJobExecution().getExecutionContext().toMap();
}
/**
* @return a map containing the items from the {@link JobParameters}
*/
public Map<String, Object> getJobParameters() {
Map<String, Object> result = new HashMap<>();
for (Entry<String, JobParameter<?>> entry : stepExecution.getJobParameters().getParameters().entrySet()) {
result.put(entry.getKey(), entry.getValue().getValue());
}
return Collections.unmodifiableMap(result);
}
/**
* Allow clients to register callbacks for clean up on close.
* @param name the callback id (unique attribute key in this context)
* @param callback a callback to execute on close
*/
public void registerDestructionCallback(String name, Runnable callback) {
synchronized (callbacks) {
Set<Runnable> set = callbacks.computeIfAbsent(name, k -> new HashSet<>());
set.add(callback);
}
}
private void unregisterDestructionCallbacks(String name) {
synchronized (callbacks) {
callbacks.remove(name);
}
}
/**
* Override base class behaviour to ensure destruction callbacks are unregistered as
* well as the default behaviour.
*
* @see SynchronizedAttributeAccessor#removeAttribute(String)
*/
@Override
@Nullable
public Object removeAttribute(String name) {
unregisterDestructionCallbacks(name);
return super.removeAttribute(name);
}
/**
* Clean up the context at the end of a step execution. Must be called once at the end
* of a step execution to honour the destruction callback contract from the
* {@link StepScope}.
*/
public void close() {
List<Exception> errors = new ArrayList<>();
Map<String, Set<Runnable>> copy = Collections.unmodifiableMap(callbacks);
for (Entry<String, Set<Runnable>> entry : copy.entrySet()) {
Set<Runnable> set = entry.getValue();
for (Runnable callback : set) {
if (callback != null) {
/*
* The documentation of the interface says that these callbacks must
* not throw exceptions, but we don't trust them necessarily...
*/
try {
callback.run();
}
catch (RuntimeException t) {
errors.add(t);
}
}
}
}
if (errors.isEmpty()) {
return;
}
Exception error = errors.get(0);
if (error instanceof RuntimeException) {
throw (RuntimeException) error;
}
else {
throw new UnexpectedJobExecutionException(
"Could not close step context, rethrowing first of " + errors.size() + " exceptions.", error);
}
}
/**
* The current {@link StepExecution} that is active in this context.
* @return the current {@link StepExecution}
*/
public StepExecution getStepExecution() {
return stepExecution;
}
/**
* @return unique identifier for this context based on the step execution
*/
public String getId() {
Assert.state(stepExecution.getId() != null,
"StepExecution has no id. " + "It must be saved before it can be used in step scope.");
return "execution#" + stepExecution.getId();
}
/**
* Extend the base class method to include the step execution itself as a key (i.e.
* two contexts are only equal if their step executions are the same).
*
* @see SynchronizedAttributeAccessor#equals(Object)
*/
@Override
public boolean equals(Object other) {
if (!(other instanceof StepContext context)) {
return false;
}
if (other == this) {
return true;
}
if (context.stepExecution == stepExecution) {
return true;
}
return stepExecution.equals(context.stepExecution);
}
/**
* Overrides the default behaviour to provide a hash code based only on the step
* execution.
*
* @see SynchronizedAttributeAccessor#hashCode()
*/
@Override
public int hashCode() {
return stepExecution.hashCode();
}
@Override
public String toString() {
return super.toString() + ", stepExecutionContext=" + getStepExecutionContext() + ", jobExecutionContext="
+ getJobExecutionContext() + ", jobParameters=" + getJobParameters();
}
}
|
Assert.state(stepExecution.getJobExecution() != null, "StepExecution does not have a JobExecution");
Assert.state(stepExecution.getJobExecution().getJobInstance() != null,
"StepExecution does not have a JobInstance");
return stepExecution.getJobExecution().getJobInstance().getInstanceId();
| 1,731
| 82
| 1,813
|
<methods>public non-sealed void <init>() ,public java.lang.String[] attributeNames() ,public boolean equals(java.lang.Object) ,public java.lang.Object getAttribute(java.lang.String) ,public boolean hasAttribute(java.lang.String) ,public int hashCode() ,public java.lang.Object removeAttribute(java.lang.String) ,public void setAttribute(java.lang.String, java.lang.Object) ,public java.lang.Object setAttributeIfAbsent(java.lang.String, java.lang.Object) ,public java.lang.String toString() <variables>org.springframework.core.AttributeAccessorSupport support
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/StepContextRepeatCallback.java
|
StepContextRepeatCallback
|
doInIteration
|
class StepContextRepeatCallback implements RepeatCallback {
private final Queue<ChunkContext> attributeQueue = new LinkedBlockingQueue<>();
private final StepExecution stepExecution;
private final Log logger = LogFactory.getLog(StepContextRepeatCallback.class);
/**
* @param stepExecution instance of {@link StepExecution} to be used by
* StepContextRepeatCallback.
*/
public StepContextRepeatCallback(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
/**
* Manage the {@link StepContext} lifecycle. Business processing should be delegated
* to {@link #doInChunkContext(RepeatContext, ChunkContext)}. This is to ensure that
* the current thread has a reference to the context, even if the callback is executed
* in a pooled thread. Handles the registration and unregistration of the step
* context, so clients should not duplicate those calls.
*
* @see RepeatCallback#doInIteration(RepeatContext)
*/
@Override
public RepeatStatus doInIteration(RepeatContext context) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Do the work required for this chunk of the step. The {@link ChunkContext} provided
* is managed by the base class, so that if there is still work to do for the task in
* hand state can be stored here. In a multi-threaded client, the base class ensures
* that only one thread at a time can be working on each instance of
* {@link ChunkContext}. Workers should signal that they are finished with a context
* by removing all the attributes they have added. If a worker does not remove them
* another thread might see stale state.
* @param context the current {@link RepeatContext}
* @param chunkContext the chunk context in which to carry out the work
* @return the repeat status from the execution
* @throws Exception implementations can throw an exception if anything goes wrong
*/
public abstract RepeatStatus doInChunkContext(RepeatContext context, ChunkContext chunkContext) throws Exception;
}
|
// The StepContext has to be the same for all chunks,
// otherwise step-scoped beans will be re-initialised for each chunk.
StepContext stepContext = StepSynchronizationManager.register(stepExecution);
if (logger.isDebugEnabled()) {
logger.debug("Preparing chunk execution for StepContext: " + ObjectUtils.identityToString(stepContext));
}
ChunkContext chunkContext = attributeQueue.poll();
if (chunkContext == null) {
chunkContext = new ChunkContext(stepContext);
}
try {
if (logger.isDebugEnabled()) {
logger.debug("Chunk execution starting: queue size=" + attributeQueue.size());
}
return doInChunkContext(context, chunkContext);
}
finally {
// Still some stuff to do with the data in this chunk,
// pass it back.
if (!chunkContext.isComplete()) {
attributeQueue.add(chunkContext);
}
StepSynchronizationManager.close();
}
| 508
| 271
| 779
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/StepScopeManager.java
|
StepScopeManager
|
execute
|
class StepScopeManager {
@Around("execution(void org.springframework.batch.core.Step+.execute(*)) && target(step) && args(stepExecution)")
public void execute(Step step, StepExecution stepExecution) throws JobInterruptedException {<FILL_FUNCTION_BODY>}
}
|
StepSynchronizationManager.register(stepExecution);
try {
step.execute(stepExecution);
}
finally {
StepSynchronizationManager.release();
}
| 75
| 55
| 130
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/SynchronizationManagerSupport.java
|
SynchronizationManagerSupport
|
increment
|
class SynchronizationManagerSupport<E, C> {
/*
* We have to deal with single and multi-threaded execution, with a single and with
* multiple step execution instances. That's 2x2 = 4 scenarios.
*/
/**
* Storage for the current execution; has to be ThreadLocal because it is needed to
* locate a context in components that are not part of a step/job (like when
* re-hydrating a scoped proxy). Doesn't use InheritableThreadLocal because there are
* side effects if a step is trying to run multiple child steps (e.g. with
* partitioning). The Stack is used to cover the single threaded case, so that the API
* is the same as multi-threaded.
*/
private final ThreadLocal<Stack<E>> executionHolder = new ThreadLocal<>();
/**
* Reference counter for each execution: how many threads are using the same one?
*/
private final Map<E, AtomicInteger> counts = new ConcurrentHashMap<>();
/**
* Simple map from a running execution to the associated context.
*/
private final Map<E, C> contexts = new ConcurrentHashMap<>();
/**
* Getter for the current context if there is one, otherwise returns {@code null}.
* @return the current context or {@code null} if there is none (if one has not been
* registered for this thread).
*/
@Nullable
public C getContext() {
if (getCurrent().isEmpty()) {
return null;
}
synchronized (contexts) {
return contexts.get(getCurrent().peek());
}
}
/**
* Register a context with the current thread - always put a matching {@link #close()}
* call in a finally block to ensure that the correct context is available in the
* enclosing block.
* @param execution the execution to register
* @return a new context or the current one if it has the same execution
*/
@Nullable
public C register(@Nullable E execution) {
if (execution == null) {
return null;
}
getCurrent().push(execution);
C context;
synchronized (contexts) {
context = contexts.get(execution);
if (context == null) {
context = createNewContext(execution);
contexts.put(execution, context);
}
}
increment();
return context;
}
/**
* Method for unregistering the current context - should always and only be used by in
* conjunction with a matching {@link #register(Object)} to ensure that
* {@link #getContext()} always returns the correct value. Does not call close on the
* context - that is left up to the caller because he has a reference to the context
* (having registered it) and only he has knowledge of when the execution actually
* ended.
*/
public void close() {
C oldSession = getContext();
if (oldSession == null) {
return;
}
decrement();
}
private void decrement() {
E current = getCurrent().pop();
if (current != null) {
int remaining = counts.get(current).decrementAndGet();
if (remaining <= 0) {
synchronized (contexts) {
contexts.remove(current);
counts.remove(current);
}
}
}
}
public void increment() {<FILL_FUNCTION_BODY>}
public Stack<E> getCurrent() {
if (executionHolder.get() == null) {
executionHolder.set(new Stack<>());
}
return executionHolder.get();
}
/**
* A convenient "deep" close operation. Call this instead of {@link #close()} if the
* execution for the current context is ending. Delegates to {@link #close(Object)}
* and then ensures that {@link #close()} is also called in a finally block.
*/
public void release() {
C context = getContext();
try {
if (context != null) {
close(context);
}
}
finally {
close();
}
}
protected abstract void close(C context);
protected abstract C createNewContext(E execution);
}
|
E current = getCurrent().peek();
if (current != null) {
AtomicInteger count;
synchronized (counts) {
count = counts.get(current);
if (count == null) {
count = new AtomicInteger();
counts.put(current, count);
}
}
count.incrementAndGet();
}
| 1,070
| 104
| 1,174
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/step/NoWorkFoundStepExecutionListener.java
|
NoWorkFoundStepExecutionListener
|
afterStep
|
class NoWorkFoundStepExecutionListener implements StepExecutionListener {
@Nullable
@Override
public ExitStatus afterStep(StepExecution stepExecution) {<FILL_FUNCTION_BODY>}
}
|
if (stepExecution.getReadCount() == 0) {
return ExitStatus.FAILED;
}
return null;
| 49
| 37
| 86
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/step/ThreadStepInterruptionPolicy.java
|
ThreadStepInterruptionPolicy
|
checkInterrupted
|
class ThreadStepInterruptionPolicy implements StepInterruptionPolicy {
protected static final Log logger = LogFactory.getLog(ThreadStepInterruptionPolicy.class);
/**
* Returns if the current job lifecycle has been interrupted by checking if the
* current thread is interrupted.
*/
@Override
public void checkInterrupted(StepExecution stepExecution) throws JobInterruptedException {<FILL_FUNCTION_BODY>}
/**
* @param stepExecution the current context
* @return true if the job has been interrupted
*/
private boolean isInterrupted(StepExecution stepExecution) {
boolean interrupted = Thread.currentThread().isInterrupted();
if (interrupted) {
logger.info("Step interrupted through Thread API");
}
else {
interrupted = stepExecution.isTerminateOnly();
if (interrupted) {
logger.info("Step interrupted through StepExecution");
}
}
return interrupted;
}
}
|
if (isInterrupted(stepExecution)) {
throw new JobInterruptedException("Job interrupted status detected.");
}
| 239
| 35
| 274
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/FlowStepBuilder.java
|
FlowStepBuilder
|
build
|
class FlowStepBuilder extends StepBuilderHelper<FlowStepBuilder> {
private Flow flow;
/**
* Create a new builder initialized with any properties in the parent. The parent is
* copied, so it can be re-used.
* @param parent a parent helper containing common step properties
*/
public FlowStepBuilder(StepBuilderHelper<?> parent) {
super(parent);
}
/**
* Provide a flow to execute during the step.
* @param flow the flow to execute
* @return this for fluent chaining
*/
public FlowStepBuilder flow(Flow flow) {
this.flow = flow;
return this;
}
/**
* Build a step that executes the flow provided, normally composed of other steps. The
* flow is not executed in a transaction because the individual steps are supposed to
* manage their own transaction state.
* @return a flow step
*/
public Step build() {<FILL_FUNCTION_BODY>}
@Override
protected FlowStepBuilder self() {
return this;
}
}
|
FlowStep step = new FlowStep();
step.setName(getName());
step.setFlow(flow);
super.enhance(step);
try {
step.afterPropertiesSet();
}
catch (Exception e) {
throw new StepBuilderException(e);
}
return step;
| 262
| 90
| 352
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, org.springframework.batch.core.repository.JobRepository) ,public org.springframework.batch.core.step.builder.FlowStepBuilder allowStartIfComplete(boolean) ,public org.springframework.batch.core.step.builder.FlowStepBuilder listener(java.lang.Object) ,public org.springframework.batch.core.step.builder.FlowStepBuilder listener(org.springframework.batch.core.StepExecutionListener) ,public org.springframework.batch.core.step.builder.FlowStepBuilder meterRegistry(io.micrometer.core.instrument.MeterRegistry) ,public org.springframework.batch.core.step.builder.FlowStepBuilder observationConvention(org.springframework.batch.core.observability.BatchStepObservationConvention) ,public org.springframework.batch.core.step.builder.FlowStepBuilder observationRegistry(io.micrometer.observation.ObservationRegistry) ,public org.springframework.batch.core.step.builder.FlowStepBuilder repository(org.springframework.batch.core.repository.JobRepository) ,public org.springframework.batch.core.step.builder.FlowStepBuilder startLimit(int) <variables>protected final org.apache.commons.logging.Log logger,protected final non-sealed org.springframework.batch.core.step.builder.StepBuilderHelper.CommonStepProperties properties
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.