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-integration/src/main/java/org/springframework/batch/integration/chunk/JmsRedeliveredExtractor.java
|
JmsRedeliveredExtractor
|
extract
|
class JmsRedeliveredExtractor {
private static final Log logger = LogFactory.getLog(JmsRedeliveredExtractor.class);
public ChunkResponse extract(ChunkResponse input, @Header(JmsHeaders.REDELIVERED) boolean redelivered) {<FILL_FUNCTION_BODY>}
}
|
if (logger.isDebugEnabled()) {
logger.debug("Extracted redelivered flag for response, value=" + redelivered);
}
return new ChunkResponse(input, redelivered);
| 82
| 55
| 137
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/MessageSourcePollerInterceptor.java
|
MessageSourcePollerInterceptor
|
preReceive
|
class MessageSourcePollerInterceptor implements ChannelInterceptor, InitializingBean {
private static final Log logger = LogFactory.getLog(MessageSourcePollerInterceptor.class);
private MessageSource<?> source;
private MessageChannel channel;
/**
* Convenient default constructor for configuration purposes.
*/
public MessageSourcePollerInterceptor() {
}
/**
* @param source a message source to poll for messages on receive.
*/
public MessageSourcePollerInterceptor(MessageSource<?> source) {
this.source = source;
}
/**
* Optional MessageChannel for injecting the message received from the source
* (defaults to the channel intercepted in {@link #preReceive(MessageChannel)}).
* @param channel the channel to set
*/
public void setChannel(MessageChannel channel) {
this.channel = channel;
}
/**
* Asserts that mandatory properties are set.
* @see InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(source != null, "A MessageSource must be provided");
}
/**
* @param source a message source to poll for messages on receive.
*/
public void setMessageSource(MessageSource<?> source) {
this.source = source;
}
/**
* Receive from the {@link MessageSource} and send immediately to the input channel,
* so that the call that we are intercepting always a message to receive.
*
* @see ChannelInterceptor#preReceive(MessageChannel)
*/
@Override
public boolean preReceive(MessageChannel channel) {<FILL_FUNCTION_BODY>}
}
|
Message<?> message = source.receive();
if (message != null) {
if (this.channel != null) {
channel = this.channel;
}
channel.send(message);
if (logger.isDebugEnabled()) {
logger.debug("Sent " + message + " to channel " + channel);
}
return true;
}
return true;
| 423
| 106
| 529
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/RemoteChunkingWorkerBuilder.java
|
RemoteChunkingWorkerBuilder
|
itemProcessor
|
class RemoteChunkingWorkerBuilder<I, O> {
private static final String SERVICE_ACTIVATOR_METHOD_NAME = "handleChunk";
private ItemProcessor<I, O> itemProcessor;
private ItemWriter<O> itemWriter;
private MessageChannel inputChannel;
private MessageChannel outputChannel;
/**
* Set the {@link ItemProcessor} to use to process items sent by the manager step.
* @param itemProcessor to use
* @return this builder instance for fluent chaining
*/
public RemoteChunkingWorkerBuilder<I, O> itemProcessor(ItemProcessor<I, O> itemProcessor) {<FILL_FUNCTION_BODY>}
/**
* Set the {@link ItemWriter} to use to write items sent by the manager step.
* @param itemWriter to use
* @return this builder instance for fluent chaining
*/
public RemoteChunkingWorkerBuilder<I, O> itemWriter(ItemWriter<O> itemWriter) {
Assert.notNull(itemWriter, "itemWriter must not be null");
this.itemWriter = itemWriter;
return this;
}
/**
* Set the input channel on which items sent by the manager are received.
* @param inputChannel the input channel
* @return this builder instance for fluent chaining
*/
public RemoteChunkingWorkerBuilder<I, O> inputChannel(MessageChannel inputChannel) {
Assert.notNull(inputChannel, "inputChannel must not be null");
this.inputChannel = inputChannel;
return this;
}
/**
* Set the output channel on which replies will be sent to the manager step.
* @param outputChannel the output channel
* @return this builder instance for fluent chaining
*/
public RemoteChunkingWorkerBuilder<I, O> outputChannel(MessageChannel outputChannel) {
Assert.notNull(outputChannel, "outputChannel must not be null");
this.outputChannel = outputChannel;
return this;
}
/**
* Create an {@link IntegrationFlow} with a {@link ChunkProcessorChunkHandler}
* configured as a service activator listening to the input channel and replying on
* the output channel.
* @return the integration flow
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public IntegrationFlow build() {
Assert.notNull(this.itemWriter, "An ItemWriter must be provided");
Assert.notNull(this.inputChannel, "An InputChannel must be provided");
Assert.notNull(this.outputChannel, "An OutputChannel must be provided");
if (this.itemProcessor == null) {
this.itemProcessor = new PassThroughItemProcessor();
}
SimpleChunkProcessor<I, O> chunkProcessor = new SimpleChunkProcessor<>(this.itemProcessor, this.itemWriter);
ChunkProcessorChunkHandler<I> chunkProcessorChunkHandler = new ChunkProcessorChunkHandler<>();
chunkProcessorChunkHandler.setChunkProcessor(chunkProcessor);
return IntegrationFlow.from(this.inputChannel)
.handle(chunkProcessorChunkHandler, SERVICE_ACTIVATOR_METHOD_NAME)
.channel(this.outputChannel)
.get();
}
}
|
Assert.notNull(itemProcessor, "itemProcessor must not be null");
this.itemProcessor = itemProcessor;
return this;
| 804
| 37
| 841
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/config/annotation/BatchIntegrationConfiguration.java
|
BatchIntegrationConfiguration
|
afterPropertiesSet
|
class BatchIntegrationConfiguration<I, O> implements InitializingBean {
private final JobExplorer jobExplorer;
private final JobRepository jobRepository;
private final PlatformTransactionManager transactionManager;
private RemoteChunkingManagerStepBuilderFactory remoteChunkingManagerStepBuilderFactory;
private RemoteChunkingWorkerBuilder<I, O> remoteChunkingWorkerBuilder;
private RemotePartitioningManagerStepBuilderFactory remotePartitioningManagerStepBuilderFactory;
private RemotePartitioningWorkerStepBuilderFactory remotePartitioningWorkerStepBuilderFactory;
@Autowired
public BatchIntegrationConfiguration(JobRepository jobRepository, JobExplorer jobExplorer,
PlatformTransactionManager transactionManager) {
this.jobRepository = jobRepository;
this.jobExplorer = jobExplorer;
this.transactionManager = transactionManager;
}
@Bean
public RemoteChunkingManagerStepBuilderFactory remoteChunkingManagerStepBuilderFactory() {
return this.remoteChunkingManagerStepBuilderFactory;
}
@Bean
public RemoteChunkingWorkerBuilder<I, O> remoteChunkingWorkerBuilder() {
return remoteChunkingWorkerBuilder;
}
@Bean
public RemotePartitioningManagerStepBuilderFactory remotePartitioningManagerStepBuilderFactory() {
return this.remotePartitioningManagerStepBuilderFactory;
}
@Bean
public RemotePartitioningWorkerStepBuilderFactory remotePartitioningWorkerStepBuilderFactory() {
return this.remotePartitioningWorkerStepBuilderFactory;
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
}
|
this.remoteChunkingManagerStepBuilderFactory = new RemoteChunkingManagerStepBuilderFactory(this.jobRepository,
this.transactionManager);
this.remoteChunkingWorkerBuilder = new RemoteChunkingWorkerBuilder<>();
this.remotePartitioningManagerStepBuilderFactory = new RemotePartitioningManagerStepBuilderFactory(
this.jobRepository, this.jobExplorer);
this.remotePartitioningWorkerStepBuilderFactory = new RemotePartitioningWorkerStepBuilderFactory(
this.jobRepository, this.jobExplorer);
| 385
| 130
| 515
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/config/xml/BatchIntegrationNamespaceHandler.java
|
BatchIntegrationNamespaceHandler
|
init
|
class BatchIntegrationNamespaceHandler extends AbstractIntegrationNamespaceHandler {
@Override
public void init() {<FILL_FUNCTION_BODY>}
}
|
this.registerBeanDefinitionParser("job-launching-gateway", new JobLaunchingGatewayParser());
RemoteChunkingManagerParser remoteChunkingManagerParser = new RemoteChunkingManagerParser();
this.registerBeanDefinitionParser("remote-chunking-manager", remoteChunkingManagerParser);
RemoteChunkingWorkerParser remoteChunkingWorkerParser = new RemoteChunkingWorkerParser();
this.registerBeanDefinitionParser("remote-chunking-worker", remoteChunkingWorkerParser);
| 40
| 130
| 170
|
<methods>public void <init>() ,public final org.springframework.beans.factory.config.BeanDefinition parse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext) <variables>private final java.util.concurrent.atomic.AtomicBoolean initialized
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/config/xml/JobLaunchingGatewayParser.java
|
JobLaunchingGatewayParser
|
parseHandler
|
class JobLaunchingGatewayParser extends AbstractConsumerEndpointParser {
private static final Log logger = LogFactory.getLog(JobLaunchingGatewayParser.class);
@Override
protected String getInputChannelAttributeName() {
return "request-channel";
}
@Override
protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) {<FILL_FUNCTION_BODY>}
}
|
final BeanDefinitionBuilder jobLaunchingGatewayBuilder = BeanDefinitionBuilder
.genericBeanDefinition(JobLaunchingGateway.class);
final String jobLauncher = element.getAttribute("job-launcher");
if (StringUtils.hasText(jobLauncher)) {
jobLaunchingGatewayBuilder.addConstructorArgReference(jobLauncher);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("No jobLauncher specified, using default 'jobLauncher' reference instead.");
}
jobLaunchingGatewayBuilder.addConstructorArgReference("jobLauncher");
}
IntegrationNamespaceUtils.setValueIfAttributeDefined(jobLaunchingGatewayBuilder, element, "reply-timeout",
"sendTimeout");
final String replyChannel = element.getAttribute("reply-channel");
if (StringUtils.hasText(replyChannel)) {
jobLaunchingGatewayBuilder.addPropertyReference("outputChannel", replyChannel);
}
return jobLaunchingGatewayBuilder;
| 105
| 280
| 385
|
<methods>public void <init>() <variables>protected static final java.lang.String EXPRESSION_ATTRIBUTE,protected static final java.lang.String METHOD_ATTRIBUTE,protected static final java.lang.String REF_ATTRIBUTE
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/config/xml/RemoteChunkingManagerParser.java
|
RemoteChunkingManagerParser
|
parseInternal
|
class RemoteChunkingManagerParser extends AbstractBeanDefinitionParser {
private static final String MESSAGE_TEMPLATE_ATTRIBUTE = "message-template";
private static final String STEP_ATTRIBUTE = "step";
private static final String REPLY_CHANNEL_ATTRIBUTE = "reply-channel";
private static final String MESSAGING_OPERATIONS_PROPERTY = "messagingOperations";
private static final String REPLY_CHANNEL_PROPERTY = "replyChannel";
private static final String CHUNK_WRITER_PROPERTY = "chunkWriter";
private static final String STEP_PROPERTY = "step";
private static final String CHUNK_HANDLER_BEAN_NAME_PREFIX = "remoteChunkHandlerFactoryBean_";
@Override
public AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {<FILL_FUNCTION_BODY>}
}
|
String id = element.getAttribute(ID_ATTRIBUTE);
Assert.hasText(id, "The id attribute must be specified");
String messageTemplate = element.getAttribute(MESSAGE_TEMPLATE_ATTRIBUTE);
Assert.hasText(messageTemplate, "The message-template attribute must be specified");
String step = element.getAttribute(STEP_ATTRIBUTE);
Assert.hasText(step, "The step attribute must be specified");
String replyChannel = element.getAttribute(REPLY_CHANNEL_ATTRIBUTE);
Assert.hasText(replyChannel, "The reply-channel attribute must be specified");
BeanDefinitionRegistry beanDefinitionRegistry = parserContext.getRegistry();
BeanDefinition chunkMessageChannelItemWriter = BeanDefinitionBuilder
.genericBeanDefinition(ChunkMessageChannelItemWriter.class)
.addPropertyReference(MESSAGING_OPERATIONS_PROPERTY, messageTemplate)
.addPropertyReference(REPLY_CHANNEL_PROPERTY, replyChannel)
.getBeanDefinition();
beanDefinitionRegistry.registerBeanDefinition(id, chunkMessageChannelItemWriter);
BeanDefinition remoteChunkHandlerFactoryBean = BeanDefinitionBuilder
.genericBeanDefinition(RemoteChunkHandlerFactoryBean.class)
.addPropertyValue(CHUNK_WRITER_PROPERTY, chunkMessageChannelItemWriter)
.addPropertyValue(STEP_PROPERTY, step)
.getBeanDefinition();
beanDefinitionRegistry.registerBeanDefinition(CHUNK_HANDLER_BEAN_NAME_PREFIX + step,
remoteChunkHandlerFactoryBean);
return null;
| 238
| 417
| 655
|
<methods>public void <init>() ,public final org.springframework.beans.factory.config.BeanDefinition parse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext) <variables>public static final java.lang.String ID_ATTRIBUTE,public static final java.lang.String NAME_ATTRIBUTE
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/config/xml/RemoteChunkingWorkerParser.java
|
RemoteChunkingWorkerParser
|
parseInternal
|
class RemoteChunkingWorkerParser extends AbstractBeanDefinitionParser {
private static final String INPUT_CHANNEL_ATTRIBUTE = "input-channel";
private static final String OUTPUT_CHANNEL_ATTRIBUTE = "output-channel";
private static final String ITEM_PROCESSOR_ATTRIBUTE = "item-processor";
private static final String ITEM_WRITER_ATTRIBUTE = "item-writer";
private static final String ITEM_PROCESSOR_PROPERTY_NAME = "itemProcessor";
private static final String ITEM_WRITER_PROPERTY_NAME = "itemWriter";
private static final String CHUNK_PROCESSOR_PROPERTY_NAME = "chunkProcessor";
private static final String CHUNK_PROCESSOR_CHUNK_HANDLER_BEAN_NAME_PREFIX = "chunkProcessorChunkHandler_";
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {<FILL_FUNCTION_BODY>}
private static class ServiceActivatorParser extends AbstractConsumerEndpointParser {
private static final String TARGET_METHOD_NAME_PROPERTY_NAME = "targetMethodName";
private static final String TARGET_OBJECT_PROPERTY_NAME = "targetObject";
private static final String HANDLE_CHUNK_METHOD_NAME = "handleChunk";
private static final String CHUNK_PROCESSOR_CHUNK_HANDLER_BEAN_NAME_PREFIX = "chunkProcessorChunkHandler_";
private final String id;
public ServiceActivatorParser(String id) {
this.id = id;
}
@Override
protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder
.genericBeanDefinition(ServiceActivatorFactoryBean.class);
builder.addPropertyValue(TARGET_METHOD_NAME_PROPERTY_NAME, HANDLE_CHUNK_METHOD_NAME);
builder.addPropertyValue(TARGET_OBJECT_PROPERTY_NAME,
new RuntimeBeanReference(CHUNK_PROCESSOR_CHUNK_HANDLER_BEAN_NAME_PREFIX + id));
return builder;
}
}
}
|
String id = element.getAttribute(ID_ATTRIBUTE);
Assert.hasText(id, "The id attribute must be specified");
String inputChannel = element.getAttribute(INPUT_CHANNEL_ATTRIBUTE);
Assert.hasText(inputChannel, "The input-channel attribute must be specified");
String outputChannel = element.getAttribute(OUTPUT_CHANNEL_ATTRIBUTE);
Assert.hasText(outputChannel, "The output-channel attribute must be specified");
String itemProcessor = element.getAttribute(ITEM_PROCESSOR_ATTRIBUTE);
String itemWriter = element.getAttribute(ITEM_WRITER_ATTRIBUTE);
Assert.hasText(itemWriter, "The item-writer attribute must be specified");
BeanDefinitionRegistry beanDefinitionRegistry = parserContext.getRegistry();
BeanDefinitionBuilder chunkProcessorBuilder = BeanDefinitionBuilder
.genericBeanDefinition(SimpleChunkProcessor.class)
.addPropertyReference(ITEM_WRITER_PROPERTY_NAME, itemWriter);
if (StringUtils.hasText(itemProcessor)) {
chunkProcessorBuilder.addPropertyReference(ITEM_PROCESSOR_PROPERTY_NAME, itemProcessor);
}
else {
chunkProcessorBuilder.addPropertyValue(ITEM_PROCESSOR_PROPERTY_NAME, new PassThroughItemProcessor<>());
}
BeanDefinition chunkProcessorChunkHandler = BeanDefinitionBuilder
.genericBeanDefinition(ChunkProcessorChunkHandler.class)
.addPropertyValue(CHUNK_PROCESSOR_PROPERTY_NAME, chunkProcessorBuilder.getBeanDefinition())
.getBeanDefinition();
beanDefinitionRegistry.registerBeanDefinition(CHUNK_PROCESSOR_CHUNK_HANDLER_BEAN_NAME_PREFIX + id,
chunkProcessorChunkHandler);
new ServiceActivatorParser(id).parse(element, parserContext);
return null;
| 576
| 490
| 1,066
|
<methods>public void <init>() ,public final org.springframework.beans.factory.config.BeanDefinition parse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext) <variables>public static final java.lang.String ID_ATTRIBUTE,public static final java.lang.String NAME_ATTRIBUTE
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/launch/JobLaunchRequest.java
|
JobLaunchRequest
|
toString
|
class JobLaunchRequest {
private final Job job;
private final JobParameters jobParameters;
/**
* @param job job to be launched
* @param jobParameters parameters to run the job with
*/
public JobLaunchRequest(Job job, JobParameters jobParameters) {
super();
this.job = job;
this.jobParameters = jobParameters;
}
/**
* @return the {@link Job} to be executed
*/
public Job getJob() {
return this.job;
}
/**
* @return the {@link JobParameters} for this request
*/
public JobParameters getJobParameters() {
return this.jobParameters;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "JobLaunchRequest: " + job.getName() + ", parameters=" + jobParameters;
| 193
| 27
| 220
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/launch/JobLaunchingGateway.java
|
JobLaunchingGateway
|
handleRequestMessage
|
class JobLaunchingGateway extends AbstractReplyProducingMessageHandler {
private final JobLaunchingMessageHandler jobLaunchingMessageHandler;
/**
* Constructor taking a {@link JobLauncher} as parameter.
* @param jobLauncher Must not be null.
*
*/
public JobLaunchingGateway(JobLauncher jobLauncher) {
Assert.notNull(jobLauncher, "jobLauncher must not be null.");
this.jobLaunchingMessageHandler = new JobLaunchingMessageHandler(jobLauncher);
}
/**
* Launches a Batch Job using the provided request {@link Message}. The payload of the
* {@link Message} <em>must</em> be an instance of {@link JobLaunchRequest}.
* @param requestMessage must not be null.
* @return Generally a {@link JobExecution} will always be returned. An exception
* ({@link MessageHandlingException}) will only be thrown if there is a failure to
* start the job. The cause of the exception will be a {@link JobExecutionException}.
* @throws MessageHandlingException when a job cannot be launched
*/
@Override
protected Object handleRequestMessage(Message<?> requestMessage) {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(requestMessage, "The provided requestMessage must not be null.");
final Object payload = requestMessage.getPayload();
Assert.isInstanceOf(JobLaunchRequest.class, payload, "The payload must be of type JobLaunchRequest.");
final JobLaunchRequest jobLaunchRequest = (JobLaunchRequest) payload;
final JobExecution jobExecution;
try {
jobExecution = this.jobLaunchingMessageHandler.launch(jobLaunchRequest);
}
catch (JobExecutionException e) {
throw new MessageHandlingException(requestMessage, e);
}
return jobExecution;
| 315
| 171
| 486
|
<methods>public void <init>() ,public org.springframework.integration.IntegrationPatternType getIntegrationPatternType() ,public void setAdviceChain(List<org.aopalliance.aop.Advice>) ,public void setBeanClassLoader(java.lang.ClassLoader) ,public void setRequiresReply(boolean) <variables>private final List<org.aopalliance.aop.Advice> adviceChain,private volatile org.springframework.integration.handler.AbstractReplyProducingMessageHandler.RequestHandler advisedRequestHandler,private java.lang.ClassLoader beanClassLoader,private final java.util.concurrent.locks.Lock lock,private boolean requiresReply
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/launch/JobLaunchingMessageHandler.java
|
JobLaunchingMessageHandler
|
launch
|
class JobLaunchingMessageHandler implements JobLaunchRequestHandler {
private final JobLauncher jobLauncher;
/**
* @param jobLauncher {@link org.springframework.batch.core.launch.JobLauncher} used
* to execute Spring Batch jobs
*/
public JobLaunchingMessageHandler(JobLauncher jobLauncher) {
super();
this.jobLauncher = jobLauncher;
}
@Override
@ServiceActivator
public JobExecution launch(JobLaunchRequest request) throws JobExecutionException {<FILL_FUNCTION_BODY>}
}
|
Job job = request.getJob();
JobParameters jobParameters = request.getJobParameters();
return jobLauncher.run(job, jobParameters);
| 143
| 43
| 186
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/partition/StepExecutionRequestHandler.java
|
StepExecutionRequestHandler
|
handle
|
class StepExecutionRequestHandler {
private JobExplorer jobExplorer;
private StepLocator stepLocator;
/**
* Used to locate a {@link Step} to execute for each request.
* @param stepLocator a {@link StepLocator}
*/
public void setStepLocator(StepLocator stepLocator) {
this.stepLocator = stepLocator;
}
/**
* An explorer that should be used to check for {@link StepExecution} completion.
* @param jobExplorer a {@link JobExplorer} that is linked to the shared repository
* used by all remote workers.
*/
public void setJobExplorer(JobExplorer jobExplorer) {
this.jobExplorer = jobExplorer;
}
@ServiceActivator
public StepExecution handle(StepExecutionRequest request) {<FILL_FUNCTION_BODY>}
}
|
Long jobExecutionId = request.getJobExecutionId();
Long stepExecutionId = request.getStepExecutionId();
StepExecution stepExecution = jobExplorer.getStepExecution(jobExecutionId, stepExecutionId);
if (stepExecution == null) {
throw new NoSuchStepException("No StepExecution could be located for this request: " + request);
}
String stepName = request.getStepName();
Step step = stepLocator.getStep(stepName);
if (step == null) {
throw new NoSuchStepException(String.format("No Step with name [%s] could be located.", stepName));
}
try {
step.execute(stepExecution);
}
catch (JobInterruptedException e) {
stepExecution.setStatus(BatchStatus.STOPPED);
// The receiver should update the stepExecution in repository
}
catch (Throwable e) {
stepExecution.addFailureException(e);
stepExecution.setStatus(BatchStatus.FAILED);
// The receiver should update the stepExecution in repository
}
return stepExecution;
| 215
| 289
| 504
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/step/DelegateStep.java
|
DelegateStep
|
afterPropertiesSet
|
class DelegateStep extends AbstractStep {
private Step delegate;
/**
* @param delegate the delegate to set
*/
public void setDelegate(Step delegate) {
this.delegate = delegate;
}
/**
* Check mandatory properties (delegate).
*/
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
@Override
protected void doExecute(StepExecution stepExecution) throws Exception {
delegate.execute(stepExecution);
}
}
|
Assert.state(delegate != null, "A delegate Step must be provided");
super.afterPropertiesSet();
| 132
| 34
| 166
|
<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-samples/src/main/java/org/springframework/batch/samples/amqp/AmqpJobConfiguration.java
|
AmqpJobConfiguration
|
step
|
class AmqpJobConfiguration {
@Bean
public Job job(JobRepository jobRepository, Step step) {
return new JobBuilder("amqp-config-job", jobRepository).start(step).build();
}
@Bean
public Step step(JobRepository jobRepository, JdbcTransactionManager transactionManager,
RabbitTemplate rabbitInputTemplate, RabbitTemplate rabbitOutputTemplate) {<FILL_FUNCTION_BODY>}
/**
* Reads from the designated queue.
* @param rabbitInputTemplate the template to be used by the {@link ItemReader}.
* @return instance of {@link ItemReader}.
*/
@Bean
public ItemReader<String> amqpItemReader(RabbitTemplate rabbitInputTemplate) {
AmqpItemReaderBuilder<String> builder = new AmqpItemReaderBuilder<>();
return builder.amqpTemplate(rabbitInputTemplate).build();
}
/**
* Reads from the designated destination.
* @param rabbitOutputTemplate the template to be used by the {@link ItemWriter}.
* @return instance of {@link ItemWriter}.
*/
@Bean
public ItemWriter<String> amqpItemWriter(RabbitTemplate rabbitOutputTemplate) {
AmqpItemWriterBuilder<String> builder = new AmqpItemWriterBuilder<>();
return builder.amqpTemplate(rabbitOutputTemplate).build();
}
}
|
return new StepBuilder("step", jobRepository).<String, String>chunk(1, transactionManager)
.reader(amqpItemReader(rabbitInputTemplate))
.processor(new MessageProcessor())
.writer(amqpItemWriter(rabbitOutputTemplate))
.build();
| 343
| 74
| 417
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/amqp/AmqpMessageProducer.java
|
AmqpMessageProducer
|
main
|
class AmqpMessageProducer {
private AmqpMessageProducer() {
}
private static final int SEND_MESSAGE_COUNT = 10;
private static final String[] BEAN_CONFIG = {
"classpath:org/springframework/batch/samples/amqp/job/rabbitmq-beans.xml" };
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(BEAN_CONFIG);
AmqpTemplate amqpTemplate = applicationContext.getBean("inboundAmqpTemplate", RabbitTemplate.class);
for (int i = 0; i < SEND_MESSAGE_COUNT; i++) {
amqpTemplate.convertAndSend("foo message: " + i);
}
((ConfigurableApplicationContext) applicationContext).close();
| 111
| 116
| 227
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/amqp/MessageProcessor.java
|
MessageProcessor
|
process
|
class MessageProcessor implements ItemProcessor<String, String> {
@Nullable
@Override
public String process(String message) throws Exception {<FILL_FUNCTION_BODY>}
}
|
return "Message: \"" + message + "\" processed on: " + new Date();
| 46
| 24
| 70
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/chunking/WorkerConfiguration.java
|
WorkerConfiguration
|
itemProcessor
|
class WorkerConfiguration {
@Value("${broker.url}")
private String brokerUrl;
@Autowired
private RemoteChunkingWorkerBuilder<Integer, Integer> remoteChunkingWorkerBuilder;
@Bean
public ActiveMQConnectionFactory connectionFactory() throws JMSException {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
connectionFactory.setBrokerURL(this.brokerUrl);
return connectionFactory;
}
/*
* Configure inbound flow (requests coming from the manager)
*/
@Bean
public DirectChannel requests() {
return new DirectChannel();
}
@Bean
public IntegrationFlow inboundFlow(ActiveMQConnectionFactory connectionFactory) {
return IntegrationFlow.from(Jms.messageDrivenChannelAdapter(connectionFactory).destination("requests"))
.channel(requests())
.get();
}
/*
* Configure outbound flow (replies going to the manager)
*/
@Bean
public DirectChannel replies() {
return new DirectChannel();
}
@Bean
public IntegrationFlow outboundFlow(ActiveMQConnectionFactory connectionFactory) {
return IntegrationFlow.from(replies())
.handle(Jms.outboundAdapter(connectionFactory).destination("replies"))
.get();
}
/*
* Configure worker components
*/
@Bean
public ItemProcessor<Integer, Integer> itemProcessor() {<FILL_FUNCTION_BODY>}
@Bean
public ItemWriter<Integer> itemWriter() {
return items -> {
for (Integer item : items) {
System.out.println("writing item " + item);
}
};
}
@Bean
public IntegrationFlow workerIntegrationFlow() {
return this.remoteChunkingWorkerBuilder.itemProcessor(itemProcessor())
.itemWriter(itemWriter())
.inputChannel(requests())
.outputChannel(replies())
.build();
}
}
|
return item -> {
System.out.println("processing item " + item);
return item;
};
| 491
| 33
| 524
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/common/ColumnRangePartitioner.java
|
ColumnRangePartitioner
|
partition
|
class ColumnRangePartitioner implements Partitioner {
private JdbcOperations jdbcTemplate;
private String table;
private String column;
/**
* The name of the SQL table the data are in.
* @param table the name of the table
*/
public void setTable(String table) {
this.table = table;
}
/**
* The name of the column to partition.
* @param column the column name.
*/
public void setColumn(String column) {
this.column = column;
}
/**
* The data source for connecting to the database.
* @param dataSource a {@link DataSource}
*/
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
/**
* Partition a database table assuming that the data in the column specified are
* uniformly distributed. The execution context values will have keys
* <code>minValue</code> and <code>maxValue</code> specifying the range of values to
* consider in each partition.
*
* @see Partitioner#partition(int)
*/
@Override
public Map<String, ExecutionContext> partition(int gridSize) {<FILL_FUNCTION_BODY>}
}
|
int min = jdbcTemplate.queryForObject("SELECT MIN(" + column + ") from " + table, Integer.class);
int max = jdbcTemplate.queryForObject("SELECT MAX(" + column + ") from " + table, Integer.class);
int targetSize = (max - min) / gridSize + 1;
Map<String, ExecutionContext> result = new HashMap<>();
int number = 0;
int start = min;
int end = start + targetSize - 1;
while (start <= max) {
ExecutionContext value = new ExecutionContext();
result.put("partition" + number, value);
if (end >= max) {
end = max;
}
value.putInt("minValue", start);
value.putInt("maxValue", end);
start += targetSize;
end += targetSize;
number++;
}
return result;
| 317
| 238
| 555
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/common/ErrorLogTasklet.java
|
ErrorLogTasklet
|
getSkipCount
|
class ErrorLogTasklet implements Tasklet, StepExecutionListener {
private JdbcOperations jdbcTemplate;
private String jobName;
private StepExecution stepExecution;
private String stepName;
@Nullable
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
Assert.notNull(this.stepName, "Step name not set. Either this class was not registered as a listener "
+ "or the key 'stepName' was not found in the Job's ExecutionContext.");
this.jdbcTemplate.update("insert into ERROR_LOG values (?, ?, '" + getSkipCount() + " records were skipped!')",
jobName, stepName);
return RepeatStatus.FINISHED;
}
/**
* @return the skip count
*/
private long getSkipCount() {<FILL_FUNCTION_BODY>}
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public void beforeStep(StepExecution stepExecution) {
this.jobName = stepExecution.getJobExecution().getJobInstance().getJobName().trim();
this.stepName = (String) stepExecution.getJobExecution().getExecutionContext().get("stepName");
this.stepExecution = stepExecution;
stepExecution.getJobExecution().getExecutionContext().remove("stepName");
}
@Nullable
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
}
|
if (stepExecution == null || stepName == null) {
return 0;
}
for (StepExecution execution : stepExecution.getJobExecution().getStepExecutions()) {
if (execution.getStepName().equals(stepName)) {
return execution.getSkipCount();
}
}
return 0;
| 380
| 85
| 465
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/common/OutputFileListener.java
|
OutputFileListener
|
createOutputNameFromInput
|
class OutputFileListener {
private String outputKeyName = "outputFile";
private String inputKeyName = "fileName";
private String path = "file:./target/output/";
public void setPath(String path) {
this.path = path;
}
public void setOutputKeyName(String outputKeyName) {
this.outputKeyName = outputKeyName;
}
public void setInputKeyName(String inputKeyName) {
this.inputKeyName = inputKeyName;
}
@BeforeStep
public void createOutputNameFromInput(StepExecution stepExecution) {<FILL_FUNCTION_BODY>}
}
|
ExecutionContext executionContext = stepExecution.getExecutionContext();
String inputName = stepExecution.getStepName().replace(":", "-");
if (executionContext.containsKey(inputKeyName)) {
inputName = executionContext.getString(inputKeyName);
}
if (!executionContext.containsKey(outputKeyName)) {
executionContext.putString(outputKeyName, path + FilenameUtils.getBaseName(inputName) + ".csv");
}
| 159
| 118
| 277
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/common/SkipCheckingDecider.java
|
SkipCheckingDecider
|
decide
|
class SkipCheckingDecider implements JobExecutionDecider {
@Override
public FlowExecutionStatus decide(JobExecution jobExecution, @Nullable StepExecution stepExecution) {<FILL_FUNCTION_BODY>}
}
|
if (!stepExecution.getExitStatus().getExitCode().equals(ExitStatus.FAILED.getExitCode())
&& stepExecution.getSkipCount() > 0) {
return new FlowExecutionStatus("COMPLETED WITH SKIPS");
}
else {
return new FlowExecutionStatus(ExitStatus.COMPLETED.getExitCode());
}
| 53
| 89
| 142
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/common/SkipCheckingListener.java
|
SkipCheckingListener
|
checkForSkips
|
class SkipCheckingListener {
private static final Log logger = LogFactory.getLog(SkipCheckingListener.class);
private static int processSkips;
@AfterStep
public ExitStatus checkForSkips(StepExecution stepExecution) {<FILL_FUNCTION_BODY>}
/**
* Convenience method for testing
* @return the processSkips
*/
public static int getProcessSkips() {
return processSkips;
}
/**
* Convenience method for testing
*/
public static void resetProcessSkips() {
processSkips = 0;
}
@OnSkipInWrite
public void skipWrite(Trade trade, Throwable t) {
logger.debug("Skipped writing " + trade);
}
@OnSkipInProcess
public void skipProcess(Trade trade, Throwable t) {
logger.debug("Skipped processing " + trade);
processSkips++;
}
@BeforeStep
public void saveStepName(StepExecution stepExecution) {
stepExecution.getExecutionContext().put("stepName", stepExecution.getStepName());
}
}
|
if (!stepExecution.getExitStatus().getExitCode().equals(ExitStatus.FAILED.getExitCode())
&& stepExecution.getSkipCount() > 0) {
return new ExitStatus("COMPLETED WITH SKIPS");
}
else {
return null;
}
| 281
| 75
| 356
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/common/StagingItemListener.java
|
StagingItemListener
|
afterRead
|
class StagingItemListener extends StepListenerSupport<Long, Long> implements InitializingBean {
private JdbcOperations jdbcTemplate;
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public final void afterPropertiesSet() throws Exception {
Assert.state(jdbcTemplate != null, "You must provide a DataSource.");
}
@Override
public void afterRead(Long id) {<FILL_FUNCTION_BODY>}
}
|
int count = jdbcTemplate.update("UPDATE BATCH_STAGING SET PROCESSED=? WHERE ID=? AND PROCESSED=?",
StagingItemWriter.DONE, id, StagingItemWriter.NEW);
if (count != 1) {
throw new OptimisticLockingFailureException("The staging record with ID=" + id
+ " was updated concurrently when trying to mark as complete (updated " + count + " records.");
}
| 130
| 119
| 249
|
<methods>public non-sealed void <init>() <variables>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/common/StagingItemProcessor.java
|
StagingItemProcessor
|
afterPropertiesSet
|
class StagingItemProcessor<T> implements ItemProcessor<ProcessIndicatorItemWrapper<T>, T>, InitializingBean {
private JdbcOperations jdbcTemplate;
public void setJdbcTemplate(JdbcOperations jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
/**
* Use the technical identifier to mark the input row as processed and return
* unwrapped item.
*/
@Nullable
@Override
public T process(ProcessIndicatorItemWrapper<T> wrapper) throws Exception {
int count = jdbcTemplate.update("UPDATE BATCH_STAGING SET PROCESSED=? WHERE ID=? AND PROCESSED=?",
StagingItemWriter.DONE, wrapper.getId(), StagingItemWriter.NEW);
if (count != 1) {
throw new OptimisticLockingFailureException("The staging record with ID=" + wrapper.getId()
+ " was updated concurrently when trying to mark as complete (updated " + count + " records.");
}
return wrapper.getItem();
}
}
|
Assert.state(jdbcTemplate != null, "Either jdbcTemplate or dataSource must be set");
| 321
| 30
| 351
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/common/StagingItemReader.java
|
StagingItemReader
|
retrieveKeys
|
class StagingItemReader<T>
implements ItemReader<ProcessIndicatorItemWrapper<T>>, StepExecutionListener, InitializingBean, DisposableBean {
private static final Log logger = LogFactory.getLog(StagingItemReader.class);
private StepExecution stepExecution;
private final Lock lock = new ReentrantLock();
private volatile boolean initialized = false;
private volatile Iterator<Long> keys;
private JdbcOperations jdbcTemplate;
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public void destroy() throws Exception {
initialized = false;
keys = null;
}
@Override
public final void afterPropertiesSet() throws Exception {
Assert.state(jdbcTemplate != null, "You must provide a DataSource.");
}
private List<Long> retrieveKeys() {<FILL_FUNCTION_BODY>}
@Nullable
@Override
public ProcessIndicatorItemWrapper<T> read() {
if (!initialized) {
throw new ReaderNotOpenException("Reader must be open before it can be used.");
}
Long id = null;
synchronized (lock) {
if (keys.hasNext()) {
id = keys.next();
}
}
if (logger.isDebugEnabled()) {
logger.debug("Retrieved key from list: " + id);
}
if (id == null) {
return null;
}
@SuppressWarnings("unchecked")
T result = (T) jdbcTemplate.queryForObject("SELECT VALUE FROM BATCH_STAGING WHERE ID=?",
(rs, rowNum) -> deserialize(rs.getBinaryStream(1)), id);
return new ProcessIndicatorItemWrapper<>(id, result);
}
private static Object deserialize(InputStream inputStream) {
if (inputStream == null) {
return null;
}
try (var objectInputStream = new ObjectInputStream(inputStream)) {
return objectInputStream.readObject();
}
catch (Exception e) {
throw new IllegalArgumentException("Failed to deserialize object", e);
}
}
@Nullable
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
@Override
public void beforeStep(StepExecution stepExecution) {
this.stepExecution = stepExecution;
synchronized (lock) {
if (keys == null) {
keys = retrieveKeys().iterator();
logger.info("Keys obtained for staging.");
initialized = true;
}
}
}
}
|
this.lock.lock();
try {
return jdbcTemplate.query(
"SELECT ID FROM BATCH_STAGING WHERE JOB_ID=? AND PROCESSED=? ORDER BY ID",
(rs, rowNum) -> rs.getLong(1),
stepExecution.getJobExecution().getJobId(), StagingItemWriter.NEW);
}
finally {
this.lock.unlock();
}
| 671
| 121
| 792
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/common/StagingItemWriter.java
|
StagingItemWriter
|
write
|
class StagingItemWriter<T> extends JdbcDaoSupport implements StepExecutionListener, ItemWriter<T> {
protected static final String NEW = "N";
protected static final String DONE = "Y";
private DataFieldMaxValueIncrementer incrementer;
private StepExecution stepExecution;
/**
* Check mandatory properties.
*
* @see org.springframework.dao.support.DaoSupport#initDao()
*/
@Override
protected void initDao() throws Exception {
super.initDao();
Assert.notNull(incrementer, "DataFieldMaxValueIncrementer is required - set the incrementer property in the "
+ ClassUtils.getShortName(StagingItemWriter.class));
}
/**
* Setter for the key generator for the staging table.
* @param incrementer the {@link DataFieldMaxValueIncrementer} to set
*/
public void setIncrementer(DataFieldMaxValueIncrementer incrementer) {
this.incrementer = incrementer;
}
/**
* Serialize the item to the staging table, and add a NEW processed flag.
*
* @see ItemWriter#write(Chunk)
*/
@Override
public void write(final Chunk<? extends T> chunk) {<FILL_FUNCTION_BODY>}
@Nullable
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
@Override
public void beforeStep(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
}
|
final ListIterator<? extends T> itemIterator = chunk.getItems().listIterator();
getJdbcTemplate().batchUpdate("INSERT into BATCH_STAGING (ID, JOB_ID, VALUE, PROCESSED) values (?,?,?,?)",
new BatchPreparedStatementSetter() {
@Override
public int getBatchSize() {
return chunk.size();
}
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
Assert.state(itemIterator.nextIndex() == i,
"Item ordering must be preserved in batch sql update");
ps.setLong(1, incrementer.nextLongValue());
ps.setLong(2, stepExecution.getJobExecution().getJobId());
ps.setBytes(3, SerializationUtils.serialize(itemIterator.next()));
ps.setString(4, NEW);
}
});
| 393
| 238
| 631
|
<methods>public void <init>() ,public final javax.sql.DataSource getDataSource() ,public final org.springframework.jdbc.core.JdbcTemplate getJdbcTemplate() ,public final void setDataSource(javax.sql.DataSource) ,public final void setJdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) <variables>private org.springframework.jdbc.core.JdbcTemplate jdbcTemplate
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/person/Child.java
|
Child
|
equals
|
class Child {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Child [name=" + name + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Child other = (Child) obj;
if (name == null) {
if (other.name != null) {
return false;
}
}
else if (!name.equals(other.name)) {
return false;
}
return true;
| 160
| 135
| 295
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/person/Person.java
|
Person
|
toString
|
class Person {
private String title = "";
private String firstName = "";
private String last_name = "";
private int age = 0;
private Address address = new Address();
private List<Child> children = new ArrayList<>();
public Person() {
children.add(new Child());
children.add(new Child());
}
/**
* @return the address
*/
public Address getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(Address address) {
this.address = address;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the children
*/
public List<Child> getChildren() {
return children;
}
/**
* @param children the children to set
*/
public void setChildren(List<Child> children) {
this.children = children;
}
/**
* Intentionally non-standard method name for testing purposes
* @return the last_name
*/
public String getLast_name() {
return last_name;
}
/**
* Intentionally non-standard method name for testing purposes
* @param last_name the last_name to set
*/
public void setLast_name(String last_name) {
this.last_name = last_name;
}
/**
* @return the person_title
*/
public String getTitle() {
return title;
}
/**
* @param title the person title to set
*/
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + age;
result = prime * result + ((children == null) ? 0 : children.hashCode());
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((last_name == null) ? 0 : last_name.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Person other = (Person) obj;
if (address == null) {
if (other.address != null) {
return false;
}
}
else if (!address.equals(other.address)) {
return false;
}
if (age != other.age) {
return false;
}
if (children == null) {
if (other.children != null) {
return false;
}
}
else if (!children.equals(other.children)) {
return false;
}
if (firstName == null) {
if (other.firstName != null) {
return false;
}
}
else if (!firstName.equals(other.firstName)) {
return false;
}
if (last_name == null) {
if (other.last_name != null) {
return false;
}
}
else if (!last_name.equals(other.last_name)) {
return false;
}
if (title == null) {
if (other.title != null) {
return false;
}
}
else if (!title.equals(other.title)) {
return false;
}
return true;
}
}
|
return "Person [address=" + address + ", age=" + age + ", children=" + children + ", firstName=" + firstName
+ ", last_name=" + last_name + ", title=" + title + "]";
| 1,123
| 61
| 1,184
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/person/PersonService.java
|
PersonService
|
getData
|
class PersonService {
private static final int GENERATION_LIMIT = 10;
private int generatedCounter = 0;
private int processedCounter = 0;
public Person getData() {<FILL_FUNCTION_BODY>}
/*
* Badly designed method signature which accepts multiple implicitly related arguments
* instead of a single Person argument.
*/
public void processPerson(String name, String city) {
processedCounter++;
}
public int getReturnedCount() {
return generatedCounter;
}
public int getReceivedCount() {
return processedCounter;
}
}
|
if (generatedCounter >= GENERATION_LIMIT) {
return null;
}
Person person = new Person();
Address address = new Address();
Child child = new Child();
List<Child> children = new ArrayList<>(1);
children.add(child);
person.setFirstName("John" + generatedCounter);
person.setAge(20 + generatedCounter);
address.setCity("Johnsville" + generatedCounter);
child.setName("Little Johny" + generatedCounter);
person.setAddress(address);
person.setChildren(children);
generatedCounter++;
return person;
| 153
| 178
| 331
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/CompositeCustomerUpdateLineTokenizer.java
|
CompositeCustomerUpdateLineTokenizer
|
tokenize
|
class CompositeCustomerUpdateLineTokenizer implements StepExecutionListener, LineTokenizer {
private LineTokenizer customerTokenizer;
private LineTokenizer footerTokenizer;
private StepExecution stepExecution;
@Override
public FieldSet tokenize(@Nullable String line) {<FILL_FUNCTION_BODY>}
@Override
public void beforeStep(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
/**
* Set the {@link LineTokenizer} that will be used to tokenize any lines that begin
* with A, U, or D, and are thus a customer operation.
* @param customerTokenizer tokenizer to delegate to for customer operation records
*/
public void setCustomerTokenizer(LineTokenizer customerTokenizer) {
this.customerTokenizer = customerTokenizer;
}
/**
* Set the {@link LineTokenizer} that will be used to tokenize any lines that being
* with F and is thus a footer record.
* @param footerTokenizer tokenizer to delegate to for footer records
*/
public void setFooterTokenizer(LineTokenizer footerTokenizer) {
this.footerTokenizer = footerTokenizer;
}
}
|
if (line.charAt(0) == 'F') {
// line starts with F, so the footer tokenizer should tokenize it.
FieldSet fs = footerTokenizer.tokenize(line);
long customerUpdateTotal = stepExecution.getReadCount();
long fileUpdateTotal = fs.readLong(1);
if (customerUpdateTotal != fileUpdateTotal) {
throw new IllegalStateException(
"The total number of customer updates in the file footer does not match the "
+ "number entered File footer total: [" + fileUpdateTotal
+ "] Total encountered during processing: [" + customerUpdateTotal + "]");
}
else {
// return null, because the footer indicates an end of processing.
return null;
}
}
else if (line.charAt(0) == 'A' || line.charAt(0) == 'U' || line.charAt(0) == 'D') {
// line starts with A,U, or D, so it must be a customer operation.
return customerTokenizer.tokenize(line);
}
else {
// If the line doesn't start with any of the characters above, it must
// obviously be invalid.
throw new IllegalArgumentException("Invalid line encountered for tokenizing: " + line);
}
| 291
| 327
| 618
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/CustomerCredit.java
|
CustomerCredit
|
toString
|
class CustomerCredit {
@Id
private int id;
private String name;
private BigDecimal credit;
public CustomerCredit() {
}
public CustomerCredit(int id, String name, BigDecimal credit) {
this.id = id;
this.name = name;
this.credit = credit;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public BigDecimal getCredit() {
return credit;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setCredit(BigDecimal credit) {
this.credit = credit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CustomerCredit increaseCreditBy(BigDecimal sum) {
CustomerCredit newCredit = new CustomerCredit();
newCredit.credit = this.credit.add(sum);
newCredit.name = this.name;
newCredit.id = this.id;
return newCredit;
}
@Override
public boolean equals(Object o) {
return (o instanceof CustomerCredit) && ((CustomerCredit) o).id == id;
}
@Override
public int hashCode() {
return id;
}
}
|
return "CustomerCredit [id=" + id + ",name=" + name + ", credit=" + credit + "]";
| 367
| 34
| 401
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/CustomerDebit.java
|
CustomerDebit
|
hashCode
|
class CustomerDebit {
private String name;
private BigDecimal debit;
public CustomerDebit() {
}
CustomerDebit(String name, BigDecimal debit) {
this.name = name;
this.debit = debit;
}
public BigDecimal getDebit() {
return debit;
}
public void setDebit(BigDecimal debit) {
this.debit = debit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "CustomerDebit [name=" + name + ", debit=" + debit + "]";
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
CustomerDebit other = (CustomerDebit) obj;
if (debit == null) {
if (other.debit != null) {
return false;
}
}
else if (!debit.equals(other.debit)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
}
else if (!name.equals(other.name)) {
return false;
}
return true;
}
}
|
final int prime = 31;
int result = 1;
result = prime * result + ((debit == null) ? 0 : debit.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
| 420
| 73
| 493
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/CustomerUpdate.java
|
CustomerUpdate
|
toString
|
class CustomerUpdate {
private final CustomerOperation operation;
private final String customerName;
private final BigDecimal credit;
public CustomerUpdate(CustomerOperation operation, String customerName, BigDecimal credit) {
this.operation = operation;
this.customerName = customerName;
this.credit = credit;
}
public CustomerOperation getOperation() {
return operation;
}
public String getCustomerName() {
return customerName;
}
public BigDecimal getCredit() {
return credit;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Customer Update, name: [" + customerName + "], operation: [" + operation + "], credit: [" + credit
+ "]";
| 156
| 38
| 194
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/CustomerUpdateFieldSetMapper.java
|
CustomerUpdateFieldSetMapper
|
mapFieldSet
|
class CustomerUpdateFieldSetMapper implements FieldSetMapper<CustomerUpdate> {
@Override
public CustomerUpdate mapFieldSet(FieldSet fs) {<FILL_FUNCTION_BODY>}
}
|
if (fs == null) {
return null;
}
CustomerOperation operation = CustomerOperation.fromCode(fs.readChar(0));
String name = fs.readString(1);
BigDecimal credit = fs.readBigDecimal(2);
return new CustomerUpdate(operation, name, credit);
| 48
| 86
| 134
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/CustomerUpdateProcessor.java
|
CustomerUpdateProcessor
|
process
|
class CustomerUpdateProcessor implements ItemProcessor<CustomerUpdate, CustomerUpdate> {
private CustomerDao customerDao;
private InvalidCustomerLogger invalidCustomerLogger;
@Nullable
@Override
public CustomerUpdate process(CustomerUpdate item) throws Exception {<FILL_FUNCTION_BODY>}
public void setCustomerDao(CustomerDao customerDao) {
this.customerDao = customerDao;
}
public void setInvalidCustomerLogger(InvalidCustomerLogger invalidCustomerLogger) {
this.invalidCustomerLogger = invalidCustomerLogger;
}
}
|
if (item.getOperation() == DELETE) {
// delete is not supported
invalidCustomerLogger.log(item);
return null;
}
CustomerCredit customerCredit = customerDao.getCustomerByName(item.getCustomerName());
if (item.getOperation() == ADD && customerCredit == null) {
return item;
}
else if (item.getOperation() == ADD && customerCredit != null) {
// veto processing
invalidCustomerLogger.log(item);
return null;
}
if (item.getOperation() == UPDATE && customerCredit != null) {
return item;
}
else if (item.getOperation() == UPDATE && customerCredit == null) {
// veto processing
invalidCustomerLogger.log(item);
return null;
}
// if an item makes it through all these checks it can be assumed to be bad,
// logged, and skipped
invalidCustomerLogger.log(item);
return null;
| 133
| 263
| 396
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/CustomerUpdateWriter.java
|
CustomerUpdateWriter
|
write
|
class CustomerUpdateWriter implements ItemWriter<CustomerUpdate> {
private CustomerDao customerDao;
@Override
public void write(Chunk<? extends CustomerUpdate> items) throws Exception {<FILL_FUNCTION_BODY>}
public void setCustomerDao(CustomerDao customerDao) {
this.customerDao = customerDao;
}
}
|
for (CustomerUpdate customerUpdate : items) {
if (customerUpdate.getOperation() == CustomerOperation.ADD) {
customerDao.insertCustomer(customerUpdate.getCustomerName(), customerUpdate.getCredit());
}
else if (customerUpdate.getOperation() == CustomerOperation.UPDATE) {
customerDao.updateCustomer(customerUpdate.getCustomerName(), customerUpdate.getCredit());
}
}
// flush and/or clear resources
| 91
| 117
| 208
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/Trade.java
|
Trade
|
equals
|
class Trade implements Serializable {
private String isin = "";
private long quantity = 0;
private BigDecimal price = BigDecimal.ZERO;
private String customer = "";
private Long id;
private long version = 0;
public Trade() {
}
public Trade(String isin, long quantity, BigDecimal price, String customer) {
this.isin = isin;
this.quantity = quantity;
this.price = price;
this.customer = customer;
}
/**
* @param id id of the trade
*/
public Trade(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public void setIsin(String isin) {
this.isin = isin;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public void setQuantity(long quantity) {
this.quantity = quantity;
}
public String getIsin() {
return isin;
}
public BigDecimal getPrice() {
return price;
}
public long getQuantity() {
return quantity;
}
public String getCustomer() {
return customer;
}
@Override
public String toString() {
return "Trade: [isin=" + this.isin + ",quantity=" + this.quantity + ",price=" + this.price + ",customer="
+ this.customer + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((customer == null) ? 0 : customer.hashCode());
result = prime * result + ((isin == null) ? 0 : isin.hashCode());
result = prime * result + ((price == null) ? 0 : price.hashCode());
result = prime * result + (int) (quantity ^ (quantity >>> 32));
result = prime * result + (int) (version ^ (version >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Trade other = (Trade) obj;
if (customer == null) {
if (other.customer != null) {
return false;
}
}
else if (!customer.equals(other.customer)) {
return false;
}
if (isin == null) {
if (other.isin != null) {
return false;
}
}
else if (!isin.equals(other.isin)) {
return false;
}
if (price == null) {
if (other.price != null) {
return false;
}
}
else if (!price.equals(other.price)) {
return false;
}
if (quantity != other.quantity) {
return false;
}
if (version != other.version) {
return false;
}
return true;
| 636
| 286
| 922
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/CommonsLoggingInvalidCustomerLogger.java
|
CommonsLoggingInvalidCustomerLogger
|
log
|
class CommonsLoggingInvalidCustomerLogger implements InvalidCustomerLogger {
protected static final Log LOG = LogFactory.getLog(CommandLineJobRunner.class);
@Override
public void log(CustomerUpdate customerUpdate) {<FILL_FUNCTION_BODY>}
}
|
LOG.error("invalid customer encountered: [ " + customerUpdate + "]");
| 65
| 23
| 88
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/CustomerCreditFieldSetMapper.java
|
CustomerCreditFieldSetMapper
|
mapFieldSet
|
class CustomerCreditFieldSetMapper implements FieldSetMapper<CustomerCredit> {
public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1;
public static final int CREDIT_COLUMN = 2;
@Override
public CustomerCredit mapFieldSet(FieldSet fieldSet) {<FILL_FUNCTION_BODY>}
}
|
CustomerCredit trade = new CustomerCredit();
trade.setId(fieldSet.readInt(ID_COLUMN));
trade.setName(fieldSet.readString(NAME_COLUMN));
trade.setCredit(fieldSet.readBigDecimal(CREDIT_COLUMN));
return trade;
| 96
| 90
| 186
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/CustomerCreditRowMapper.java
|
CustomerCreditRowMapper
|
mapRow
|
class CustomerCreditRowMapper implements RowMapper<CustomerCredit> {
public static final String ID_COLUMN = "id";
public static final String NAME_COLUMN = "name";
public static final String CREDIT_COLUMN = "credit";
@Override
public CustomerCredit mapRow(ResultSet rs, int rowNum) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
CustomerCredit customerCredit = new CustomerCredit();
customerCredit.setId(rs.getInt(ID_COLUMN));
customerCredit.setName(rs.getString(NAME_COLUMN));
customerCredit.setCredit(rs.getBigDecimal(CREDIT_COLUMN));
return customerCredit;
| 104
| 94
| 198
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/CustomerCreditUpdateWriter.java
|
CustomerCreditUpdateWriter
|
write
|
class CustomerCreditUpdateWriter implements ItemWriter<CustomerCredit> {
private double creditFilter = 800;
private CustomerCreditDao dao;
@Override
public void write(Chunk<? extends CustomerCredit> customerCredits) throws Exception {<FILL_FUNCTION_BODY>}
public void setCreditFilter(double creditFilter) {
this.creditFilter = creditFilter;
}
public void setDao(CustomerCreditDao dao) {
this.dao = dao;
}
}
|
for (CustomerCredit customerCredit : customerCredits) {
if (customerCredit.getCredit().doubleValue() > creditFilter) {
dao.writeCredit(customerCredit);
}
}
| 134
| 59
| 193
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/CustomerDebitRowMapper.java
|
CustomerDebitRowMapper
|
mapRow
|
class CustomerDebitRowMapper implements RowMapper<CustomerDebit> {
public static final String CUSTOMER_COLUMN = "customer";
public static final String PRICE_COLUMN = "price";
@Override
public CustomerDebit mapRow(ResultSet rs, int ignoredRowNumber) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
CustomerDebit customerDebit = new CustomerDebit();
customerDebit.setName(rs.getString(CUSTOMER_COLUMN));
customerDebit.setDebit(rs.getBigDecimal(PRICE_COLUMN));
return customerDebit;
| 91
| 75
| 166
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/CustomerUpdateWriter.java
|
CustomerUpdateWriter
|
write
|
class CustomerUpdateWriter implements ItemWriter<Trade> {
private CustomerDebitDao dao;
@Override
public void write(Chunk<? extends Trade> trades) {<FILL_FUNCTION_BODY>}
public void setDao(CustomerDebitDao outputSource) {
this.dao = outputSource;
}
}
|
for (Trade trade : trades) {
CustomerDebit customerDebit = new CustomerDebit();
customerDebit.setName(trade.getCustomer());
customerDebit.setDebit(trade.getPrice());
dao.write(customerDebit);
}
| 87
| 77
| 164
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/FlatFileCustomerCreditDao.java
|
FlatFileCustomerCreditDao
|
open
|
class FlatFileCustomerCreditDao implements CustomerCreditDao, DisposableBean {
private ItemWriter<String> itemWriter;
private String separator = "\t";
private volatile boolean opened = false;
@Override
public void writeCredit(CustomerCredit customerCredit) throws Exception {
if (!opened) {
open(new ExecutionContext());
}
String line = customerCredit.getName() + separator + customerCredit.getCredit();
itemWriter.write(Chunk.of(line));
}
public void setSeparator(String separator) {
this.separator = separator;
}
public void setItemWriter(ItemWriter<String> itemWriter) {
this.itemWriter = itemWriter;
}
public void open(ExecutionContext executionContext) throws Exception {<FILL_FUNCTION_BODY>}
public void close() throws Exception {
if (itemWriter instanceof ItemStream) {
((ItemStream) itemWriter).close();
}
}
@Override
public void destroy() throws Exception {
close();
}
}
|
if (itemWriter instanceof ItemStream) {
((ItemStream) itemWriter).open(executionContext);
}
opened = true;
| 275
| 40
| 315
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/GeneratingTradeItemReader.java
|
GeneratingTradeItemReader
|
read
|
class GeneratingTradeItemReader implements ItemReader<Trade> {
private int limit = 1;
private int counter = 0;
@Nullable
@Override
public Trade read() throws Exception {<FILL_FUNCTION_BODY>}
/**
* @param limit number of items that will be generated (null returned on consecutive
* calls).
*/
public void setLimit(int limit) {
this.limit = limit;
}
public int getCounter() {
return counter;
}
public int getLimit() {
return limit;
}
public void resetCounter() {
this.counter = 0;
}
}
|
if (counter < limit) {
counter++;
return new Trade("isin" + counter, counter, new BigDecimal(counter), "customer" + counter);
}
return null;
| 159
| 53
| 212
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/HibernateAwareCustomerCreditItemWriter.java
|
HibernateAwareCustomerCreditItemWriter
|
afterPropertiesSet
|
class HibernateAwareCustomerCreditItemWriter implements ItemWriter<CustomerCredit>, InitializingBean {
private CustomerCreditDao dao;
private SessionFactory sessionFactory;
@Override
public void write(Chunk<? extends CustomerCredit> items) throws Exception {
for (CustomerCredit credit : items) {
dao.writeCredit(credit);
}
try {
sessionFactory.getCurrentSession().flush();
}
finally {
// this should happen automatically on commit, but to be on the safe
// side...
sessionFactory.getCurrentSession().clear();
}
}
public void setDao(CustomerCreditDao dao) {
this.dao = dao;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
}
|
Assert.state(sessionFactory != null, "Hibernate SessionFactory is required");
Assert.state(dao != null, "Delegate DAO must be set");
| 244
| 47
| 291
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/HibernateCreditDao.java
|
HibernateCreditDao
|
writeCredit
|
class HibernateCreditDao implements CustomerCreditDao, RepeatListener {
private int failOnFlush = -1;
private final List<Throwable> errors = new ArrayList<>();
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/**
* Public accessor for the errors property.
* @return the errors - a list of Throwable instances
*/
public List<Throwable> getErrors() {
return errors;
}
@Override
public void writeCredit(CustomerCredit customerCredit) {<FILL_FUNCTION_BODY>}
public void write(Object output) {
writeCredit((CustomerCredit) output);
}
/**
* Public setter for the failOnFlush property.
* @param failOnFlush the ID of the record you want to fail on flush (for testing)
*/
public void setFailOnFlush(int failOnFlush) {
this.failOnFlush = failOnFlush;
}
@Override
public void onError(RepeatContext context, Throwable e) {
errors.add(e);
}
@Override
public void after(RepeatContext context, RepeatStatus result) {
}
@Override
public void before(RepeatContext context) {
}
@Override
public void close(RepeatContext context) {
}
@Override
public void open(RepeatContext context) {
}
}
|
if (customerCredit.getId() == failOnFlush) {
// try to insert one with a duplicate ID
CustomerCredit newCredit = new CustomerCredit();
newCredit.setId(customerCredit.getId());
newCredit.setName(customerCredit.getName());
newCredit.setCredit(customerCredit.getCredit());
sessionFactory.getCurrentSession().save(newCredit);
}
else {
sessionFactory.getCurrentSession().update(customerCredit);
}
| 371
| 139
| 510
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/ItemTrackingTradeItemWriter.java
|
ItemTrackingTradeItemWriter
|
write
|
class ItemTrackingTradeItemWriter implements ItemWriter<Trade> {
private final List<Trade> items = new ArrayList<>();
private String writeFailureISIN;
private JdbcOperations jdbcTemplate;
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
public void setWriteFailureISIN(String writeFailureISIN) {
this.writeFailureISIN = writeFailureISIN;
}
public List<Trade> getItems() {
return items;
}
@Override
public void write(Chunk<? extends Trade> items) throws Exception {<FILL_FUNCTION_BODY>}
}
|
List<Trade> newItems = new ArrayList<>();
for (Trade t : items) {
if (t.getIsin().equals(this.writeFailureISIN)) {
throw new IOException("write failed");
}
newItems.add(t);
if (jdbcTemplate != null) {
jdbcTemplate.update("UPDATE TRADE set VERSION=? where ID=? and version=?", t.getVersion() + 1,
t.getId(), t.getVersion());
}
}
this.items.addAll(newItems);
| 171
| 153
| 324
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/JdbcCustomerDao.java
|
JdbcCustomerDao
|
getCustomerByName
|
class JdbcCustomerDao extends JdbcDaoSupport implements CustomerDao {
private static final String GET_CUSTOMER_BY_NAME = "SELECT ID, NAME, CREDIT from CUSTOMER where NAME = ?";
private static final String INSERT_CUSTOMER = "INSERT into CUSTOMER(ID, NAME, CREDIT) values(?,?,?)";
private static final String UPDATE_CUSTOMER = "UPDATE CUSTOMER set CREDIT = ? where NAME = ?";
private DataFieldMaxValueIncrementer incrementer;
public void setIncrementer(DataFieldMaxValueIncrementer incrementer) {
this.incrementer = incrementer;
}
@Override
public CustomerCredit getCustomerByName(String name) {<FILL_FUNCTION_BODY>}
@Override
public void insertCustomer(String name, BigDecimal credit) {
getJdbcTemplate().update(INSERT_CUSTOMER, new Object[] { incrementer.nextIntValue(), name, credit });
}
@Override
public void updateCustomer(String name, BigDecimal credit) {
getJdbcTemplate().update(UPDATE_CUSTOMER, new Object[] { credit, name });
}
}
|
List<CustomerCredit> customers = getJdbcTemplate().query(GET_CUSTOMER_BY_NAME, (rs, rowNum) -> {
CustomerCredit customer = new CustomerCredit();
customer.setName(rs.getString("NAME"));
customer.setId(rs.getInt("ID"));
customer.setCredit(rs.getBigDecimal("CREDIT"));
return customer;
}, name);
if (customers.size() == 0) {
return null;
}
else {
return customers.get(0);
}
| 303
| 153
| 456
|
<methods>public void <init>() ,public final javax.sql.DataSource getDataSource() ,public final org.springframework.jdbc.core.JdbcTemplate getJdbcTemplate() ,public final void setDataSource(javax.sql.DataSource) ,public final void setJdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) <variables>private org.springframework.jdbc.core.JdbcTemplate jdbcTemplate
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/JdbcTradeDao.java
|
JdbcTradeDao
|
writeTrade
|
class JdbcTradeDao implements TradeDao {
private final Log log = LogFactory.getLog(JdbcTradeDao.class);
/**
* template for inserting a row
*/
private static final String INSERT_TRADE_RECORD = "INSERT INTO TRADE (id, version, isin, quantity, price, customer) VALUES (?, 0, ?, ? ,?, ?)";
/**
* handles the processing of SQL query
*/
private JdbcOperations jdbcTemplate;
/**
* database is not expected to be setup for auto increment
*/
private DataFieldMaxValueIncrementer incrementer;
/**
* @see TradeDao
*/
@Override
public void writeTrade(Trade trade) {<FILL_FUNCTION_BODY>}
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void setIncrementer(DataFieldMaxValueIncrementer incrementer) {
this.incrementer = incrementer;
}
}
|
Long id = incrementer.nextLongValue();
if (log.isDebugEnabled()) {
log.debug("Processing: " + trade);
}
jdbcTemplate.update(INSERT_TRADE_RECORD, id, trade.getIsin(), trade.getQuantity(), trade.getPrice(),
trade.getCustomer());
| 267
| 91
| 358
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/TradeFieldSetMapper.java
|
TradeFieldSetMapper
|
mapFieldSet
|
class TradeFieldSetMapper implements FieldSetMapper<Trade> {
public static final int ISIN_COLUMN = 0;
public static final int QUANTITY_COLUMN = 1;
public static final int PRICE_COLUMN = 2;
public static final int CUSTOMER_COLUMN = 3;
@Override
public Trade mapFieldSet(FieldSet fieldSet) {<FILL_FUNCTION_BODY>}
}
|
Trade trade = new Trade();
trade.setIsin(fieldSet.readString(ISIN_COLUMN));
trade.setQuantity(fieldSet.readLong(QUANTITY_COLUMN));
trade.setPrice(fieldSet.readBigDecimal(PRICE_COLUMN));
trade.setCustomer(fieldSet.readString(CUSTOMER_COLUMN));
return trade;
| 110
| 115
| 225
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/TradeProcessor.java
|
TradeProcessor
|
process
|
class TradeProcessor implements ItemProcessor<Trade, Trade> {
private int failure = -1;
private int index = 0;
private Trade failedItem = null;
/**
* Public setter for the index on which failure should occur.
* @param failure the failure to set
*/
public void setValidationFailure(int failure) {
this.failure = failure;
}
@Nullable
@Override
public Trade process(Trade item) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if ((failedItem == null && index++ == failure) || (failedItem != null && failedItem.equals(item))) {
failedItem = item;
throw new ValidationException("Some bad data for " + failedItem);
}
return item;
| 127
| 67
| 194
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/TradeRowMapper.java
|
TradeRowMapper
|
mapRow
|
class TradeRowMapper implements RowMapper<Trade> {
public static final int ISIN_COLUMN = 1;
public static final int QUANTITY_COLUMN = 2;
public static final int PRICE_COLUMN = 3;
public static final int CUSTOMER_COLUMN = 4;
public static final int ID_COLUMN = 5;
public static final int VERSION_COLUMN = 6;
@Override
public Trade mapRow(ResultSet rs, int rowNum) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
Trade trade = new Trade(rs.getLong(ID_COLUMN));
trade.setIsin(rs.getString(ISIN_COLUMN));
trade.setQuantity(rs.getLong(QUANTITY_COLUMN));
trade.setPrice(rs.getBigDecimal(PRICE_COLUMN));
trade.setCustomer(rs.getString(CUSTOMER_COLUMN));
trade.setVersion(rs.getInt(VERSION_COLUMN));
return trade;
| 144
| 140
| 284
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/TradeWriter.java
|
TradeWriter
|
write
|
class TradeWriter extends ItemStreamSupport implements ItemWriter<Trade> {
private static final Log log = LogFactory.getLog(TradeWriter.class);
public static final String TOTAL_AMOUNT_KEY = "TOTAL_AMOUNT";
private TradeDao dao;
private List<String> failingCustomers = new ArrayList<>();
private BigDecimal totalPrice = BigDecimal.ZERO;
@Override
public void write(Chunk<? extends Trade> trades) {<FILL_FUNCTION_BODY>}
@AfterWrite
public void updateTotalPrice(Chunk<Trade> trades) {
for (Trade trade : trades) {
this.totalPrice = this.totalPrice.add(trade.getPrice());
}
}
@Override
public void open(ExecutionContext executionContext) {
if (executionContext.containsKey(TOTAL_AMOUNT_KEY)) {
this.totalPrice = (BigDecimal) executionContext.get(TOTAL_AMOUNT_KEY);
}
else {
//
// Fresh run. Disregard old state.
//
this.totalPrice = BigDecimal.ZERO;
}
}
@Override
public void update(ExecutionContext executionContext) {
executionContext.put(TOTAL_AMOUNT_KEY, this.totalPrice);
}
public BigDecimal getTotalPrice() {
return totalPrice;
}
public void setDao(TradeDao dao) {
this.dao = dao;
}
/**
* Public setter for the customers on which failure should occur.
* @param failingCustomers The customers to fail on
*/
public void setFailingCustomers(List<String> failingCustomers) {
this.failingCustomers = failingCustomers;
}
}
|
for (Trade trade : trades) {
log.debug(trade);
dao.writeTrade(trade);
Assert.notNull(trade.getPrice(), "price must not be null"); // There must be a
// price to total
if (this.failingCustomers.contains(trade.getCustomer())) {
throw new WriteFailedException("Something unexpected happened!");
}
}
| 455
| 117
| 572
|
<methods>public non-sealed void <init>() ,public void close() ,public java.lang.String getExecutionContextKey(java.lang.String) ,public java.lang.String getName() ,public void open(org.springframework.batch.item.ExecutionContext) ,public void setName(java.lang.String) ,public void update(org.springframework.batch.item.ExecutionContext) <variables>private final org.springframework.batch.item.util.ExecutionContextUserSupport executionContextUserSupport
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/internal/validator/TradeValidator.java
|
TradeValidator
|
validate
|
class TradeValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return clazz.equals(Trade.class);
}
@Override
public void validate(Object target, Errors errors) {<FILL_FUNCTION_BODY>}
}
|
Trade trade = (Trade) target;
if (trade.getIsin().length() >= 13) {
errors.rejectValue("isin", "isin_length");
}
| 72
| 56
| 128
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/delimited/DelimitedJobConfiguration.java
|
DelimitedJobConfiguration
|
itemReader
|
class DelimitedJobConfiguration {
@Bean
@StepScope
public FlatFileItemReader<CustomerCredit> itemReader(@Value("#{jobParameters[inputFile]}") Resource resource) {<FILL_FUNCTION_BODY>}
@Bean
@StepScope
public FlatFileItemWriter<CustomerCredit> itemWriter(
@Value("#{jobParameters[outputFile]}") WritableResource resource) {
return new FlatFileItemWriterBuilder<CustomerCredit>().name("itemWriter")
.resource(resource)
.delimited()
.names("name", "credit")
.build();
}
@Bean
public Job job(JobRepository jobRepository, JdbcTransactionManager transactionManager,
ItemReader<CustomerCredit> itemReader, ItemWriter<CustomerCredit> itemWriter) {
return new JobBuilder("ioSampleJob", jobRepository)
.start(new StepBuilder("step1", jobRepository).<CustomerCredit, CustomerCredit>chunk(2, transactionManager)
.reader(itemReader)
.processor(new CustomerCreditIncreaseProcessor())
.writer(itemWriter)
.build())
.build();
}
}
|
return new FlatFileItemReaderBuilder<CustomerCredit>().name("itemReader")
.resource(resource)
.delimited()
.names("name", "credit")
.targetType(CustomerCredit.class)
.build();
| 286
| 65
| 351
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/fixed/FixedLengthJobConfiguration.java
|
FixedLengthJobConfiguration
|
itemWriter
|
class FixedLengthJobConfiguration {
@Bean
@StepScope
public FlatFileItemReader<CustomerCredit> itemReader(@Value("#{jobParameters[inputFile]}") Resource resource) {
return new FlatFileItemReaderBuilder<CustomerCredit>().name("itemReader")
.resource(resource)
.fixedLength()
.columns(new Range(1, 9), new Range(10, 11))
.names("name", "credit")
.targetType(CustomerCredit.class)
.build();
}
@Bean
@StepScope
public FlatFileItemWriter<CustomerCredit> itemWriter(
@Value("#{jobParameters[outputFile]}") WritableResource resource) {<FILL_FUNCTION_BODY>}
@Bean
public Job job(JobRepository jobRepository, JdbcTransactionManager transactionManager,
ItemReader<CustomerCredit> itemReader, ItemWriter<CustomerCredit> itemWriter) {
return new JobBuilder("ioSampleJob", jobRepository)
.start(new StepBuilder("step1", jobRepository).<CustomerCredit, CustomerCredit>chunk(2, transactionManager)
.reader(itemReader)
.processor(new CustomerCreditIncreaseProcessor())
.writer(itemWriter)
.build())
.build();
}
}
|
return new FlatFileItemWriterBuilder<CustomerCredit>().name("itemWriter")
.resource(resource)
.formatted()
.format("%-9s%-2.0f")
.names("name", "credit")
.build();
| 319
| 67
| 386
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/json/JsonJobConfiguration.java
|
JsonJobConfiguration
|
itemWriter
|
class JsonJobConfiguration {
@Bean
@StepScope
public JsonItemReader<Trade> itemReader(@Value("#{jobParameters[inputFile]}") Resource resource) {
return new JsonItemReaderBuilder<Trade>().name("tradesJsonItemReader")
.resource(resource)
.jsonObjectReader(new GsonJsonObjectReader<>(Trade.class))
.build();
}
@Bean
@StepScope
public JsonFileItemWriter<Trade> itemWriter(@Value("#{jobParameters[outputFile]}") WritableResource resource) {<FILL_FUNCTION_BODY>}
@Bean
public Step step(JobRepository jobRepository, JdbcTransactionManager transactionManager,
JsonItemReader<Trade> itemReader, JsonFileItemWriter<Trade> itemWriter) {
return new StepBuilder("step", jobRepository).<Trade, Trade>chunk(2, transactionManager)
.reader(itemReader)
.writer(itemWriter)
.build();
}
@Bean
public Job job(JobRepository jobRepository, Step step) {
return new JobBuilder("job", jobRepository).start(step).build();
}
}
|
return new JsonFileItemWriterBuilder<Trade>().resource(resource)
.lineSeparator("\n")
.jsonObjectMarshaller(new JacksonJsonObjectMarshaller<>())
.name("tradesJsonFileItemWriter")
.shouldDeleteIfExists(true)
.build();
| 281
| 75
| 356
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multiline/MultiLineJobConfiguration.java
|
MultiLineJobConfiguration
|
itemReader
|
class MultiLineJobConfiguration {
@Bean
@StepScope
public MultiLineTradeItemReader itemReader(@Value("#{jobParameters[inputFile]}") Resource resource) {<FILL_FUNCTION_BODY>}
@Bean
@StepScope
public MultiLineTradeItemWriter itemWriter(@Value("#{jobParameters[outputFile]}") WritableResource resource) {
FlatFileItemWriter<String> delegate = new FlatFileItemWriterBuilder<String>().name("delegateItemWriter")
.resource(resource)
.lineAggregator(new PassThroughLineAggregator<>())
.build();
MultiLineTradeItemWriter writer = new MultiLineTradeItemWriter();
writer.setDelegate(delegate);
return writer;
}
@Bean
public Job job(JobRepository jobRepository, JdbcTransactionManager transactionManager,
MultiLineTradeItemReader itemReader, MultiLineTradeItemWriter itemWriter) {
return new JobBuilder("ioSampleJob", jobRepository)
.start(new StepBuilder("step1", jobRepository).<Trade, Trade>chunk(2, transactionManager)
.reader(itemReader)
.writer(itemWriter)
.build())
.build();
}
}
|
FlatFileItemReader<FieldSet> delegate = new FlatFileItemReaderBuilder<FieldSet>().name("delegateItemReader")
.resource(resource)
.lineTokenizer(new DelimitedLineTokenizer())
.fieldSetMapper(new PassThroughFieldSetMapper())
.build();
MultiLineTradeItemReader reader = new MultiLineTradeItemReader();
reader.setDelegate(delegate);
return reader;
| 301
| 113
| 414
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multiline/MultiLineTradeItemReader.java
|
MultiLineTradeItemReader
|
read
|
class MultiLineTradeItemReader implements ItemReader<Trade>, ItemStream {
private FlatFileItemReader<FieldSet> delegate;
/**
* @see org.springframework.batch.item.ItemReader#read()
*/
@Nullable
@Override
public Trade read() throws Exception {<FILL_FUNCTION_BODY>}
public void setDelegate(FlatFileItemReader<FieldSet> delegate) {
this.delegate = delegate;
}
@Override
public void close() throws ItemStreamException {
this.delegate.close();
}
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
this.delegate.open(executionContext);
}
@Override
public void update(ExecutionContext executionContext) throws ItemStreamException {
this.delegate.update(executionContext);
}
}
|
Trade t = null;
for (FieldSet line; (line = this.delegate.read()) != null;) {
String prefix = line.readString(0);
switch (prefix) {
case "BEGIN" -> t = new Trade(); // Record must start with 'BEGIN'
case "INFO" -> {
Assert.notNull(t, "No 'BEGIN' was found.");
t.setIsin(line.readString(1));
t.setCustomer(line.readString(2));
}
case "AMNT" -> {
Assert.notNull(t, "No 'BEGIN' was found.");
t.setQuantity(line.readInt(1));
t.setPrice(line.readBigDecimal(2));
}
case "END" -> {
return t; // Record must end with 'END'
}
}
}
Assert.isNull(t, "No 'END' was found.");
return null;
| 210
| 253
| 463
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multiline/MultiLineTradeItemWriter.java
|
MultiLineTradeItemWriter
|
write
|
class MultiLineTradeItemWriter implements ItemWriter<Trade>, ItemStream {
private FlatFileItemWriter<String> delegate;
@Override
public void write(Chunk<? extends Trade> items) throws Exception {<FILL_FUNCTION_BODY>}
public void setDelegate(FlatFileItemWriter<String> delegate) {
this.delegate = delegate;
}
@Override
public void close() throws ItemStreamException {
this.delegate.close();
}
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
this.delegate.open(executionContext);
}
@Override
public void update(ExecutionContext executionContext) throws ItemStreamException {
this.delegate.update(executionContext);
}
}
|
Chunk<String> lines = new Chunk<>();
for (Trade t : items) {
lines.add("BEGIN");
lines.add("INFO," + t.getIsin() + "," + t.getCustomer());
lines.add("AMNT," + t.getQuantity() + "," + t.getPrice());
lines.add("END");
}
this.delegate.write(lines);
| 191
| 115
| 306
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multiline/Trade.java
|
Trade
|
hashCode
|
class Trade implements Serializable {
private String isin = "";
private long quantity = 0;
private BigDecimal price = BigDecimal.ZERO;
private String customer = "";
private Long id;
private long version = 0;
public Trade() {
}
public Trade(String isin, long quantity, BigDecimal price, String customer) {
this.isin = isin;
this.quantity = quantity;
this.price = price;
this.customer = customer;
}
/**
* @param id id of the trade
*/
public Trade(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public void setIsin(String isin) {
this.isin = isin;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public void setQuantity(long quantity) {
this.quantity = quantity;
}
public String getIsin() {
return isin;
}
public BigDecimal getPrice() {
return price;
}
public long getQuantity() {
return quantity;
}
public String getCustomer() {
return customer;
}
@Override
public String toString() {
return "Trade: [isin=" + this.isin + ",quantity=" + this.quantity + ",price=" + this.price + ",customer="
+ this.customer + "]";
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Trade other = (Trade) obj;
if (customer == null) {
if (other.customer != null) {
return false;
}
}
else if (!customer.equals(other.customer)) {
return false;
}
if (isin == null) {
if (other.isin != null) {
return false;
}
}
else if (!isin.equals(other.isin)) {
return false;
}
if (price == null) {
if (other.price != null) {
return false;
}
}
else if (!price.equals(other.price)) {
return false;
}
if (quantity != other.quantity) {
return false;
}
if (version != other.version) {
return false;
}
return true;
}
}
|
final int prime = 31;
int result = 1;
result = prime * result + ((customer == null) ? 0 : customer.hashCode());
result = prime * result + ((isin == null) ? 0 : isin.hashCode());
result = prime * result + ((price == null) ? 0 : price.hashCode());
result = prime * result + (int) (quantity ^ (quantity >>> 32));
result = prime * result + (int) (version ^ (version >>> 32));
return result;
| 778
| 144
| 922
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multilineaggregate/AggregateItemFieldSetMapper.java
|
AggregateItemFieldSetMapper
|
mapFieldSet
|
class AggregateItemFieldSetMapper<T> implements FieldSetMapper<AggregateItem<T>>, InitializingBean {
private FieldSetMapper<T> delegate;
private String end = "END";
private String begin = "BEGIN";
/**
* Public setter for the delegate.
* @param delegate the delegate to set
*/
public void setDelegate(FieldSetMapper<T> delegate) {
this.delegate = delegate;
}
/**
* Public setter for the end field value. If the {@link FieldSet} input has a first
* field with this value that signals the start of an aggregate record.
* @param end the end to set
*/
public void setEnd(String end) {
this.end = end;
}
/**
* Public setter for the begin value. If the {@link FieldSet} input has a first field
* with this value that signals the end of an aggregate record.
* @param begin the begin to set
*/
public void setBegin(String begin) {
this.begin = begin;
}
/**
* Check mandatory properties (delegate).
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(delegate != null, "A FieldSetMapper delegate must be provided.");
}
/**
* Build an {@link AggregateItem} based on matching the first column in the input
* {@link FieldSet} to check for begin and end delimiters. If the current record is
* neither a begin nor an end marker then it is mapped using the delegate.
* @param fieldSet a {@link FieldSet} to map
* @return an {@link AggregateItem} that wraps the return value from the delegate
* @throws BindException if one of the delegates does
*/
@Override
public AggregateItem<T> mapFieldSet(FieldSet fieldSet) throws BindException {<FILL_FUNCTION_BODY>}
}
|
if (fieldSet.readString(0).equals(begin)) {
return AggregateItem.getHeader();
}
if (fieldSet.readString(0).equals(end)) {
return AggregateItem.getFooter();
}
return new AggregateItem<>(delegate.mapFieldSet(fieldSet));
| 497
| 90
| 587
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multilineaggregate/AggregateItemReader.java
|
AggregateItemReader
|
process
|
class AggregateItemReader<T> implements ItemReader<List<T>> {
private static final Log LOG = LogFactory.getLog(AggregateItemReader.class);
private ItemReader<AggregateItem<T>> itemReader;
/**
* Get the next list of records.
*
* @see org.springframework.batch.item.ItemReader#read()
*/
@Nullable
@Override
public List<T> read() throws Exception {
ResultHolder holder = new ResultHolder();
while (process(itemReader.read(), holder)) {
continue;
}
if (!holder.isExhausted()) {
return holder.getRecords();
}
else {
return null;
}
}
private boolean process(AggregateItem<T> value, ResultHolder holder) {<FILL_FUNCTION_BODY>}
public void setItemReader(ItemReader<AggregateItem<T>> itemReader) {
this.itemReader = itemReader;
}
/**
* Private class for temporary state management while item is being collected.
*
* @author Dave Syer
*
*/
private class ResultHolder {
private final List<T> records = new ArrayList<>();
private boolean exhausted = false;
public List<T> getRecords() {
return records;
}
public boolean isExhausted() {
return exhausted;
}
public void addRecord(T record) {
records.add(record);
}
public void setExhausted(boolean exhausted) {
this.exhausted = exhausted;
}
}
}
|
// finish processing if we hit the end of file
if (value == null) {
LOG.debug("Exhausted ItemReader");
holder.setExhausted(true);
return false;
}
// start a new collection
if (value.isHeader()) {
LOG.debug("Start of new record detected");
return true;
}
// mark we are finished with current collection
if (value.isFooter()) {
LOG.debug("End of record detected");
return false;
}
// add a simple record to the current collection
if (LOG.isDebugEnabled()) {
LOG.debug("Mapping: " + value);
}
holder.addRecord(value.getItem());
return true;
| 410
| 195
| 605
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multirecordtype/DelegatingTradeLineAggregator.java
|
DelegatingTradeLineAggregator
|
aggregate
|
class DelegatingTradeLineAggregator implements LineAggregator<Object> {
private LineAggregator<Trade> tradeLineAggregator;
private LineAggregator<CustomerCredit> customerLineAggregator;
@Override
public String aggregate(Object item) {<FILL_FUNCTION_BODY>}
public void setTradeLineAggregator(LineAggregator<Trade> tradeLineAggregator) {
this.tradeLineAggregator = tradeLineAggregator;
}
public void setCustomerLineAggregator(LineAggregator<CustomerCredit> customerLineAggregator) {
this.customerLineAggregator = customerLineAggregator;
}
}
|
if (item instanceof Trade) {
return this.tradeLineAggregator.aggregate((Trade) item);
}
else if (item instanceof CustomerCredit) {
return this.customerLineAggregator.aggregate((CustomerCredit) item);
}
else {
throw new RuntimeException();
}
| 158
| 85
| 243
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multirecordtype/MultiRecordTypeJobConfiguration.java
|
MultiRecordTypeJobConfiguration
|
tradeLineAggregator
|
class MultiRecordTypeJobConfiguration {
@Bean
@StepScope
public FlatFileItemReader itemReader(PatternMatchingCompositeLineMapper lineMapper,
@Value("#{jobParameters[inputFile]}") Resource resource) {
return new FlatFileItemReaderBuilder().name("itemReader").resource(resource).lineMapper(lineMapper).build();
}
@Bean
public PatternMatchingCompositeLineMapper prefixMatchingLineMapper() {
PatternMatchingCompositeLineMapper mapper = new PatternMatchingCompositeLineMapper();
mapper.setTokenizers(Map.of("TRAD*", tradeLineTokenizer(), "CUST*", customerLineTokenizer()));
mapper.setFieldSetMappers(
Map.of("TRAD*", new TradeFieldSetMapper(), "CUST*", new CustomerCreditFieldSetMapper()));
return mapper;
}
@Bean
public FixedLengthTokenizer tradeLineTokenizer() {
FixedLengthTokenizer tokenizer = new FixedLengthTokenizer();
tokenizer.setNames("isin", "quantity", "price", "customer");
tokenizer.setColumns(new Range(5, 16), new Range(17, 19), new Range(20, 25), new Range(26, 34));
return tokenizer;
}
@Bean
public FixedLengthTokenizer customerLineTokenizer() {
FixedLengthTokenizer tokenizer = new FixedLengthTokenizer();
tokenizer.setNames("id", "name", "credit");
tokenizer.setColumns(new Range(5, 9), new Range(10, 18), new Range(19, 26));
return tokenizer;
}
@Bean
@StepScope
public FlatFileItemWriter itemWriter(DelegatingTradeLineAggregator delegatingTradeLineAggregator,
@Value("#{jobParameters[outputFile]}") WritableResource resource) {
return new FlatFileItemWriterBuilder().name("iemWriter")
.resource(resource)
.lineAggregator(delegatingTradeLineAggregator)
.build();
}
@Bean
public DelegatingTradeLineAggregator delegatingTradeLineAggregator(
FormatterLineAggregator<Trade> tradeLineAggregator,
FormatterLineAggregator<CustomerCredit> customerLineAggregator) {
DelegatingTradeLineAggregator lineAggregator = new DelegatingTradeLineAggregator();
lineAggregator.setTradeLineAggregator(tradeLineAggregator);
lineAggregator.setCustomerLineAggregator(customerLineAggregator);
return lineAggregator;
}
@Bean
public FormatterLineAggregator<Trade> tradeLineAggregator() {<FILL_FUNCTION_BODY>}
@Bean
public FormatterLineAggregator<CustomerCredit> customerLineAggregator() {
FormatterLineAggregator<CustomerCredit> formatterLineAggregator = new FormatterLineAggregator<>();
BeanWrapperFieldExtractor<CustomerCredit> fieldExtractor = new BeanWrapperFieldExtractor<>();
fieldExtractor.setNames(new String[] { "id", "name", "credit" });
formatterLineAggregator.setFieldExtractor(fieldExtractor);
formatterLineAggregator.setFormat("CUST%05d%-9s%08.0f");
return formatterLineAggregator;
}
@Bean
public Job job(JobRepository jobRepository, JdbcTransactionManager transactionManager,
FlatFileItemReader itemReader, FlatFileItemWriter itemWriter) {
return new JobBuilder("ioSampleJob", jobRepository)
.start(new StepBuilder("step1", jobRepository).chunk(2, transactionManager)
.reader(itemReader)
.writer(itemWriter)
.build())
.build();
}
}
|
FormatterLineAggregator<Trade> formatterLineAggregator = new FormatterLineAggregator<>();
BeanWrapperFieldExtractor<Trade> fieldExtractor = new BeanWrapperFieldExtractor<>();
fieldExtractor.setNames(new String[] { "isin", "quantity", "price", "customer" });
formatterLineAggregator.setFieldExtractor(fieldExtractor);
formatterLineAggregator.setFormat("TRAD%-12s%-3d%6s%-9s");
return formatterLineAggregator;
| 941
| 141
| 1,082
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multiresource/MultiResourceJobConfiguration.java
|
MultiResourceJobConfiguration
|
job
|
class MultiResourceJobConfiguration {
@Bean
@StepScope
public MultiResourceItemReader<CustomerCredit> itemReader(
@Value("#{jobParameters[inputFiles]}") Resource[] resources) {
return new MultiResourceItemReaderBuilder<CustomerCredit>().name("itemReader")
.resources(resources)
.delegate(delegateReader())
.build();
}
@Bean
public FlatFileItemReader<CustomerCredit> delegateReader() {
return new FlatFileItemReaderBuilder<CustomerCredit>().name("delegateItemReader")
.delimited()
.names("name", "credit")
.targetType(CustomerCredit.class)
.build();
}
@Bean
@StepScope
public MultiResourceItemWriter<CustomerCredit> itemWriter(
@Value("#{jobParameters[outputFiles]}") WritableResource resource) {
return new MultiResourceItemWriterBuilder<CustomerCredit>().name("itemWriter")
.delegate(delegateWriter())
.resource(resource)
.itemCountLimitPerResource(6)
.build();
}
@Bean
public FlatFileItemWriter<CustomerCredit> delegateWriter() {
return new FlatFileItemWriterBuilder<CustomerCredit>().name("delegateItemWriter")
.delimited()
.names("name", "credit")
.build();
}
@Bean
public Job job(JobRepository jobRepository, JdbcTransactionManager transactionManager,
ItemReader<CustomerCredit> itemReader, ItemWriter<CustomerCredit> itemWriter) {<FILL_FUNCTION_BODY>}
}
|
return new JobBuilder("ioSampleJob", jobRepository)
.start(new StepBuilder("step1", jobRepository).<CustomerCredit, CustomerCredit>chunk(2, transactionManager)
.reader(itemReader)
.processor(new CustomerCreditIncreaseProcessor())
.writer(itemWriter)
.build())
.build();
| 398
| 89
| 487
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/Address.java
|
Address
|
toString
|
class Address {
public static final String LINE_ID_BILLING_ADDR = "BAD";
public static final String LINE_ID_SHIPPING_ADDR = "SAD";
private String addressee;
private String addrLine1;
private String addrLine2;
private String city;
private String zipCode;
private String state;
private String country;
public String getAddrLine1() {
return addrLine1;
}
public void setAddrLine1(String addrLine1) {
this.addrLine1 = addrLine1;
}
public String getAddrLine2() {
return addrLine2;
}
public void setAddrLine2(String addrLine2) {
this.addrLine2 = addrLine2;
}
public String getAddressee() {
return addressee;
}
public void setAddressee(String addressee) {
this.addressee = addressee;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((addressee == null) ? 0 : addressee.hashCode());
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((zipCode == null) ? 0 : zipCode.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Address other = (Address) obj;
if (addressee == null) {
if (other.addressee != null) {
return false;
}
}
else if (!addressee.equals(other.addressee)) {
return false;
}
if (country == null) {
if (other.country != null) {
return false;
}
}
else if (!country.equals(other.country)) {
return false;
}
if (zipCode == null) {
if (other.zipCode != null) {
return false;
}
}
else if (!zipCode.equals(other.zipCode)) {
return false;
}
return true;
}
}
|
return "Address [addressee=" + addressee + ", city=" + city + ", country=" + country + ", state=" + state
+ ", zipCode=" + zipCode + "]";
| 791
| 54
| 845
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/BillingInfo.java
|
BillingInfo
|
equals
|
class BillingInfo {
public static final String LINE_ID_BILLING_INFO = "BIN";
private String paymentId;
private String paymentDesc;
public String getPaymentDesc() {
return paymentDesc;
}
public void setPaymentDesc(String paymentDesc) {
this.paymentDesc = paymentDesc;
}
public String getPaymentId() {
return paymentId;
}
public void setPaymentId(String paymentId) {
this.paymentId = paymentId;
}
@Override
public String toString() {
return "BillingInfo [paymentDesc=" + paymentDesc + ", paymentId=" + paymentId + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((paymentDesc == null) ? 0 : paymentDesc.hashCode());
result = prime * result + ((paymentId == null) ? 0 : paymentId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
BillingInfo other = (BillingInfo) obj;
if (paymentDesc == null) {
if (other.paymentDesc != null) {
return false;
}
}
else if (!paymentDesc.equals(other.paymentDesc)) {
return false;
}
if (paymentId == null) {
if (other.paymentId != null) {
return false;
}
}
else if (!paymentId.equals(other.paymentId)) {
return false;
}
return true;
| 287
| 205
| 492
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/Customer.java
|
Customer
|
equals
|
class Customer {
public static final String LINE_ID_BUSINESS_CUST = "BCU";
public static final String LINE_ID_NON_BUSINESS_CUST = "NCU";
private boolean businessCustomer;
private boolean registered;
private long registrationId;
// non-business customer
private String firstName;
private String lastName;
private String middleName;
private boolean vip;
// business customer
private String companyName;
public boolean isBusinessCustomer() {
return businessCustomer;
}
public void setBusinessCustomer(boolean bussinessCustomer) {
this.businessCustomer = bussinessCustomer;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public boolean isRegistered() {
return registered;
}
public void setRegistered(boolean registered) {
this.registered = registered;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public long getRegistrationId() {
return registrationId;
}
public void setRegistrationId(long registrationId) {
this.registrationId = registrationId;
}
public boolean isVip() {
return vip;
}
public void setVip(boolean vip) {
this.vip = vip;
}
@Override
public String toString() {
return "Customer [companyName=" + companyName + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (businessCustomer ? 1231 : 1237);
result = prime * result + ((companyName == null) ? 0 : companyName.hashCode());
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result + ((middleName == null) ? 0 : middleName.hashCode());
result = prime * result + (registered ? 1231 : 1237);
result = prime * result + (int) (registrationId ^ (registrationId >>> 32));
result = prime * result + (vip ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Customer other = (Customer) obj;
if (businessCustomer != other.businessCustomer) {
return false;
}
if (companyName == null) {
if (other.companyName != null) {
return false;
}
}
else if (!companyName.equals(other.companyName)) {
return false;
}
if (firstName == null) {
if (other.firstName != null) {
return false;
}
}
else if (!firstName.equals(other.firstName)) {
return false;
}
if (lastName == null) {
if (other.lastName != null) {
return false;
}
}
else if (!lastName.equals(other.lastName)) {
return false;
}
if (middleName == null) {
if (other.middleName != null) {
return false;
}
}
else if (!middleName.equals(other.middleName)) {
return false;
}
if (registered != other.registered) {
return false;
}
if (registrationId != other.registrationId) {
return false;
}
if (vip != other.vip) {
return false;
}
return true;
| 771
| 398
| 1,169
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/LineItem.java
|
LineItem
|
toString
|
class LineItem {
public static final String LINE_ID_ITEM = "LIT";
private long itemId;
private BigDecimal price;
private BigDecimal discountPerc;
private BigDecimal discountAmount;
private BigDecimal shippingPrice;
private BigDecimal handlingPrice;
private int quantity;
private BigDecimal totalPrice;
public BigDecimal getDiscountAmount() {
return discountAmount;
}
public void setDiscountAmount(BigDecimal discountAmount) {
this.discountAmount = discountAmount;
}
public BigDecimal getDiscountPerc() {
return discountPerc;
}
public void setDiscountPerc(BigDecimal discountPerc) {
this.discountPerc = discountPerc;
}
public BigDecimal getHandlingPrice() {
return handlingPrice;
}
public void setHandlingPrice(BigDecimal handlingPrice) {
this.handlingPrice = handlingPrice;
}
public long getItemId() {
return itemId;
}
public void setItemId(long itemId) {
this.itemId = itemId;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public BigDecimal getShippingPrice() {
return shippingPrice;
}
public void setShippingPrice(BigDecimal shippingPrice) {
this.shippingPrice = shippingPrice;
}
public BigDecimal getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(BigDecimal totalPrice) {
this.totalPrice = totalPrice;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (itemId ^ (itemId >>> 32));
result = prime * result + quantity;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
LineItem other = (LineItem) obj;
if (itemId != other.itemId) {
return false;
}
if (quantity != other.quantity) {
return false;
}
return true;
}
}
|
return "LineItem [price=" + price + ", quantity=" + quantity + ", totalPrice=" + totalPrice + "]";
| 697
| 35
| 732
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/Order.java
|
Order
|
hashCode
|
class Order {
public static final String LINE_ID_HEADER = "HEA";
public static final String LINE_ID_FOOTER = "FOT";
// header
private long orderId;
private Date orderDate;
// footer
private int totalLines;
private int totalItems;
private BigDecimal totalPrice;
private Customer customer;
private Address billingAddress;
private Address shippingAddress;
private BillingInfo billing;
private ShippingInfo shipping;
// order items
private List<LineItem> lineItems;
public BillingInfo getBilling() {
return billing;
}
public void setBilling(BillingInfo billing) {
this.billing = billing;
}
public Address getBillingAddress() {
return billingAddress;
}
public void setBillingAddress(Address billingAddress) {
this.billingAddress = billingAddress;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<LineItem> getLineItems() {
return lineItems;
}
public void setLineItems(List<LineItem> lineItems) {
this.lineItems = lineItems;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public ShippingInfo getShipping() {
return shipping;
}
public void setShipping(ShippingInfo shipping) {
this.shipping = shipping;
}
public Address getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(Address shippingAddress) {
this.shippingAddress = shippingAddress;
}
public BigDecimal getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(BigDecimal totalPrice) {
this.totalPrice = totalPrice;
}
public int getTotalItems() {
return totalItems;
}
public void setTotalItems(int totalItems) {
this.totalItems = totalItems;
}
public int getTotalLines() {
return totalLines;
}
public void setTotalLines(int totalLines) {
this.totalLines = totalLines;
}
@Override
public String toString() {
return "Order [customer=" + customer + ", orderId=" + orderId + ", totalItems=" + totalItems + ", totalPrice="
+ totalPrice + "]";
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Order other = (Order) obj;
if (billing == null) {
if (other.billing != null) {
return false;
}
}
else if (!billing.equals(other.billing)) {
return false;
}
if (billingAddress == null) {
if (other.billingAddress != null) {
return false;
}
}
else if (!billingAddress.equals(other.billingAddress)) {
return false;
}
if (customer == null) {
if (other.customer != null) {
return false;
}
}
else if (!customer.equals(other.customer)) {
return false;
}
if (lineItems == null) {
if (other.lineItems != null) {
return false;
}
}
else if (!lineItems.equals(other.lineItems)) {
return false;
}
if (orderDate == null) {
if (other.orderDate != null) {
return false;
}
}
else if (!orderDate.equals(other.orderDate)) {
return false;
}
if (orderId != other.orderId) {
return false;
}
if (shipping == null) {
if (other.shipping != null) {
return false;
}
}
else if (!shipping.equals(other.shipping)) {
return false;
}
if (shippingAddress == null) {
if (other.shippingAddress != null) {
return false;
}
}
else if (!shippingAddress.equals(other.shippingAddress)) {
return false;
}
if (totalItems != other.totalItems) {
return false;
}
if (totalLines != other.totalLines) {
return false;
}
if (totalPrice == null) {
if (other.totalPrice != null) {
return false;
}
}
else if (!totalPrice.equals(other.totalPrice)) {
return false;
}
return true;
}
}
|
final int prime = 31;
int result = 1;
result = prime * result + ((billing == null) ? 0 : billing.hashCode());
result = prime * result + ((billingAddress == null) ? 0 : billingAddress.hashCode());
result = prime * result + ((customer == null) ? 0 : customer.hashCode());
result = prime * result + ((lineItems == null) ? 0 : lineItems.hashCode());
result = prime * result + ((orderDate == null) ? 0 : orderDate.hashCode());
result = prime * result + (int) (orderId ^ (orderId >>> 32));
result = prime * result + ((shipping == null) ? 0 : shipping.hashCode());
result = prime * result + ((shippingAddress == null) ? 0 : shippingAddress.hashCode());
result = prime * result + totalItems;
result = prime * result + totalLines;
result = prime * result + ((totalPrice == null) ? 0 : totalPrice.hashCode());
return result;
| 1,336
| 275
| 1,611
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/ShippingInfo.java
|
ShippingInfo
|
equals
|
class ShippingInfo {
public static final String LINE_ID_SHIPPING_INFO = "SIN";
private String shipperId;
private String shippingTypeId;
private String shippingInfo;
public String getShipperId() {
return shipperId;
}
public void setShipperId(String shipperId) {
this.shipperId = shipperId;
}
public String getShippingInfo() {
return shippingInfo;
}
public void setShippingInfo(String shippingInfo) {
this.shippingInfo = shippingInfo;
}
public String getShippingTypeId() {
return shippingTypeId;
}
public void setShippingTypeId(String shippingTypeId) {
this.shippingTypeId = shippingTypeId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((shipperId == null) ? 0 : shipperId.hashCode());
result = prime * result + ((shippingInfo == null) ? 0 : shippingInfo.hashCode());
result = prime * result + ((shippingTypeId == null) ? 0 : shippingTypeId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ShippingInfo other = (ShippingInfo) obj;
if (shipperId == null) {
if (other.shipperId != null) {
return false;
}
}
else if (!shipperId.equals(other.shipperId)) {
return false;
}
if (shippingInfo == null) {
if (other.shippingInfo != null) {
return false;
}
}
else if (!shippingInfo.equals(other.shippingInfo)) {
return false;
}
if (shippingTypeId == null) {
if (other.shippingTypeId != null) {
return false;
}
}
else if (!shippingTypeId.equals(other.shippingTypeId)) {
return false;
}
return true;
| 343
| 273
| 616
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/OrderItemReader.java
|
OrderItemReader
|
process
|
class OrderItemReader implements ItemReader<Order> {
private static final Log log = LogFactory.getLog(OrderItemReader.class);
private Order order;
private boolean recordFinished;
private FieldSetMapper<Order> headerMapper;
private FieldSetMapper<Customer> customerMapper;
private FieldSetMapper<Address> addressMapper;
private FieldSetMapper<BillingInfo> billingMapper;
private FieldSetMapper<LineItem> itemMapper;
private FieldSetMapper<ShippingInfo> shippingMapper;
private ItemReader<FieldSet> fieldSetReader;
/**
* @see org.springframework.batch.item.ItemReader#read()
*/
@Nullable
@Override
public Order read() throws Exception {
recordFinished = false;
while (!recordFinished) {
process(fieldSetReader.read());
}
if (log.isInfoEnabled()) {
log.info("Mapped: " + order);
}
Order result = order;
order = null;
return result;
}
private void process(FieldSet fieldSet) throws Exception {<FILL_FUNCTION_BODY>}
/**
* @param fieldSetReader reads lines from the file converting them to
* {@link FieldSet}.
*/
public void setFieldSetReader(ItemReader<FieldSet> fieldSetReader) {
this.fieldSetReader = fieldSetReader;
}
public void setAddressMapper(FieldSetMapper<Address> addressMapper) {
this.addressMapper = addressMapper;
}
public void setBillingMapper(FieldSetMapper<BillingInfo> billingMapper) {
this.billingMapper = billingMapper;
}
public void setCustomerMapper(FieldSetMapper<Customer> customerMapper) {
this.customerMapper = customerMapper;
}
public void setHeaderMapper(FieldSetMapper<Order> headerMapper) {
this.headerMapper = headerMapper;
}
public void setItemMapper(FieldSetMapper<LineItem> itemMapper) {
this.itemMapper = itemMapper;
}
public void setShippingMapper(FieldSetMapper<ShippingInfo> shippingMapper) {
this.shippingMapper = shippingMapper;
}
}
|
// finish processing if we hit the end of file
if (fieldSet == null) {
log.debug("FINISHED");
recordFinished = true;
order = null;
return;
}
String lineId = fieldSet.readString(0);
switch (lineId) {
case Order.LINE_ID_HEADER -> {
log.debug("STARTING NEW RECORD");
order = headerMapper.mapFieldSet(fieldSet);
}
case Order.LINE_ID_FOOTER -> {
log.debug("END OF RECORD");
// Do mapping for footer here, because mapper does not allow to pass
// an Order object as input.
// Mapper always creates new object
order.setTotalPrice(fieldSet.readBigDecimal("TOTAL_PRICE"));
order.setTotalLines(fieldSet.readInt("TOTAL_LINE_ITEMS"));
order.setTotalItems(fieldSet.readInt("TOTAL_ITEMS"));
// mark we are finished with current Order
recordFinished = true;
}
case Customer.LINE_ID_BUSINESS_CUST -> {
log.debug("MAPPING CUSTOMER");
if (order.getCustomer() == null) {
Customer customer = customerMapper.mapFieldSet(fieldSet);
customer.setBusinessCustomer(true);
order.setCustomer(customer);
}
}
case Customer.LINE_ID_NON_BUSINESS_CUST -> {
log.debug("MAPPING CUSTOMER");
if (order.getCustomer() == null) {
Customer customer = customerMapper.mapFieldSet(fieldSet);
customer.setBusinessCustomer(false);
order.setCustomer(customer);
}
}
case Address.LINE_ID_BILLING_ADDR -> {
log.debug("MAPPING BILLING ADDRESS");
order.setBillingAddress(addressMapper.mapFieldSet(fieldSet));
}
case Address.LINE_ID_SHIPPING_ADDR -> {
log.debug("MAPPING SHIPPING ADDRESS");
order.setShippingAddress(addressMapper.mapFieldSet(fieldSet));
}
case BillingInfo.LINE_ID_BILLING_INFO -> {
log.debug("MAPPING BILLING INFO");
order.setBilling(billingMapper.mapFieldSet(fieldSet));
}
case ShippingInfo.LINE_ID_SHIPPING_INFO -> {
log.debug("MAPPING SHIPPING INFO");
order.setShipping(shippingMapper.mapFieldSet(fieldSet));
}
case LineItem.LINE_ID_ITEM -> {
log.debug("MAPPING LINE ITEM");
if (order.getLineItems() == null) {
order.setLineItems(new ArrayList<>());
}
order.getLineItems().add(itemMapper.mapFieldSet(fieldSet));
}
default -> {
if (log.isDebugEnabled()) {
log.debug("Could not map LINE_ID=" + lineId);
}
}
}
| 547
| 838
| 1,385
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/OrderLineAggregator.java
|
OrderLineAggregator
|
aggregate
|
class OrderLineAggregator implements LineAggregator<Order> {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
private Map<String, LineAggregator<Object>> aggregators;
@Override
public String aggregate(Order order) {<FILL_FUNCTION_BODY>}
/**
* Set aggregators for all types of lines in the output file
* @param aggregators Map of LineAggregators used to map the various record types for
* each order
*/
public void setAggregators(Map<String, LineAggregator<Object>> aggregators) {
this.aggregators = aggregators;
}
}
|
StringBuilder result = new StringBuilder();
result.append(aggregators.get("header").aggregate(order)).append(LINE_SEPARATOR);
result.append(aggregators.get("customer").aggregate(order)).append(LINE_SEPARATOR);
result.append(aggregators.get("address").aggregate(order)).append(LINE_SEPARATOR);
result.append(aggregators.get("billing").aggregate(order)).append(LINE_SEPARATOR);
for (LineItem lineItem : order.getLineItems()) {
result.append(aggregators.get("item").aggregate(lineItem)).append(LINE_SEPARATOR);
}
result.append(aggregators.get("footer").aggregate(order));
return result.toString();
| 160
| 211
| 371
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/extractor/AddressFieldExtractor.java
|
AddressFieldExtractor
|
extract
|
class AddressFieldExtractor implements FieldExtractor<Order> {
@Override
public Object[] extract(Order order) {<FILL_FUNCTION_BODY>}
}
|
Address address = order.getBillingAddress();
return new Object[] { "ADDRESS:", address.getAddrLine1(), address.getCity(), address.getZipCode() };
| 43
| 48
| 91
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/extractor/BillingInfoFieldExtractor.java
|
BillingInfoFieldExtractor
|
extract
|
class BillingInfoFieldExtractor implements FieldExtractor<Order> {
@Override
public Object[] extract(Order order) {<FILL_FUNCTION_BODY>}
}
|
BillingInfo billingInfo = order.getBilling();
return new Object[] { "BILLING:", billingInfo.getPaymentId(), billingInfo.getPaymentDesc() };
| 45
| 51
| 96
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/extractor/CustomerFieldExtractor.java
|
CustomerFieldExtractor
|
extract
|
class CustomerFieldExtractor implements FieldExtractor<Order> {
@Override
public Object[] extract(Order order) {<FILL_FUNCTION_BODY>}
private String emptyIfNull(String s) {
return s != null ? s : "";
}
}
|
Customer customer = order.getCustomer();
return new Object[] { "CUSTOMER:", customer.getRegistrationId(), emptyIfNull(customer.getFirstName()),
emptyIfNull(customer.getMiddleName()), emptyIfNull(customer.getLastName()) };
| 68
| 70
| 138
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/mapper/AddressFieldSetMapper.java
|
AddressFieldSetMapper
|
mapFieldSet
|
class AddressFieldSetMapper implements FieldSetMapper<Address> {
public static final String ADDRESSEE_COLUMN = "ADDRESSEE";
public static final String ADDRESS_LINE1_COLUMN = "ADDR_LINE1";
public static final String ADDRESS_LINE2_COLUMN = "ADDR_LINE2";
public static final String CITY_COLUMN = "CITY";
public static final String ZIP_CODE_COLUMN = "ZIP_CODE";
public static final String STATE_COLUMN = "STATE";
public static final String COUNTRY_COLUMN = "COUNTRY";
@Override
public Address mapFieldSet(FieldSet fieldSet) {<FILL_FUNCTION_BODY>}
}
|
Address address = new Address();
address.setAddressee(fieldSet.readString(ADDRESSEE_COLUMN));
address.setAddrLine1(fieldSet.readString(ADDRESS_LINE1_COLUMN));
address.setAddrLine2(fieldSet.readString(ADDRESS_LINE2_COLUMN));
address.setCity(fieldSet.readString(CITY_COLUMN));
address.setZipCode(fieldSet.readString(ZIP_CODE_COLUMN));
address.setState(fieldSet.readString(STATE_COLUMN));
address.setCountry(fieldSet.readString(COUNTRY_COLUMN));
return address;
| 184
| 183
| 367
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/mapper/BillingFieldSetMapper.java
|
BillingFieldSetMapper
|
mapFieldSet
|
class BillingFieldSetMapper implements FieldSetMapper<BillingInfo> {
public static final String PAYMENT_TYPE_ID_COLUMN = "PAYMENT_TYPE_ID";
public static final String PAYMENT_DESC_COLUMN = "PAYMENT_DESC";
@Override
public BillingInfo mapFieldSet(FieldSet fieldSet) {<FILL_FUNCTION_BODY>}
}
|
BillingInfo info = new BillingInfo();
info.setPaymentId(fieldSet.readString(PAYMENT_TYPE_ID_COLUMN));
info.setPaymentDesc(fieldSet.readString(PAYMENT_DESC_COLUMN));
return info;
| 103
| 78
| 181
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/mapper/CustomerFieldSetMapper.java
|
CustomerFieldSetMapper
|
mapFieldSet
|
class CustomerFieldSetMapper implements FieldSetMapper<Customer> {
public static final String LINE_ID_COLUMN = "LINE_ID";
public static final String COMPANY_NAME_COLUMN = "COMPANY_NAME";
public static final String LAST_NAME_COLUMN = "LAST_NAME";
public static final String FIRST_NAME_COLUMN = "FIRST_NAME";
public static final String MIDDLE_NAME_COLUMN = "MIDDLE_NAME";
public static final String TRUE_SYMBOL = "T";
public static final String REGISTERED_COLUMN = "REGISTERED";
public static final String REG_ID_COLUMN = "REG_ID";
public static final String VIP_COLUMN = "VIP";
@Override
public Customer mapFieldSet(FieldSet fieldSet) {<FILL_FUNCTION_BODY>}
}
|
Customer customer = new Customer();
if (Customer.LINE_ID_BUSINESS_CUST.equals(fieldSet.readString(LINE_ID_COLUMN))) {
customer.setCompanyName(fieldSet.readString(COMPANY_NAME_COLUMN));
// business customer must be always registered
customer.setRegistered(true);
}
if (Customer.LINE_ID_NON_BUSINESS_CUST.equals(fieldSet.readString(LINE_ID_COLUMN))) {
customer.setLastName(fieldSet.readString(LAST_NAME_COLUMN));
customer.setFirstName(fieldSet.readString(FIRST_NAME_COLUMN));
customer.setMiddleName(fieldSet.readString(MIDDLE_NAME_COLUMN));
customer.setRegistered(TRUE_SYMBOL.equals(fieldSet.readString(REGISTERED_COLUMN)));
}
customer.setRegistrationId(fieldSet.readLong(REG_ID_COLUMN));
customer.setVip(TRUE_SYMBOL.equals(fieldSet.readString(VIP_COLUMN)));
return customer;
| 230
| 306
| 536
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/mapper/HeaderFieldSetMapper.java
|
HeaderFieldSetMapper
|
mapFieldSet
|
class HeaderFieldSetMapper implements FieldSetMapper<Order> {
public static final String ORDER_ID_COLUMN = "ORDER_ID";
public static final String ORDER_DATE_COLUMN = "ORDER_DATE";
@Override
public Order mapFieldSet(FieldSet fieldSet) {<FILL_FUNCTION_BODY>}
}
|
Order order = new Order();
order.setOrderId(fieldSet.readLong(ORDER_ID_COLUMN));
order.setOrderDate(fieldSet.readDate(ORDER_DATE_COLUMN));
return order;
| 85
| 64
| 149
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/mapper/OrderItemFieldSetMapper.java
|
OrderItemFieldSetMapper
|
mapFieldSet
|
class OrderItemFieldSetMapper implements FieldSetMapper<LineItem> {
public static final String TOTAL_PRICE_COLUMN = "TOTAL_PRICE";
public static final String QUANTITY_COLUMN = "QUANTITY";
public static final String HANDLING_PRICE_COLUMN = "HANDLING_PRICE";
public static final String SHIPPING_PRICE_COLUMN = "SHIPPING_PRICE";
public static final String DISCOUNT_AMOUNT_COLUMN = "DISCOUNT_AMOUNT";
public static final String DISCOUNT_PERC_COLUMN = "DISCOUNT_PERC";
public static final String PRICE_COLUMN = "PRICE";
public static final String ITEM_ID_COLUMN = "ITEM_ID";
@Override
public LineItem mapFieldSet(FieldSet fieldSet) {<FILL_FUNCTION_BODY>}
}
|
LineItem item = new LineItem();
item.setItemId(fieldSet.readLong(ITEM_ID_COLUMN));
item.setPrice(fieldSet.readBigDecimal(PRICE_COLUMN));
item.setDiscountPerc(fieldSet.readBigDecimal(DISCOUNT_PERC_COLUMN));
item.setDiscountAmount(fieldSet.readBigDecimal(DISCOUNT_AMOUNT_COLUMN));
item.setShippingPrice(fieldSet.readBigDecimal(SHIPPING_PRICE_COLUMN));
item.setHandlingPrice(fieldSet.readBigDecimal(HANDLING_PRICE_COLUMN));
item.setQuantity(fieldSet.readInt(QUANTITY_COLUMN));
item.setTotalPrice(fieldSet.readBigDecimal(TOTAL_PRICE_COLUMN));
return item;
| 234
| 238
| 472
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/mapper/ShippingFieldSetMapper.java
|
ShippingFieldSetMapper
|
mapFieldSet
|
class ShippingFieldSetMapper implements FieldSetMapper<ShippingInfo> {
public static final String ADDITIONAL_SHIPPING_INFO_COLUMN = "ADDITIONAL_SHIPPING_INFO";
public static final String SHIPPING_TYPE_ID_COLUMN = "SHIPPING_TYPE_ID";
public static final String SHIPPER_ID_COLUMN = "SHIPPER_ID";
@Override
public ShippingInfo mapFieldSet(FieldSet fieldSet) {<FILL_FUNCTION_BODY>}
}
|
ShippingInfo info = new ShippingInfo();
info.setShipperId(fieldSet.readString(SHIPPER_ID_COLUMN));
info.setShippingTypeId(fieldSet.readString(SHIPPING_TYPE_ID_COLUMN));
info.setShippingInfo(fieldSet.readString(ADDITIONAL_SHIPPING_INFO_COLUMN));
return info;
| 135
| 113
| 248
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/xml/Customer.java
|
Customer
|
toString
|
class Customer {
private String name;
private String address;
private int age;
private int moo;
private int poo;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMoo() {
return moo;
}
public void setMoo(int moo) {
this.moo = moo;
}
public int getPoo() {
return poo;
}
public void setPoo(int poo) {
this.poo = poo;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "Customer [address=" + address + ", age=" + age + ", name=" + name + "]";
| 256
| 32
| 288
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/xml/XmlJobConfiguration.java
|
XmlJobConfiguration
|
customerCreditMarshaller
|
class XmlJobConfiguration {
@Bean
public XStreamMarshaller customerCreditMarshaller() {<FILL_FUNCTION_BODY>}
@Bean
@StepScope
public StaxEventItemReader<CustomerCredit> itemReader(@Value("#{jobParameters[inputFile]}") Resource resource) {
return new StaxEventItemReaderBuilder<CustomerCredit>().name("itemReader")
.resource(resource)
.addFragmentRootElements("customer")
.unmarshaller(customerCreditMarshaller())
.build();
}
@Bean
@StepScope
public StaxEventItemWriter<CustomerCredit> itemWriter(
@Value("#{jobParameters[outputFile]}") WritableResource resource) {
return new StaxEventItemWriterBuilder<CustomerCredit>().name("itemWriter")
.resource(resource)
.marshaller(customerCreditMarshaller())
.rootTagName("customers")
.overwriteOutput(true)
.build();
}
@Bean
public Job job(JobRepository jobRepository, JdbcTransactionManager transactionManager,
ItemReader<CustomerCredit> itemReader, ItemWriter<CustomerCredit> itemWriter) {
return new JobBuilder("ioSampleJob", jobRepository)
.start(new StepBuilder("step1", jobRepository).<CustomerCredit, CustomerCredit>chunk(2, transactionManager)
.reader(itemReader)
.processor(new CustomerCreditIncreaseProcessor())
.writer(itemWriter)
.build())
.build();
}
}
|
XStreamMarshaller marshaller = new XStreamMarshaller();
marshaller
.setAliases(Map.of("customer", CustomerCredit.class, "credit", BigDecimal.class, "name", String.class));
marshaller.setTypePermissions(new ExplicitTypePermission(new Class[] { CustomerCredit.class }));
return marshaller;
| 382
| 100
| 482
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/FootballJobConfiguration.java
|
FootballJobConfiguration
|
playerFileItemReader
|
class FootballJobConfiguration {
// step 1 configuration
@Bean
public FlatFileItemReader<Player> playerFileItemReader() {<FILL_FUNCTION_BODY>}
@Bean
public PlayerItemWriter playerWriter(DataSource dataSource) {
PlayerItemWriter playerItemWriter = new PlayerItemWriter();
JdbcPlayerDao playerDao = new JdbcPlayerDao();
playerDao.setDataSource(dataSource);
playerItemWriter.setPlayerDao(playerDao);
return playerItemWriter;
}
@Bean
public Step playerLoad(JobRepository jobRepository, JdbcTransactionManager transactionManager,
FlatFileItemReader<Player> playerFileItemReader, PlayerItemWriter playerWriter) {
return new StepBuilder("playerLoad", jobRepository).<Player, Player>chunk(2, transactionManager)
.reader(playerFileItemReader)
.writer(playerWriter)
.build();
}
// step 2 configuration
@Bean
public FlatFileItemReader<Game> gameFileItemReader() {
return new FlatFileItemReaderBuilder<Game>().name("gameFileItemReader")
.resource(new ClassPathResource("org/springframework/batch/samples/football/data/games-small.csv"))
.delimited()
.names("id", "year", "team", "week", "opponent", "completes", "attempts", "passingYards", "passingTd",
"interceptions", "rushes", "rushYards", "receptions", "receptionYards", "totalTd")
.fieldSetMapper(new GameFieldSetMapper())
.build();
}
@Bean
public JdbcGameDao gameWriter(DataSource dataSource) {
JdbcGameDao jdbcGameDao = new JdbcGameDao();
jdbcGameDao.setDataSource(dataSource);
return jdbcGameDao;
}
@Bean
public Step gameLoad(JobRepository jobRepository, JdbcTransactionManager transactionManager,
FlatFileItemReader<Game> gameFileItemReader, JdbcGameDao gameWriter) {
return new StepBuilder("gameLoad", jobRepository).<Game, Game>chunk(2, transactionManager)
.reader(gameFileItemReader)
.writer(gameWriter)
.build();
}
// step 3 configuration
@Bean
public JdbcCursorItemReader<PlayerSummary> playerSummarizationSource(DataSource dataSource) {
String sql = """
SELECT GAMES.player_id, GAMES.year_no, SUM(COMPLETES),
SUM(ATTEMPTS), SUM(PASSING_YARDS), SUM(PASSING_TD),
SUM(INTERCEPTIONS), SUM(RUSHES), SUM(RUSH_YARDS),
SUM(RECEPTIONS), SUM(RECEPTIONS_YARDS), SUM(TOTAL_TD)
from GAMES, PLAYERS where PLAYERS.player_id =
GAMES.player_id group by GAMES.player_id, GAMES.year_no
""";
return new JdbcCursorItemReaderBuilder<PlayerSummary>().name("playerSummarizationSource")
.ignoreWarnings(true)
.sql(sql)
.dataSource(dataSource)
.rowMapper(new PlayerSummaryMapper())
.build();
}
@Bean
public JdbcPlayerSummaryDao summaryWriter(DataSource dataSource) {
JdbcPlayerSummaryDao jdbcPlayerSummaryDao = new JdbcPlayerSummaryDao();
jdbcPlayerSummaryDao.setDataSource(dataSource);
return jdbcPlayerSummaryDao;
}
@Bean
public Step summarizationStep(JobRepository jobRepository, JdbcTransactionManager transactionManager,
JdbcCursorItemReader<PlayerSummary> playerSummarizationSource, JdbcPlayerSummaryDao summaryWriter) {
return new StepBuilder("summarizationStep", jobRepository)
.<PlayerSummary, PlayerSummary>chunk(2, transactionManager)
.reader(playerSummarizationSource)
.writer(summaryWriter)
.build();
}
// job configuration
@Bean
public Job job(JobRepository jobRepository, Step playerLoad, Step gameLoad, Step summarizationStep) {
return new JobBuilder("footballJob", jobRepository).start(playerLoad)
.next(gameLoad)
.next(summarizationStep)
.build();
}
}
|
return new FlatFileItemReaderBuilder<Player>().name("playerFileItemReader")
.resource(new ClassPathResource("org/springframework/batch/samples/football/data/player-small1.csv"))
.delimited()
.names("ID", "lastName", "firstName", "position", "birthYear", "debutYear")
.fieldSetMapper(new PlayerFieldSetMapper())
.build();
| 1,098
| 107
| 1,205
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/Game.java
|
Game
|
equals
|
class Game implements Serializable {
private String id;
private int year;
private String team;
private int week;
private String opponent;
private int completes;
private int attempts;
private int passingYards;
private int passingTd;
private int interceptions;
private int rushes;
private int rushYards;
private int receptions;
private int receptionYards;
private int totalTd;
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @return the year
*/
public int getYear() {
return year;
}
/**
* @return the team
*/
public String getTeam() {
return team;
}
/**
* @return the week
*/
public int getWeek() {
return week;
}
/**
* @return the opponent
*/
public String getOpponent() {
return opponent;
}
/**
* @return the completes
*/
public int getCompletes() {
return completes;
}
/**
* @return the attempts
*/
public int getAttempts() {
return attempts;
}
/**
* @return the passingYards
*/
public int getPassingYards() {
return passingYards;
}
/**
* @return the passingTd
*/
public int getPassingTd() {
return passingTd;
}
/**
* @return the interceptions
*/
public int getInterceptions() {
return interceptions;
}
/**
* @return the rushes
*/
public int getRushes() {
return rushes;
}
/**
* @return the rushYards
*/
public int getRushYards() {
return rushYards;
}
/**
* @return the receptions
*/
public int getReceptions() {
return receptions;
}
/**
* @return the receptionYards
*/
public int getReceptionYards() {
return receptionYards;
}
/**
* @return the totalTd
*/
public int getTotalTd() {
return totalTd;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @param year the year to set
*/
public void setYear(int year) {
this.year = year;
}
/**
* @param team the team to set
*/
public void setTeam(String team) {
this.team = team;
}
/**
* @param week the week to set
*/
public void setWeek(int week) {
this.week = week;
}
/**
* @param opponent the opponent to set
*/
public void setOpponent(String opponent) {
this.opponent = opponent;
}
/**
* @param completes the completes to set
*/
public void setCompletes(int completes) {
this.completes = completes;
}
/**
* @param attempts the attempts to set
*/
public void setAttempts(int attempts) {
this.attempts = attempts;
}
/**
* @param passingYards the passingYards to set
*/
public void setPassingYards(int passingYards) {
this.passingYards = passingYards;
}
/**
* @param passingTd the passingTd to set
*/
public void setPassingTd(int passingTd) {
this.passingTd = passingTd;
}
/**
* @param interceptions the interceptions to set
*/
public void setInterceptions(int interceptions) {
this.interceptions = interceptions;
}
/**
* @param rushes the rushes to set
*/
public void setRushes(int rushes) {
this.rushes = rushes;
}
/**
* @param rushYards the rushYards to set
*/
public void setRushYards(int rushYards) {
this.rushYards = rushYards;
}
/**
* @param receptions the receptions to set
*/
public void setReceptions(int receptions) {
this.receptions = receptions;
}
/**
* @param receptionYards the receptionYards to set
*/
public void setReceptionYards(int receptionYards) {
this.receptionYards = receptionYards;
}
/**
* @param totalTd the totalTd to set
*/
public void setTotalTd(int totalTd) {
this.totalTd = totalTd;
}
@Override
public String toString() {
return "Game: ID=" + id + " " + team + " vs. " + opponent + " - " + year;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Game other = (Game) obj;
if (id == null) {
if (other.id != null) {
return false;
}
}
else if (!id.equals(other.id)) {
return false;
}
return true;
| 1,326
| 131
| 1,457
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/Player.java
|
Player
|
toString
|
class Player implements Serializable {
private String id;
private String lastName;
private String firstName;
private String position;
private int birthYear;
private int debutYear;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public String getId() {
return id;
}
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
public String getPosition() {
return position;
}
public int getBirthYear() {
return birthYear;
}
public int getDebutYear() {
return debutYear;
}
public void setId(String id) {
this.id = id;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setPosition(String position) {
this.position = position;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
public void setDebutYear(int debutYear) {
this.debutYear = debutYear;
}
}
|
return "PLAYER:id=" + id + ",Last Name=" + lastName + ",First Name=" + firstName + ",Position=" + position
+ ",Birth Year=" + birthYear + ",DebutYear=" + debutYear;
| 319
| 65
| 384
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/PlayerSummary.java
|
PlayerSummary
|
toString
|
class PlayerSummary {
private String id;
private int year;
private int completes;
private int attempts;
private int passingYards;
private int passingTd;
private int interceptions;
private int rushes;
private int rushYards;
private int receptions;
private int receptionYards;
private int totalTd;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getCompletes() {
return completes;
}
public void setCompletes(int completes) {
this.completes = completes;
}
public int getAttempts() {
return attempts;
}
public void setAttempts(int attempts) {
this.attempts = attempts;
}
public int getPassingYards() {
return passingYards;
}
public void setPassingYards(int passingYards) {
this.passingYards = passingYards;
}
public int getPassingTd() {
return passingTd;
}
public void setPassingTd(int passingTd) {
this.passingTd = passingTd;
}
public int getInterceptions() {
return interceptions;
}
public void setInterceptions(int interceptions) {
this.interceptions = interceptions;
}
public int getRushes() {
return rushes;
}
public void setRushes(int rushes) {
this.rushes = rushes;
}
public int getRushYards() {
return rushYards;
}
public void setRushYards(int rushYards) {
this.rushYards = rushYards;
}
public int getReceptions() {
return receptions;
}
public void setReceptions(int receptions) {
this.receptions = receptions;
}
public int getReceptionYards() {
return receptionYards;
}
public void setReceptionYards(int receptionYards) {
this.receptionYards = receptionYards;
}
public int getTotalTd() {
return totalTd;
}
public void setTotalTd(int totalTd) {
this.totalTd = totalTd;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PlayerSummary other = (PlayerSummary) obj;
if (id == null) {
if (other.id != null) {
return false;
}
}
else if (!id.equals(other.id)) {
return false;
}
return true;
}
}
|
return "Player Summary: ID=" + id + " Year=" + year + "[" + completes + ";" + attempts + ";" + passingYards
+ ";" + passingTd + ";" + interceptions + ";" + rushes + ";" + rushYards + ";" + receptions + ";"
+ receptionYards + ";" + totalTd;
| 850
| 90
| 940
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/internal/GameFieldSetMapper.java
|
GameFieldSetMapper
|
mapFieldSet
|
class GameFieldSetMapper implements FieldSetMapper<Game> {
@Override
public Game mapFieldSet(FieldSet fs) {<FILL_FUNCTION_BODY>}
}
|
if (fs == null) {
return null;
}
Game game = new Game();
game.setId(fs.readString("id"));
game.setYear(fs.readInt("year"));
game.setTeam(fs.readString("team"));
game.setWeek(fs.readInt("week"));
game.setOpponent(fs.readString("opponent"));
game.setCompletes(fs.readInt("completes"));
game.setAttempts(fs.readInt("attempts"));
game.setPassingYards(fs.readInt("passingYards"));
game.setPassingTd(fs.readInt("passingTd"));
game.setInterceptions(fs.readInt("interceptions"));
game.setRushes(fs.readInt("rushes"));
game.setRushYards(fs.readInt("rushYards"));
game.setReceptions(fs.readInt("receptions", 0));
game.setReceptionYards(fs.readInt("receptionYards"));
game.setTotalTd(fs.readInt("totalTd"));
return game;
| 45
| 307
| 352
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/internal/JdbcGameDao.java
|
JdbcGameDao
|
write
|
class JdbcGameDao extends JdbcDaoSupport implements ItemWriter<Game> {
private SimpleJdbcInsert insertGame;
@Override
protected void initDao() throws Exception {
super.initDao();
insertGame = new SimpleJdbcInsert(getDataSource()).withTableName("GAMES")
.usingColumns("player_id", "year_no", "team", "week", "opponent", " completes", "attempts", "passing_yards",
"passing_td", "interceptions", "rushes", "rush_yards", "receptions", "receptions_yards",
"total_td");
}
@Override
public void write(Chunk<? extends Game> games) {<FILL_FUNCTION_BODY>}
}
|
for (Game game : games) {
SqlParameterSource values = new MapSqlParameterSource().addValue("player_id", game.getId())
.addValue("year_no", game.getYear())
.addValue("team", game.getTeam())
.addValue("week", game.getWeek())
.addValue("opponent", game.getOpponent())
.addValue("completes", game.getCompletes())
.addValue("attempts", game.getAttempts())
.addValue("passing_yards", game.getPassingYards())
.addValue("passing_td", game.getPassingTd())
.addValue("interceptions", game.getInterceptions())
.addValue("rushes", game.getRushes())
.addValue("rush_yards", game.getRushYards())
.addValue("receptions", game.getReceptions())
.addValue("receptions_yards", game.getReceptionYards())
.addValue("total_td", game.getTotalTd());
this.insertGame.execute(values);
}
| 194
| 285
| 479
|
<methods>public void <init>() ,public final javax.sql.DataSource getDataSource() ,public final org.springframework.jdbc.core.JdbcTemplate getJdbcTemplate() ,public final void setDataSource(javax.sql.DataSource) ,public final void setJdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) <variables>private org.springframework.jdbc.core.JdbcTemplate jdbcTemplate
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/internal/JdbcPlayerSummaryDao.java
|
JdbcPlayerSummaryDao
|
write
|
class JdbcPlayerSummaryDao implements ItemWriter<PlayerSummary> {
private static final String INSERT_SUMMARY = "INSERT into PLAYER_SUMMARY(ID, YEAR_NO, COMPLETES, ATTEMPTS, PASSING_YARDS, PASSING_TD, "
+ "INTERCEPTIONS, RUSHES, RUSH_YARDS, RECEPTIONS, RECEPTIONS_YARDS, TOTAL_TD) "
+ "values(:id, :year, :completes, :attempts, :passingYards, :passingTd, "
+ ":interceptions, :rushes, :rushYards, :receptions, :receptionYards, :totalTd)";
private NamedParameterJdbcOperations namedParameterJdbcTemplate;
@Override
public void write(Chunk<? extends PlayerSummary> summaries) {<FILL_FUNCTION_BODY>}
public void setDataSource(DataSource dataSource) {
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
}
|
for (PlayerSummary summary : summaries) {
MapSqlParameterSource args = new MapSqlParameterSource().addValue("id", summary.getId())
.addValue("year", summary.getYear())
.addValue("completes", summary.getCompletes())
.addValue("attempts", summary.getAttempts())
.addValue("passingYards", summary.getPassingYards())
.addValue("passingTd", summary.getPassingTd())
.addValue("interceptions", summary.getInterceptions())
.addValue("rushes", summary.getRushes())
.addValue("rushYards", summary.getRushYards())
.addValue("receptions", summary.getReceptions())
.addValue("receptionYards", summary.getReceptionYards())
.addValue("totalTd", summary.getTotalTd());
namedParameterJdbcTemplate.update(INSERT_SUMMARY, args);
}
| 268
| 247
| 515
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/internal/PlayerFieldSetMapper.java
|
PlayerFieldSetMapper
|
mapFieldSet
|
class PlayerFieldSetMapper implements FieldSetMapper<Player> {
@Override
public Player mapFieldSet(FieldSet fs) {<FILL_FUNCTION_BODY>}
}
|
if (fs == null) {
return null;
}
Player player = new Player();
player.setId(fs.readString("ID"));
player.setLastName(fs.readString("lastName"));
player.setFirstName(fs.readString("firstName"));
player.setPosition(fs.readString("position"));
player.setDebutYear(fs.readInt("debutYear"));
player.setBirthYear(fs.readInt("birthYear"));
return player;
| 45
| 139
| 184
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/internal/PlayerSummaryMapper.java
|
PlayerSummaryMapper
|
mapRow
|
class PlayerSummaryMapper implements RowMapper<PlayerSummary> {
@Override
public PlayerSummary mapRow(ResultSet rs, int rowNum) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
PlayerSummary summary = new PlayerSummary();
summary.setId(rs.getString(1));
summary.setYear(rs.getInt(2));
summary.setCompletes(rs.getInt(3));
summary.setAttempts(rs.getInt(4));
summary.setPassingYards(rs.getInt(5));
summary.setPassingTd(rs.getInt(6));
summary.setInterceptions(rs.getInt(7));
summary.setRushes(rs.getInt(8));
summary.setRushYards(rs.getInt(9));
summary.setReceptions(rs.getInt(10));
summary.setReceptionYards(rs.getInt(11));
summary.setTotalTd(rs.getInt(12));
return summary;
| 52
| 224
| 276
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/football/internal/PlayerSummaryRowMapper.java
|
PlayerSummaryRowMapper
|
mapRow
|
class PlayerSummaryRowMapper implements RowMapper<PlayerSummary> {
@Override
public PlayerSummary mapRow(ResultSet rs, int rowNum) throws SQLException {<FILL_FUNCTION_BODY>}
}
|
PlayerSummary summary = new PlayerSummary();
summary.setId(rs.getString(1));
summary.setYear(rs.getInt(2));
summary.setCompletes(rs.getInt(3));
summary.setAttempts(rs.getInt(4));
summary.setPassingYards(rs.getInt(5));
summary.setPassingTd(rs.getInt(6));
summary.setInterceptions(rs.getInt(7));
summary.setRushes(rs.getInt(8));
summary.setRushYards(rs.getInt(9));
summary.setReceptions(rs.getInt(10));
summary.setReceptionYards(rs.getInt(11));
summary.setTotalTd(rs.getInt(12));
return summary;
| 53
| 224
| 277
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/helloworld/HelloWorldJobConfiguration.java
|
HelloWorldJobConfiguration
|
step
|
class HelloWorldJobConfiguration {
@Bean
public Step step(JobRepository jobRepository, JdbcTransactionManager transactionManager) {<FILL_FUNCTION_BODY>}
@Bean
public Job job(JobRepository jobRepository, Step step) {
return new JobBuilder("job", jobRepository).start(step).build();
}
}
|
return new StepBuilder("step", jobRepository).tasklet((contribution, chunkContext) -> {
System.out.println("Hello world!");
return RepeatStatus.FINISHED;
}, transactionManager).build();
| 83
| 60
| 143
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/jdbc/JdbcReaderBatchWriterSampleJob.java
|
JdbcReaderBatchWriterSampleJob
|
itemWriter
|
class JdbcReaderBatchWriterSampleJob {
@Bean
public JdbcBatchItemWriter<CustomerCredit> itemWriter(DataSource dataSource) {<FILL_FUNCTION_BODY>}
@Bean
public Job job(JobRepository jobRepository, JdbcTransactionManager transactionManager,
ItemReader<CustomerCredit> itemReader, JdbcBatchItemWriter<CustomerCredit> itemWriter) {
return new JobBuilder("ioSampleJob", jobRepository)
.start(new StepBuilder("step1", jobRepository).<CustomerCredit, CustomerCredit>chunk(2, transactionManager)
.reader(itemReader)
.processor(new CustomerCreditIncreaseProcessor())
.writer(itemWriter)
.build())
.build();
}
}
|
String sql = "UPDATE CUSTOMER set credit = :credit where id = :id";
return new JdbcBatchItemWriterBuilder<CustomerCredit>().dataSource(dataSource)
.sql(sql)
.itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
.assertUpdates(true)
.build();
| 186
| 89
| 275
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/jdbc/cursor/JdbcCursorReaderBatchWriterSampleJob.java
|
JdbcCursorReaderBatchWriterSampleJob
|
itemReader
|
class JdbcCursorReaderBatchWriterSampleJob extends JdbcReaderBatchWriterSampleJob {
@Bean
public JdbcCursorItemReader<CustomerCredit> itemReader(DataSource dataSource) {<FILL_FUNCTION_BODY>}
}
|
String sql = "select ID, NAME, CREDIT from CUSTOMER";
return new JdbcCursorItemReaderBuilder<CustomerCredit>().name("customerReader")
.dataSource(dataSource)
.sql(sql)
.rowMapper(new CustomerCreditRowMapper())
.build();
| 59
| 78
| 137
|
<methods>public non-sealed void <init>() ,public JdbcBatchItemWriter<org.springframework.batch.samples.domain.trade.CustomerCredit> itemWriter(javax.sql.DataSource) ,public org.springframework.batch.core.Job job(org.springframework.batch.core.repository.JobRepository, org.springframework.jdbc.support.JdbcTransactionManager, ItemReader<org.springframework.batch.samples.domain.trade.CustomerCredit>, JdbcBatchItemWriter<org.springframework.batch.samples.domain.trade.CustomerCredit>) <variables>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/jdbc/paging/JdbcPagingReaderBatchWriterSampleJob.java
|
JdbcPagingReaderBatchWriterSampleJob
|
itemReader
|
class JdbcPagingReaderBatchWriterSampleJob extends JdbcReaderBatchWriterSampleJob {
@Bean
@StepScope
public JdbcPagingItemReader<CustomerCredit> itemReader(DataSource dataSource,
@Value("#{jobParameters['credit']}") Double credit) {<FILL_FUNCTION_BODY>}
}
|
Map<String, Object> parameterValues = new HashMap<>();
parameterValues.put("statusCode", "PE");
parameterValues.put("credit", credit);
parameterValues.put("type", "COLLECTION");
return new JdbcPagingItemReaderBuilder<CustomerCredit>().name("customerReader")
.dataSource(dataSource)
.selectClause("select NAME, ID, CREDIT")
.fromClause("FROM CUSTOMER")
.whereClause("WHERE CREDIT > :credit")
.sortKeys(Map.of("ID", Order.ASCENDING))
.rowMapper(new CustomerCreditRowMapper())
.pageSize(2)
.parameterValues(parameterValues)
.build();
| 82
| 193
| 275
|
<methods>public non-sealed void <init>() ,public JdbcBatchItemWriter<org.springframework.batch.samples.domain.trade.CustomerCredit> itemWriter(javax.sql.DataSource) ,public org.springframework.batch.core.Job job(org.springframework.batch.core.repository.JobRepository, org.springframework.jdbc.support.JdbcTransactionManager, ItemReader<org.springframework.batch.samples.domain.trade.CustomerCredit>, JdbcBatchItemWriter<org.springframework.batch.samples.domain.trade.CustomerCredit>) <variables>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.