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-infrastructure/src/main/java/org/springframework/batch/item/file/transform/FormatterLineAggregator.java
|
FormatterLineAggregator
|
doAggregate
|
class FormatterLineAggregator<T> extends ExtractorLineAggregator<T> {
private String format;
private Locale locale = Locale.getDefault();
private int maximumLength = 0;
private int minimumLength = 0;
/**
* Public setter for the minimum length of the formatted string. If this is not set
* the default is to allow any length.
* @param minimumLength the minimum length to set
*/
public void setMinimumLength(int minimumLength) {
this.minimumLength = minimumLength;
}
/**
* Public setter for the maximum length of the formatted string. If this is not set
* the default is to allow any length.
* @param maximumLength the maximum length to set
*/
public void setMaximumLength(int maximumLength) {
this.maximumLength = maximumLength;
}
/**
* Set the format string used to aggregate items.
* @param format {@link String} containing the format to use.
*
* @see Formatter
*/
public void setFormat(String format) {
this.format = format;
}
/**
* Public setter for the locale.
* @param locale the locale to set
*/
public void setLocale(Locale locale) {
this.locale = locale;
}
@Override
protected String doAggregate(Object[] fields) {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(format, "A format is required");
String value = String.format(locale, format, fields);
if (maximumLength > 0) {
Assert.state(value.length() <= maximumLength, String
.format("String overflowed in formatter -" + " longer than %d characters: [%s", maximumLength, value));
}
if (minimumLength > 0) {
Assert.state(value.length() >= minimumLength, String.format(
"String underflowed in formatter -" + " shorter than %d characters: [%s", minimumLength, value));
}
return value;
| 350
| 165
| 515
|
<methods>public non-sealed void <init>() ,public java.lang.String aggregate(T) ,public void setFieldExtractor(FieldExtractor<T>) <variables>private FieldExtractor<T> fieldExtractor
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/PassThroughFieldExtractor.java
|
PassThroughFieldExtractor
|
extract
|
class PassThroughFieldExtractor<T> implements FieldExtractor<T> {
/**
* Get an array of fields as close as possible to the input. The result depends on the
* type of the input:
* <ul>
* <li>A {@link FieldSet} or array will be returned as is</li>
* <li>For a Collection the <code>toArray()</code> method will be used</li>
* <li>For a Map the <code>values()</code> will be returned as an array</li>
* <li>Otherwise it is wrapped in a single element array.</li>
* </ul>
* Note that no attempt is made to sort the values, so passing in an unordered
* collection or map is probably a bad idea. Spring often gives you an ordered Map
* (e.g. if extracting data from a generic query using JDBC), so check the
* documentation for whatever is being used to generate the input.
* @param item the object to convert
* @return an array of objects as close as possible to the original item
*/
@Override
public Object[] extract(T item) {<FILL_FUNCTION_BODY>}
}
|
if (item.getClass().isArray()) {
return (Object[]) item;
}
if (item instanceof Collection<?>) {
return ((Collection<?>) item).toArray();
}
if (item instanceof Map<?, ?>) {
return ((Map<?, ?>) item).values().toArray();
}
if (item instanceof FieldSet) {
return ((FieldSet) item).getValues();
}
return new Object[] { item };
| 299
| 130
| 429
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/Range.java
|
Range
|
checkMinMaxValues
|
class Range {
public final static int UPPER_BORDER_NOT_DEFINED = Integer.MAX_VALUE;
final private int min;
final private int max;
public Range(int min) {
this(min, UPPER_BORDER_NOT_DEFINED);
}
public Range(int min, int max) {
checkMinMaxValues(min, max);
this.min = min;
this.max = max;
}
public int getMax() {
return max;
}
public int getMin() {
return min;
}
public boolean hasMaxValue() {
return max != UPPER_BORDER_NOT_DEFINED;
}
@Override
public String toString() {
return hasMaxValue() ? min + "-" + max : String.valueOf(min);
}
private void checkMinMaxValues(int min, int max) {<FILL_FUNCTION_BODY>}
}
|
Assert.isTrue(min > 0, "Min value must be higher than zero");
Assert.isTrue(min <= max, "Min value should be lower or equal to max value");
| 243
| 48
| 291
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/RangeArrayPropertyEditor.java
|
RangeArrayPropertyEditor
|
getAsText
|
class RangeArrayPropertyEditor extends PropertyEditorSupport {
private boolean forceDisjointRanges = false;
/**
* Set force disjoint ranges. If set to TRUE, ranges are validated to be disjoint. For
* example: defining ranges '1-10, 5-15' will cause IllegalArgumentException in case
* of forceDisjointRanges=TRUE.
* @param forceDisjointRanges true to force disjoint ranges.
*/
public void setForceDisjointRanges(boolean forceDisjointRanges) {
this.forceDisjointRanges = forceDisjointRanges;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
// split text into ranges
String[] strRanges = text.split(",");
Range[] ranges = new Range[strRanges.length];
// parse ranges and create array of Range objects
for (int i = 0; i < strRanges.length; i++) {
String[] range = strRanges[i].split("-");
int min;
int max;
if ((range.length == 1) && (StringUtils.hasText(range[0]))) {
min = Integer.parseInt(range[0].trim());
// correct max value will be assigned later
ranges[i] = new Range(min);
}
else if ((range.length == 2) && (StringUtils.hasText(range[0])) && (StringUtils.hasText(range[1]))) {
min = Integer.parseInt(range[0].trim());
max = Integer.parseInt(range[1].trim());
ranges[i] = new Range(min, max);
}
else {
throw new IllegalArgumentException("Range[" + i + "]: range (" + strRanges[i] + ") is invalid");
}
}
setMaxValues(ranges);
setValue(ranges);
}
@Override
public String getAsText() {<FILL_FUNCTION_BODY>}
private void setMaxValues(final Range[] ranges) {
// Array of integers to track range values by index
Integer[] c = new Integer[ranges.length];
for (int i = 0; i < c.length; i++) {
c[i] = i;
}
// sort array of Ranges
Arrays.sort(c, Comparator.comparingInt(r -> ranges[r].getMin()));
// set max values for all unbound ranges (except last range)
for (int i = 0; i < c.length - 1; i++) {
if (!ranges[c[i]].hasMaxValue()) {
// set max value to (min value - 1) of the next range
ranges[c[i]] = new Range(ranges[c[i]].getMin(), ranges[c[i + 1]].getMin() - 1);
}
}
if (forceDisjointRanges) {
verifyRanges(ranges);
}
}
private void verifyRanges(Range[] ranges) {
// verify that ranges are disjoint
for (int i = 1; i < ranges.length; i++) {
Assert.isTrue(ranges[i - 1].getMax() < ranges[i].getMin(), "Ranges must be disjoint. Range[" + (i - 1)
+ "]: (" + ranges[i - 1] + ") Range[" + i + "]: (" + ranges[i] + ")");
}
}
}
|
Range[] ranges = (Range[]) getValue();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ranges.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(ranges[i]);
}
return sb.toString();
| 880
| 91
| 971
|
<methods>public void <init>() ,public void <init>(java.lang.Object) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public void firePropertyChange() ,public java.lang.String getAsText() ,public java.awt.Component getCustomEditor() ,public java.lang.String getJavaInitializationString() ,public java.lang.Object getSource() ,public java.lang.String[] getTags() ,public java.lang.Object getValue() ,public boolean isPaintable() ,public void paintValue(java.awt.Graphics, java.awt.Rectangle) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setAsText(java.lang.String) throws java.lang.IllegalArgumentException,public void setSource(java.lang.Object) ,public void setValue(java.lang.Object) ,public boolean supportsCustomEditor() <variables>private Vector<java.beans.PropertyChangeListener> listeners,private java.lang.Object source,private java.lang.Object value
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/RecordFieldExtractor.java
|
RecordFieldExtractor
|
extract
|
class RecordFieldExtractor<T> implements FieldExtractor<T> {
private List<String> names;
private final Class<? extends T> targetType;
private final RecordComponent[] recordComponents;
public RecordFieldExtractor(Class<? extends T> targetType) {
Assert.notNull(targetType, "target type must not be null");
Assert.isTrue(targetType.isRecord(), "target type must be a record");
this.targetType = targetType;
this.recordComponents = this.targetType.getRecordComponents();
this.names = getRecordComponentNames();
}
/**
* Set the names of record components to extract.
* @param names of record component to be extracted.
*/
public void setNames(String... names) {
Assert.notNull(names, "Names must not be null");
Assert.notEmpty(names, "Names must not be empty");
validate(names);
this.names = Arrays.stream(names).toList();
}
/**
* @see FieldExtractor#extract(Object)
*/
@Override
public Object[] extract(T item) {<FILL_FUNCTION_BODY>}
private List<String> getRecordComponentNames() {
return Arrays.stream(this.recordComponents).map(RecordComponent::getName).toList();
}
private void validate(String[] names) {
for (String name : names) {
if (getRecordComponentByName(name) == null) {
throw new IllegalArgumentException(
"Component '" + name + "' is not defined in record " + targetType.getName());
}
}
}
@Nullable
private RecordComponent getRecordComponentByName(String name) {
return Arrays.stream(this.recordComponents)
.filter(recordComponent -> recordComponent.getName().equals(name))
.findFirst()
.orElse(null);
}
}
|
List<Object> values = new ArrayList<>();
for (String componentName : this.names) {
RecordComponent recordComponent = getRecordComponentByName(componentName);
Object value;
try {
value = recordComponent.getAccessor().invoke(item);
values.add(value);
}
catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Unable to extract value for record component " + componentName, e);
}
}
return values.toArray();
| 479
| 139
| 618
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/RecursiveCollectionLineAggregator.java
|
RecursiveCollectionLineAggregator
|
aggregate
|
class RecursiveCollectionLineAggregator<T> implements LineAggregator<Collection<T>> {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
private LineAggregator<T> delegate = new PassThroughLineAggregator<>();
/**
* Public setter for the {@link LineAggregator} to use on single items, that are not
* Strings. This can be used to strategise the conversion of collection and array
* elements to a String.<br>
* @param delegate the line aggregator to set. Defaults to a pass through.
*/
public void setDelegate(LineAggregator<T> delegate) {
this.delegate = delegate;
}
@Override
public String aggregate(Collection<T> items) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder builder = new StringBuilder();
for (T value : items) {
builder.append(delegate.aggregate(value)).append(LINE_SEPARATOR);
}
return builder.delete(builder.length() - LINE_SEPARATOR.length(), builder.length()).toString();
| 200
| 77
| 277
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/RegexLineTokenizer.java
|
RegexLineTokenizer
|
doTokenize
|
class RegexLineTokenizer extends AbstractLineTokenizer {
private Pattern pattern;
@Override
protected List<String> doTokenize(String line) {<FILL_FUNCTION_BODY>}
/**
* Sets the regex pattern to use.
* @param pattern Regular Expression pattern
*/
public void setPattern(Pattern pattern) {
Assert.notNull(pattern, "a non-null pattern is required");
this.pattern = pattern;
}
/**
* Sets the regular expression to use.
* @param regex regular expression (as a String)
*/
public void setRegex(String regex) {
Assert.hasText(regex, "a valid regex is required");
this.pattern = Pattern.compile(regex);
}
}
|
Matcher matcher = pattern.matcher(line);
boolean matchFound = matcher.find();
if (matchFound) {
List<String> tokens = new ArrayList<>(matcher.groupCount());
for (int i = 1; i <= matcher.groupCount(); i++) {
tokens.add(matcher.group(i));
}
return tokens;
}
return Collections.emptyList();
| 192
| 114
| 306
|
<methods>public non-sealed void <init>() ,public boolean hasNames() ,public void setFieldSetFactory(org.springframework.batch.item.file.transform.FieldSetFactory) ,public transient void setNames(java.lang.String[]) ,public void setStrict(boolean) ,public org.springframework.batch.item.file.transform.FieldSet tokenize(java.lang.String) <variables>private final java.lang.String emptyToken,private org.springframework.batch.item.file.transform.FieldSetFactory fieldSetFactory,protected java.lang.String[] names,private boolean strict
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsItemReader.java
|
JmsItemReader
|
read
|
class JmsItemReader<T> implements ItemReader<T>, InitializingBean {
protected Log logger = LogFactory.getLog(getClass());
protected Class<? extends T> itemType;
protected JmsOperations jmsTemplate;
/**
* Setter for JMS template.
* @param jmsTemplate a {@link JmsOperations} instance
*/
public void setJmsTemplate(JmsOperations jmsTemplate) {
this.jmsTemplate = jmsTemplate;
if (jmsTemplate instanceof JmsTemplate template) {
Assert.isTrue(template.getReceiveTimeout() != JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT,
"JmsTemplate must have a receive timeout!");
Assert.isTrue(template.getDefaultDestination() != null || template.getDefaultDestinationName() != null,
"JmsTemplate must have a defaultDestination or defaultDestinationName!");
}
}
/**
* Set the expected type of incoming message payloads. Set this to {@link Message} to
* receive the raw underlying message.
* @param itemType the java class of the items to be delivered. Typically the same as
* the class parameter
* @throws IllegalStateException if the message payload is of the wrong type.
*/
public void setItemType(Class<? extends T> itemType) {
this.itemType = itemType;
}
@Nullable
@Override
@SuppressWarnings("unchecked")
public T read() {<FILL_FUNCTION_BODY>}
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(this.jmsTemplate != null, "The 'jmsTemplate' is required.");
}
}
|
if (itemType != null && itemType.isAssignableFrom(Message.class)) {
return (T) jmsTemplate.receive();
}
Object result = jmsTemplate.receiveAndConvert();
if (itemType != null && result != null) {
Assert.state(itemType.isAssignableFrom(result.getClass()),
"Received message payload of wrong type: expected [" + itemType + "]");
}
return (T) result;
| 433
| 126
| 559
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsItemWriter.java
|
JmsItemWriter
|
setJmsTemplate
|
class JmsItemWriter<T> implements ItemWriter<T> {
protected Log logger = LogFactory.getLog(getClass());
private JmsOperations jmsTemplate;
/**
* Setter for JMS template.
* @param jmsTemplate a {@link JmsOperations} instance
*/
public void setJmsTemplate(JmsOperations jmsTemplate) {<FILL_FUNCTION_BODY>}
/**
* Send the items one-by-one to the default destination of the JMS template.
*
* @see org.springframework.batch.item.ItemWriter#write(Chunk)
*/
@Override
public void write(Chunk<? extends T> items) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Writing to JMS with " + items.size() + " items.");
}
for (T item : items) {
jmsTemplate.convertAndSend(item);
}
}
}
|
this.jmsTemplate = jmsTemplate;
if (jmsTemplate instanceof JmsTemplate template) {
Assert.isTrue(template.getDefaultDestination() != null || template.getDefaultDestinationName() != null,
"JmsTemplate must have a defaultDestination or defaultDestinationName!");
}
| 247
| 82
| 329
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsMethodArgumentsKeyGenerator.java
|
JmsMethodArgumentsKeyGenerator
|
getKey
|
class JmsMethodArgumentsKeyGenerator implements MethodArgumentsKeyGenerator {
/**
* If the message is a {@link Message} then returns the JMS message ID. Otherwise just
* return the first argument.
*
* @see org.springframework.retry.interceptor.MethodArgumentsKeyGenerator#getKey(Object[])
* @throws UnexpectedInputException if the JMS id cannot be determined from a JMS
* Message
* @throws IllegalArgumentException if the arguments are empty
*/
@Override
public Object getKey(Object[] items) {<FILL_FUNCTION_BODY>}
}
|
for (Object item : items) {
if (item instanceof Message) {
try {
return ((Message) item).getJMSMessageID();
}
catch (JMSException e) {
throw new UnexpectedInputException("Could not extract message ID", e);
}
}
}
if (items.length == 0) {
throw new IllegalArgumentException(
"Method parameters are empty. The key generator cannot determine a unique key.");
}
return items[0];
| 147
| 130
| 277
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsMethodInvocationRecoverer.java
|
JmsMethodInvocationRecoverer
|
recover
|
class JmsMethodInvocationRecoverer<T> implements MethodInvocationRecoverer<T> {
protected Log logger = LogFactory.getLog(getClass());
private JmsOperations jmsTemplate;
/**
* Setter for jms template.
* @param jmsTemplate a {@link JmsOperations} instance
*/
public void setJmsTemplate(JmsOperations jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
/**
* Send one message per item in the arguments list using the default destination of
* the jms template. If the recovery is successful {@code null} is returned.
*
* @see org.springframework.retry.interceptor.MethodInvocationRecoverer#recover(Object[],
* Throwable)
*/
@Override
@Nullable
public T recover(Object[] items, Throwable cause) {<FILL_FUNCTION_BODY>}
}
|
try {
for (Object item : items) {
jmsTemplate.convertAndSend(item);
}
return null;
}
catch (JmsException e) {
logger.error("Could not recover because of JmsException.", e);
throw e;
}
| 233
| 80
| 313
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsNewMethodArgumentsIdentifier.java
|
JmsNewMethodArgumentsIdentifier
|
isNew
|
class JmsNewMethodArgumentsIdentifier<T> implements NewMethodArgumentsIdentifier {
/**
* If any of the arguments is a message, check the JMS re-delivered flag and return
* it, otherwise return false to be on the safe side.
*
* @see org.springframework.retry.interceptor.NewMethodArgumentsIdentifier#isNew(java.lang.Object[])
*/
@Override
public boolean isNew(Object[] args) {<FILL_FUNCTION_BODY>}
}
|
for (Object item : args) {
if (item instanceof Message) {
try {
return !((Message) item).getJMSRedelivered();
}
catch (JMSException e) {
throw new UnexpectedInputException("Could not extract message ID", e);
}
}
}
return false;
| 124
| 91
| 215
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/builder/JmsItemReaderBuilder.java
|
JmsItemReaderBuilder
|
build
|
class JmsItemReaderBuilder<T> {
protected Class<? extends T> itemType;
protected JmsOperations jmsTemplate;
/**
* Establish the JMS template that will be used by the JmsItemReader.
* @param jmsTemplate a {@link JmsOperations} instance
* @return this instance for method chaining.
* @see JmsItemReader#setJmsTemplate(JmsOperations)
*/
public JmsItemReaderBuilder<T> jmsTemplate(JmsOperations jmsTemplate) {
this.jmsTemplate = jmsTemplate;
return this;
}
/**
* Set the expected type of incoming message payloads. Set this to {@link Message} to
* receive the raw underlying message.
* @param itemType the java class of the items to be delivered. Typically the same as
* the class parameter
* @return this instance for method chaining.
* @throws IllegalStateException if the message payload is of the wrong type.
* @see JmsItemReader#setItemType(Class)
*/
public JmsItemReaderBuilder<T> itemType(Class<? extends T> itemType) {
this.itemType = itemType;
return this;
}
/**
* Returns a fully constructed {@link JmsItemReader}.
* @return a new {@link JmsItemReader}
*/
public JmsItemReader<T> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(this.jmsTemplate, "jmsTemplate is required.");
JmsItemReader<T> jmsItemReader = new JmsItemReader<>();
jmsItemReader.setItemType(this.itemType);
jmsItemReader.setJmsTemplate(this.jmsTemplate);
return jmsItemReader;
| 367
| 91
| 458
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/builder/JmsItemWriterBuilder.java
|
JmsItemWriterBuilder
|
build
|
class JmsItemWriterBuilder<T> {
private JmsOperations jmsTemplate;
/**
* Establish the JMS template that will be used by the {@link JmsItemWriter}.
* @param jmsTemplate a {@link JmsOperations} instance
* @return this instance for method chaining.
* @see JmsItemWriter#setJmsTemplate(JmsOperations)
*/
public JmsItemWriterBuilder<T> jmsTemplate(JmsOperations jmsTemplate) {
this.jmsTemplate = jmsTemplate;
return this;
}
/**
* Returns a fully constructed {@link JmsItemWriter}.
* @return a new {@link JmsItemWriter}
*/
public JmsItemWriter<T> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(this.jmsTemplate, "jmsTemplate is required.");
JmsItemWriter<T> jmsItemWriter = new JmsItemWriter<>();
jmsItemWriter.setJmsTemplate(this.jmsTemplate);
return jmsItemWriter;
| 204
| 74
| 278
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/json/GsonJsonObjectReader.java
|
GsonJsonObjectReader
|
open
|
class GsonJsonObjectReader<T> implements JsonObjectReader<T> {
private final Class<? extends T> itemType;
private JsonReader jsonReader;
private Gson mapper;
private InputStream inputStream;
/**
* Create a new {@link GsonJsonObjectReader} instance.
* @param itemType the target item type
*/
public GsonJsonObjectReader(Class<? extends T> itemType) {
this(new Gson(), itemType);
}
public GsonJsonObjectReader(Gson mapper, Class<? extends T> itemType) {
this.mapper = mapper;
this.itemType = itemType;
}
/**
* Set the object mapper to use to map Json objects to domain objects.
* @param mapper the object mapper to use
* @see #GsonJsonObjectReader(Gson, Class)
*/
public void setMapper(Gson mapper) {
Assert.notNull(mapper, "The mapper must not be null");
this.mapper = mapper;
}
@Override
public void open(Resource resource) throws Exception {<FILL_FUNCTION_BODY>}
@Nullable
@Override
public T read() throws Exception {
try {
if (this.jsonReader.hasNext()) {
return this.mapper.fromJson(this.jsonReader, this.itemType);
}
}
catch (IOException | JsonIOException | JsonSyntaxException e) {
throw new ParseException("Unable to read next JSON object", e);
}
return null;
}
@Override
public void close() throws Exception {
this.inputStream.close();
this.jsonReader.close();
}
@Override
public void jumpToItem(int itemIndex) throws Exception {
for (int i = 0; i < itemIndex; i++) {
this.jsonReader.skipValue();
}
}
}
|
Assert.notNull(resource, "The resource must not be null");
this.inputStream = resource.getInputStream();
this.jsonReader = this.mapper.newJsonReader(new InputStreamReader(this.inputStream));
Assert.state(this.jsonReader.peek() == JsonToken.BEGIN_ARRAY,
"The Json input stream must start with an array of Json objects");
this.jsonReader.beginArray();
| 481
| 109
| 590
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/json/JacksonJsonObjectMarshaller.java
|
JacksonJsonObjectMarshaller
|
marshal
|
class JacksonJsonObjectMarshaller<T> implements JsonObjectMarshaller<T> {
private ObjectMapper objectMapper;
public JacksonJsonObjectMarshaller() {
this(new ObjectMapper());
}
public JacksonJsonObjectMarshaller(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
/**
* Set the {@link ObjectMapper} to use.
* @param objectMapper to use
* @see #JacksonJsonObjectMarshaller(ObjectMapper)
*/
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public String marshal(T item) {<FILL_FUNCTION_BODY>}
}
|
try {
return objectMapper.writeValueAsString(item);
}
catch (JsonProcessingException e) {
throw new ItemStreamException("Unable to marshal object " + item + " to Json", e);
}
| 177
| 64
| 241
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/json/JacksonJsonObjectReader.java
|
JacksonJsonObjectReader
|
open
|
class JacksonJsonObjectReader<T> implements JsonObjectReader<T> {
private final Class<? extends T> itemType;
private JsonParser jsonParser;
private ObjectMapper mapper;
private InputStream inputStream;
/**
* Create a new {@link JacksonJsonObjectReader} instance.
* @param itemType the target item type
*/
public JacksonJsonObjectReader(Class<? extends T> itemType) {
this(new ObjectMapper(), itemType);
}
public JacksonJsonObjectReader(ObjectMapper mapper, Class<? extends T> itemType) {
this.mapper = mapper;
this.itemType = itemType;
}
/**
* Set the object mapper to use to map Json objects to domain objects.
* @param mapper the object mapper to use
* @see #JacksonJsonObjectReader(ObjectMapper, Class)
*/
public void setMapper(ObjectMapper mapper) {
Assert.notNull(mapper, "The mapper must not be null");
this.mapper = mapper;
}
@Override
public void open(Resource resource) throws Exception {<FILL_FUNCTION_BODY>}
@Nullable
@Override
public T read() throws Exception {
try {
if (this.jsonParser.nextToken() == JsonToken.START_OBJECT) {
return this.mapper.readValue(this.jsonParser, this.itemType);
}
}
catch (IOException e) {
throw new ParseException("Unable to read next JSON object", e);
}
return null;
}
@Override
public void close() throws Exception {
this.inputStream.close();
this.jsonParser.close();
}
@Override
public void jumpToItem(int itemIndex) throws Exception {
for (int i = 0; i < itemIndex; i++) {
if (this.jsonParser.nextToken() == JsonToken.START_OBJECT) {
this.jsonParser.skipChildren();
}
}
}
}
|
Assert.notNull(resource, "The resource must not be null");
this.inputStream = resource.getInputStream();
this.jsonParser = this.mapper.getFactory().createParser(this.inputStream);
Assert.state(this.jsonParser.nextToken() == JsonToken.START_ARRAY,
"The Json input stream must start with an array of Json objects");
| 504
| 96
| 600
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/json/JsonFileItemWriter.java
|
JsonFileItemWriter
|
doWrite
|
class JsonFileItemWriter<T> extends AbstractFileItemWriter<T> {
private static final char JSON_OBJECT_SEPARATOR = ',';
private static final char JSON_ARRAY_START = '[';
private static final char JSON_ARRAY_STOP = ']';
private JsonObjectMarshaller<T> jsonObjectMarshaller;
/**
* Create a new {@link JsonFileItemWriter} instance.
* @param resource to write json data to
* @param jsonObjectMarshaller used to marshal object into json representation
*/
public JsonFileItemWriter(WritableResource resource, JsonObjectMarshaller<T> jsonObjectMarshaller) {
Assert.notNull(resource, "resource must not be null");
Assert.notNull(jsonObjectMarshaller, "json object marshaller must not be null");
setResource(resource);
setJsonObjectMarshaller(jsonObjectMarshaller);
setHeaderCallback(writer -> writer.write(JSON_ARRAY_START));
setFooterCallback(writer -> writer.write(this.lineSeparator + JSON_ARRAY_STOP + this.lineSeparator));
setExecutionContextName(ClassUtils.getShortName(JsonFileItemWriter.class));
}
/**
* Assert that mandatory properties (jsonObjectMarshaller) are set.
*
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {
if (this.append) {
this.shouldDeleteIfExists = false;
}
}
/**
* Set the {@link JsonObjectMarshaller} to use to marshal object to json.
* @param jsonObjectMarshaller the marshaller to use
*/
public void setJsonObjectMarshaller(JsonObjectMarshaller<T> jsonObjectMarshaller) {
this.jsonObjectMarshaller = jsonObjectMarshaller;
}
@Override
public String doWrite(Chunk<? extends T> items) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder lines = new StringBuilder();
Iterator<? extends T> iterator = items.iterator();
if (!items.isEmpty() && state.getLinesWritten() > 0) {
lines.append(JSON_OBJECT_SEPARATOR).append(this.lineSeparator);
}
while (iterator.hasNext()) {
T item = iterator.next();
lines.append(' ').append(this.jsonObjectMarshaller.marshal(item));
if (iterator.hasNext()) {
lines.append(JSON_OBJECT_SEPARATOR).append(this.lineSeparator);
}
}
return lines.toString();
| 516
| 170
| 686
|
<methods>public non-sealed void <init>() ,public void close() ,public void open(org.springframework.batch.item.ExecutionContext) throws org.springframework.batch.item.ItemStreamException,public void setAppendAllowed(boolean) ,public void setEncoding(java.lang.String) ,public void setFooterCallback(org.springframework.batch.item.file.FlatFileFooterCallback) ,public void setForceSync(boolean) ,public void setHeaderCallback(org.springframework.batch.item.file.FlatFileHeaderCallback) ,public void setLineSeparator(java.lang.String) ,public void setResource(org.springframework.core.io.WritableResource) ,public void setSaveState(boolean) ,public void setShouldDeleteIfEmpty(boolean) ,public void setShouldDeleteIfExists(boolean) ,public void setTransactional(boolean) ,public void update(org.springframework.batch.item.ExecutionContext) ,public void write(Chunk<? extends T>) throws java.lang.Exception<variables>public static final java.lang.String DEFAULT_CHARSET,public static final java.lang.String DEFAULT_LINE_SEPARATOR,public static final boolean DEFAULT_TRANSACTIONAL,private static final java.lang.String RESTART_DATA_NAME,private static final java.lang.String WRITTEN_STATISTICS_NAME,protected boolean append,private java.lang.String encoding,private org.springframework.batch.item.file.FlatFileFooterCallback footerCallback,private boolean forceSync,private org.springframework.batch.item.file.FlatFileHeaderCallback headerCallback,protected java.lang.String lineSeparator,protected static final org.apache.commons.logging.Log logger,private org.springframework.core.io.WritableResource resource,private boolean saveState,private boolean shouldDeleteIfEmpty,protected boolean shouldDeleteIfExists,protected OutputState state,private boolean transactional
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/json/JsonItemReader.java
|
JsonItemReader
|
doOpen
|
class JsonItemReader<T> extends AbstractItemCountingItemStreamItemReader<T>
implements ResourceAwareItemReaderItemStream<T> {
private static final Log LOGGER = LogFactory.getLog(JsonItemReader.class);
private Resource resource;
private JsonObjectReader<T> jsonObjectReader;
private boolean strict = true;
/**
* Create a new {@link JsonItemReader} instance.
* @param resource the input json resource
* @param jsonObjectReader the json object reader to use
*/
public JsonItemReader(Resource resource, JsonObjectReader<T> jsonObjectReader) {
Assert.notNull(resource, "The resource must not be null.");
Assert.notNull(jsonObjectReader, "The json object reader must not be null.");
this.resource = resource;
this.jsonObjectReader = jsonObjectReader;
setExecutionContextName(ClassUtils.getShortName(JsonItemReader.class));
}
/**
* Create a new {@link JsonItemReader} instance.
*/
public JsonItemReader() {
setExecutionContextName(ClassUtils.getShortName(JsonItemReader.class));
}
/**
* Set the {@link JsonObjectReader} to use to read and map Json fragments to domain
* objects.
* @param jsonObjectReader the json object reader to use
*/
public void setJsonObjectReader(JsonObjectReader<T> jsonObjectReader) {
this.jsonObjectReader = jsonObjectReader;
}
/**
* In strict mode the reader will throw an exception on
* {@link #open(org.springframework.batch.item.ExecutionContext)} if the input
* resource does not exist.
* @param strict true by default
*/
public void setStrict(boolean strict) {
this.strict = strict;
}
@Override
public void setResource(Resource resource) {
this.resource = resource;
}
@Nullable
@Override
protected T doRead() throws Exception {
return jsonObjectReader.read();
}
@Override
protected void doOpen() throws Exception {<FILL_FUNCTION_BODY>}
@Override
protected void doClose() throws Exception {
this.jsonObjectReader.close();
}
@Override
protected void jumpToItem(int itemIndex) throws Exception {
this.jsonObjectReader.jumpToItem(itemIndex);
}
}
|
Assert.notNull(this.resource, "The resource must not be null.");
Assert.notNull(this.jsonObjectReader, "The json object reader must not be null.");
if (!this.resource.exists()) {
if (this.strict) {
throw new IllegalStateException("Input resource must exist (reader is in 'strict' mode)");
}
LOGGER.warn("Input resource does not exist " + this.resource.getDescription());
return;
}
if (!this.resource.isReadable()) {
if (this.strict) {
throw new IllegalStateException("Input resource must be readable (reader is in 'strict' mode)");
}
LOGGER.warn("Input resource is not readable " + this.resource.getDescription());
return;
}
this.jsonObjectReader.open(this.resource);
| 583
| 216
| 799
|
<methods>public non-sealed void <init>() ,public void close() throws org.springframework.batch.item.ItemStreamException,public int getCurrentItemCount() ,public boolean isSaveState() ,public void open(org.springframework.batch.item.ExecutionContext) throws org.springframework.batch.item.ItemStreamException,public T read() throws java.lang.Exception,public void setCurrentItemCount(int) ,public void setMaxItemCount(int) ,public void setSaveState(boolean) ,public void update(org.springframework.batch.item.ExecutionContext) throws org.springframework.batch.item.ItemStreamException<variables>private static final java.lang.String READ_COUNT,private static final java.lang.String READ_COUNT_MAX,private int currentItemCount,private int maxItemCount,private boolean saveState
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/json/builder/JsonFileItemWriterBuilder.java
|
JsonFileItemWriterBuilder
|
build
|
class JsonFileItemWriterBuilder<T> {
private WritableResource resource;
private JsonObjectMarshaller<T> jsonObjectMarshaller;
private FlatFileHeaderCallback headerCallback;
private FlatFileFooterCallback footerCallback;
private String name;
private String encoding = JsonFileItemWriter.DEFAULT_CHARSET;
private String lineSeparator = JsonFileItemWriter.DEFAULT_LINE_SEPARATOR;
private boolean append = false;
private boolean forceSync = false;
private boolean saveState = true;
private boolean shouldDeleteIfExists = true;
private boolean shouldDeleteIfEmpty = false;
private boolean transactional = JsonFileItemWriter.DEFAULT_TRANSACTIONAL;
/**
* Configure if the state of the
* {@link org.springframework.batch.item.ItemStreamSupport} should be persisted within
* the {@link org.springframework.batch.item.ExecutionContext} for restart purposes.
* @param saveState defaults to true
* @return The current instance of the builder.
*/
public JsonFileItemWriterBuilder<T> saveState(boolean saveState) {
this.saveState = saveState;
return this;
}
/**
* The name used to calculate the key within the
* {@link org.springframework.batch.item.ExecutionContext}. Required if
* {@link #saveState(boolean)} is set to true.
* @param name name of the reader instance
* @return The current instance of the builder.
* @see org.springframework.batch.item.ItemStreamSupport#setName(String)
*/
public JsonFileItemWriterBuilder<T> name(String name) {
this.name = name;
return this;
}
/**
* A flag indicating that changes should be force-synced to disk on flush. Defaults to
* false.
* @param forceSync value to set the flag to
* @return The current instance of the builder.
* @see JsonFileItemWriter#setForceSync(boolean)
*/
public JsonFileItemWriterBuilder<T> forceSync(boolean forceSync) {
this.forceSync = forceSync;
return this;
}
/**
* String used to separate lines in output. Defaults to the System property
* <code>line.separator</code>.
* @param lineSeparator value to use for a line separator
* @return The current instance of the builder.
* @see JsonFileItemWriter#setLineSeparator(String)
*/
public JsonFileItemWriterBuilder<T> lineSeparator(String lineSeparator) {
this.lineSeparator = lineSeparator;
return this;
}
/**
* Set the {@link JsonObjectMarshaller} to use to marshal objects to json.
* @param jsonObjectMarshaller to use
* @return The current instance of the builder.
* @see JsonFileItemWriter#setJsonObjectMarshaller(JsonObjectMarshaller)
*/
public JsonFileItemWriterBuilder<T> jsonObjectMarshaller(JsonObjectMarshaller<T> jsonObjectMarshaller) {
this.jsonObjectMarshaller = jsonObjectMarshaller;
return this;
}
/**
* The {@link WritableResource} to be used as output.
* @param resource the output of the writer.
* @return The current instance of the builder.
* @see JsonFileItemWriter#setResource(WritableResource)
*/
public JsonFileItemWriterBuilder<T> resource(WritableResource resource) {
this.resource = resource;
return this;
}
/**
* Encoding used for output.
* @param encoding encoding type.
* @return The current instance of the builder.
* @see JsonFileItemWriter#setEncoding(String)
*/
public JsonFileItemWriterBuilder<T> encoding(String encoding) {
this.encoding = encoding;
return this;
}
/**
* If set to true, once the step is complete, if the resource previously provided is
* empty, it will be deleted.
* @param shouldDelete defaults to false
* @return The current instance of the builder
* @see JsonFileItemWriter#setShouldDeleteIfEmpty(boolean)
*/
public JsonFileItemWriterBuilder<T> shouldDeleteIfEmpty(boolean shouldDelete) {
this.shouldDeleteIfEmpty = shouldDelete;
return this;
}
/**
* If set to true, upon the start of the step, if the resource already exists, it will
* be deleted and recreated.
* @param shouldDelete defaults to true
* @return The current instance of the builder
* @see JsonFileItemWriter#setShouldDeleteIfExists(boolean)
*/
public JsonFileItemWriterBuilder<T> shouldDeleteIfExists(boolean shouldDelete) {
this.shouldDeleteIfExists = shouldDelete;
return this;
}
/**
* If set to true and the file exists, the output will be appended to the existing
* file.
* @param append defaults to false
* @return The current instance of the builder
* @see JsonFileItemWriter#setAppendAllowed(boolean)
*/
public JsonFileItemWriterBuilder<T> append(boolean append) {
this.append = append;
return this;
}
/**
* A callback for header processing.
* @param callback {@link FlatFileHeaderCallback} implementation
* @return The current instance of the builder
* @see JsonFileItemWriter#setHeaderCallback(FlatFileHeaderCallback)
*/
public JsonFileItemWriterBuilder<T> headerCallback(FlatFileHeaderCallback callback) {
this.headerCallback = callback;
return this;
}
/**
* A callback for footer processing.
* @param callback {@link FlatFileFooterCallback} implementation
* @return The current instance of the builder
* @see JsonFileItemWriter#setFooterCallback(FlatFileFooterCallback)
*/
public JsonFileItemWriterBuilder<T> footerCallback(FlatFileFooterCallback callback) {
this.footerCallback = callback;
return this;
}
/**
* If set to true, the flushing of the buffer is delayed while a transaction is
* active.
* @param transactional defaults to true
* @return The current instance of the builder
* @see JsonFileItemWriter#setTransactional(boolean)
*/
public JsonFileItemWriterBuilder<T> transactional(boolean transactional) {
this.transactional = transactional;
return this;
}
/**
* Validate the configuration and build a new {@link JsonFileItemWriter}.
* @return a new instance of the {@link JsonFileItemWriter}
*/
public JsonFileItemWriter<T> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(this.resource, "A resource is required.");
Assert.notNull(this.jsonObjectMarshaller, "A json object marshaller is required.");
if (this.saveState) {
Assert.hasText(this.name, "A name is required when saveState is true");
}
JsonFileItemWriter<T> jsonFileItemWriter = new JsonFileItemWriter<>(this.resource, this.jsonObjectMarshaller);
jsonFileItemWriter.setName(this.name);
jsonFileItemWriter.setAppendAllowed(this.append);
jsonFileItemWriter.setEncoding(this.encoding);
if (this.headerCallback != null) {
jsonFileItemWriter.setHeaderCallback(this.headerCallback);
}
if (this.footerCallback != null) {
jsonFileItemWriter.setFooterCallback(this.footerCallback);
}
jsonFileItemWriter.setForceSync(this.forceSync);
jsonFileItemWriter.setLineSeparator(this.lineSeparator);
jsonFileItemWriter.setSaveState(this.saveState);
jsonFileItemWriter.setShouldDeleteIfEmpty(this.shouldDeleteIfEmpty);
jsonFileItemWriter.setShouldDeleteIfExists(this.shouldDeleteIfExists);
jsonFileItemWriter.setTransactional(this.transactional);
return jsonFileItemWriter;
| 1,670
| 355
| 2,025
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/json/builder/JsonItemReaderBuilder.java
|
JsonItemReaderBuilder
|
build
|
class JsonItemReaderBuilder<T> {
protected Log logger = LogFactory.getLog(getClass());
private JsonObjectReader<T> jsonObjectReader;
private Resource resource;
private String name;
private boolean strict = true;
private boolean saveState = true;
private int maxItemCount = Integer.MAX_VALUE;
private int currentItemCount;
/**
* Set the {@link JsonObjectReader} to use to read and map Json objects to domain
* objects.
* @param jsonObjectReader to use
* @return The current instance of the builder.
* @see JsonItemReader#setJsonObjectReader(JsonObjectReader)
*/
public JsonItemReaderBuilder<T> jsonObjectReader(JsonObjectReader<T> jsonObjectReader) {
this.jsonObjectReader = jsonObjectReader;
return this;
}
/**
* The {@link Resource} to be used as input.
* @param resource the input to the reader.
* @return The current instance of the builder.
* @see JsonItemReader#setResource(Resource)
*/
public JsonItemReaderBuilder<T> resource(Resource resource) {
this.resource = resource;
return this;
}
/**
* The name used to calculate the key within the
* {@link org.springframework.batch.item.ExecutionContext}. Required if
* {@link #saveState(boolean)} is set to true.
* @param name name of the reader instance
* @return The current instance of the builder.
* @see org.springframework.batch.item.ItemStreamSupport#setName(String)
*/
public JsonItemReaderBuilder<T> name(String name) {
this.name = name;
return this;
}
/**
* Setting this value to true indicates that it is an error if the input does not
* exist and an exception will be thrown. Defaults to true.
* @param strict indicates the input resource must exist
* @return The current instance of the builder.
* @see JsonItemReader#setStrict(boolean)
*/
public JsonItemReaderBuilder<T> strict(boolean strict) {
this.strict = strict;
return this;
}
/**
* Configure if the state of the
* {@link org.springframework.batch.item.ItemStreamSupport} should be persisted within
* the {@link org.springframework.batch.item.ExecutionContext} for restart purposes.
* @param saveState defaults to true
* @return The current instance of the builder.
*/
public JsonItemReaderBuilder<T> saveState(boolean saveState) {
this.saveState = saveState;
return this;
}
/**
* Configure the max number of items to be read.
* @param maxItemCount the max items to be read
* @return The current instance of the builder.
* @see org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader#setMaxItemCount(int)
*/
public JsonItemReaderBuilder<T> maxItemCount(int maxItemCount) {
this.maxItemCount = maxItemCount;
return this;
}
/**
* Index for the current item. Used on restarts to indicate where to start from.
* @param currentItemCount current index
* @return The current instance of the builder.
* @see org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader#setCurrentItemCount(int)
*/
public JsonItemReaderBuilder<T> currentItemCount(int currentItemCount) {
this.currentItemCount = currentItemCount;
return this;
}
/**
* Validate the configuration and build a new {@link JsonItemReader}.
* @return a new instance of the {@link JsonItemReader}
*/
public JsonItemReader<T> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(this.jsonObjectReader, "A json object reader is required.");
if (this.saveState) {
Assert.state(StringUtils.hasText(this.name), "A name is required when saveState is set to true.");
}
if (this.resource == null) {
logger.debug("The resource is null. This is only a valid scenario when "
+ "injecting it later as in when using the MultiResourceItemReader");
}
JsonItemReader<T> reader = new JsonItemReader<>();
reader.setResource(this.resource);
reader.setJsonObjectReader(this.jsonObjectReader);
reader.setName(this.name);
reader.setStrict(this.strict);
reader.setSaveState(this.saveState);
reader.setMaxItemCount(this.maxItemCount);
reader.setCurrentItemCount(this.currentItemCount);
return reader;
| 950
| 245
| 1,195
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/kafka/KafkaItemReader.java
|
KafkaItemReader
|
open
|
class KafkaItemReader<K, V> extends AbstractItemStreamItemReader<V> {
private static final String TOPIC_PARTITION_OFFSETS = "topic.partition.offsets";
private static final long DEFAULT_POLL_TIMEOUT = 30L;
private final List<TopicPartition> topicPartitions;
private Map<TopicPartition, Long> partitionOffsets;
private KafkaConsumer<K, V> kafkaConsumer;
private final Properties consumerProperties;
private Iterator<ConsumerRecord<K, V>> consumerRecords;
private Duration pollTimeout = Duration.ofSeconds(DEFAULT_POLL_TIMEOUT);
private boolean saveState = true;
/**
* Create a new {@link KafkaItemReader}.
* <p>
* <strong>{@code consumerProperties} must contain the following keys:
* 'bootstrap.servers', 'group.id', 'key.deserializer' and 'value.deserializer'
* </strong>
* </p>
* .
* @param consumerProperties properties of the consumer
* @param topicName name of the topic to read data from
* @param partitions list of partitions to read data from
*/
public KafkaItemReader(Properties consumerProperties, String topicName, Integer... partitions) {
this(consumerProperties, topicName, Arrays.asList(partitions));
}
/**
* Create a new {@link KafkaItemReader}.
* <p>
* <strong>{@code consumerProperties} must contain the following keys:
* 'bootstrap.servers', 'group.id', 'key.deserializer' and 'value.deserializer'
* </strong>
* </p>
* .
* @param consumerProperties properties of the consumer
* @param topicName name of the topic to read data from
* @param partitions list of partitions to read data from
*/
public KafkaItemReader(Properties consumerProperties, String topicName, List<Integer> partitions) {
Assert.notNull(consumerProperties, "Consumer properties must not be null");
Assert.isTrue(consumerProperties.containsKey(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG),
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG + " property must be provided");
Assert.isTrue(consumerProperties.containsKey(ConsumerConfig.GROUP_ID_CONFIG),
ConsumerConfig.GROUP_ID_CONFIG + " property must be provided");
Assert.isTrue(consumerProperties.containsKey(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG),
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG + " property must be provided");
Assert.isTrue(consumerProperties.containsKey(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG),
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG + " property must be provided");
this.consumerProperties = consumerProperties;
Assert.hasLength(topicName, "Topic name must not be null or empty");
Assert.isTrue(!partitions.isEmpty(), "At least one partition must be provided");
this.topicPartitions = new ArrayList<>();
for (Integer partition : partitions) {
this.topicPartitions.add(new TopicPartition(topicName, partition));
}
}
/**
* Set a timeout for the consumer topic polling duration. Default to 30 seconds.
* @param pollTimeout for the consumer poll operation
*/
public void setPollTimeout(Duration pollTimeout) {
Assert.notNull(pollTimeout, "pollTimeout must not be null");
Assert.isTrue(!pollTimeout.isZero(), "pollTimeout must not be zero");
Assert.isTrue(!pollTimeout.isNegative(), "pollTimeout must not be negative");
this.pollTimeout = pollTimeout;
}
/**
* Set the flag that determines whether to save internal data for
* {@link ExecutionContext}. Only switch this to false if you don't want to save any
* state from this stream, and you don't need it to be restartable. Always set it to
* false if the reader is being used in a concurrent environment.
* @param saveState flag value (default true).
*/
public void setSaveState(boolean saveState) {
this.saveState = saveState;
}
/**
* The flag that determines whether to save internal state for restarts.
* @return true if the flag was set
*/
public boolean isSaveState() {
return this.saveState;
}
/**
* Setter for partition offsets. This mapping tells the reader the offset to start
* reading from in each partition. This is optional, defaults to starting from offset
* 0 in each partition. Passing an empty map makes the reader start from the offset
* stored in Kafka for the consumer group ID.
*
* <p>
* <strong>In case of a restart, offsets stored in the execution context will take
* precedence.</strong>
* </p>
* @param partitionOffsets mapping of starting offset in each partition
*/
public void setPartitionOffsets(Map<TopicPartition, Long> partitionOffsets) {
this.partitionOffsets = partitionOffsets;
}
@SuppressWarnings("unchecked")
@Override
public void open(ExecutionContext executionContext) {<FILL_FUNCTION_BODY>}
@Nullable
@Override
public V read() {
if (this.consumerRecords == null || !this.consumerRecords.hasNext()) {
this.consumerRecords = this.kafkaConsumer.poll(this.pollTimeout).iterator();
}
if (this.consumerRecords.hasNext()) {
ConsumerRecord<K, V> record = this.consumerRecords.next();
this.partitionOffsets.put(new TopicPartition(record.topic(), record.partition()), record.offset());
return record.value();
}
else {
return null;
}
}
@Override
public void update(ExecutionContext executionContext) {
if (this.saveState) {
executionContext.put(TOPIC_PARTITION_OFFSETS, new HashMap<>(this.partitionOffsets));
}
this.kafkaConsumer.commitSync();
}
@Override
public void close() {
if (this.kafkaConsumer != null) {
this.kafkaConsumer.close();
}
}
}
|
this.kafkaConsumer = new KafkaConsumer<>(this.consumerProperties);
if (this.partitionOffsets == null) {
this.partitionOffsets = new HashMap<>();
for (TopicPartition topicPartition : this.topicPartitions) {
this.partitionOffsets.put(topicPartition, 0L);
}
}
if (this.saveState && executionContext.containsKey(TOPIC_PARTITION_OFFSETS)) {
Map<TopicPartition, Long> offsets = (Map<TopicPartition, Long>) executionContext
.get(TOPIC_PARTITION_OFFSETS);
for (Map.Entry<TopicPartition, Long> entry : offsets.entrySet()) {
this.partitionOffsets.put(entry.getKey(), entry.getValue() == 0 ? 0 : entry.getValue() + 1);
}
}
this.kafkaConsumer.assign(this.topicPartitions);
this.partitionOffsets.forEach(this.kafkaConsumer::seek);
| 1,603
| 257
| 1,860
|
<methods>public non-sealed void <init>() <variables>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/kafka/KafkaItemWriter.java
|
KafkaItemWriter
|
writeKeyValue
|
class KafkaItemWriter<K, T> extends KeyValueItemWriter<K, T> {
protected KafkaTemplate<K, T> kafkaTemplate;
protected final List<CompletableFuture<SendResult<K, T>>> completableFutures = new ArrayList<>();
private long timeout = -1;
@Override
protected void writeKeyValue(K key, T value) {<FILL_FUNCTION_BODY>}
@Override
protected void flush() throws Exception {
this.kafkaTemplate.flush();
for (var future : this.completableFutures) {
if (this.timeout >= 0) {
future.get(this.timeout, TimeUnit.MILLISECONDS);
}
else {
future.get();
}
}
this.completableFutures.clear();
}
@Override
protected void init() {
Assert.state(this.kafkaTemplate != null, "KafkaTemplate must not be null.");
Assert.state(this.kafkaTemplate.getDefaultTopic() != null, "KafkaTemplate must have the default topic set.");
}
/**
* Set the {@link KafkaTemplate} to use.
* @param kafkaTemplate to use
*/
public void setKafkaTemplate(KafkaTemplate<K, T> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
/**
* The time limit to wait when flushing items to Kafka.
* @param timeout milliseconds to wait, defaults to -1 (no timeout).
* @since 4.3.2
*/
public void setTimeout(long timeout) {
this.timeout = timeout;
}
}
|
if (this.delete) {
this.completableFutures.add(this.kafkaTemplate.sendDefault(key, null));
}
else {
this.completableFutures.add(this.kafkaTemplate.sendDefault(key, value));
}
| 435
| 72
| 507
|
<methods>public non-sealed void <init>() ,public void afterPropertiesSet() throws java.lang.Exception,public void setDelete(boolean) ,public void setItemKeyMapper(Converter<T,K>) ,public void write(Chunk<? extends T>) throws java.lang.Exception<variables>protected boolean delete,protected Converter<T,K> itemKeyMapper
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/kafka/builder/KafkaItemReaderBuilder.java
|
KafkaItemReaderBuilder
|
build
|
class KafkaItemReaderBuilder<K, V> {
private Properties consumerProperties;
private String topic;
private List<Integer> partitions = new ArrayList<>();
private Map<TopicPartition, Long> partitionOffsets;
private Duration pollTimeout = Duration.ofSeconds(30L);
private boolean saveState = true;
private String name;
/**
* Configure if the state of the
* {@link org.springframework.batch.item.ItemStreamSupport} should be persisted within
* the {@link org.springframework.batch.item.ExecutionContext} for restart purposes.
* @param saveState defaults to true
* @return The current instance of the builder.
*/
public KafkaItemReaderBuilder<K, V> saveState(boolean saveState) {
this.saveState = saveState;
return this;
}
/**
* The name used to calculate the key within the
* {@link org.springframework.batch.item.ExecutionContext}. Required if
* {@link #saveState(boolean)} is set to true.
* @param name name of the reader instance
* @return The current instance of the builder.
* @see org.springframework.batch.item.ItemStreamSupport#setName(String)
*/
public KafkaItemReaderBuilder<K, V> name(String name) {
this.name = name;
return this;
}
/**
* Configure the underlying consumer properties.
* <p>
* <strong>{@code consumerProperties} must contain the following keys:
* 'bootstrap.servers', 'group.id', 'key.deserializer' and 'value.deserializer'
* </strong>
* </p>
* .
* @param consumerProperties properties of the consumer
* @return The current instance of the builder.
*/
public KafkaItemReaderBuilder<K, V> consumerProperties(Properties consumerProperties) {
this.consumerProperties = consumerProperties;
return this;
}
/**
* A list of partitions to manually assign to the consumer.
* @param partitions list of partitions to assign to the consumer
* @return The current instance of the builder.
*/
public KafkaItemReaderBuilder<K, V> partitions(Integer... partitions) {
return partitions(Arrays.asList(partitions));
}
/**
* A list of partitions to manually assign to the consumer.
* @param partitions list of partitions to assign to the consumer
* @return The current instance of the builder.
*/
public KafkaItemReaderBuilder<K, V> partitions(List<Integer> partitions) {
this.partitions = partitions;
return this;
}
/**
* Setter for partition offsets. This mapping tells the reader the offset to start
* reading from in each partition. This is optional, defaults to starting from offset
* 0 in each partition. Passing an empty map makes the reader start from the offset
* stored in Kafka for the consumer group ID.
*
* <p>
* <strong>In case of a restart, offsets stored in the execution context will take
* precedence.</strong>
* </p>
* @param partitionOffsets mapping of starting offset in each partition
* @return The current instance of the builder.
*/
public KafkaItemReaderBuilder<K, V> partitionOffsets(Map<TopicPartition, Long> partitionOffsets) {
this.partitionOffsets = partitionOffsets;
return this;
}
/**
* A topic name to manually assign to the consumer.
* @param topic name to assign to the consumer
* @return The current instance of the builder.
*/
public KafkaItemReaderBuilder<K, V> topic(String topic) {
this.topic = topic;
return this;
}
/**
* Set the pollTimeout for the poll() operations. Default to 30 seconds.
* @param pollTimeout timeout for the poll operation
* @return The current instance of the builder.
* @see KafkaItemReader#setPollTimeout(Duration)
*/
public KafkaItemReaderBuilder<K, V> pollTimeout(Duration pollTimeout) {
this.pollTimeout = pollTimeout;
return this;
}
public KafkaItemReader<K, V> build() {<FILL_FUNCTION_BODY>}
}
|
if (this.saveState) {
Assert.hasText(this.name, "A name is required when saveState is set to true");
}
Assert.notNull(consumerProperties, "Consumer properties must not be null");
Assert.isTrue(consumerProperties.containsKey(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG),
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG + " property must be provided");
Assert.isTrue(consumerProperties.containsKey(ConsumerConfig.GROUP_ID_CONFIG),
ConsumerConfig.GROUP_ID_CONFIG + " property must be provided");
Assert.isTrue(consumerProperties.containsKey(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG),
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG + " property must be provided");
Assert.isTrue(consumerProperties.containsKey(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG),
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG + " property must be provided");
Assert.hasLength(topic, "Topic name must not be null or empty");
Assert.notNull(pollTimeout, "pollTimeout must not be null");
Assert.isTrue(!pollTimeout.isZero(), "pollTimeout must not be zero");
Assert.isTrue(!pollTimeout.isNegative(), "pollTimeout must not be negative");
Assert.isTrue(!partitions.isEmpty(), "At least one partition must be provided");
KafkaItemReader<K, V> reader = new KafkaItemReader<>(this.consumerProperties, this.topic, this.partitions);
reader.setPollTimeout(this.pollTimeout);
reader.setSaveState(this.saveState);
reader.setName(this.name);
reader.setPartitionOffsets(this.partitionOffsets);
return reader;
| 1,070
| 476
| 1,546
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/kafka/builder/KafkaItemWriterBuilder.java
|
KafkaItemWriterBuilder
|
build
|
class KafkaItemWriterBuilder<K, V> {
private KafkaTemplate<K, V> kafkaTemplate;
private Converter<V, K> itemKeyMapper;
private boolean delete;
private long timeout = -1;
/**
* Establish the KafkaTemplate to be used by the KafkaItemWriter.
* @param kafkaTemplate the template to be used
* @return this instance for method chaining
* @see KafkaItemWriter#setKafkaTemplate(KafkaTemplate)
*/
public KafkaItemWriterBuilder<K, V> kafkaTemplate(KafkaTemplate<K, V> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
return this;
}
/**
* Set the {@link Converter} to use to derive the key from the item.
* @param itemKeyMapper the Converter to use.
* @return The current instance of the builder.
* @see KafkaItemWriter#setItemKeyMapper(Converter)
*/
public KafkaItemWriterBuilder<K, V> itemKeyMapper(Converter<V, K> itemKeyMapper) {
this.itemKeyMapper = itemKeyMapper;
return this;
}
/**
* Indicate if the items being passed to the writer are all to be sent as delete
* events to the topic. A delete event is made of a key with a null value. If set to
* false (default), the items will be sent with provided value and key converter by
* the itemKeyMapper. If set to true, the items will be sent with the key converter
* from the value by the itemKeyMapper and a null value.
* @param delete removal indicator.
* @return The current instance of the builder.
* @see KafkaItemWriter#setDelete(boolean)
*/
public KafkaItemWriterBuilder<K, V> delete(boolean delete) {
this.delete = delete;
return this;
}
/**
* The time limit to wait when flushing items to Kafka.
* @param timeout milliseconds to wait, defaults to -1 (no timeout).
* @return The current instance of the builder.
* @see KafkaItemWriter#setTimeout(long)
* @since 4.3.2
*/
public KafkaItemWriterBuilder<K, V> timeout(long timeout) {
this.timeout = timeout;
return this;
}
/**
* Validates and builds a {@link KafkaItemWriter}.
* @return a {@link KafkaItemWriter}
*/
public KafkaItemWriter<K, V> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(this.kafkaTemplate, "kafkaTemplate is required.");
Assert.notNull(this.itemKeyMapper, "itemKeyMapper is required.");
KafkaItemWriter<K, V> writer = new KafkaItemWriter<>();
writer.setKafkaTemplate(this.kafkaTemplate);
writer.setItemKeyMapper(this.itemKeyMapper);
writer.setDelete(this.delete);
writer.setTimeout(this.timeout);
return writer;
| 666
| 134
| 800
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ldif/LdifReader.java
|
LdifReader
|
afterPropertiesSet
|
class LdifReader extends AbstractItemCountingItemStreamItemReader<LdapAttributes>
implements ResourceAwareItemReaderItemStream<LdapAttributes>, InitializingBean {
private static final Logger LOG = LoggerFactory.getLogger(LdifReader.class);
private Resource resource;
private LdifParser ldifParser;
private int recordCount = 0;
private int recordsToSkip = 0;
private boolean strict = true;
private RecordCallbackHandler skippedRecordsCallback;
public LdifReader() {
setName(ClassUtils.getShortName(LdifReader.class));
}
/**
* In strict mode the reader will throw an exception on
* {@link #open(org.springframework.batch.item.ExecutionContext)} if the input
* resource does not exist.
* @param strict true by default
*/
public void setStrict(boolean strict) {
this.strict = strict;
}
/**
* {@link RecordCallbackHandler RecordCallbackHandler} implementations can be used to
* take action on skipped records.
* @param skippedRecordsCallback will be called for each one of the initial skipped
* lines before any items are read.
*/
public void setSkippedRecordsCallback(RecordCallbackHandler skippedRecordsCallback) {
this.skippedRecordsCallback = skippedRecordsCallback;
}
/**
* Public setter for the number of lines to skip at the start of a file. Can be used
* if the file contains a header without useful (column name) information, and without
* a comment delimiter at the beginning of the lines.
* @param recordsToSkip the number of lines to skip
*/
public void setRecordsToSkip(int recordsToSkip) {
this.recordsToSkip = recordsToSkip;
}
@Override
protected void doClose() throws Exception {
if (ldifParser != null) {
ldifParser.close();
}
this.recordCount = 0;
}
@Override
protected void doOpen() throws Exception {
if (resource == null)
throw new IllegalStateException("A resource has not been set.");
if (!resource.exists()) {
if (strict) {
throw new IllegalStateException("Input resource must exist (reader is in 'strict' mode): " + resource);
}
else {
LOG.warn("Input resource does not exist " + resource.getDescription());
return;
}
}
ldifParser.open();
for (int i = 0; i < recordsToSkip; i++) {
LdapAttributes record = ldifParser.getRecord();
if (skippedRecordsCallback != null) {
skippedRecordsCallback.handleRecord(record);
}
}
}
@Nullable
@Override
protected LdapAttributes doRead() throws Exception {
LdapAttributes attributes = null;
try {
if (ldifParser != null) {
while (attributes == null && ldifParser.hasMoreRecords()) {
attributes = ldifParser.getRecord();
}
recordCount++;
}
return attributes;
}
catch (Exception ex) {
LOG.error("Parsing error at record " + recordCount + " in resource=" + resource.getDescription()
+ ", input=[" + attributes + "]", ex);
throw ex;
}
}
/**
* Establishes the resource that will be used as the input for the LdifReader.
* @param resource the resource that will be read.
*/
@Override
public void setResource(Resource resource) {
this.resource = resource;
this.ldifParser = new LdifParser(resource);
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
}
|
Assert.state(resource != null, "A resource is required to parse.");
Assert.state(ldifParser != null, "A parser is required");
| 971
| 43
| 1,014
|
<methods>public non-sealed void <init>() ,public void close() throws org.springframework.batch.item.ItemStreamException,public int getCurrentItemCount() ,public boolean isSaveState() ,public void open(org.springframework.batch.item.ExecutionContext) throws org.springframework.batch.item.ItemStreamException,public org.springframework.ldap.core.LdapAttributes read() throws java.lang.Exception,public void setCurrentItemCount(int) ,public void setMaxItemCount(int) ,public void setSaveState(boolean) ,public void update(org.springframework.batch.item.ExecutionContext) throws org.springframework.batch.item.ItemStreamException<variables>private static final java.lang.String READ_COUNT,private static final java.lang.String READ_COUNT_MAX,private int currentItemCount,private int maxItemCount,private boolean saveState
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ldif/MappingLdifReader.java
|
MappingLdifReader
|
doOpen
|
class MappingLdifReader<T> extends AbstractItemCountingItemStreamItemReader<T>
implements ResourceAwareItemReaderItemStream<T>, InitializingBean {
private static final Logger LOG = LoggerFactory.getLogger(MappingLdifReader.class);
private Resource resource;
private LdifParser ldifParser;
private int recordCount = 0;
private int recordsToSkip = 0;
private boolean strict = true;
private RecordCallbackHandler skippedRecordsCallback;
private RecordMapper<T> recordMapper;
public MappingLdifReader() {
setName(ClassUtils.getShortName(MappingLdifReader.class));
}
/**
* In strict mode the reader will throw an exception on
* {@link #open(org.springframework.batch.item.ExecutionContext)} if the input
* resource does not exist.
* @param strict false by default
*/
public void setStrict(boolean strict) {
this.strict = strict;
}
/**
* {@link RecordCallbackHandler RecordCallbackHandler} implementations can be used to
* take action on skipped records.
* @param skippedRecordsCallback will be called for each one of the initial skipped
* lines before any items are read.
*/
public void setSkippedRecordsCallback(RecordCallbackHandler skippedRecordsCallback) {
this.skippedRecordsCallback = skippedRecordsCallback;
}
/**
* Public setter for the number of lines to skip at the start of a file. Can be used
* if the file contains a header without useful (column name) information, and without
* a comment delimiter at the beginning of the lines.
* @param recordsToSkip the number of lines to skip
*/
public void setRecordsToSkip(int recordsToSkip) {
this.recordsToSkip = recordsToSkip;
}
/**
* Setter for object mapper. This property is required to be set.
* @param recordMapper maps record to an object
*/
public void setRecordMapper(RecordMapper<T> recordMapper) {
this.recordMapper = recordMapper;
}
@Override
protected void doClose() throws Exception {
if (ldifParser != null) {
ldifParser.close();
}
this.recordCount = 0;
}
@Override
protected void doOpen() throws Exception {<FILL_FUNCTION_BODY>}
@Nullable
@Override
protected T doRead() throws Exception {
LdapAttributes attributes = null;
try {
if (ldifParser != null) {
while (attributes == null && ldifParser.hasMoreRecords()) {
attributes = ldifParser.getRecord();
}
recordCount++;
return recordMapper.mapRecord(attributes);
}
return null;
}
catch (Exception ex) {
LOG.error("Parsing error at record " + recordCount + " in resource=" + resource.getDescription()
+ ", input=[" + attributes + "]", ex);
throw ex;
}
}
@Override
public void setResource(Resource resource) {
this.resource = resource;
this.ldifParser = new LdifParser(resource);
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(resource != null, "A resource is required to parse.");
Assert.state(ldifParser != null, "A parser is required");
}
}
|
if (resource == null)
throw new IllegalStateException("A resource has not been set.");
if (!resource.exists()) {
if (strict) {
throw new IllegalStateException("Input resource must exist (reader is in 'strict' mode): " + resource);
}
else {
LOG.warn("Input resource does not exist " + resource.getDescription());
return;
}
}
ldifParser.open();
for (int i = 0; i < recordsToSkip; i++) {
LdapAttributes record = ldifParser.getRecord();
if (skippedRecordsCallback != null) {
skippedRecordsCallback.handleRecord(record);
}
}
| 872
| 187
| 1,059
|
<methods>public non-sealed void <init>() ,public void close() throws org.springframework.batch.item.ItemStreamException,public int getCurrentItemCount() ,public boolean isSaveState() ,public void open(org.springframework.batch.item.ExecutionContext) throws org.springframework.batch.item.ItemStreamException,public T read() throws java.lang.Exception,public void setCurrentItemCount(int) ,public void setMaxItemCount(int) ,public void setSaveState(boolean) ,public void update(org.springframework.batch.item.ExecutionContext) throws org.springframework.batch.item.ItemStreamException<variables>private static final java.lang.String READ_COUNT,private static final java.lang.String READ_COUNT_MAX,private int currentItemCount,private int maxItemCount,private boolean saveState
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ldif/builder/LdifReaderBuilder.java
|
LdifReaderBuilder
|
build
|
class LdifReaderBuilder {
private Resource resource;
private int recordsToSkip = 0;
private boolean strict = true;
private RecordCallbackHandler skippedRecordsCallback;
private boolean saveState = true;
private String name;
private int maxItemCount = Integer.MAX_VALUE;
private int currentItemCount;
/**
* Configure if the state of the
* {@link org.springframework.batch.item.ItemStreamSupport} should be persisted within
* the {@link org.springframework.batch.item.ExecutionContext} for restart purposes.
* @param saveState defaults to true
* @return The current instance of the builder.
*/
public LdifReaderBuilder saveState(boolean saveState) {
this.saveState = saveState;
return this;
}
/**
* The name used to calculate the key within the
* {@link org.springframework.batch.item.ExecutionContext}. Required if
* {@link #saveState(boolean)} is set to true.
* @param name name of the reader instance
* @return The current instance of the builder.
* @see org.springframework.batch.item.ItemStreamSupport#setName(String)
*/
public LdifReaderBuilder name(String name) {
this.name = name;
return this;
}
/**
* Configure the max number of items to be read.
* @param maxItemCount the max items to be read
* @return The current instance of the builder.
* @see org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader#setMaxItemCount(int)
*/
public LdifReaderBuilder maxItemCount(int maxItemCount) {
this.maxItemCount = maxItemCount;
return this;
}
/**
* Index for the current item. Used on restarts to indicate where to start from.
* @param currentItemCount current index
* @return this instance for method chaining
* @see org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader#setCurrentItemCount(int)
*/
public LdifReaderBuilder currentItemCount(int currentItemCount) {
this.currentItemCount = currentItemCount;
return this;
}
/**
* In strict mode the reader will throw an exception on
* {@link LdifReader#open(org.springframework.batch.item.ExecutionContext)} if the
* input resource does not exist.
* @param strict true by default
* @return this instance for method chaining.
* @see LdifReader#setStrict(boolean)
*/
public LdifReaderBuilder strict(boolean strict) {
this.strict = strict;
return this;
}
/**
* {@link RecordCallbackHandler RecordCallbackHandler} implementations can be used to
* take action on skipped records.
* @param skippedRecordsCallback will be called for each one of the initial skipped
* lines before any items are read.
* @return this instance for method chaining.
* @see LdifReader#setSkippedRecordsCallback(RecordCallbackHandler)
*/
public LdifReaderBuilder skippedRecordsCallback(RecordCallbackHandler skippedRecordsCallback) {
this.skippedRecordsCallback = skippedRecordsCallback;
return this;
}
/**
* Public setter for the number of lines to skip at the start of a file. Can be used
* if the file contains a header without useful (column name) information, and without
* a comment delimiter at the beginning of the lines.
* @param recordsToSkip the number of lines to skip
* @return this instance for method chaining.
* @see LdifReader#setRecordsToSkip(int)
*/
public LdifReaderBuilder recordsToSkip(int recordsToSkip) {
this.recordsToSkip = recordsToSkip;
return this;
}
/**
* Establishes the resource that will be used as the input for the LdifReader.
* @param resource the resource that will be read.
* @return this instance for method chaining.
* @see LdifReader#setResource(Resource)
*/
public LdifReaderBuilder resource(Resource resource) {
this.resource = resource;
return this;
}
/**
* Returns a fully constructed {@link LdifReader}.
* @return a new {@link org.springframework.batch.item.ldif.LdifReader}
*/
public LdifReader build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(this.resource, "Resource is required.");
if (this.saveState) {
Assert.hasText(this.name, "A name is required when saveState is set to true");
}
LdifReader reader = new LdifReader();
reader.setResource(this.resource);
reader.setRecordsToSkip(this.recordsToSkip);
reader.setSaveState(this.saveState);
reader.setName(this.name);
reader.setCurrentItemCount(this.currentItemCount);
reader.setMaxItemCount(this.maxItemCount);
if (this.skippedRecordsCallback != null) {
reader.setSkippedRecordsCallback(this.skippedRecordsCallback);
}
reader.setStrict(this.strict);
return reader;
| 1,126
| 219
| 1,345
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ldif/builder/MappingLdifReaderBuilder.java
|
MappingLdifReaderBuilder
|
build
|
class MappingLdifReaderBuilder<T> {
private Resource resource;
private int recordsToSkip = 0;
private boolean strict = true;
private RecordCallbackHandler skippedRecordsCallback;
private RecordMapper<T> recordMapper;
private boolean saveState = true;
private String name;
private int maxItemCount = Integer.MAX_VALUE;
private int currentItemCount;
/**
* Configure if the state of the
* {@link org.springframework.batch.item.ItemStreamSupport} should be persisted within
* the {@link org.springframework.batch.item.ExecutionContext} for restart purposes.
* @param saveState defaults to true
* @return The current instance of the builder.
*/
public MappingLdifReaderBuilder<T> saveState(boolean saveState) {
this.saveState = saveState;
return this;
}
/**
* The name used to calculate the key within the
* {@link org.springframework.batch.item.ExecutionContext}. Required if
* {@link #saveState(boolean)} is set to true.
* @param name name of the reader instance
* @return The current instance of the builder.
* @see org.springframework.batch.item.ItemStreamSupport#setName(String)
*/
public MappingLdifReaderBuilder<T> name(String name) {
this.name = name;
return this;
}
/**
* Configure the max number of items to be read.
* @param maxItemCount the max items to be read
* @return The current instance of the builder.
* @see org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader#setMaxItemCount(int)
*/
public MappingLdifReaderBuilder<T> maxItemCount(int maxItemCount) {
this.maxItemCount = maxItemCount;
return this;
}
/**
* Index for the current item. Used on restarts to indicate where to start from.
* @param currentItemCount current index
* @return this instance for method chaining
* @see org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader#setCurrentItemCount(int)
*/
public MappingLdifReaderBuilder<T> currentItemCount(int currentItemCount) {
this.currentItemCount = currentItemCount;
return this;
}
/**
* In strict mode the reader will throw an exception on
* {@link MappingLdifReader#open(org.springframework.batch.item.ExecutionContext)} if
* the input resource does not exist.
* @param strict true by default
* @return this instance for method chaining.
* @see MappingLdifReader#setStrict(boolean)
*/
public MappingLdifReaderBuilder<T> strict(boolean strict) {
this.strict = strict;
return this;
}
/**
* {@link RecordCallbackHandler RecordCallbackHandler} implementations can be used to
* take action on skipped records.
* @param skippedRecordsCallback will be called for each one of the initial skipped
* lines before any items are read.
* @return this instance for method chaining.
* @see MappingLdifReader#setSkippedRecordsCallback(RecordCallbackHandler)
*/
public MappingLdifReaderBuilder<T> skippedRecordsCallback(RecordCallbackHandler skippedRecordsCallback) {
this.skippedRecordsCallback = skippedRecordsCallback;
return this;
}
/**
* Public setter for the number of lines to skip at the start of a file. Can be used
* if the file contains a header without useful (column name) information, and without
* a comment delimiter at the beginning of the lines.
* @param recordsToSkip the number of lines to skip
* @return this instance for method chaining.
* @see MappingLdifReader#setRecordsToSkip(int)
*/
public MappingLdifReaderBuilder<T> recordsToSkip(int recordsToSkip) {
this.recordsToSkip = recordsToSkip;
return this;
}
/**
* Establishes the resource that will be used as the input for the MappingLdifReader.
* @param resource the resource that will be read.
* @return this instance for method chaining.
* @see MappingLdifReader#setResource(Resource)
*/
public MappingLdifReaderBuilder<T> resource(Resource resource) {
this.resource = resource;
return this;
}
/**
* Setter for object mapper. This property is required to be set.
* @param recordMapper maps record to an object
* @return this instance for method chaining.
*/
public MappingLdifReaderBuilder<T> recordMapper(RecordMapper<T> recordMapper) {
this.recordMapper = recordMapper;
return this;
}
/**
* Returns a fully constructed {@link MappingLdifReader}.
* @return a new {@link org.springframework.batch.item.ldif.MappingLdifReader}
*/
public MappingLdifReader<T> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(this.resource, "Resource is required.");
Assert.notNull(this.recordMapper, "RecordMapper is required.");
if (this.saveState) {
Assert.hasText(this.name, "A name is required when saveState is set to true");
}
MappingLdifReader<T> reader = new MappingLdifReader<>();
reader.setResource(this.resource);
reader.setRecordsToSkip(this.recordsToSkip);
reader.setSaveState(saveState);
reader.setCurrentItemCount(this.currentItemCount);
reader.setMaxItemCount(this.maxItemCount);
reader.setRecordMapper(this.recordMapper);
reader.setName(this.name);
if (this.skippedRecordsCallback != null) {
reader.setSkippedRecordsCallback(this.skippedRecordsCallback);
}
reader.setStrict(this.strict);
return reader;
| 1,292
| 257
| 1,549
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/DefaultMailErrorHandler.java
|
DefaultMailErrorHandler
|
handle
|
class DefaultMailErrorHandler implements MailErrorHandler {
private static final int DEFAULT_MAX_MESSAGE_LENGTH = 1024;
private int maxMessageLength = DEFAULT_MAX_MESSAGE_LENGTH;
/**
* The limit for the size of message that will be copied to the exception message.
* Output will be truncated beyond that. Default value is 1024.
* @param maxMessageLength the maximum message length
*/
public void setMaxMessageLength(int maxMessageLength) {
this.maxMessageLength = maxMessageLength;
}
/**
* Wraps the input exception with a runtime {@link MailException}. The exception
* message will contain the failed message (using toString).
* @param message a failed message
* @param exception a MessagingException
* @throws MailException a translation of the Exception
* @see MailErrorHandler#handle(MailMessage, Exception)
*/
@Override
public void handle(MailMessage message, Exception exception) throws MailException {<FILL_FUNCTION_BODY>}
}
|
String msg = message.toString();
throw new MailSendException(
"Mail server send failed: " + msg.substring(0, Math.min(maxMessageLength, msg.length())), exception);
| 257
| 53
| 310
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriter.java
|
SimpleMailMessageItemWriter
|
write
|
class SimpleMailMessageItemWriter implements ItemWriter<SimpleMailMessage>, InitializingBean {
private MailSender mailSender;
private MailErrorHandler mailErrorHandler = new DefaultMailErrorHandler();
/**
* A {@link MailSender} to be used to send messages in {@link #write(Chunk)}.
* @param mailSender The {@link MailSender} to be used.
*/
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
/**
* The handler for failed messages. Defaults to a {@link DefaultMailErrorHandler}.
* @param mailErrorHandler the mail error handler to set
*/
public void setMailErrorHandler(MailErrorHandler mailErrorHandler) {
this.mailErrorHandler = mailErrorHandler;
}
/**
* Check mandatory properties (mailSender).
* @throws IllegalStateException if the mandatory properties are not set
*
* @see InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws IllegalStateException {
Assert.state(mailSender != null, "A MailSender must be provided.");
}
/**
* @param chunk the chunk of items to send
* @see ItemWriter#write(Chunk)
*/
@Override
public void write(Chunk<? extends SimpleMailMessage> chunk) throws MailException {<FILL_FUNCTION_BODY>}
}
|
try {
mailSender.send(chunk.getItems().toArray(new SimpleMailMessage[chunk.size()]));
}
catch (MailSendException e) {
Map<Object, Exception> failedMessages = e.getFailedMessages();
for (Entry<Object, Exception> entry : failedMessages.entrySet()) {
mailErrorHandler.handle((SimpleMailMessage) entry.getKey(), entry.getValue());
}
}
| 353
| 117
| 470
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilder.java
|
SimpleMailMessageItemWriterBuilder
|
build
|
class SimpleMailMessageItemWriterBuilder {
private MailSender mailSender;
private MailErrorHandler mailErrorHandler = new DefaultMailErrorHandler();
/**
* A {@link MailSender} to be used to send messages in
* {@link SimpleMailMessageItemWriter#write(Chunk)}.
* @param mailSender strategy for sending simple mails.
* @return this instance for method chaining.
* @see SimpleMailMessageItemWriter#setMailSender(MailSender)
*/
public SimpleMailMessageItemWriterBuilder mailSender(MailSender mailSender) {
this.mailSender = mailSender;
return this;
}
/**
* The handler for failed messages. Defaults to a {@link DefaultMailErrorHandler}.
* @param mailErrorHandler the mail error handler to set.
* @return this instance for method chaining.
* @see SimpleMailMessageItemWriter#setMailErrorHandler(MailErrorHandler)
*/
public SimpleMailMessageItemWriterBuilder mailErrorHandler(MailErrorHandler mailErrorHandler) {
this.mailErrorHandler = mailErrorHandler;
return this;
}
/**
* Returns a fully constructed {@link SimpleMailMessageItemWriter}.
* @return a new {@link SimpleMailMessageItemWriter}
*/
public SimpleMailMessageItemWriter build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(this.mailSender, "A mailSender is required");
SimpleMailMessageItemWriter writer = new SimpleMailMessageItemWriter();
writer.setMailSender(this.mailSender);
if (mailErrorHandler != null) {
writer.setMailErrorHandler(this.mailErrorHandler);
}
return writer;
| 333
| 96
| 429
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriter.java
|
MimeMessageItemWriter
|
write
|
class MimeMessageItemWriter implements ItemWriter<MimeMessage> {
private JavaMailSender mailSender;
private MailErrorHandler mailErrorHandler = new DefaultMailErrorHandler();
/**
* A {@link JavaMailSender} to be used to send messages in {@link #write(Chunk)}.
* @param mailSender service for doing the work of sending a MIME message
*/
public void setJavaMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
/**
* The handler for failed messages. Defaults to a {@link DefaultMailErrorHandler}.
* @param mailErrorHandler the mail error handler to set
*/
public void setMailErrorHandler(MailErrorHandler mailErrorHandler) {
this.mailErrorHandler = mailErrorHandler;
}
/**
* Check mandatory properties (mailSender).
* @throws IllegalStateException if the mandatory properties are not set
*
* @see InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws IllegalStateException {
Assert.state(mailSender != null, "A MailSender must be provided.");
}
/**
* @param chunk the chunk of items to send
* @see ItemWriter#write(Chunk)
*/
@Override
public void write(Chunk<? extends MimeMessage> chunk) throws MailException {<FILL_FUNCTION_BODY>}
}
|
try {
mailSender.send(chunk.getItems().toArray(new MimeMessage[chunk.size()]));
}
catch (MailSendException e) {
Map<Object, Exception> failedMessages = e.getFailedMessages();
for (Entry<Object, Exception> entry : failedMessages.entrySet()) {
mailErrorHandler.handle(new MimeMailMessage((MimeMessage) entry.getKey()), entry.getValue());
}
}
| 350
| 123
| 473
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/redis/RedisItemReader.java
|
RedisItemReader
|
read
|
class RedisItemReader<K, V> implements ItemStreamReader<V> {
private final RedisTemplate<K, V> redisTemplate;
private final ScanOptions scanOptions;
private Cursor<K> cursor;
public RedisItemReader(RedisTemplate<K, V> redisTemplate, ScanOptions scanOptions) {
Assert.notNull(redisTemplate, "redisTemplate must not be null");
Assert.notNull(scanOptions, "scanOptions must no be null");
this.redisTemplate = redisTemplate;
this.scanOptions = scanOptions;
}
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
this.cursor = this.redisTemplate.scan(this.scanOptions);
}
@Override
public V read() throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void close() throws ItemStreamException {
this.cursor.close();
}
}
|
if (this.cursor.hasNext()) {
K nextKey = this.cursor.next();
return this.redisTemplate.opsForValue().get(nextKey);
}
else {
return null;
}
| 235
| 61
| 296
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/redis/RedisItemWriter.java
|
RedisItemWriter
|
writeKeyValue
|
class RedisItemWriter<K, T> extends KeyValueItemWriter<K, T> {
private RedisTemplate<K, T> redisTemplate;
@Override
protected void writeKeyValue(K key, T value) {<FILL_FUNCTION_BODY>}
@Override
protected void init() {
Assert.notNull(this.redisTemplate, "RedisTemplate must not be null");
}
/**
* Set the {@link RedisTemplate} to use.
* @param redisTemplate the template to use
*/
public void setRedisTemplate(RedisTemplate<K, T> redisTemplate) {
this.redisTemplate = redisTemplate;
}
}
|
if (this.delete) {
this.redisTemplate.delete(key);
}
else {
this.redisTemplate.opsForValue().set(key, value);
}
| 174
| 52
| 226
|
<methods>public non-sealed void <init>() ,public void afterPropertiesSet() throws java.lang.Exception,public void setDelete(boolean) ,public void setItemKeyMapper(Converter<T,K>) ,public void write(Chunk<? extends T>) throws java.lang.Exception<variables>protected boolean delete,protected Converter<T,K> itemKeyMapper
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/redis/builder/RedisItemWriterBuilder.java
|
RedisItemWriterBuilder
|
build
|
class RedisItemWriterBuilder<K, V> {
private RedisTemplate<K, V> redisTemplate;
private Converter<V, K> itemKeyMapper;
private boolean delete;
/**
* Set the {@link RedisTemplate} to use to write items to Redis.
* @param redisTemplate the template to use.
* @return The current instance of the builder.
* @see RedisItemWriter#setRedisTemplate(RedisTemplate)
*/
public RedisItemWriterBuilder<K, V> redisTemplate(RedisTemplate<K, V> redisTemplate) {
this.redisTemplate = redisTemplate;
return this;
}
/**
* Set the {@link Converter} to use to derive the key from the item.
* @param itemKeyMapper the Converter to use.
* @return The current instance of the builder.
* @see RedisItemWriter#setItemKeyMapper(Converter)
*/
public RedisItemWriterBuilder<K, V> itemKeyMapper(Converter<V, K> itemKeyMapper) {
this.itemKeyMapper = itemKeyMapper;
return this;
}
/**
* Indicate if the items being passed to the writer should be deleted.
* @param delete removal indicator.
* @return The current instance of the builder.
* @see RedisItemWriter#setDelete(boolean)
*/
public RedisItemWriterBuilder<K, V> delete(boolean delete) {
this.delete = delete;
return this;
}
/**
* Validates and builds a {@link RedisItemWriter}.
* @return a {@link RedisItemWriter}
*/
public RedisItemWriter<K, V> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(this.redisTemplate, "RedisTemplate is required.");
Assert.notNull(this.itemKeyMapper, "itemKeyMapper is required.");
RedisItemWriter<K, V> writer = new RedisItemWriter<>();
writer.setRedisTemplate(this.redisTemplate);
writer.setItemKeyMapper(this.itemKeyMapper);
writer.setDelete(this.delete);
return writer;
| 436
| 116
| 552
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractItemCountingItemStreamItemReader.java
|
AbstractItemCountingItemStreamItemReader
|
open
|
class AbstractItemCountingItemStreamItemReader<T> extends AbstractItemStreamItemReader<T> {
private static final String READ_COUNT = "read.count";
private static final String READ_COUNT_MAX = "read.count.max";
private int currentItemCount = 0;
private int maxItemCount = Integer.MAX_VALUE;
private boolean saveState = true;
/**
* Read next item from input.
* @return an item or {@code null} if the data source is exhausted
* @throws Exception Allows subclasses to throw checked exceptions for interpretation
* by the framework
*/
@Nullable
protected abstract T doRead() throws Exception;
/**
* Open resources necessary to start reading input.
* @throws Exception Allows subclasses to throw checked exceptions for interpretation
* by the framework
*/
protected abstract void doOpen() throws Exception;
/**
* Close the resources opened in {@link #doOpen()}.
* @throws Exception Allows subclasses to throw checked exceptions for interpretation
* by the framework
*/
protected abstract void doClose() throws Exception;
/**
* Move to the given item index. Subclasses should override this method if there is a
* more efficient way of moving to given index than re-reading the input using
* {@link #doRead()}.
* @param itemIndex index of item (0 based) to jump to.
* @throws Exception Allows subclasses to throw checked exceptions for interpretation
* by the framework
*/
protected void jumpToItem(int itemIndex) throws Exception {
for (int i = 0; i < itemIndex; i++) {
read();
}
}
@Nullable
@Override
public T read() throws Exception {
if (currentItemCount >= maxItemCount) {
return null;
}
currentItemCount++;
T item = doRead();
if (item instanceof ItemCountAware) {
((ItemCountAware) item).setItemCount(currentItemCount);
}
return item;
}
/**
* Returns the current item count.
* @return the current item count
* @since 5.1
*/
public int getCurrentItemCount() {
return this.currentItemCount;
}
/**
* The index of the item to start reading from. If the {@link ExecutionContext}
* contains a key <code>[name].read.count</code> (where <code>[name]</code> is the
* name of this component) the value from the {@link ExecutionContext} will be used in
* preference.
*
* @see #setName(String)
* @param count the value of the current item count
*/
public void setCurrentItemCount(int count) {
this.currentItemCount = count;
}
/**
* The maximum index of the items to be read. If the {@link ExecutionContext} contains
* a key <code>[name].read.count.max</code> (where <code>[name]</code> is the name of
* this component) the value from the {@link ExecutionContext} will be used in
* preference.
*
* @see #setName(String)
* @param count the value of the maximum item count. count must be greater than zero.
*/
public void setMaxItemCount(int count) {
Assert.isTrue(count > 0, "count must be greater than zero");
this.maxItemCount = count;
}
@Override
public void close() throws ItemStreamException {
super.close();
currentItemCount = 0;
try {
doClose();
}
catch (Exception e) {
throw new ItemStreamException("Error while closing item reader", e);
}
}
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {<FILL_FUNCTION_BODY>}
@Override
public void update(ExecutionContext executionContext) throws ItemStreamException {
super.update(executionContext);
if (saveState) {
Assert.notNull(executionContext, "ExecutionContext must not be null");
executionContext.putInt(getExecutionContextKey(READ_COUNT), currentItemCount);
if (maxItemCount < Integer.MAX_VALUE) {
executionContext.putInt(getExecutionContextKey(READ_COUNT_MAX), maxItemCount);
}
}
}
/**
* Set the flag that determines whether to save internal data for
* {@link ExecutionContext}. Only switch this to false if you don't want to save any
* state from this stream, and you don't need it to be restartable. Always set it to
* false if the reader is being used in a concurrent environment.
* @param saveState flag value (default true).
*/
public void setSaveState(boolean saveState) {
this.saveState = saveState;
}
/**
* The flag that determines whether to save internal state for restarts.
* @return true if the flag was set
*/
public boolean isSaveState() {
return saveState;
}
}
|
super.open(executionContext);
try {
doOpen();
}
catch (Exception e) {
throw new ItemStreamException("Failed to initialize the reader", e);
}
if (!isSaveState()) {
return;
}
if (executionContext.containsKey(getExecutionContextKey(READ_COUNT_MAX))) {
maxItemCount = executionContext.getInt(getExecutionContextKey(READ_COUNT_MAX));
}
int itemCount = 0;
if (executionContext.containsKey(getExecutionContextKey(READ_COUNT))) {
itemCount = executionContext.getInt(getExecutionContextKey(READ_COUNT));
}
else if (currentItemCount > 0) {
itemCount = currentItemCount;
}
if (itemCount > 0 && itemCount < maxItemCount) {
try {
jumpToItem(itemCount);
}
catch (Exception e) {
throw new ItemStreamException("Could not move to stored position on restart", e);
}
}
currentItemCount = itemCount;
| 1,257
| 284
| 1,541
|
<methods>public non-sealed void <init>() <variables>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ClassifierCompositeItemWriter.java
|
ClassifierCompositeItemWriter
|
write
|
class ClassifierCompositeItemWriter<T> implements ItemWriter<T> {
private Classifier<T, ItemWriter<? super T>> classifier = new ClassifierSupport<>(null);
/**
* @param classifier the classifier to set
*/
public void setClassifier(Classifier<T, ItemWriter<? super T>> classifier) {
Assert.notNull(classifier, "A classifier is required.");
this.classifier = classifier;
}
/**
* Delegates to injected {@link ItemWriter} instances according to their
* classification by the {@link Classifier}.
*/
@Override
public void write(Chunk<? extends T> items) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Map<ItemWriter<? super T>, Chunk<T>> map = new LinkedHashMap<>();
for (T item : items) {
ItemWriter<? super T> key = classifier.classify(item);
if (!map.containsKey(key)) {
map.put(key, new Chunk<>());
}
map.get(key).add(item);
}
for (ItemWriter<? super T> writer : map.keySet()) {
writer.write(map.get(writer));
}
| 185
| 143
| 328
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/CompositeItemProcessor.java
|
CompositeItemProcessor
|
afterPropertiesSet
|
class CompositeItemProcessor<I, O> implements ItemProcessor<I, O>, InitializingBean {
private List<? extends ItemProcessor<?, ?>> delegates;
/**
* Default constructor
*/
public CompositeItemProcessor() {
}
/**
* Convenience constructor for setting the delegates.
* @param delegates array of {@link ItemProcessor} delegates that will work on the
* item.
*/
public CompositeItemProcessor(ItemProcessor<?, ?>... delegates) {
this(Arrays.asList(delegates));
}
/**
* Convenience constructor for setting the delegates.
* @param delegates list of {@link ItemProcessor} delegates that will work on the
* item.
*/
public CompositeItemProcessor(List<? extends ItemProcessor<?, ?>> delegates) {
setDelegates(delegates);
}
@Nullable
@Override
@SuppressWarnings("unchecked")
public O process(I item) throws Exception {
Object result = item;
for (ItemProcessor<?, ?> delegate : delegates) {
if (result == null) {
return null;
}
result = processItem(delegate, result);
}
return (O) result;
}
/*
* Helper method to work around wildcard capture compiler error: see
* https://docs.oracle.com/javase/tutorial/java/generics/capture.html The method
* process(capture#1-of ?) in the type ItemProcessor<capture#1-of ?,capture#2-of ?> is
* not applicable for the arguments (Object)
*/
@SuppressWarnings("unchecked")
private <T> Object processItem(ItemProcessor<T, ?> processor, Object input) throws Exception {
return processor.process((T) input);
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
/**
* Establishes the {@link ItemProcessor} delegates that will work on the item to be
* processed.
* @param delegates list of {@link ItemProcessor} delegates that will work on the
* item.
*/
public void setDelegates(List<? extends ItemProcessor<?, ?>> delegates) {
this.delegates = delegates;
}
}
|
Assert.state(delegates != null, "The 'delegates' may not be null");
Assert.state(!delegates.isEmpty(), "The 'delegates' may not be empty");
| 589
| 54
| 643
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/CompositeItemStream.java
|
CompositeItemStream
|
register
|
class CompositeItemStream implements ItemStream {
private final List<ItemStream> streams = new ArrayList<>();
/**
* Public setter for the {@link ItemStream}s.
* @param streams {@link List} of {@link ItemStream}.
*/
public void setStreams(List<ItemStream> streams) {
this.streams.addAll(streams);
}
/**
* Public setter for the {@link ItemStream}s.
* @param streams array of {@link ItemStream}.
*/
public void setStreams(ItemStream[] streams) {
this.streams.addAll(Arrays.asList(streams));
}
/**
* Register a {@link ItemStream} as one of the interesting providers under the
* provided key.
* @param stream an instance of {@link ItemStream} to be added to the list of streams.
*/
public void register(ItemStream stream) {<FILL_FUNCTION_BODY>}
/**
* Default constructor
*/
public CompositeItemStream() {
super();
}
/**
* Convenience constructor for setting the {@link ItemStream}s.
* @param streams {@link List} of {@link ItemStream}.
*/
public CompositeItemStream(List<ItemStream> streams) {
setStreams(streams);
}
/**
* Convenience constructor for setting the {@link ItemStream}s.
* @param streams array of {@link ItemStream}.
*/
public CompositeItemStream(ItemStream... streams) {
setStreams(streams);
}
/**
* Simple aggregate {@link ExecutionContext} provider for the contributions registered
* under the given key.
*
* @see org.springframework.batch.item.ItemStream#update(ExecutionContext)
*/
@Override
public void update(ExecutionContext executionContext) {
for (ItemStream itemStream : streams) {
itemStream.update(executionContext);
}
}
/**
* Broadcast the call to close.
* @throws ItemStreamException thrown if one of the {@link ItemStream}s in the list
* fails to close. This is a sequential operation so all itemStreams in the list after
* the one that failed to close will remain open.
*/
@Override
public void close() throws ItemStreamException {
for (ItemStream itemStream : streams) {
itemStream.close();
}
}
/**
* Broadcast the call to open.
* @throws ItemStreamException thrown if one of the {@link ItemStream}s in the list
* fails to open. This is a sequential operation so all itemStreams in the list after
* the one that failed to open will not be opened.
*/
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
for (ItemStream itemStream : streams) {
itemStream.open(executionContext);
}
}
}
|
synchronized (streams) {
if (!streams.contains(stream)) {
streams.add(stream);
}
}
| 718
| 41
| 759
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/CompositeItemWriter.java
|
CompositeItemWriter
|
open
|
class CompositeItemWriter<T> implements ItemStreamWriter<T>, InitializingBean {
private List<ItemWriter<? super T>> delegates;
private boolean ignoreItemStream = false;
/**
* Default constructor
*/
public CompositeItemWriter() {
}
/**
* Convenience constructor for setting the delegates.
* @param delegates the list of delegates to use.
*/
public CompositeItemWriter(List<ItemWriter<? super T>> delegates) {
setDelegates(delegates);
}
/**
* Convenience constructor for setting the delegates.
* @param delegates the array of delegates to use.
*/
@SafeVarargs
public CompositeItemWriter(ItemWriter<? super T>... delegates) {
this(Arrays.asList(delegates));
}
/**
* Establishes the policy whether to call the open, close, or update methods for the
* item writer delegates associated with the CompositeItemWriter.
* @param ignoreItemStream if false the delegates' open, close, or update methods will
* be called when the corresponding methods on the CompositeItemWriter are called. If
* true the delegates' open, close, nor update methods will not be called (default is
* false).
*/
public void setIgnoreItemStream(boolean ignoreItemStream) {
this.ignoreItemStream = ignoreItemStream;
}
@Override
public void write(Chunk<? extends T> chunk) throws Exception {
for (ItemWriter<? super T> writer : delegates) {
writer.write(chunk);
}
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(delegates != null, "The 'delegates' may not be null");
Assert.state(!delegates.isEmpty(), "The 'delegates' may not be empty");
}
/**
* The list of item writers to use as delegates. Items are written to each of the
* delegates.
* @param delegates the list of delegates to use. The delegates list must not be null
* nor be empty.
*/
public void setDelegates(List<ItemWriter<? super T>> delegates) {
this.delegates = delegates;
}
@Override
public void close() throws ItemStreamException {
for (ItemWriter<? super T> writer : delegates) {
if (!ignoreItemStream && (writer instanceof ItemStream)) {
((ItemStream) writer).close();
}
}
}
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {<FILL_FUNCTION_BODY>}
@Override
public void update(ExecutionContext executionContext) throws ItemStreamException {
for (ItemWriter<? super T> writer : delegates) {
if (!ignoreItemStream && (writer instanceof ItemStream)) {
((ItemStream) writer).update(executionContext);
}
}
}
}
|
for (ItemWriter<? super T> writer : delegates) {
if (!ignoreItemStream && (writer instanceof ItemStream)) {
((ItemStream) writer).open(executionContext);
}
}
| 738
| 55
| 793
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/IteratorItemReader.java
|
IteratorItemReader
|
read
|
class IteratorItemReader<T> implements ItemReader<T> {
/**
* Internal iterator
*/
private final Iterator<T> iterator;
/**
* Construct a new reader from this iterable (could be a collection), by extracting an
* instance of {@link Iterator} from it.
* @param iterable in instance of {@link Iterable}
*
* @see Iterable#iterator()
*/
public IteratorItemReader(Iterable<T> iterable) {
Assert.notNull(iterable, "Iterable argument cannot be null!");
this.iterator = iterable.iterator();
}
/**
* Construct a new reader from this iterator directly.
* @param iterator an instance of {@link Iterator}
*/
public IteratorItemReader(Iterator<T> iterator) {
Assert.notNull(iterator, "Iterator argument cannot be null!");
this.iterator = iterator;
}
/**
* Implementation of {@link ItemReader#read()} that just iterates over the iterator
* provided.
*/
@Nullable
@Override
public T read() {<FILL_FUNCTION_BODY>}
}
|
if (iterator.hasNext())
return iterator.next();
else
return null; // end of data
| 294
| 32
| 326
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ScriptItemProcessor.java
|
ScriptItemProcessor
|
process
|
class ScriptItemProcessor<I, O> implements ItemProcessor<I, O>, InitializingBean {
public static final String ITEM_BINDING_VARIABLE_NAME = "item";
private String language;
private ScriptSource script;
private ScriptSource scriptSource;
private ScriptEvaluator scriptEvaluator;
private String itemBindingVariableName = ITEM_BINDING_VARIABLE_NAME;
@Nullable
@Override
@SuppressWarnings("unchecked")
public O process(I item) throws Exception {<FILL_FUNCTION_BODY>}
/**
* <p>
* Sets the {@link org.springframework.core.io.Resource} location of the script to
* use. The script language will be deduced from the filename extension.
* </p>
* @param resource the {@link org.springframework.core.io.Resource} location of the
* script to use.
*/
public void setScript(Resource resource) {
Assert.notNull(resource, "The script resource cannot be null");
this.script = new ResourceScriptSource(resource);
}
/**
* <p>
* Sets the provided {@link String} as the script source code to use.
* </p>
* @param scriptSource the {@link String} form of the script source code to use.
* @param language the language of the script.
*/
public void setScriptSource(String scriptSource, String language) {
Assert.hasText(language, "Language must contain the script language");
Assert.hasText(scriptSource, "Script source must contain the script source to evaluate");
this.language = language;
this.scriptSource = new StaticScriptSource(scriptSource);
}
/**
* <p>
* Provides the ability to change the key name that scripts use to obtain the current
* item to process if the variable represented by:
* {@link org.springframework.batch.item.support.ScriptItemProcessor#ITEM_BINDING_VARIABLE_NAME}
* is not suitable ("item").
* </p>
* @param itemBindingVariableName the desired binding variable name
*/
public void setItemBindingVariableName(String itemBindingVariableName) {
this.itemBindingVariableName = itemBindingVariableName;
}
/**
* <p>
* Provides the ability to set a custom
* {@link org.springframework.scripting.ScriptEvaluator} implementation. If not set, a
* {@link org.springframework.scripting.support.StandardScriptEvaluator} will be used
* by default.
* </p>
* @param scriptEvaluator the {@link org.springframework.scripting.ScriptEvaluator} to
* use
*/
public void setScriptEvaluator(ScriptEvaluator scriptEvaluator) {
this.scriptEvaluator = scriptEvaluator;
}
@Override
public void afterPropertiesSet() throws Exception {
if (scriptEvaluator == null) {
scriptEvaluator = new StandardScriptEvaluator();
}
Assert.state(scriptSource != null || script != null,
"Either the script source or script file must be provided");
Assert.state(scriptSource == null || script == null,
"Either a script source or script file must be provided, not both");
if (scriptSource != null && scriptEvaluator instanceof StandardScriptEvaluator) {
Assert.state(StringUtils.hasLength(language),
"Language must be provided when using the default ScriptEvaluator and raw source code");
((StandardScriptEvaluator) scriptEvaluator).setLanguage(language);
}
}
private ScriptSource getScriptSource() {
if (script != null) {
return script;
}
if (scriptSource != null) {
return scriptSource;
}
throw new IllegalStateException("Either a script source or script needs to be provided.");
}
}
|
Map<String, Object> arguments = new HashMap<>();
arguments.put(itemBindingVariableName, item);
return (O) scriptEvaluator.evaluate(getScriptSource(), arguments);
| 983
| 54
| 1,037
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SingleItemPeekableItemReader.java
|
SingleItemPeekableItemReader
|
update
|
class SingleItemPeekableItemReader<T> implements ItemStreamReader<T>, PeekableItemReader<T> {
private ItemReader<T> delegate;
private T next;
private ExecutionContext executionContext = new ExecutionContext();
/**
* The item reader to use as a delegate. Items are read from the delegate and passed
* to the caller in {@link #read()}.
* @param delegate the delegate to set
*/
public void setDelegate(ItemReader<T> delegate) {
this.delegate = delegate;
}
/**
* Get the next item from the delegate (whether or not it has already been peeked at).
*
* @see ItemReader#read()
*/
@Nullable
@Override
public T read() throws Exception {
if (next != null) {
T item = next;
next = null;
return item;
}
return delegate.read();
}
/**
* Peek at the next item, ensuring that if the delegate is an {@link ItemStream} the
* state is stored for the next call to {@link #update(ExecutionContext)}.
* @return the next item (or null if there is none).
*
* @see PeekableItemReader#peek()
*/
@Nullable
@Override
public T peek() throws Exception {
if (next == null) {
updateDelegate(executionContext);
next = delegate.read();
}
return next;
}
/**
* If the delegate is an {@link ItemStream}, just pass the call on, otherwise reset
* the peek cache.
* @throws ItemStreamException if there is a problem
* @see ItemStream#close()
*/
@Override
public void close() throws ItemStreamException {
next = null;
if (delegate instanceof ItemStream) {
((ItemStream) delegate).close();
}
executionContext = new ExecutionContext();
}
/**
* If the delegate is an {@link ItemStream}, just pass the call on, otherwise reset
* the peek cache.
* @param executionContext the current context
* @throws ItemStreamException if there is a problem
* @see ItemStream#open(ExecutionContext)
*/
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
next = null;
if (delegate instanceof ItemStream) {
((ItemStream) delegate).open(executionContext);
}
executionContext = new ExecutionContext();
}
/**
* If there is a cached peek, then retrieve the execution context state from that
* point. If there is no peek cached, then call directly to the delegate.
* @param executionContext the current context
* @throws ItemStreamException if there is a problem
* @see ItemStream#update(ExecutionContext)
*/
@Override
public void update(ExecutionContext executionContext) throws ItemStreamException {<FILL_FUNCTION_BODY>}
private void updateDelegate(ExecutionContext executionContext) {
if (delegate instanceof ItemStream) {
((ItemStream) delegate).update(executionContext);
}
}
}
|
if (next != null) {
// Get the last state from the delegate instead of using
// current value.
for (Entry<String, Object> entry : this.executionContext.entrySet()) {
executionContext.put(entry.getKey(), entry.getValue());
}
return;
}
updateDelegate(executionContext);
| 780
| 89
| 869
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SynchronizedItemReader.java
|
SynchronizedItemReader
|
read
|
class SynchronizedItemReader<T> implements ItemReader<T> {
private final ItemReader<T> delegate;
private final Lock lock = new ReentrantLock();
public SynchronizedItemReader(ItemReader<T> delegate) {
Assert.notNull(delegate, "The delegate must not be null");
this.delegate = delegate;
}
/**
* This method delegates to the {@code read} method of the delegate and is
* synchronized with a lock.
*/
@Override
@Nullable
public T read() throws Exception {<FILL_FUNCTION_BODY>}
}
|
this.lock.lock();
try {
return this.delegate.read();
}
finally {
this.lock.unlock();
}
| 153
| 47
| 200
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SynchronizedItemStreamReader.java
|
SynchronizedItemStreamReader
|
afterPropertiesSet
|
class SynchronizedItemStreamReader<T> implements ItemStreamReader<T>, InitializingBean {
private ItemStreamReader<T> delegate;
private final Lock lock = new ReentrantLock();
public void setDelegate(ItemStreamReader<T> delegate) {
this.delegate = delegate;
}
/**
* This delegates to the read method of the <code>delegate</code>
*/
@Override
@Nullable
public T read() throws Exception {
this.lock.lock();
try {
return this.delegate.read();
}
finally {
this.lock.unlock();
}
}
@Override
public void close() {
this.delegate.close();
}
@Override
public void open(ExecutionContext executionContext) {
this.delegate.open(executionContext);
}
@Override
public void update(ExecutionContext executionContext) {
this.delegate.update(executionContext);
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
}
|
Assert.state(this.delegate != null, "A delegate item reader is required");
| 274
| 27
| 301
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SynchronizedItemStreamWriter.java
|
SynchronizedItemStreamWriter
|
afterPropertiesSet
|
class SynchronizedItemStreamWriter<T> implements ItemStreamWriter<T>, InitializingBean {
private ItemStreamWriter<T> delegate;
private final Lock lock = new ReentrantLock();
/**
* Set the delegate {@link ItemStreamWriter}.
* @param delegate the delegate to set
*/
public void setDelegate(ItemStreamWriter<T> delegate) {
this.delegate = delegate;
}
/**
* This method delegates to the {@code write} method of the {@code delegate}.
*/
@Override
public void write(Chunk<? extends T> items) throws Exception {
this.lock.lock();
try {
this.delegate.write(items);
}
finally {
this.lock.unlock();
}
}
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
this.delegate.open(executionContext);
}
@Override
public void update(ExecutionContext executionContext) throws ItemStreamException {
this.delegate.update(executionContext);
}
@Override
public void close() throws ItemStreamException {
this.delegate.close();
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
}
|
Assert.state(this.delegate != null, "A delegate item writer is required");
| 318
| 27
| 345
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SynchronizedItemWriter.java
|
SynchronizedItemWriter
|
write
|
class SynchronizedItemWriter<T> implements ItemWriter<T> {
private final ItemWriter<T> delegate;
private final Lock lock = new ReentrantLock();
public SynchronizedItemWriter(ItemWriter<T> delegate) {
Assert.notNull(delegate, "The delegate must not be null");
this.delegate = delegate;
}
/**
* This method delegates to the {@code write} method of the delegate and is
* synchronized with a lock.
*/
@Override
public void write(Chunk<? extends T> items) throws Exception {<FILL_FUNCTION_BODY>}
}
|
this.lock.lock();
try {
this.delegate.write(items);
}
finally {
this.lock.unlock();
}
| 159
| 48
| 207
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/builder/ClassifierCompositeItemProcessorBuilder.java
|
ClassifierCompositeItemProcessorBuilder
|
build
|
class ClassifierCompositeItemProcessorBuilder<I, O> {
private Classifier<? super I, ItemProcessor<?, ? extends O>> classifier;
/**
* Establishes the classifier that will determine which {@link ItemProcessor} to use.
* @param classifier the classifier to set
* @return this instance for method chaining
* @see ClassifierCompositeItemProcessor#setClassifier(Classifier)
*/
public ClassifierCompositeItemProcessorBuilder<I, O> classifier(
Classifier<? super I, ItemProcessor<?, ? extends O>> classifier) {
this.classifier = classifier;
return this;
}
/**
* Returns a fully constructed {@link ClassifierCompositeItemProcessor}.
* @return a new {@link ClassifierCompositeItemProcessor}
*/
public ClassifierCompositeItemProcessor<I, O> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(classifier, "A classifier is required.");
ClassifierCompositeItemProcessor<I, O> processor = new ClassifierCompositeItemProcessor<>();
processor.setClassifier(this.classifier);
return processor;
| 231
| 66
| 297
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/builder/ClassifierCompositeItemWriterBuilder.java
|
ClassifierCompositeItemWriterBuilder
|
build
|
class ClassifierCompositeItemWriterBuilder<T> {
private Classifier<T, ItemWriter<? super T>> classifier;
/**
* Establish the classifier to be used for the selection of which {@link ItemWriter}
* to use.
* @param classifier the classifier to set
* @return this instance for method chaining
* @see org.springframework.batch.item.support.ClassifierCompositeItemWriter#setClassifier(Classifier)
*/
public ClassifierCompositeItemWriterBuilder<T> classifier(Classifier<T, ItemWriter<? super T>> classifier) {
this.classifier = classifier;
return this;
}
/**
* Returns a fully constructed {@link ClassifierCompositeItemWriter}.
* @return a new {@link ClassifierCompositeItemWriter}
*/
public ClassifierCompositeItemWriter<T> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(classifier, "A classifier is required.");
ClassifierCompositeItemWriter<T> writer = new ClassifierCompositeItemWriter<>();
writer.setClassifier(this.classifier);
return writer;
| 233
| 64
| 297
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/builder/CompositeItemProcessorBuilder.java
|
CompositeItemProcessorBuilder
|
build
|
class CompositeItemProcessorBuilder<I, O> {
private List<? extends ItemProcessor<?, ?>> delegates;
/**
* Establishes the {@link ItemProcessor} delegates that will work on the item to be
* processed.
* @param delegates list of {@link ItemProcessor} delegates that will work on the
* item.
* @return this instance for method chaining.
* @see CompositeItemProcessor#setDelegates(List)
*/
public CompositeItemProcessorBuilder<I, O> delegates(List<? extends ItemProcessor<?, ?>> delegates) {
this.delegates = delegates;
return this;
}
/**
* Establishes the {@link ItemProcessor} delegates that will work on the item to be
* processed.
* @param delegates the {@link ItemProcessor} delegates that will work on the item.
* @return this instance for method chaining.
* @see CompositeItemProcessorBuilder#delegates(List)
*/
public CompositeItemProcessorBuilder<I, O> delegates(ItemProcessor<?, ?>... delegates) {
return delegates(Arrays.asList(delegates));
}
/**
* Returns a fully constructed {@link CompositeItemProcessor}.
* @return a new {@link CompositeItemProcessor}
*/
public CompositeItemProcessor<I, O> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(delegates, "A list of delegates is required.");
Assert.notEmpty(delegates, "The delegates list must have one or more delegates.");
CompositeItemProcessor<I, O> processor = new CompositeItemProcessor<>();
processor.setDelegates(this.delegates);
return processor;
| 356
| 92
| 448
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/builder/CompositeItemWriterBuilder.java
|
CompositeItemWriterBuilder
|
build
|
class CompositeItemWriterBuilder<T> {
private List<ItemWriter<? super T>> delegates;
private boolean ignoreItemStream = false;
/**
* Establishes the policy whether to call the open, close, or update methods for the
* item writer delegates associated with the CompositeItemWriter.
* @param ignoreItemStream if false the delegates' open, close, or update methods will
* be called when the corresponding methods on the CompositeItemWriter are called. If
* true the delegates' open, close, nor update methods will not be called (default is
* false).
* @return this instance for method chaining.
*
* @see CompositeItemWriter#setIgnoreItemStream(boolean)
*/
public CompositeItemWriterBuilder<T> ignoreItemStream(boolean ignoreItemStream) {
this.ignoreItemStream = ignoreItemStream;
return this;
}
/**
* The list of item writers to use as delegates. Items are written to each of the
* delegates.
* @param delegates the list of delegates to use. The delegates list must not be null
* nor be empty.
* @return this instance for method chaining.
*
* @see CompositeItemWriter#setDelegates(List)
*/
public CompositeItemWriterBuilder<T> delegates(List<ItemWriter<? super T>> delegates) {
this.delegates = delegates;
return this;
}
/**
* The item writers to use as delegates. Items are written to each of the delegates.
* @param delegates the delegates to use.
* @return this instance for method chaining.
*
* @see CompositeItemWriter#setDelegates(List)
*/
@SafeVarargs
@SuppressWarnings("varargs")
public final CompositeItemWriterBuilder<T> delegates(ItemWriter<? super T>... delegates) {
return delegates(Arrays.asList(delegates));
}
/**
* Returns a fully constructed {@link CompositeItemWriter}.
* @return a new {@link CompositeItemWriter}
*/
public CompositeItemWriter<T> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(delegates, "A list of delegates is required.");
Assert.notEmpty(delegates, "The delegates list must have one or more delegates.");
CompositeItemWriter<T> writer = new CompositeItemWriter<>();
writer.setDelegates(this.delegates);
writer.setIgnoreItemStream(this.ignoreItemStream);
return writer;
| 554
| 106
| 660
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/builder/ScriptItemProcessorBuilder.java
|
ScriptItemProcessorBuilder
|
build
|
class ScriptItemProcessorBuilder<I, O> {
private String language;
private Resource scriptResource;
private String scriptSource;
private String itemBindingVariableName;
/**
* Sets the {@link org.springframework.core.io.Resource} location of the script to
* use. The script language will be deduced from the filename extension.
* @param resource the {@link org.springframework.core.io.Resource} location of the
* script to use.
* @return this instance for method chaining
* @see ScriptItemProcessor#setScript(Resource)
*
*/
public ScriptItemProcessorBuilder<I, O> scriptResource(Resource resource) {
this.scriptResource = resource;
return this;
}
/**
* Establishes the language of the script.
* @param language the language of the script.
* @return this instance for method chaining
* @see ScriptItemProcessor#setScriptSource(String, String)
*/
public ScriptItemProcessorBuilder<I, O> language(String language) {
this.language = language;
return this;
}
/**
* Sets the provided {@link String} as the script source code to use. Language must
* not be null nor empty when using script.
* @param scriptSource the {@link String} form of the script source code to use.
* @return this instance for method chaining
* @see ScriptItemProcessor#setScriptSource(String, String)
*/
public ScriptItemProcessorBuilder<I, O> scriptSource(String scriptSource) {
this.scriptSource = scriptSource;
return this;
}
/**
* Provides the ability to change the key name that scripts use to obtain the current
* item to process if the variable represented by:
* {@link ScriptItemProcessor#ITEM_BINDING_VARIABLE_NAME} is not suitable ("item").
* @param itemBindingVariableName the desired binding variable name
* @return this instance for method chaining
* @see ScriptItemProcessor#setItemBindingVariableName(String)
*/
public ScriptItemProcessorBuilder<I, O> itemBindingVariableName(String itemBindingVariableName) {
this.itemBindingVariableName = itemBindingVariableName;
return this;
}
/**
* Returns a fully constructed {@link ScriptItemProcessor}.
* @return a new {@link ScriptItemProcessor}
*/
public ScriptItemProcessor<I, O> build() {<FILL_FUNCTION_BODY>}
}
|
if (this.scriptResource == null && !StringUtils.hasText(this.scriptSource)) {
throw new IllegalArgumentException("scriptResource or scriptSource is required.");
}
if (StringUtils.hasText(this.scriptSource)) {
Assert.hasText(this.language, "language is required when using scriptSource.");
}
ScriptItemProcessor<I, O> processor = new ScriptItemProcessor<>();
if (StringUtils.hasText(this.itemBindingVariableName)) {
processor.setItemBindingVariableName(this.itemBindingVariableName);
}
if (this.scriptResource != null) {
processor.setScript(this.scriptResource);
}
if (this.scriptSource != null) {
processor.setScriptSource(this.scriptSource, this.language);
}
return processor;
| 605
| 217
| 822
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/builder/SingleItemPeekableItemReaderBuilder.java
|
SingleItemPeekableItemReaderBuilder
|
build
|
class SingleItemPeekableItemReaderBuilder<T> {
private ItemReader<T> delegate;
/**
* The item reader to use as a delegate. Items are read from the delegate and passed
* to the caller in
* {@link org.springframework.batch.item.support.SingleItemPeekableItemReader#read()}.
* @param delegate the delegate to set
* @return this instance for method chaining
* @see SingleItemPeekableItemReader#setDelegate(ItemReader)
*/
public SingleItemPeekableItemReaderBuilder<T> delegate(ItemReader<T> delegate) {
this.delegate = delegate;
return this;
}
/**
* Returns a fully constructed {@link SingleItemPeekableItemReader}.
* @return a new {@link SingleItemPeekableItemReader}
*/
public SingleItemPeekableItemReader<T> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(this.delegate, "A delegate is required");
SingleItemPeekableItemReader<T> reader = new SingleItemPeekableItemReader<>();
reader.setDelegate(this.delegate);
return reader;
| 236
| 68
| 304
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/builder/SynchronizedItemStreamReaderBuilder.java
|
SynchronizedItemStreamReaderBuilder
|
build
|
class SynchronizedItemStreamReaderBuilder<T> {
private ItemStreamReader<T> delegate;
/**
* The item stream reader to use as a delegate. Items are read from the delegate and
* passed to the caller in
* {@link org.springframework.batch.item.support.SynchronizedItemStreamReader#read()}.
* @param delegate the delegate to set
* @return this instance for method chaining
* @see SynchronizedItemStreamReader#setDelegate(ItemStreamReader)
*/
public SynchronizedItemStreamReaderBuilder<T> delegate(ItemStreamReader<T> delegate) {
this.delegate = delegate;
return this;
}
/**
* Returns a fully constructed {@link SynchronizedItemStreamReader}.
* @return a new {@link SynchronizedItemStreamReader}
*/
public SynchronizedItemStreamReader<T> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(this.delegate, "A delegate is required");
SynchronizedItemStreamReader<T> reader = new SynchronizedItemStreamReader<>();
reader.setDelegate(this.delegate);
return reader;
| 233
| 66
| 299
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/builder/SynchronizedItemStreamWriterBuilder.java
|
SynchronizedItemStreamWriterBuilder
|
build
|
class SynchronizedItemStreamWriterBuilder<T> {
private ItemStreamWriter<T> delegate;
/**
* Set the delegate {@link ItemStreamWriter}.
* @param delegate the delegate to set
* @return this instance for method chaining
*/
public SynchronizedItemStreamWriterBuilder<T> delegate(ItemStreamWriter<T> delegate) {
this.delegate = delegate;
return this;
}
/**
* Returns a fully constructed {@link SynchronizedItemStreamWriter}.
* @return a new {@link SynchronizedItemStreamWriter}
*/
public SynchronizedItemStreamWriter<T> build() {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(this.delegate, "A delegate item writer is required");
SynchronizedItemStreamWriter<T> writer = new SynchronizedItemStreamWriter<>();
writer.setDelegate(this.delegate);
return writer;
| 171
| 68
| 239
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/util/FileUtils.java
|
FileUtils
|
setUpOutputFile
|
class FileUtils {
// forbids instantiation
private FileUtils() {
}
/**
* Set up output file for batch processing. This method implements common logic for
* handling output files when starting or restarting file I/O. When starting output
* file processing, creates/overwrites new file. When restarting output file
* processing, checks whether file is writable.
* @param file file to be set up
* @param restarted true signals that we are restarting output file processing
* @param append true signals input file may already exist (but doesn't have to)
* @param overwriteOutputFile If set to true, output file will be overwritten (this
* flag is ignored when processing is restart)
*/
public static void setUpOutputFile(File file, boolean restarted, boolean append, boolean overwriteOutputFile) {<FILL_FUNCTION_BODY>}
/**
* Create a new file if it doesn't already exist.
* @param file the file to create on the filesystem
* @return true if file was created else false.
* @throws IOException is thrown if error occurs during creation and file does not
* exist.
*/
public static boolean createNewFile(File file) throws IOException {
if (file.exists()) {
return false;
}
try {
return file.createNewFile() && file.exists();
}
catch (IOException e) {
// On some file systems you can get an exception here even though the
// files was successfully created
if (file.exists()) {
return true;
}
else {
throw e;
}
}
}
}
|
Assert.notNull(file, "An output file is required");
try {
if (!restarted) {
if (!append) {
if (file.exists()) {
if (!overwriteOutputFile) {
throw new ItemStreamException("File already exists: [" + file.getAbsolutePath() + "]");
}
if (!file.delete()) {
throw new IOException("Could not delete file: " + file);
}
}
if (file.getParent() != null) {
new File(file.getParent()).mkdirs();
}
if (!createNewFile(file)) {
throw new ItemStreamException("Output file was not created: [" + file.getAbsolutePath() + "]");
}
}
else {
if (!file.exists()) {
if (file.getParent() != null) {
new File(file.getParent()).mkdirs();
}
if (!createNewFile(file)) {
throw new ItemStreamException(
"Output file was not created: [" + file.getAbsolutePath() + "]");
}
}
}
}
}
catch (IOException ioe) {
throw new ItemStreamException("Unable to create file: [" + file.getAbsolutePath() + "]", ioe);
}
if (!file.canWrite()) {
throw new ItemStreamException("File is not writable: [" + file.getAbsolutePath() + "]");
}
| 408
| 388
| 796
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/validator/BeanValidatingItemProcessor.java
|
BeanValidatingItemProcessor
|
afterPropertiesSet
|
class BeanValidatingItemProcessor<T> extends ValidatingItemProcessor<T> {
private final Validator validator;
/**
* Create a new instance of {@link BeanValidatingItemProcessor} with the default
* configuration.
*/
public BeanValidatingItemProcessor() {
try (LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean()) {
localValidatorFactoryBean.afterPropertiesSet();
this.validator = localValidatorFactoryBean.getValidator();
}
}
/**
* Create a new instance of {@link BeanValidatingItemProcessor}.
* @param localValidatorFactoryBean used to configure the Bean Validation validator
*/
public BeanValidatingItemProcessor(LocalValidatorFactoryBean localValidatorFactoryBean) {
Assert.notNull(localValidatorFactoryBean, "localValidatorFactoryBean must not be null");
this.validator = localValidatorFactoryBean.getValidator();
}
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
}
|
SpringValidatorAdapter springValidatorAdapter = new SpringValidatorAdapter(this.validator);
SpringValidator<T> springValidator = new SpringValidator<>();
springValidator.setValidator(springValidatorAdapter);
springValidator.afterPropertiesSet();
setValidator(springValidator);
super.afterPropertiesSet();
| 253
| 82
| 335
|
<methods>public void <init>() ,public void <init>(Validator<? super T>) ,public void afterPropertiesSet() throws java.lang.Exception,public T process(T) throws org.springframework.batch.item.validator.ValidationException,public void setFilter(boolean) ,public void setValidator(Validator<? super T>) <variables>private boolean filter,private Validator<? super T> validator
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/validator/SpringValidator.java
|
SpringValidator
|
appendCollection
|
class SpringValidator<T> implements Validator<T>, InitializingBean {
private org.springframework.validation.Validator validator;
/**
* @see Validator#validate(Object)
*/
@Override
public void validate(T item) throws ValidationException {
if (!validator.supports(item.getClass())) {
throw new ValidationException("Validation failed for " + item + ": " + item.getClass().getName()
+ " class is not supported by validator.");
}
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(item, "item");
validator.validate(item, errors);
if (errors.hasErrors()) {
throw new ValidationException("Validation failed for " + item + ": " + errorsToString(errors),
new BindException(errors));
}
}
/**
* @return string of field errors followed by global errors.
*/
private String errorsToString(Errors errors) {
StringBuilder builder = new StringBuilder();
appendCollection(errors.getFieldErrors(), builder);
appendCollection(errors.getGlobalErrors(), builder);
return builder.toString();
}
/**
* Append the string representation of elements of the collection (separated by new
* lines) to the given StringBuilder.
*/
private void appendCollection(Collection<?> collection, StringBuilder builder) {<FILL_FUNCTION_BODY>}
public void setValidator(org.springframework.validation.Validator validator) {
this.validator = validator;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(validator != null, "validator must be set");
}
}
|
for (Object value : collection) {
builder.append("\n");
builder.append(value.toString());
}
| 423
| 36
| 459
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/validator/ValidatingItemProcessor.java
|
ValidatingItemProcessor
|
process
|
class ValidatingItemProcessor<T> implements ItemProcessor<T, T>, InitializingBean {
private Validator<? super T> validator;
private boolean filter = false;
/**
* Default constructor
*/
public ValidatingItemProcessor() {
}
/**
* Creates a ValidatingItemProcessor based on the given Validator.
* @param validator the {@link Validator} instance to be used.
*/
public ValidatingItemProcessor(Validator<? super T> validator) {
this.validator = validator;
}
/**
* Set the validator used to validate each item.
* @param validator the {@link Validator} instance to be used.
*/
public void setValidator(Validator<? super T> validator) {
this.validator = validator;
}
/**
* Should the processor filter invalid records instead of skipping them?
* @param filter if set to {@code true}, items that fail validation are filtered
* ({@code null} is returned). Otherwise, a {@link ValidationException} will be
* thrown.
*/
public void setFilter(boolean filter) {
this.filter = filter;
}
/**
* Validate the item and return it unmodified
* @return the input item
* @throws ValidationException if validation fails
*/
@Nullable
@Override
public T process(T item) throws ValidationException {<FILL_FUNCTION_BODY>}
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(validator != null, "Validator must not be null.");
}
}
|
try {
validator.validate(item);
}
catch (ValidationException e) {
if (filter) {
return null; // filter the item
}
else {
throw e; // skip the item
}
}
return item;
| 395
| 75
| 470
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/builder/StaxEventItemReaderBuilder.java
|
StaxEventItemReaderBuilder
|
build
|
class StaxEventItemReaderBuilder<T> {
protected Log logger = LogFactory.getLog(getClass());
private boolean strict = true;
private Resource resource;
private Unmarshaller unmarshaller;
private final List<String> fragmentRootElements = new ArrayList<>();
private boolean saveState = true;
private String name;
private int maxItemCount = Integer.MAX_VALUE;
private int currentItemCount;
private XMLInputFactory xmlInputFactory = StaxUtils.createDefensiveInputFactory();
private String encoding = StaxEventItemReader.DEFAULT_ENCODING;
/**
* Configure if the state of the
* {@link org.springframework.batch.item.ItemStreamSupport} should be persisted within
* the {@link org.springframework.batch.item.ExecutionContext} for restart purposes.
* @param saveState defaults to true
* @return The current instance of the builder.
*/
public StaxEventItemReaderBuilder<T> saveState(boolean saveState) {
this.saveState = saveState;
return this;
}
/**
* The name used to calculate the key within the
* {@link org.springframework.batch.item.ExecutionContext}. Required if
* {@link #saveState(boolean)} is set to true.
* @param name name of the reader instance
* @return The current instance of the builder.
* @see org.springframework.batch.item.ItemStreamSupport#setName(String)
*/
public StaxEventItemReaderBuilder<T> name(String name) {
this.name = name;
return this;
}
/**
* Configure the max number of items to be read.
* @param maxItemCount the max items to be read
* @return The current instance of the builder.
* @see org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader#setMaxItemCount(int)
*/
public StaxEventItemReaderBuilder<T> maxItemCount(int maxItemCount) {
this.maxItemCount = maxItemCount;
return this;
}
/**
* Index for the current item. Used on restarts to indicate where to start from.
* @param currentItemCount current index
* @return this instance for method chaining
* @see org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader#setCurrentItemCount(int)
*/
public StaxEventItemReaderBuilder<T> currentItemCount(int currentItemCount) {
this.currentItemCount = currentItemCount;
return this;
}
/**
* The {@link Resource} to be used as input.
* @param resource the input to the reader.
* @return The current instance of the builder.
* @see StaxEventItemReader#setResource(Resource)
*/
public StaxEventItemReaderBuilder<T> resource(Resource resource) {
this.resource = resource;
return this;
}
/**
* An implementation of the {@link Unmarshaller} from Spring's OXM module.
* @param unmarshaller component responsible for unmarshalling XML chunks
* @return The current instance of the builder.
* @see StaxEventItemReader#setUnmarshaller
*/
public StaxEventItemReaderBuilder<T> unmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
return this;
}
/**
* Adds the list of fragments to be used as the root of each chunk to the
* configuration.
* @param fragmentRootElements the XML root elements to be used to identify XML
* chunks.
* @return The current instance of the builder.
* @see StaxEventItemReader#setFragmentRootElementNames(String[])
*/
public StaxEventItemReaderBuilder<T> addFragmentRootElements(String... fragmentRootElements) {
this.fragmentRootElements.addAll(Arrays.asList(fragmentRootElements));
return this;
}
/**
* Adds the list of fragments to be used as the root of each chunk to the
* configuration.
* @param fragmentRootElements the XML root elements to be used to identify XML
* chunks.
* @return The current instance of the builder.
* @see StaxEventItemReader#setFragmentRootElementNames(String[])
*/
public StaxEventItemReaderBuilder<T> addFragmentRootElements(List<String> fragmentRootElements) {
this.fragmentRootElements.addAll(fragmentRootElements);
return this;
}
/**
* Setting this value to true indicates that it is an error if the input does not
* exist and an exception will be thrown. Defaults to true.
* @param strict indicates the input file must exist
* @return The current instance of the builder
* @see StaxEventItemReader#setStrict(boolean)
*/
public StaxEventItemReaderBuilder<T> strict(boolean strict) {
this.strict = strict;
return this;
}
/**
* Set the {@link XMLInputFactory}.
* @param xmlInputFactory to use
* @return The current instance of the builder
* @see StaxEventItemReader#setXmlInputFactory(XMLInputFactory)
*/
public StaxEventItemReaderBuilder<T> xmlInputFactory(XMLInputFactory xmlInputFactory) {
this.xmlInputFactory = xmlInputFactory;
return this;
}
/**
* Encoding for the input file. Defaults to
* {@link StaxEventItemReader#DEFAULT_ENCODING}. Can be {@code null}, in which case
* the XML event reader will attempt to auto-detect the encoding from tht input file.
* @param encoding String encoding algorithm
* @return the current instance of the builder
* @see StaxEventItemReader#setEncoding(String)
*/
public StaxEventItemReaderBuilder<T> encoding(@Nullable String encoding) {
this.encoding = encoding;
return this;
}
/**
* Validates the configuration and builds a new {@link StaxEventItemReader}
* @return a new instance of the {@link StaxEventItemReader}
*/
public StaxEventItemReader<T> build() {<FILL_FUNCTION_BODY>}
}
|
StaxEventItemReader<T> reader = new StaxEventItemReader<>();
if (this.resource == null) {
logger.debug("The resource is null. This is only a valid scenario when "
+ "injecting resource later as in when using the MultiResourceItemReader");
}
if (this.saveState) {
Assert.state(StringUtils.hasText(this.name), "A name is required when saveState is set to true.");
}
Assert.notEmpty(this.fragmentRootElements, "At least one fragment root element is required");
reader.setName(this.name);
reader.setSaveState(this.saveState);
reader.setResource(this.resource);
reader.setFragmentRootElementNames(
this.fragmentRootElements.toArray(new String[this.fragmentRootElements.size()]));
reader.setStrict(this.strict);
reader.setUnmarshaller(this.unmarshaller);
reader.setCurrentItemCount(this.currentItemCount);
reader.setMaxItemCount(this.maxItemCount);
reader.setXmlInputFactory(this.xmlInputFactory);
reader.setEncoding(this.encoding);
return reader;
| 1,547
| 319
| 1,866
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/stax/DefaultFragmentEventReader.java
|
DefaultFragmentEventReader
|
alterEvent
|
class DefaultFragmentEventReader extends AbstractEventReaderWrapper implements FragmentEventReader {
// true when the next event is the StartElement of next fragment
private boolean startFragmentFollows = false;
// true when the next event is the EndElement of current fragment
private boolean endFragmentFollows = false;
// true while cursor is inside fragment
private boolean insideFragment = false;
// true when reader should behave like the cursor was at the end of document
private boolean fakeDocumentEnd = false;
private final StartDocument startDocumentEvent;
private final EndDocument endDocumentEvent;
// fragment root name is remembered so that the matching closing element can
// be identified
private QName fragmentRootName = null;
// counts the occurrences of current fragmentRootName (increased for
// StartElement, decreased for EndElement)
private int matchCounter = 0;
/**
* Caches the StartDocument event for later use.
* @param wrappedEventReader the original wrapped event reader
*/
public DefaultFragmentEventReader(XMLEventReader wrappedEventReader) {
super(wrappedEventReader);
try {
startDocumentEvent = (StartDocument) wrappedEventReader.peek();
}
catch (XMLStreamException e) {
throw new ItemStreamException("Error reading start document from event reader", e);
}
endDocumentEvent = XMLEventFactory.newInstance().createEndDocument();
}
@Override
public void markStartFragment() {
startFragmentFollows = true;
fragmentRootName = null;
}
@Override
public boolean hasNext() {
try {
if (peek() != null) {
return true;
}
}
catch (XMLStreamException e) {
throw new ItemStreamException("Error reading XML stream", e);
}
return false;
}
@Override
public Object next() {
try {
return nextEvent();
}
catch (XMLStreamException e) {
throw new ItemStreamException("Error reading XML stream", e);
}
}
@Override
public XMLEvent nextEvent() throws XMLStreamException {
if (fakeDocumentEnd) {
throw new NoSuchElementException();
}
XMLEvent event = wrappedEventReader.peek();
XMLEvent proxyEvent = alterEvent(event, false);
checkFragmentEnd(proxyEvent);
if (event == proxyEvent) {
wrappedEventReader.nextEvent();
}
return proxyEvent;
}
/**
* Sets the endFragmentFollows flag to true if next event is the last event of the
* fragment.
* @param event peek() from wrapped event reader
*/
private void checkFragmentEnd(XMLEvent event) {
if (event.isStartElement() && ((StartElement) event).getName().equals(fragmentRootName)) {
matchCounter++;
}
else if (event.isEndElement() && ((EndElement) event).getName().equals(fragmentRootName)) {
matchCounter--;
if (matchCounter == 0) {
endFragmentFollows = true;
}
}
}
/**
* @param event peek() from wrapped event reader
* @param peek if true do not change the internal state
* @return StartDocument event if peek() points to beginning of fragment EndDocument
* event if cursor is right behind the end of fragment original event otherwise
*/
private XMLEvent alterEvent(XMLEvent event, boolean peek) {<FILL_FUNCTION_BODY>}
@Override
public XMLEvent peek() throws XMLStreamException {
if (fakeDocumentEnd) {
return null;
}
return alterEvent(wrappedEventReader.peek(), true);
}
/**
* Finishes reading the fragment in case the fragment was processed without being read
* until the end.
*/
@Override
public void markFragmentProcessed() {
if (insideFragment || startFragmentFollows) {
try {
while (!(nextEvent() instanceof EndDocument)) {
// just read all events until EndDocument
}
}
catch (XMLStreamException e) {
throw new ItemStreamException("Error reading XML stream", e);
}
}
fakeDocumentEnd = false;
}
@Override
public void reset() {
insideFragment = false;
startFragmentFollows = false;
endFragmentFollows = false;
fakeDocumentEnd = false;
fragmentRootName = null;
matchCounter = 0;
}
}
|
if (startFragmentFollows) {
fragmentRootName = ((StartElement) event).getName();
if (!peek) {
startFragmentFollows = false;
insideFragment = true;
}
return startDocumentEvent;
}
else if (endFragmentFollows) {
if (!peek) {
endFragmentFollows = false;
insideFragment = false;
fakeDocumentEnd = true;
}
return endDocumentEvent;
}
return event;
| 1,132
| 133
| 1,265
|
<methods>public void <init>(javax.xml.stream.XMLEventReader) ,public void close() throws javax.xml.stream.XMLStreamException,public java.lang.String getElementText() throws javax.xml.stream.XMLStreamException,public java.lang.Object getProperty(java.lang.String) throws java.lang.IllegalArgumentException,public boolean hasNext() ,public java.lang.Object next() ,public javax.xml.stream.events.XMLEvent nextEvent() throws javax.xml.stream.XMLStreamException,public javax.xml.stream.events.XMLEvent nextTag() throws javax.xml.stream.XMLStreamException,public javax.xml.stream.events.XMLEvent peek() throws javax.xml.stream.XMLStreamException,public void remove() <variables>protected javax.xml.stream.XMLEventReader wrappedEventReader
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/stax/UnclosedElementCollectingEventWriter.java
|
UnclosedElementCollectingEventWriter
|
add
|
class UnclosedElementCollectingEventWriter extends AbstractEventWriterWrapper {
private final LinkedList<QName> unclosedElements = new LinkedList<>();
public UnclosedElementCollectingEventWriter(XMLEventWriter wrappedEventWriter) {
super(wrappedEventWriter);
}
@Override
public void add(XMLEvent event) throws XMLStreamException {<FILL_FUNCTION_BODY>}
public List<QName> getUnclosedElements() {
return unclosedElements;
}
}
|
if (event.isStartElement()) {
unclosedElements.addLast(event.asStartElement().getName());
}
else if (event.isEndElement()) {
unclosedElements.removeLast();
}
super.add(event);
| 125
| 69
| 194
|
<methods>public void <init>(javax.xml.stream.XMLEventWriter) ,public void add(javax.xml.stream.events.XMLEvent) throws javax.xml.stream.XMLStreamException,public void add(javax.xml.stream.XMLEventReader) throws javax.xml.stream.XMLStreamException,public void close() throws javax.xml.stream.XMLStreamException,public void flush() throws javax.xml.stream.XMLStreamException,public javax.xml.namespace.NamespaceContext getNamespaceContext() ,public java.lang.String getPrefix(java.lang.String) throws javax.xml.stream.XMLStreamException,public void setDefaultNamespace(java.lang.String) throws javax.xml.stream.XMLStreamException,public void setNamespaceContext(javax.xml.namespace.NamespaceContext) throws javax.xml.stream.XMLStreamException,public void setPrefix(java.lang.String, java.lang.String) throws javax.xml.stream.XMLStreamException<variables>protected javax.xml.stream.XMLEventWriter wrappedEventWriter
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/stax/UnopenedElementClosingEventWriter.java
|
UnopenedElementClosingEventWriter
|
add
|
class UnopenedElementClosingEventWriter extends AbstractEventWriterWrapper {
private final LinkedList<QName> unopenedElements;
private final Writer ioWriter;
public UnopenedElementClosingEventWriter(XMLEventWriter wrappedEventWriter, Writer ioWriter,
List<QName> unopenedElements) {
super(wrappedEventWriter);
this.unopenedElements = new LinkedList<>(unopenedElements);
this.ioWriter = ioWriter;
}
@Override
public void add(XMLEvent event) throws XMLStreamException {<FILL_FUNCTION_BODY>}
private boolean isUnopenedElementCloseEvent(XMLEvent event) {
if (unopenedElements.isEmpty()) {
return false;
}
else if (!event.isEndElement()) {
return false;
}
else {
return unopenedElements.getLast().equals(event.asEndElement().getName());
}
}
}
|
if (isUnopenedElementCloseEvent(event)) {
QName element = unopenedElements.removeLast();
String nsPrefix = !StringUtils.hasText(element.getPrefix()) ? "" : element.getPrefix() + ":";
try {
super.flush();
ioWriter.write("</" + nsPrefix + element.getLocalPart() + ">");
ioWriter.flush();
}
catch (IOException ioe) {
throw new XMLStreamException("Unable to close tag: " + element, ioe);
}
}
else {
super.add(event);
}
| 245
| 164
| 409
|
<methods>public void <init>(javax.xml.stream.XMLEventWriter) ,public void add(javax.xml.stream.events.XMLEvent) throws javax.xml.stream.XMLStreamException,public void add(javax.xml.stream.XMLEventReader) throws javax.xml.stream.XMLStreamException,public void close() throws javax.xml.stream.XMLStreamException,public void flush() throws javax.xml.stream.XMLStreamException,public javax.xml.namespace.NamespaceContext getNamespaceContext() ,public java.lang.String getPrefix(java.lang.String) throws javax.xml.stream.XMLStreamException,public void setDefaultNamespace(java.lang.String) throws javax.xml.stream.XMLStreamException,public void setNamespaceContext(javax.xml.namespace.NamespaceContext) throws javax.xml.stream.XMLStreamException,public void setPrefix(java.lang.String, java.lang.String) throws javax.xml.stream.XMLStreamException<variables>protected javax.xml.stream.XMLEventWriter wrappedEventWriter
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/poller/DirectPoller.java
|
DirectPollingFuture
|
get
|
class DirectPollingFuture<S> implements Future<S> {
private final long startTime = System.currentTimeMillis();
private volatile boolean cancelled;
private volatile S result = null;
private final long interval;
private final Callable<S> callable;
public DirectPollingFuture(long interval, Callable<S> callable) {
this.interval = interval;
this.callable = callable;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
cancelled = true;
return true;
}
@Override
public S get() throws InterruptedException, ExecutionException {
try {
return get(-1, TimeUnit.MILLISECONDS);
}
catch (TimeoutException e) {
throw new IllegalStateException("Unexpected timeout waiting for result", e);
}
}
@Override
public S get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {<FILL_FUNCTION_BODY>}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public boolean isDone() {
return cancelled || result != null;
}
}
|
try {
result = callable.call();
}
catch (Exception e) {
throw new ExecutionException(e);
}
long nextExecutionTime = startTime + interval;
long currentTimeMillis = System.currentTimeMillis();
long timeoutMillis = TimeUnit.MILLISECONDS.convert(timeout, unit);
while (result == null && !cancelled) {
long delta = nextExecutionTime - startTime;
if (delta >= timeoutMillis && timeoutMillis > 0) {
throw new TimeoutException("Timed out waiting for task to return non-null result");
}
if (nextExecutionTime > currentTimeMillis) {
Thread.sleep(nextExecutionTime - currentTimeMillis);
}
currentTimeMillis = System.currentTimeMillis();
nextExecutionTime = currentTimeMillis + interval;
try {
result = callable.call();
}
catch (Exception e) {
throw new ExecutionException(e);
}
}
return result;
| 324
| 287
| 611
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/context/RepeatContextSupport.java
|
RepeatContextSupport
|
close
|
class RepeatContextSupport extends SynchronizedAttributeAccessor implements RepeatContext {
private final RepeatContext parent;
private int count;
private volatile boolean completeOnly;
private volatile boolean terminateOnly;
private final Map<String, Set<Runnable>> callbacks = new HashMap<>();
/**
* Constructor for {@link RepeatContextSupport}. The parent can be null, but should be
* set to the enclosing repeat context if there is one, e.g. if this context is an
* inner loop.
* @param parent {@link RepeatContext} to be used as the parent context.
*/
public RepeatContextSupport(RepeatContext parent) {
super();
this.parent = parent;
}
@Override
public boolean isCompleteOnly() {
return completeOnly;
}
@Override
public void setCompleteOnly() {
completeOnly = true;
}
@Override
public boolean isTerminateOnly() {
return terminateOnly;
}
@Override
public void setTerminateOnly() {
terminateOnly = true;
setCompleteOnly();
}
@Override
public RepeatContext getParent() {
return parent;
}
/**
* Used by clients to increment the started count.
*/
public synchronized void increment() {
count++;
}
@Override
public synchronized int getStartedCount() {
return count;
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
synchronized (callbacks) {
Set<Runnable> set = callbacks.computeIfAbsent(name, k -> new HashSet<>());
set.add(callback);
}
}
@Override
public void close() {<FILL_FUNCTION_BODY>}
}
|
List<RuntimeException> errors = new ArrayList<>();
Set<Map.Entry<String, Set<Runnable>>> copy;
synchronized (callbacks) {
copy = new HashSet<>(callbacks.entrySet());
}
for (Map.Entry<String, Set<Runnable>> entry : copy) {
for (Runnable callback : entry.getValue()) {
/*
* Potentially we could check here if there is an attribute with the given
* name - if it has been removed, maybe the callback is invalid. On the
* other hand it is less surprising for the callback register if it is
* always executed.
*/
if (callback != null) {
/*
* The documentation of the interface says that these callbacks must
* not throw exceptions, but we don't trust them necessarily...
*/
try {
callback.run();
}
catch (RuntimeException t) {
errors.add(t);
}
}
}
}
if (errors.isEmpty()) {
return;
}
throw errors.get(0);
| 449
| 289
| 738
|
<methods>public non-sealed void <init>() ,public java.lang.String[] attributeNames() ,public boolean equals(java.lang.Object) ,public java.lang.Object getAttribute(java.lang.String) ,public boolean hasAttribute(java.lang.String) ,public int hashCode() ,public java.lang.Object removeAttribute(java.lang.String) ,public void setAttribute(java.lang.String, java.lang.Object) ,public java.lang.Object setAttributeIfAbsent(java.lang.String, java.lang.Object) ,public java.lang.String toString() <variables>org.springframework.core.AttributeAccessorSupport support
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/context/SynchronizedAttributeAccessor.java
|
SynchronizedAttributeAccessor
|
toString
|
class SynchronizedAttributeAccessor implements AttributeAccessor {
/**
* All methods are delegated to this support object.
*/
AttributeAccessorSupport support = new AttributeAccessorSupport() {
/**
* Generated serial UID.
*/
private static final long serialVersionUID = -7664290016506582290L;
};
@Override
public String[] attributeNames() {
synchronized (support) {
return support.attributeNames();
}
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
AttributeAccessorSupport that;
if (other instanceof SynchronizedAttributeAccessor) {
that = ((SynchronizedAttributeAccessor) other).support;
}
else if (other instanceof AttributeAccessorSupport) {
that = (AttributeAccessorSupport) other;
}
else {
return false;
}
synchronized (support) {
return support.equals(that);
}
}
@Override
public Object getAttribute(String name) {
synchronized (support) {
return support.getAttribute(name);
}
}
@Override
public boolean hasAttribute(String name) {
synchronized (support) {
return support.hasAttribute(name);
}
}
@Override
public int hashCode() {
return support.hashCode();
}
@Override
public Object removeAttribute(String name) {
synchronized (support) {
return support.removeAttribute(name);
}
}
@Override
public void setAttribute(String name, Object value) {
synchronized (support) {
support.setAttribute(name, value);
}
}
/**
* Additional support for atomic put if absent.
* @param name the key for the attribute name
* @param value the value of the attribute
* @return null if the attribute was not already set, the existing value otherwise.
*/
@Nullable
public Object setAttributeIfAbsent(String name, Object value) {
synchronized (support) {
Object old = getAttribute(name);
if (old != null) {
return old;
}
setAttribute(name, value);
}
return null;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder buffer = new StringBuilder("SynchronizedAttributeAccessor: [");
synchronized (support) {
String[] names = attributeNames();
for (int i = 0; i < names.length; i++) {
String name = names[i];
buffer.append(names[i]).append("=").append(getAttribute(name));
if (i < names.length - 1) {
buffer.append(", ");
}
}
buffer.append("]");
return buffer.toString();
}
| 611
| 139
| 750
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/exception/CompositeExceptionHandler.java
|
CompositeExceptionHandler
|
handleException
|
class CompositeExceptionHandler implements ExceptionHandler {
private ExceptionHandler[] handlers = new ExceptionHandler[0];
public void setHandlers(ExceptionHandler[] handlers) {
this.handlers = Arrays.asList(handlers).toArray(new ExceptionHandler[handlers.length]);
}
/**
* Iterate over the handlers delegating the call to each in turn. The chain ends if an
* exception is thrown.
*
* @see ExceptionHandler#handleException(RepeatContext, Throwable)
*/
@Override
public void handleException(RepeatContext context, Throwable throwable) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
for (ExceptionHandler handler : handlers) {
handler.handleException(context, throwable);
}
| 168
| 31
| 199
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/exception/LogOrRethrowExceptionHandler.java
|
LogOrRethrowExceptionHandler
|
handleException
|
class LogOrRethrowExceptionHandler implements ExceptionHandler {
/**
* Logging levels for the handler.
*
* @author Dave Syer
*
*/
public enum Level {
/**
* Key for {@link Classifier} signalling that the throwable should be rethrown. If
* the throwable is not a RuntimeException it is wrapped in a
* {@link RepeatException}.
*/
RETHROW,
/**
* Key for {@link Classifier} signalling that the throwable should be logged at
* debug level.
*/
DEBUG,
/**
* Key for {@link Classifier} signalling that the throwable should be logged at
* warn level.
*/
WARN,
/**
* Key for {@link Classifier} signalling that the throwable should be logged at
* error level.
*/
ERROR
}
protected final Log logger = LogFactory.getLog(LogOrRethrowExceptionHandler.class);
private Classifier<Throwable, Level> exceptionClassifier = new ClassifierSupport<>(Level.RETHROW);
/**
* Setter for the {@link Classifier} used by this handler. The default is to map all
* throwable instances to {@link Level#RETHROW}.
* @param exceptionClassifier the ExceptionClassifier to use
*/
public void setExceptionClassifier(Classifier<Throwable, Level> exceptionClassifier) {
this.exceptionClassifier = exceptionClassifier;
}
/**
* Classify the throwables and decide whether to rethrow based on the result. The
* context is not used.
* @throws Throwable thrown if
* {@link LogOrRethrowExceptionHandler#exceptionClassifier} is classified as
* {@link Level#RETHROW}.
*
* @see ExceptionHandler#handleException(RepeatContext, Throwable)
*/
@Override
public void handleException(RepeatContext context, Throwable throwable) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
Level key = exceptionClassifier.classify(throwable);
if (Level.ERROR.equals(key)) {
logger.error("Exception encountered in batch repeat.", throwable);
}
else if (Level.WARN.equals(key)) {
logger.warn("Exception encountered in batch repeat.", throwable);
}
else if (Level.DEBUG.equals(key) && logger.isDebugEnabled()) {
logger.debug("Exception encountered in batch repeat.", throwable);
}
else if (Level.RETHROW.equals(key)) {
throw throwable;
}
| 508
| 153
| 661
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/exception/RethrowOnThresholdExceptionHandler.java
|
RethrowOnThresholdExceptionHandler
|
getCounter
|
class RethrowOnThresholdExceptionHandler implements ExceptionHandler {
protected static final IntegerHolder ZERO = new IntegerHolder(0);
protected final Log logger = LogFactory.getLog(RethrowOnThresholdExceptionHandler.class);
private Classifier<? super Throwable, IntegerHolder> exceptionClassifier = (Classifier<Throwable, IntegerHolder>) classifiable -> ZERO;
private boolean useParent = false;
/**
* Flag to indicate the exception counters should be shared between sibling contexts
* in a nested batch. Default is false.
* @param useParent true if the parent context should be used to store the counters.
*/
public void setUseParent(boolean useParent) {
this.useParent = useParent;
}
/**
* Set up the exception handler. Creates a default exception handler and threshold
* that maps all exceptions to a threshold of 0 - all exceptions are rethrown by
* default.
*/
public RethrowOnThresholdExceptionHandler() {
super();
}
/**
* A map from exception classes to a threshold value of type Integer.
* @param thresholds the threshold value map.
*/
public void setThresholds(Map<Class<? extends Throwable>, Integer> thresholds) {
Map<Class<? extends Throwable>, IntegerHolder> typeMap = new HashMap<>();
for (Entry<Class<? extends Throwable>, Integer> entry : thresholds.entrySet()) {
typeMap.put(entry.getKey(), new IntegerHolder(entry.getValue()));
}
exceptionClassifier = new SubclassClassifier<>(typeMap, ZERO);
}
/**
* Classify the throwables and decide whether to re-throw based on the result. The
* context is used to accumulate the number of exceptions of the same type according
* to the classifier.
* @throws Throwable is thrown if number of exceptions exceeds threshold.
* @see ExceptionHandler#handleException(RepeatContext, Throwable)
*/
@Override
public void handleException(RepeatContext context, Throwable throwable) throws Throwable {
IntegerHolder key = exceptionClassifier.classify(throwable);
RepeatContextCounter counter = getCounter(context, key);
counter.increment();
int count = counter.getCount();
int threshold = key.getValue();
if (count > threshold) {
throw throwable;
}
}
private RepeatContextCounter getCounter(RepeatContext context, IntegerHolder key) {<FILL_FUNCTION_BODY>}
/**
* @author Dave Syer
*
*/
private static class IntegerHolder {
private final int value;
/**
* @param value value within holder
*/
public IntegerHolder(int value) {
this.value = value;
}
/**
* Public getter for the value.
* @return the value
*/
public int getValue() {
return value;
}
@Override
public String toString() {
return ObjectUtils.getIdentityHexString(this) + "." + value;
}
}
}
|
String attribute = RethrowOnThresholdExceptionHandler.class.getName() + "." + key;
// Creates a new counter and stores it in the correct context:
return new RepeatContextCounter(context, attribute, useParent);
| 794
| 59
| 853
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/exception/SimpleLimitExceptionHandler.java
|
SimpleLimitExceptionHandler
|
afterPropertiesSet
|
class SimpleLimitExceptionHandler implements ExceptionHandler, InitializingBean {
private final RethrowOnThresholdExceptionHandler delegate = new RethrowOnThresholdExceptionHandler();
private Collection<Class<? extends Throwable>> exceptionClasses = Collections
.<Class<? extends Throwable>>singleton(Exception.class);
private Collection<Class<? extends Throwable>> fatalExceptionClasses = Collections
.<Class<? extends Throwable>>singleton(Error.class);
private int limit = 0;
/**
* Apply the provided properties to create a delegate handler.
*
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
/**
* Flag to indicate the exception counters should be shared between sibling contexts
* in a nested batch (i.e. inner loop). Default is false. Set this flag to true if you
* want to count exceptions for the whole (outer) loop in a typical container.
* @param useParent true if the parent context should be used to store the counters.
*/
public void setUseParent(boolean useParent) {
delegate.setUseParent(useParent);
}
/**
* Convenience constructor for the {@link SimpleLimitExceptionHandler} to set the
* limit.
* @param limit the limit
*/
public SimpleLimitExceptionHandler(int limit) {
this();
this.limit = limit;
}
/**
* Default constructor for the {@link SimpleLimitExceptionHandler}.
*/
public SimpleLimitExceptionHandler() {
super();
}
/**
* Rethrows only if the limit is breached for this context on the exception type
* specified.
*
* @see #setExceptionClasses(Collection)
* @see #setLimit(int)
*
* @see org.springframework.batch.repeat.exception.ExceptionHandler#handleException(org.springframework.batch.repeat.RepeatContext,
* Throwable)
*/
@Override
public void handleException(RepeatContext context, Throwable throwable) throws Throwable {
delegate.handleException(context, throwable);
}
/**
* The limit on the given exception type within a single context before it is
* rethrown.
* @param limit the limit
*/
public void setLimit(final int limit) {
this.limit = limit;
}
/**
* Setter for the exception classes that this handler counts. Defaults to
* {@link Exception}. If more exceptionClasses are specified handler uses single
* counter that is incremented when one of the recognized exception exceptionClasses
* is handled.
* @param classes exceptionClasses
*/
public void setExceptionClasses(Collection<Class<? extends Throwable>> classes) {
this.exceptionClasses = classes;
}
/**
* Setter for the exception classes that shouldn't be counted, but rethrown
* immediately. This list has higher priority than
* {@link #setExceptionClasses(Collection)}.
* @param fatalExceptionClasses defaults to {@link Error}
*/
public void setFatalExceptionClasses(Collection<Class<? extends Throwable>> fatalExceptionClasses) {
this.fatalExceptionClasses = fatalExceptionClasses;
}
}
|
if (limit <= 0) {
return;
}
Map<Class<? extends Throwable>, Integer> thresholds = new HashMap<>();
for (Class<? extends Throwable> type : exceptionClasses) {
thresholds.put(type, limit);
}
// do the fatalExceptionClasses last so they override the others
for (Class<? extends Throwable> type : fatalExceptionClasses) {
thresholds.put(type, 0);
}
delegate.setThresholds(thresholds);
| 811
| 144
| 955
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptor.java
|
RepeatOperationsInterceptor
|
invoke
|
class RepeatOperationsInterceptor implements MethodInterceptor {
private RepeatOperations repeatOperations = new RepeatTemplate();
/**
* Setter for the {@link RepeatOperations}.
* @param batchTemplate template to be used
* @throws IllegalArgumentException if the argument is null.
*/
public void setRepeatOperations(RepeatOperations batchTemplate) {
Assert.notNull(batchTemplate, "'repeatOperations' cannot be null.");
this.repeatOperations = batchTemplate;
}
/**
* Invoke the proceeding method call repeatedly, according to the properties of the
* injected {@link RepeatOperations}.
*
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*/
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>}
private boolean isComplete(Object result) {
return result == null || (result instanceof Boolean) && !(Boolean) result;
}
/**
* Simple wrapper exception class to enable nasty errors to be passed out of the scope
* of the repeat operations and handled by the caller.
*
* @author Dave Syer
*
*/
private static class RepeatOperationsInterceptorException extends RepeatException {
public RepeatOperationsInterceptorException(String message, Throwable e) {
super(message, e);
}
}
/**
* Simple wrapper object for the result from a method invocation.
*
* @author Dave Syer
*
*/
private static class ResultHolder {
private Object value = null;
private boolean ready = false;
/**
* Public setter for the Object.
* @param value the value to set
*/
public void setValue(Object value) {
this.ready = true;
this.value = value;
}
public void setFinalValue(Object value) {
if (ready) {
// Only set the value the last time if the last time was also
// the first time
return;
}
setValue(value);
}
/**
* Public getter for the Object.
* @return the value
*/
public Object getValue() {
return value;
}
/**
* @return true if a value has been set
*/
public boolean isReady() {
return ready;
}
}
}
|
final ResultHolder result = new ResultHolder();
// Cache void return value if intercepted method returns void
final boolean voidReturnType = Void.TYPE.equals(invocation.getMethod().getReturnType());
if (voidReturnType) {
// This will be ignored anyway, but we want it to be non-null for
// convenience of checking that there is a result.
result.setValue(new Object());
}
try {
repeatOperations.iterate(context -> {
try {
MethodInvocation clone = invocation;
if (invocation instanceof ProxyMethodInvocation) {
clone = ((ProxyMethodInvocation) invocation).invocableClone();
}
else {
throw new IllegalStateException(
"MethodInvocation of the wrong type detected - this should not happen with Spring AOP, so please raise an issue if you see this exception");
}
Object value = clone.proceed();
if (voidReturnType) {
return RepeatStatus.CONTINUABLE;
}
if (!isComplete(value)) {
// Save the last result
result.setValue(value);
return RepeatStatus.CONTINUABLE;
}
else {
result.setFinalValue(value);
return RepeatStatus.FINISHED;
}
}
catch (Throwable e) {
if (e instanceof Exception) {
throw (Exception) e;
}
else {
throw new RepeatOperationsInterceptorException("Unexpected error in batch interceptor", e);
}
}
});
}
catch (Throwable t) {
// The repeat exception should be unwrapped by the template
throw t;
}
if (result.isReady()) {
return result.getValue();
}
// No result means something weird happened
throw new IllegalStateException("No result available for attempted repeat call to " + invocation
+ ". The invocation was never called, so maybe there is a problem with the completion policy?");
| 628
| 525
| 1,153
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/listener/CompositeRepeatListener.java
|
CompositeRepeatListener
|
after
|
class CompositeRepeatListener implements RepeatListener {
private List<RepeatListener> listeners = new ArrayList<>();
/**
* Default constructor
*/
public CompositeRepeatListener() {
}
/**
* Convenience constructor for setting the {@link RepeatListener}s.
* @param listeners {@link List} of RepeatListeners to be used by the
* CompositeRepeatListener.
*/
public CompositeRepeatListener(List<RepeatListener> listeners) {
setListeners(listeners);
}
/**
* Convenience constructor for setting the {@link RepeatListener}s.
* @param listeners array of RepeatListeners to be used by the
* CompositeRepeatListener.
*/
public CompositeRepeatListener(RepeatListener... listeners) {
setListeners(listeners);
}
/**
* Public setter for the listeners.
* @param listeners {@link List} of RepeatListeners to be used by the
* CompositeRepeatListener.
*/
public void setListeners(List<RepeatListener> listeners) {
this.listeners = listeners;
}
/**
* Public setter for the listeners.
* @param listeners array of RepeatListeners to be used by the
* CompositeRepeatListener.
*/
public void setListeners(RepeatListener[] listeners) {
this.listeners = Arrays.asList(listeners);
}
/**
* Register additional listener.
* @param listener the RepeatListener to be added to the list of listeners to be
* notified.
*/
public void register(RepeatListener listener) {
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
@Override
public void after(RepeatContext context, RepeatStatus result) {<FILL_FUNCTION_BODY>}
@Override
public void before(RepeatContext context) {
for (RepeatListener listener : listeners) {
listener.before(context);
}
}
@Override
public void close(RepeatContext context) {
for (RepeatListener listener : listeners) {
listener.close(context);
}
}
@Override
public void onError(RepeatContext context, Throwable e) {
for (RepeatListener listener : listeners) {
listener.onError(context, e);
}
}
@Override
public void open(RepeatContext context) {
for (RepeatListener listener : listeners) {
listener.open(context);
}
}
}
|
for (RepeatListener listener : listeners) {
listener.after(context, result);
}
| 646
| 30
| 676
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/policy/CompletionPolicySupport.java
|
CompletionPolicySupport
|
isComplete
|
class CompletionPolicySupport implements CompletionPolicy {
/**
* If exit status is not continuable return <code>true</code>, otherwise delegate to
* {@link #isComplete(RepeatContext)}.
*
* @see org.springframework.batch.repeat.CompletionPolicy#isComplete(org.springframework.batch.repeat.RepeatContext,
* RepeatStatus)
*/
@Override
public boolean isComplete(RepeatContext context, RepeatStatus result) {<FILL_FUNCTION_BODY>}
/**
* Always true.
*
* @see org.springframework.batch.repeat.CompletionPolicy#isComplete(org.springframework.batch.repeat.RepeatContext)
*/
@Override
public boolean isComplete(RepeatContext context) {
return true;
}
/**
* Build a new {@link RepeatContextSupport} and return it.
*
* @see org.springframework.batch.repeat.CompletionPolicy#start(RepeatContext)
*/
@Override
public RepeatContext start(RepeatContext context) {
return new RepeatContextSupport(context);
}
/**
* Increment the context so the counter is up to date. Do nothing else.
*
* @see org.springframework.batch.repeat.CompletionPolicy#update(org.springframework.batch.repeat.RepeatContext)
*/
@Override
public void update(RepeatContext context) {
if (context instanceof RepeatContextSupport) {
((RepeatContextSupport) context).increment();
}
}
}
|
if (result != null && !result.isContinuable()) {
return true;
}
else {
return isComplete(context);
}
| 381
| 44
| 425
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/policy/CompositeCompletionPolicy.java
|
CompositeCompletionPolicy
|
isComplete
|
class CompositeCompletionPolicy implements CompletionPolicy {
CompletionPolicy[] policies = new CompletionPolicy[0];
/**
* Setter for the policies.
* @param policies an array of completion policies to be used to determine
* {@link #isComplete(RepeatContext)} by consensus.
*/
public void setPolicies(CompletionPolicy[] policies) {
this.policies = Arrays.asList(policies).toArray(new CompletionPolicy[policies.length]);
}
/**
* This policy is complete if any of the composed policies is complete.
*
* @see org.springframework.batch.repeat.CompletionPolicy#isComplete(org.springframework.batch.repeat.RepeatContext,
* RepeatStatus)
*/
@Override
public boolean isComplete(RepeatContext context, RepeatStatus result) {<FILL_FUNCTION_BODY>}
/**
* This policy is complete if any of the composed policies is complete.
*
* @see org.springframework.batch.repeat.CompletionPolicy#isComplete(org.springframework.batch.repeat.RepeatContext)
*/
@Override
public boolean isComplete(RepeatContext context) {
RepeatContext[] contexts = ((CompositeBatchContext) context).contexts;
CompletionPolicy[] policies = ((CompositeBatchContext) context).policies;
for (int i = 0; i < policies.length; i++) {
if (policies[i].isComplete(contexts[i])) {
return true;
}
}
return false;
}
/**
* Create a new composite context from all the available policies.
*
* @see org.springframework.batch.repeat.CompletionPolicy#start(RepeatContext)
*/
@Override
public RepeatContext start(RepeatContext context) {
List<RepeatContext> list = new ArrayList<>();
for (CompletionPolicy policy : policies) {
list.add(policy.start(context));
}
return new CompositeBatchContext(context, list);
}
/**
* Update all the composed contexts, and also increment the parent context.
*
* @see org.springframework.batch.repeat.CompletionPolicy#update(org.springframework.batch.repeat.RepeatContext)
*/
@Override
public void update(RepeatContext context) {
RepeatContext[] contexts = ((CompositeBatchContext) context).contexts;
CompletionPolicy[] policies = ((CompositeBatchContext) context).policies;
for (int i = 0; i < policies.length; i++) {
policies[i].update(contexts[i]);
}
((RepeatContextSupport) context).increment();
}
/**
* Composite context that knows about the policies and contexts is was created with.
*
* @author Dave Syer
*
*/
protected class CompositeBatchContext extends RepeatContextSupport {
private final RepeatContext[] contexts;
// Save a reference to the policies when we were created - gives some
// protection against reference changes (e.g. if the number of policies
// change).
private final CompletionPolicy[] policies;
public CompositeBatchContext(RepeatContext context, List<RepeatContext> contexts) {
super(context);
this.contexts = contexts.toArray(new RepeatContext[contexts.size()]);
this.policies = CompositeCompletionPolicy.this.policies;
}
}
}
|
RepeatContext[] contexts = ((CompositeBatchContext) context).contexts;
CompletionPolicy[] policies = ((CompositeBatchContext) context).policies;
for (int i = 0; i < policies.length; i++) {
if (policies[i].isComplete(contexts[i], result)) {
return true;
}
}
return false;
| 869
| 100
| 969
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/policy/CountingCompletionPolicy.java
|
CountingCompletionPolicy
|
isComplete
|
class CountingCompletionPolicy extends DefaultResultCompletionPolicy {
/**
* Session key for global counter.
*/
public static final String COUNT = CountingCompletionPolicy.class.getName() + ".COUNT";
private boolean useParent = false;
private int maxCount = 0;
/**
* Flag to indicate whether the count is at the level of the parent context, or just
* local to the context. If true then the count is aggregated among siblings in a
* nested batch.
* @param useParent whether to use the parent context to cache the total count.
* Default value is false.
*/
public void setUseParent(boolean useParent) {
this.useParent = useParent;
}
/**
* Setter for maximum value of count before termination.
* @param maxCount the maximum number of counts before termination. Default 0 so
* termination is immediate.
*/
public void setMaxCount(int maxCount) {
this.maxCount = maxCount;
}
/**
* Extension point for subclasses. Obtain the value of the count in the current
* context. Subclasses can count the number of attempts or violations and store the
* result in their context. This policy base class will take care of the termination
* contract and aggregating at the level of the session if required.
* @param context the current context, specific to the subclass.
* @return the value of the counter in the context.
*/
protected abstract int getCount(RepeatContext context);
/**
* Extension point for subclasses. Inspect the context and update the state of a
* counter in whatever way is appropriate. This will be added to the session-level
* counter if {@link #setUseParent(boolean)} is true.
* @param context the current context.
* @return the change in the value of the counter (default 0).
*/
protected int doUpdate(RepeatContext context) {
return 0;
}
@Override
final public boolean isComplete(RepeatContext context) {<FILL_FUNCTION_BODY>}
@Override
public RepeatContext start(RepeatContext parent) {
return new CountingBatchContext(parent);
}
@Override
final public void update(RepeatContext context) {
super.update(context);
int delta = doUpdate(context);
((CountingBatchContext) context).getCounter().increment(delta);
}
protected class CountingBatchContext extends RepeatContextSupport {
RepeatContextCounter counter;
public CountingBatchContext(RepeatContext parent) {
super(parent);
counter = new RepeatContextCounter(this, COUNT, useParent);
}
public RepeatContextCounter getCounter() {
return counter;
}
}
}
|
int count = ((CountingBatchContext) context).getCounter().getCount();
return count >= maxCount;
| 684
| 30
| 714
|
<methods>public non-sealed void <init>() ,public boolean isComplete(org.springframework.batch.repeat.RepeatContext, org.springframework.batch.repeat.RepeatStatus) ,public boolean isComplete(org.springframework.batch.repeat.RepeatContext) <variables>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/RepeatSynchronizationManager.java
|
RepeatSynchronizationManager
|
setAncestorsCompleteOnly
|
class RepeatSynchronizationManager {
private static final ThreadLocal<RepeatContext> contextHolder = new ThreadLocal<>();
private RepeatSynchronizationManager() {
}
/**
* Getter for the current context. A context is shared by all items in the batch, so
* this method is intended to return the same context object independent of whether
* the callback is running synchronously or asynchronously with the surrounding
* {@link RepeatOperations}.
* @return the current {@link RepeatContext} or null if there is none (if we are not
* in a batch).
*/
public static RepeatContext getContext() {
return contextHolder.get();
}
/**
* Convenience method to set the current repeat operation to complete if it exists.
*/
public static void setCompleteOnly() {
RepeatContext context = getContext();
if (context != null) {
context.setCompleteOnly();
}
}
/**
* Method for registering a context - should only be used by {@link RepeatOperations}
* implementations to ensure that {@link #getContext()} always returns the correct
* value.
* @param context a new context at the start of a batch.
* @return the old value if there was one.
*/
public static RepeatContext register(RepeatContext context) {
RepeatContext oldSession = getContext();
RepeatSynchronizationManager.contextHolder.set(context);
return oldSession;
}
/**
* Clear the current context at the end of a batch - should only be used by
* {@link RepeatOperations} implementations.
* @return the old value if there was one.
*/
public static RepeatContext clear() {
RepeatContext context = getContext();
RepeatSynchronizationManager.contextHolder.set(null);
return context;
}
/**
* Set current session and all ancestors (via parent) to complete.,
*/
public static void setAncestorsCompleteOnly() {<FILL_FUNCTION_BODY>}
}
|
RepeatContext context = getContext();
while (context != null) {
context.setCompleteOnly();
context = context.getParent();
}
| 510
| 47
| 557
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/ResultHolderResultQueue.java
|
ResultHolderResultQueue
|
take
|
class ResultHolderResultQueue implements ResultQueue<ResultHolder> {
// Accumulation of result objects as they finish.
private final BlockingQueue<ResultHolder> results;
// Accumulation of dummy objects flagging expected results in the future.
private final Semaphore waits;
private final Object lock = new Object();
private volatile int count = 0;
/**
* @param throttleLimit the maximum number of results that can be expected at any
* given time.
*/
public ResultHolderResultQueue(int throttleLimit) {
results = new PriorityBlockingQueue<>(throttleLimit, new ResultHolderComparator());
waits = new Semaphore(throttleLimit);
}
@Override
public boolean isEmpty() {
return results.isEmpty();
}
@Override
public boolean isExpecting() {
// Base the decision about whether we expect more results on a
// counter of the number of expected results actually collected.
// Do not synchronize! Otherwise put and expect can deadlock.
return count > 0;
}
/**
* Tell the queue to expect one more result. Blocks until a new result is available if
* already expecting too many (as determined by the throttle limit).
*
* @see ResultQueue#expect()
*/
@Override
public void expect() throws InterruptedException {
waits.acquire();
// Don't acquire the lock in a synchronized block - might deadlock
synchronized (lock) {
count++;
}
}
@Override
public void put(ResultHolder holder) throws IllegalArgumentException {
if (!isExpecting()) {
throw new IllegalArgumentException("Not expecting a result. Call expect() before put().");
}
results.add(holder);
// Take from the waits queue now to allow another result to
// accumulate. But don't decrement the counter.
waits.release();
synchronized (lock) {
lock.notifyAll();
}
}
/**
* Get the next result as soon as it becomes available. <br>
* <br>
* Release result immediately if:
* <ul>
* <li>There is a result that is continuable.</li>
* </ul>
* Otherwise block if either:
* <ul>
* <li>There is no result (as per contract of {@link ResultQueue}).</li>
* <li>The number of results is less than the number expected.</li>
* </ul>
* Error if either:
* <ul>
* <li>Not expecting.</li>
* <li>Interrupted.</li>
* </ul>
*
* @see ResultQueue#take()
*/
@Override
public ResultHolder take() throws NoSuchElementException, InterruptedException {<FILL_FUNCTION_BODY>}
private boolean isContinuable(ResultHolder value) {
return value.getResult() != null && value.getResult().isContinuable();
}
/**
* Compares ResultHolders so that one that is continuable ranks lowest.
*
* @author Dave Syer
*
*/
private static class ResultHolderComparator implements Comparator<ResultHolder> {
@Override
public int compare(ResultHolder h1, ResultHolder h2) {
RepeatStatus result1 = h1.getResult();
RepeatStatus result2 = h2.getResult();
if (result1 == null && result2 == null) {
return 0;
}
if (result1 == null) {
return -1;
}
else if (result2 == null) {
return 1;
}
if ((result1.isContinuable() && result2.isContinuable())
|| (!result1.isContinuable() && !result2.isContinuable())) {
return 0;
}
if (result1.isContinuable()) {
return -1;
}
return 1;
}
}
}
|
if (!isExpecting()) {
throw new NoSuchElementException("Not expecting a result. Call expect() before take().");
}
ResultHolder value;
synchronized (lock) {
value = results.take();
if (isContinuable(value)) {
// Decrement the counter only when the result is collected.
count--;
return value;
}
}
results.put(value);
synchronized (lock) {
while (count > results.size()) {
lock.wait();
}
value = results.take();
count--;
}
return value;
| 1,023
| 171
| 1,194
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/ThrottleLimitResultQueue.java
|
ThrottleLimitResultQueue
|
isExpecting
|
class ThrottleLimitResultQueue<T> implements ResultQueue<T> {
// Accumulation of result objects as they finish.
private final BlockingQueue<T> results;
// Accumulation of dummy objects flagging expected results in the future.
private final Semaphore waits;
private final Object lock = new Object();
private volatile int count = 0;
/**
* @param throttleLimit the maximum number of results that can be expected at any
* given time.
*/
public ThrottleLimitResultQueue(int throttleLimit) {
results = new LinkedBlockingQueue<>();
waits = new Semaphore(throttleLimit);
}
@Override
public boolean isEmpty() {
return results.isEmpty();
}
@Override
public boolean isExpecting() {<FILL_FUNCTION_BODY>}
/**
* Tell the queue to expect one more result. Blocks until a new result is available if
* already expecting too many (as determined by the throttle limit).
*
* @see ResultQueue#expect()
*/
@Override
public void expect() throws InterruptedException {
synchronized (lock) {
waits.acquire();
count++;
}
}
@Override
public void put(T holder) throws IllegalArgumentException {
if (!isExpecting()) {
throw new IllegalArgumentException("Not expecting a result. Call expect() before put().");
}
// There should be no need to block here, or to use offer()
results.add(holder);
// Take from the waits queue now to allow another result to
// accumulate. But don't decrement the counter.
waits.release();
}
@Override
public T take() throws NoSuchElementException, InterruptedException {
if (!isExpecting()) {
throw new NoSuchElementException("Not expecting a result. Call expect() before take().");
}
T value;
synchronized (lock) {
value = results.take();
// Decrement the counter only when the result is collected.
count--;
}
return value;
}
}
|
// Base the decision about whether we expect more results on a
// counter of the number of expected results actually collected.
// Do not synchronize! Otherwise put and expect can deadlock.
return count > 0;
| 542
| 53
| 595
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/AnnotationMethodResolver.java
|
AnnotationMethodResolver
|
findMethod
|
class AnnotationMethodResolver implements MethodResolver {
private final Class<? extends Annotation> annotationType;
/**
* Create a {@link MethodResolver} for the specified Method-level annotation type.
* @param annotationType establish the annotation to be used.
*/
public AnnotationMethodResolver(Class<? extends Annotation> annotationType) {
Assert.notNull(annotationType, "annotationType must not be null");
Assert.isTrue(
ObjectUtils.containsElement(annotationType.getAnnotation(Target.class).value(), ElementType.METHOD),
"Annotation [" + annotationType + "] is not a Method-level annotation.");
this.annotationType = annotationType;
}
/**
* Find a <em>single</em> Method on the Class of the given candidate object that
* contains the annotation type for which this resolver is searching.
* @param candidate the instance whose Class will be checked for the annotation
* @return a single matching Method instance or <code>null</code> if the candidate's
* Class contains no Methods with the specified annotation
* @throws IllegalArgumentException if more than one Method has the specified
* annotation
*/
@Nullable
@Override
public Method findMethod(Object candidate) {<FILL_FUNCTION_BODY>}
/**
* Find a <em>single</em> Method on the given Class that contains the annotation type
* for which this resolver is searching.
* @param clazz the Class instance to check for the annotation
* @return a single matching Method instance or <code>null</code> if the Class
* contains no Methods with the specified annotation
* @throws IllegalArgumentException if more than one Method has the specified
* annotation
*/
@Nullable
@Override
public Method findMethod(final Class<?> clazz) {
Assert.notNull(clazz, "class must not be null");
final AtomicReference<Method> annotatedMethod = new AtomicReference<>();
ReflectionUtils.doWithMethods(clazz, method -> {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Assert.isNull(annotatedMethod.get(), "found more than one method on target class [" + clazz
+ "] with the annotation type [" + annotationType + "]");
annotatedMethod.set(method);
}
});
return annotatedMethod.get();
}
}
|
Assert.notNull(candidate, "candidate object must not be null");
Class<?> targetClass = AopUtils.getTargetClass(candidate);
if (targetClass == null) {
targetClass = candidate.getClass();
}
return this.findMethod(targetClass);
| 595
| 79
| 674
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/DefaultPropertyEditorRegistrar.java
|
DefaultPropertyEditorRegistrar
|
setCustomEditors
|
class DefaultPropertyEditorRegistrar implements PropertyEditorRegistrar {
private Map<Class<?>, PropertyEditor> customEditors;
/**
* Register the custom editors with the given registry.
*
* @see org.springframework.beans.PropertyEditorRegistrar#registerCustomEditors(org.springframework.beans.PropertyEditorRegistry)
*/
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
if (this.customEditors != null) {
for (Entry<Class<?>, PropertyEditor> entry : customEditors.entrySet()) {
registry.registerCustomEditor(entry.getKey(), entry.getValue());
}
}
}
/**
* Specify the {@link PropertyEditor custom editors} to register.
* @param customEditors a map of Class to PropertyEditor (or class name to
* PropertyEditor).
* @see CustomEditorConfigurer#setCustomEditors(Map)
*/
public void setCustomEditors(Map<?, ? extends PropertyEditor> customEditors) {<FILL_FUNCTION_BODY>}
}
|
this.customEditors = new HashMap<>();
for (Entry<?, ? extends PropertyEditor> entry : customEditors.entrySet()) {
Object key = entry.getKey();
Class<?> requiredType;
if (key instanceof Class<?>) {
requiredType = (Class<?>) key;
}
else if (key instanceof String className) {
requiredType = ClassUtils.resolveClassName(className, getClass().getClassLoader());
}
else {
throw new IllegalArgumentException(
"Invalid key [" + key + "] for custom editor: needs to be Class or String.");
}
PropertyEditor value = entry.getValue();
this.customEditors.put(requiredType, value);
}
| 269
| 190
| 459
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/IntArrayPropertyEditor.java
|
IntArrayPropertyEditor
|
setAsText
|
class IntArrayPropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {<FILL_FUNCTION_BODY>}
}
|
String[] strs = StringUtils.commaDelimitedListToStringArray(text);
int[] value = new int[strs.length];
for (int i = 0; i < value.length; i++) {
value[i] = Integer.parseInt(strs[i].trim());
}
setValue(value);
| 44
| 88
| 132
|
<methods>public void <init>() ,public void <init>(java.lang.Object) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public void firePropertyChange() ,public java.lang.String getAsText() ,public java.awt.Component getCustomEditor() ,public java.lang.String getJavaInitializationString() ,public java.lang.Object getSource() ,public java.lang.String[] getTags() ,public java.lang.Object getValue() ,public boolean isPaintable() ,public void paintValue(java.awt.Graphics, java.awt.Rectangle) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setAsText(java.lang.String) throws java.lang.IllegalArgumentException,public void setSource(java.lang.Object) ,public void setValue(java.lang.Object) ,public boolean supportsCustomEditor() <variables>private Vector<java.beans.PropertyChangeListener> listeners,private java.lang.Object source,private java.lang.Object value
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/LastModifiedResourceComparator.java
|
LastModifiedResourceComparator
|
compare
|
class LastModifiedResourceComparator implements Comparator<Resource> {
/**
* Compare the two resources by last modified time, so that a sorted list of resources
* will have oldest first.
* @throws IllegalArgumentException if one of the resources doesn't exist or its last
* modified date cannot be determined
*
* @see Comparator#compare(Object, Object)
*/
@Override
public int compare(Resource r1, Resource r2) {<FILL_FUNCTION_BODY>}
}
|
Assert.isTrue(r1.exists(), "Resource does not exist: " + r1);
Assert.isTrue(r2.exists(), "Resource does not exist: " + r2);
try {
long diff = r1.getFile().lastModified() - r2.getFile().lastModified();
return diff > 0 ? 1 : diff < 0 ? -1 : 0;
}
catch (IOException e) {
throw new IllegalArgumentException("Resource modification times cannot be determined (unexpected).", e);
}
| 127
| 139
| 266
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/MethodInvokerUtils.java
|
MethodInvokerUtils
|
getMethodInvokerByAnnotation
|
class MethodInvokerUtils {
private MethodInvokerUtils() {
}
/**
* Create a {@link MethodInvoker} using the provided method name to search.
* @param object to be invoked
* @param methodName of the method to be invoked
* @param paramsRequired boolean indicating whether the parameters are required, if
* false, a no args version of the method will be searched for.
* @param paramTypes - parameter types of the method to search for.
* @return MethodInvoker if the method is found
*/
public static MethodInvoker getMethodInvokerByName(Object object, String methodName, boolean paramsRequired,
Class<?>... paramTypes) {
Assert.notNull(object, "Object to invoke must not be null");
Method method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName, paramTypes);
if (method == null) {
String errorMsg = "no method found with name [" + methodName + "] on class ["
+ object.getClass().getSimpleName() + "] compatible with the signature ["
+ getParamTypesString(paramTypes) + "].";
Assert.isTrue(!paramsRequired, errorMsg);
// if no method was found for the given parameters, and the
// parameters aren't required, then try with no params
method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName);
Assert.notNull(method, errorMsg);
}
return new SimpleMethodInvoker(object, method);
}
/**
* Create a String representation of the array of parameter types.
* @param paramTypes types of the parameters to be used
* @return String a String representation of those types
*/
public static String getParamTypesString(Class<?>... paramTypes) {
StringBuilder paramTypesList = new StringBuilder("(");
for (int i = 0; i < paramTypes.length; i++) {
paramTypesList.append(paramTypes[i].getSimpleName());
if (i + 1 < paramTypes.length) {
paramTypesList.append(", ");
}
}
return paramTypesList.append(")").toString();
}
/**
* Create a {@link MethodInvoker} using the provided interface, and method name from
* that interface.
* @param cls the interface to search for the method named
* @param methodName of the method to be invoked
* @param object to be invoked
* @param paramTypes - parameter types of the method to search for.
* @return MethodInvoker if the method is found, null if it is not.
*/
@Nullable
public static MethodInvoker getMethodInvokerForInterface(Class<?> cls, String methodName, Object object,
Class<?>... paramTypes) {
if (cls.isAssignableFrom(object.getClass())) {
return MethodInvokerUtils.getMethodInvokerByName(object, methodName, true, paramTypes);
}
else {
return null;
}
}
/**
* Create a MethodInvoker from the delegate based on the annotationType. Ensure that
* the annotated method has a valid set of parameters.
* @param annotationType the annotation to scan for
* @param target the target object
* @param expectedParamTypes the expected parameter types for the method
* @return a MethodInvoker
*/
public static MethodInvoker getMethodInvokerByAnnotation(final Class<? extends Annotation> annotationType,
final Object target, final Class<?>... expectedParamTypes) {
MethodInvoker mi = MethodInvokerUtils.getMethodInvokerByAnnotation(annotationType, target);
final Class<?> targetClass = (target instanceof Advised) ? ((Advised) target).getTargetSource().getTargetClass()
: target.getClass();
if (mi != null) {
ReflectionUtils.doWithMethods(targetClass, method -> {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 0) {
String errorMsg = "The method [" + method.getName() + "] on target class ["
+ targetClass.getSimpleName() + "] is incompatible with the signature ["
+ getParamTypesString(expectedParamTypes) + "] expected for the annotation ["
+ annotationType.getSimpleName() + "].";
Assert.isTrue(paramTypes.length == expectedParamTypes.length, errorMsg);
for (int i = 0; i < paramTypes.length; i++) {
Assert.isTrue(expectedParamTypes[i].isAssignableFrom(paramTypes[i]), errorMsg);
}
}
}
});
}
return mi;
}
/**
* Create {@link MethodInvoker} for the method with the provided annotation on the
* provided object. Annotations that cannot be applied to methods (i.e. that aren't
* annotated with an element type of METHOD) will cause an exception to be thrown.
* @param annotationType to be searched for
* @param target to be invoked
* @return MethodInvoker for the provided annotation, null if none is found.
*/
@Nullable
public static MethodInvoker getMethodInvokerByAnnotation(final Class<? extends Annotation> annotationType,
final Object target) {<FILL_FUNCTION_BODY>}
/**
* Create a {@link MethodInvoker} for the delegate from a single public method.
* @param target an object to search for an appropriate method.
* @return a {@link MethodInvoker} that calls a method on the delegate.
*/
public static MethodInvoker getMethodInvokerForSingleArgument(Object target) {
final AtomicReference<Method> methodHolder = new AtomicReference<>();
ReflectionUtils.doWithMethods(target.getClass(), method -> {
if (method.getParameterTypes() == null || method.getParameterTypes().length != 1) {
return;
}
if (method.getReturnType().equals(Void.TYPE) || ReflectionUtils.isEqualsMethod(method)) {
return;
}
Assert.state(methodHolder.get() == null,
"More than one non-void public method detected with single argument.");
methodHolder.set(method);
});
Method method = methodHolder.get();
return new SimpleMethodInvoker(target, method);
}
}
|
Assert.notNull(target, "Target must not be null");
Assert.notNull(annotationType, "AnnotationType must not be null");
Assert.isTrue(
ObjectUtils.containsElement(annotationType.getAnnotation(Target.class).value(), ElementType.METHOD),
"Annotation [" + annotationType + "] is not a Method-level annotation.");
final Class<?> targetClass = (target instanceof Advised) ? ((Advised) target).getTargetSource().getTargetClass()
: target.getClass();
if (targetClass == null) {
// Proxy with no target cannot have annotations
return null;
}
final AtomicReference<Method> annotatedMethod = new AtomicReference<>();
ReflectionUtils.doWithMethods(targetClass, method -> {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Assert.isNull(annotatedMethod.get(),
"found more than one method on target class [" + targetClass.getSimpleName()
+ "] with the annotation type [" + annotationType.getSimpleName() + "].");
annotatedMethod.set(method);
}
});
Method method = annotatedMethod.get();
if (method == null) {
return null;
}
else {
return new SimpleMethodInvoker(target, annotatedMethod.get());
}
| 1,609
| 357
| 1,966
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/PatternMatcher.java
|
PatternMatcher
|
match
|
class PatternMatcher<S> {
private final Map<String, S> map;
private final List<String> sorted;
/**
* Initialize a new {@link PatternMatcher} with a map of patterns to values
* @param map a map from String patterns to values
*/
public PatternMatcher(Map<String, S> map) {
super();
this.map = map;
// Sort keys to start with the most specific
sorted = new ArrayList<>(map.keySet());
sorted.sort(Comparator.reverseOrder());
}
/**
* Lifted from AntPathMatcher in Spring Core. Tests whether or not a string matches
* against a pattern. The pattern may contain two special characters:<br>
* '*' means zero or more characters<br>
* '?' means one and only one character
* @param pattern pattern to match against. Must not be <code>null</code>.
* @param str string which must be matched against the pattern. Must not be
* <code>null</code>.
* @return <code>true</code> if the string matches against the pattern, or
* <code>false</code> otherwise.
*/
public static boolean match(String pattern, String str) {<FILL_FUNCTION_BODY>}
/**
* <p>
* This method takes a String key and a map from Strings to values of any type. During
* processing, the method will identify the most specific key in the map that matches
* the line. Once the correct is identified, its value is returned. Note that if the
* map contains the wildcard string "*" as a key, then it will serve as the "default"
* case, matching every line that does not match anything else.
*
* <p>
* If no matching prefix is found, a {@link IllegalStateException} will be thrown.
*
* <p>
* Null keys are not allowed in the map.
* @param line An input string
* @return the value whose prefix matches the given line
*/
public S match(String line) {
S value = null;
Assert.notNull(line, "A non-null key must be provided to match against.");
for (String key : sorted) {
if (PatternMatcher.match(key, line)) {
value = map.get(key);
break;
}
}
if (value == null) {
throw new IllegalStateException("Could not find a matching pattern for key=[" + line + "]");
}
return value;
}
}
|
int patIdxStart = 0;
int patIdxEnd = pattern.length() - 1;
int strIdxStart = 0;
int strIdxEnd = str.length() - 1;
char ch;
boolean containsStar = pattern.contains("*");
if (!containsStar) {
// No '*'s, so we make a shortcut
if (patIdxEnd != strIdxEnd) {
return false; // Pattern and string do not have the same size
}
for (int i = 0; i <= patIdxEnd; i++) {
ch = pattern.charAt(i);
if (ch != '?') {
if (ch != str.charAt(i)) {
return false;// Character mismatch
}
}
}
return true; // String matches against pattern
}
if (patIdxEnd == 0) {
return true; // Pattern contains only '*', which matches anything
}
// Process characters before first star
while ((ch = pattern.charAt(patIdxStart)) != '*' && strIdxStart <= strIdxEnd) {
if (ch != '?') {
if (ch != str.charAt(strIdxStart)) {
return false;// Character mismatch
}
}
patIdxStart++;
strIdxStart++;
}
if (strIdxStart > strIdxEnd) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (pattern.charAt(i) != '*') {
return false;
}
}
return true;
}
// Process characters after last star
while ((ch = pattern.charAt(patIdxEnd)) != '*' && strIdxStart <= strIdxEnd) {
if (ch != '?') {
if (ch != str.charAt(strIdxEnd)) {
return false;// Character mismatch
}
}
patIdxEnd--;
strIdxEnd--;
}
if (strIdxStart > strIdxEnd) {
// All characters in the string are used. Check if only '*'s are
// left in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (pattern.charAt(i) != '*') {
return false;
}
}
return true;
}
// process pattern between stars. padIdxStart and patIdxEnd point
// always to a '*'.
while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) {
int patIdxTmp = -1;
for (int i = patIdxStart + 1; i <= patIdxEnd; i++) {
if (pattern.charAt(i) == '*') {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == patIdxStart + 1) {
// Two stars next to each other, skip the first one.
patIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = (patIdxTmp - patIdxStart - 1);
int strLength = (strIdxEnd - strIdxStart + 1);
int foundIdx = -1;
strLoop: for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
ch = pattern.charAt(patIdxStart + j + 1);
if (ch != '?') {
if (ch != str.charAt(strIdxStart + i + j)) {
continue strLoop;
}
}
}
foundIdx = strIdxStart + i;
break;
}
if (foundIdx == -1) {
return false;
}
patIdxStart = patIdxTmp;
strIdxStart = foundIdx + patLength;
}
// All characters in the string are used. Check if only '*'s are left
// in the pattern. If so, we succeeded. Otherwise failure.
for (int i = patIdxStart; i <= patIdxEnd; i++) {
if (pattern.charAt(i) != '*') {
return false;
}
}
return true;
| 650
| 1,232
| 1,882
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/PropertiesConverter.java
|
PropertiesConverter
|
propertiesToString
|
class PropertiesConverter {
private static final String LINE_SEPARATOR = "\n";
// prevents the class from being instantiated
private PropertiesConverter() {
}
/**
* Parse a String to a Properties object. If string is empty, an empty Properties
* object will be returned. The input String should be a set of key=value pairs,
* separated by a new line.
* @param stringToParse String to parse. Must not be {@code null}.
* @return Properties parsed from each key=value pair.
*/
public static Properties stringToProperties(@NonNull String stringToParse) {
Assert.notNull(stringToParse, "stringToParse must not be null");
if (!StringUtils.hasText(stringToParse)) {
return new Properties();
}
Properties properties = new Properties();
String[] keyValuePairs = stringToParse.split(LINE_SEPARATOR);
for (String string : keyValuePairs) {
if (!string.contains("=")) {
throw new IllegalArgumentException(string + "is not a valid key=value pair");
}
String[] keyValuePair = string.split("=");
properties.setProperty(keyValuePair[0], keyValuePair[1]);
}
return properties;
}
/**
* Convert a Properties object to a String. This is only necessary for compatibility
* with converting the String back to a properties object. If an empty properties
* object is passed in, a blank string is returned, otherwise it's string
* representation is returned.
* @param propertiesToParse contains the properties to be converted. Must not be
* {@code null}.
* @return String representation of the properties object
*/
public static String propertiesToString(@NonNull Properties propertiesToParse) {<FILL_FUNCTION_BODY>}
}
|
Assert.notNull(propertiesToParse, "propertiesToParse must not be null");
if (propertiesToParse.isEmpty()) {
return "";
}
List<String> keyValuePairs = new ArrayList<>();
for (Map.Entry<Object, Object> entry : propertiesToParse.entrySet()) {
keyValuePairs.add(entry.getKey() + "=" + entry.getValue());
}
return String.join(LINE_SEPARATOR, keyValuePairs);
| 441
| 125
| 566
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/ReflectionUtils.java
|
ReflectionUtils
|
findMethod
|
class ReflectionUtils {
private ReflectionUtils() {
}
/**
* Returns a {@link java.util.Set} of {@link java.lang.reflect.Method} instances that
* are annotated with the annotation provided.
* @param clazz The class to search for a method with the given annotation type
* @param annotationType The type of annotation to look for
* @return a set of {@link java.lang.reflect.Method} instances if any are found, an
* empty set if not.
*/
public static Set<Method> findMethod(Class<?> clazz, Class<? extends Annotation> annotationType) {<FILL_FUNCTION_BODY>}
}
|
return Arrays.stream(org.springframework.util.ReflectionUtils.getAllDeclaredMethods(clazz))
.filter(method -> AnnotationUtils.findAnnotation(method, annotationType) != null)
.collect(Collectors.toSet());
| 168
| 65
| 233
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/SimpleMethodInvoker.java
|
SimpleMethodInvoker
|
hashCode
|
class SimpleMethodInvoker implements MethodInvoker {
private final Object object;
private Method method;
public SimpleMethodInvoker(Object object, Method method) {
Assert.notNull(object, "Object to invoke must not be null");
Assert.notNull(method, "Method to invoke must not be null");
this.method = method;
this.object = object;
}
public SimpleMethodInvoker(Object object, String methodName, Class<?>... paramTypes) {
Assert.notNull(object, "Object to invoke must not be null");
this.method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName, paramTypes);
if (this.method == null) {
// try with no params
this.method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName);
}
if (this.method == null) {
throw new IllegalArgumentException("No methods found for name: [" + methodName + "] in class: ["
+ object.getClass() + "] with arguments of type: [" + Arrays.toString(paramTypes) + "]");
}
this.object = object;
}
@Nullable
@Override
public Object invokeMethod(Object... args) {
Class<?>[] parameterTypes = method.getParameterTypes();
Object[] invokeArgs;
if (parameterTypes.length == 0) {
invokeArgs = new Object[] {};
}
else if (parameterTypes.length != args.length) {
throw new IllegalArgumentException(
"Wrong number of arguments, expected no more than: [" + parameterTypes.length + "]");
}
else {
invokeArgs = args;
}
method.setAccessible(true);
try {
// Extract the target from an Advised as late as possible
// in case it contains a lazy initialization
Object target = extractTarget(object, method);
return method.invoke(target, invokeArgs);
}
catch (Exception e) {
throw new IllegalArgumentException("Unable to invoke method: [" + method + "] on object: [" + object
+ "] with arguments: [" + Arrays.toString(args) + "]", e);
}
}
private Object extractTarget(Object target, Method method) {
if (target instanceof Advised) {
Object source;
try {
source = ((Advised) target).getTargetSource().getTarget();
}
catch (Exception e) {
throw new IllegalStateException("Could not extract target from proxy", e);
}
if (source instanceof Advised) {
source = extractTarget(source, method);
}
if (method.getDeclaringClass().isAssignableFrom(source.getClass())) {
target = source;
}
}
return target;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SimpleMethodInvoker rhs)) {
return false;
}
if (obj == this) {
return true;
}
return (rhs.method.equals(this.method)) && (rhs.object.equals(this.object));
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
}
|
int result = 25;
result = 31 * result + object.hashCode();
result = 31 * result + method.hashCode();
return result;
| 818
| 46
| 864
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/SystemPropertyInitializer.java
|
SystemPropertyInitializer
|
afterPropertiesSet
|
class SystemPropertyInitializer implements InitializingBean {
/**
* Name of system property used by default.
*/
public static final String ENVIRONMENT = "org.springframework.batch.support.SystemPropertyInitializer.ENVIRONMENT";
private String keyName = ENVIRONMENT;
private String defaultValue;
/**
* Set the key name for the System property that is created. Defaults to
* {@link #ENVIRONMENT}.
* @param keyName the key name to set
*/
public void setKeyName(String keyName) {
this.keyName = keyName;
}
/**
* Mandatory property specifying the default value of the System property.
* @param defaultValue the default value to set
*/
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
/**
* Sets the System property with the provided name and default value.
*
* @see InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>}
}
|
Assert.state(defaultValue != null || System.getProperty(keyName) != null,
"Either a default value must be specified or the value should already be set for System property: "
+ keyName);
System.setProperty(keyName, System.getProperty(keyName, defaultValue));
| 272
| 79
| 351
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/transaction/ResourcelessTransactionManager.java
|
ResourcelessTransactionManager
|
doGetTransaction
|
class ResourcelessTransactionManager extends AbstractPlatformTransactionManager {
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
((ResourcelessTransaction) transaction).begin();
}
@Override
protected void doCommit(DefaultTransactionStatus status) throws TransactionException {
if (logger.isDebugEnabled()) {
logger.debug("Committing resourceless transaction on [" + status.getTransaction() + "]");
}
}
@Override
protected Object doGetTransaction() throws TransactionException {<FILL_FUNCTION_BODY>}
@Override
protected void doRollback(DefaultTransactionStatus status) throws TransactionException {
if (logger.isDebugEnabled()) {
logger.debug("Rolling back resourceless transaction on [" + status.getTransaction() + "]");
}
}
@Override
protected boolean isExistingTransaction(Object transaction) throws TransactionException {
if (TransactionSynchronizationManager.hasResource(this)) {
List<?> stack = (List<?>) TransactionSynchronizationManager.getResource(this);
return stack.size() > 1;
}
return ((ResourcelessTransaction) transaction).isActive();
}
@Override
protected void doSetRollbackOnly(DefaultTransactionStatus status) throws TransactionException {
}
@Override
protected void doCleanupAfterCompletion(Object transaction) {
List<?> resources = (List<?>) TransactionSynchronizationManager.getResource(this);
resources.clear();
TransactionSynchronizationManager.unbindResource(this);
((ResourcelessTransaction) transaction).clear();
}
private static class ResourcelessTransaction {
private boolean active = false;
public boolean isActive() {
return active;
}
public void begin() {
active = true;
}
public void clear() {
active = false;
}
}
}
|
Object transaction = new ResourcelessTransaction();
List<Object> resources;
if (!TransactionSynchronizationManager.hasResource(this)) {
resources = new ArrayList<>();
TransactionSynchronizationManager.bindResource(this, resources);
}
else {
@SuppressWarnings("unchecked")
List<Object> stack = (List<Object>) TransactionSynchronizationManager.getResource(this);
resources = stack;
}
resources.add(transaction);
return transaction;
| 498
| 136
| 634
|
<methods>public void <init>() ,public final void commit(org.springframework.transaction.TransactionStatus) throws org.springframework.transaction.TransactionException,public final int getDefaultTimeout() ,public final org.springframework.transaction.TransactionStatus getTransaction(org.springframework.transaction.TransactionDefinition) throws org.springframework.transaction.TransactionException,public final Collection<org.springframework.transaction.TransactionExecutionListener> getTransactionExecutionListeners() ,public final int getTransactionSynchronization() ,public final boolean isFailEarlyOnGlobalRollbackOnly() ,public final boolean isGlobalRollbackOnParticipationFailure() ,public final boolean isNestedTransactionAllowed() ,public final boolean isRollbackOnCommitFailure() ,public final boolean isValidateExistingTransaction() ,public final void rollback(org.springframework.transaction.TransactionStatus) throws org.springframework.transaction.TransactionException,public final void setDefaultTimeout(int) ,public final void setFailEarlyOnGlobalRollbackOnly(boolean) ,public final void setGlobalRollbackOnParticipationFailure(boolean) ,public final void setNestedTransactionAllowed(boolean) ,public final void setRollbackOnCommitFailure(boolean) ,public final void setTransactionExecutionListeners(Collection<org.springframework.transaction.TransactionExecutionListener>) ,public final void setTransactionSynchronization(int) ,public final void setTransactionSynchronizationName(java.lang.String) ,public final void setValidateExistingTransaction(boolean) <variables>public static final int SYNCHRONIZATION_ALWAYS,public static final int SYNCHRONIZATION_NEVER,public static final int SYNCHRONIZATION_ON_ACTUAL_TRANSACTION,static final Map<java.lang.String,java.lang.Integer> constants,private int defaultTimeout,private boolean failEarlyOnGlobalRollbackOnly,private boolean globalRollbackOnParticipationFailure,protected transient org.apache.commons.logging.Log logger,private boolean nestedTransactionAllowed,private boolean rollbackOnCommitFailure,private Collection<org.springframework.transaction.TransactionExecutionListener> transactionExecutionListeners,private int transactionSynchronization,private boolean validateExistingTransaction
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/transaction/TransactionAwareBufferedWriter.java
|
TransactionAwareBufferedWriter
|
getBufferSize
|
class TransactionAwareBufferedWriter extends Writer {
private final Object bufferKey;
private final Object closeKey;
private final FileChannel channel;
private final Runnable closeCallback;
// default encoding for writing to output files - set to UTF-8.
private static final String DEFAULT_CHARSET = "UTF-8";
private String encoding = DEFAULT_CHARSET;
private boolean forceSync = false;
/**
* Create a new instance with the underlying file channel provided, and a callback to
* execute on close. The callback should clean up related resources like output
* streams or channels.
* @param channel channel used to do the actual file IO
* @param closeCallback callback to execute on close
*/
public TransactionAwareBufferedWriter(FileChannel channel, Runnable closeCallback) {
super();
this.channel = channel;
this.closeCallback = closeCallback;
this.bufferKey = new Object();
this.closeKey = new Object();
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Flag to indicate that changes should be force-synced to disk on flush. Defaults to
* false, which means that even with a local disk changes could be lost if the OS
* crashes in between a write and a cache flush. Setting to true may result in slower
* performance for usage patterns involving many frequent writes.
* @param forceSync the flag value to set
*/
public void setForceSync(boolean forceSync) {
this.forceSync = forceSync;
}
/**
* @return the current buffer
*/
private StringBuilder getCurrentBuffer() {
if (!TransactionSynchronizationManager.hasResource(bufferKey)) {
TransactionSynchronizationManager.bindResource(bufferKey, new StringBuilder());
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCompletion(int status) {
clear();
}
@Override
public void beforeCommit(boolean readOnly) {
try {
if (!readOnly) {
complete();
}
}
catch (IOException e) {
throw new FlushFailedException("Could not write to output buffer", e);
}
}
private void complete() throws IOException {
StringBuilder buffer = (StringBuilder) TransactionSynchronizationManager.getResource(bufferKey);
if (buffer != null) {
String string = buffer.toString();
byte[] bytes = string.getBytes(encoding);
int bufferLength = bytes.length;
ByteBuffer bb = ByteBuffer.wrap(bytes);
int bytesWritten = channel.write(bb);
if (bytesWritten != bufferLength) {
throw new IOException("All bytes to be written were not successfully written");
}
if (forceSync) {
channel.force(false);
}
if (TransactionSynchronizationManager.hasResource(closeKey)) {
closeCallback.run();
}
}
}
private void clear() {
if (TransactionSynchronizationManager.hasResource(bufferKey)) {
TransactionSynchronizationManager.unbindResource(bufferKey);
}
if (TransactionSynchronizationManager.hasResource(closeKey)) {
TransactionSynchronizationManager.unbindResource(closeKey);
}
}
});
}
return (StringBuilder) TransactionSynchronizationManager.getResource(bufferKey);
}
/**
* Convenience method for clients to determine if there is any unflushed data.
* @return the current size (in bytes) of unflushed buffered data
*/
public long getBufferSize() {<FILL_FUNCTION_BODY>}
/**
* @return true if the actual transaction is active, false otherwise
*/
private boolean transactionActive() {
return TransactionSynchronizationManager.isActualTransactionActive();
}
@Override
public void close() throws IOException {
if (transactionActive()) {
if (getCurrentBuffer().length() > 0) {
TransactionSynchronizationManager.bindResource(closeKey, Boolean.TRUE);
}
return;
}
closeCallback.run();
}
@Override
public void flush() throws IOException {
if (!transactionActive() && forceSync) {
channel.force(false);
}
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
if (!transactionActive()) {
byte[] bytes = new String(cbuf, off, len).getBytes(encoding);
int length = bytes.length;
ByteBuffer bb = ByteBuffer.wrap(bytes);
int bytesWritten = channel.write(bb);
if (bytesWritten != length) {
throw new IOException(
"Unable to write all data. Bytes to write: " + len + ". Bytes written: " + bytesWritten);
}
return;
}
StringBuilder buffer = getCurrentBuffer();
buffer.append(cbuf, off, len);
}
@Override
public void write(String str, int off, int len) throws IOException {
if (!transactionActive()) {
byte[] bytes = str.substring(off, off + len).getBytes(encoding);
int length = bytes.length;
ByteBuffer bb = ByteBuffer.wrap(bytes);
int bytesWritten = channel.write(bb);
if (bytesWritten != length) {
throw new IOException(
"Unable to write all data. Bytes to write: " + len + ". Bytes written: " + bytesWritten);
}
return;
}
StringBuilder buffer = getCurrentBuffer();
buffer.append(str, off, off + len);
}
}
|
if (!transactionActive()) {
return 0L;
}
try {
return getCurrentBuffer().toString().getBytes(encoding).length;
}
catch (UnsupportedEncodingException e) {
throw new WriteFailedException(
"Could not determine buffer size because of unsupported encoding: " + encoding, e);
}
| 1,449
| 89
| 1,538
|
<methods>public java.io.Writer append(java.lang.CharSequence) throws java.io.IOException,public java.io.Writer append(char) throws java.io.IOException,public java.io.Writer append(java.lang.CharSequence, int, int) throws java.io.IOException,public abstract void close() throws java.io.IOException,public abstract void flush() throws java.io.IOException,public static java.io.Writer nullWriter() ,public void write(int) throws java.io.IOException,public void write(char[]) throws java.io.IOException,public void write(java.lang.String) throws java.io.IOException,public abstract void write(char[], int, int) throws java.io.IOException,public void write(java.lang.String, int, int) throws java.io.IOException<variables>private static final int WRITE_BUFFER_SIZE,protected java.lang.Object lock,private char[] writeBuffer
|
spring-projects_spring-batch
|
spring-batch/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/transaction/TransactionAwareProxyFactory.java
|
TransactionAwareInterceptor
|
invoke
|
class TransactionAwareInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
return invocation.proceed();
}
T cache;
if (!TransactionSynchronizationManager.hasResource(this)) {
cache = begin(target);
TransactionSynchronizationManager.bindResource(this, cache);
TransactionSynchronizationManager.registerSynchronization(new TargetSynchronization(this, cache));
}
else {
@SuppressWarnings("unchecked")
T retrievedCache = (T) TransactionSynchronizationManager.getResource(this);
cache = retrievedCache;
}
Object result = invocation.getMethod().invoke(cache, invocation.getArguments());
if (appendOnly) {
String methodName = invocation.getMethod().getName();
if ((result == null && methodName.equals("get"))
|| (Boolean.FALSE.equals(result) && (methodName.startsWith("contains"))
|| (Boolean.TRUE.equals(result) && methodName.startsWith("isEmpty")))) {
// In appendOnly mode the result of a get might not be
// in the cache...
return invocation.proceed();
}
if (result instanceof Collection<?>) {
HashSet<Object> set = new HashSet<>((Collection<?>) result);
set.addAll((Collection<?>) invocation.proceed());
result = set;
}
}
return result;
| 52
| 374
| 426
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/aot/IntegrationRuntimeHints.java
|
IntegrationRuntimeHints
|
registerHints
|
class IntegrationRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {<FILL_FUNCTION_BODY>}
}
|
// reflection hints
MemberCategory[] memberCategories = MemberCategory.values();
hints.reflection().registerType(ChunkRequest.class, memberCategories);
hints.reflection().registerType(ChunkResponse.class, memberCategories);
hints.reflection().registerType(StepExecutionRequestHandler.class, memberCategories);
hints.reflection().registerType(MessageChannelPartitionHandler.class, memberCategories);
// serialization hints
hints.serialization().registerType(ChunkRequest.class);
hints.serialization().registerType(ChunkResponse.class);
hints.serialization().registerType(StepExecutionRequest.class);
| 52
| 174
| 226
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemProcessor.java
|
AsyncItemProcessor
|
process
|
class AsyncItemProcessor<I, O> implements ItemProcessor<I, Future<O>>, InitializingBean {
private ItemProcessor<I, O> delegate;
private TaskExecutor taskExecutor = new SyncTaskExecutor();
/**
* Check mandatory properties (the {@link #setDelegate(ItemProcessor)}).
*
* @see InitializingBean#afterPropertiesSet()
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(delegate != null, "The delegate must be set.");
}
/**
* The {@link ItemProcessor} to use to delegate processing to in a background thread.
* @param delegate the {@link ItemProcessor} to use as a delegate
*/
public void setDelegate(ItemProcessor<I, O> delegate) {
this.delegate = delegate;
}
/**
* The {@link TaskExecutor} to use to allow the item processing to proceed in the
* background. Defaults to a {@link SyncTaskExecutor} so no threads are created unless
* this is overridden.
* @param taskExecutor a {@link TaskExecutor}
*/
public void setTaskExecutor(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* Transform the input by delegating to the provided item processor. The return value
* is wrapped in a {@link Future} so that clients can unpack it later.
*
* @see ItemProcessor#process(Object)
*/
@Override
@Nullable
public Future<O> process(final I item) throws Exception {<FILL_FUNCTION_BODY>}
/**
* @return the current step execution if there is one
*/
private StepExecution getStepExecution() {
StepContext context = StepSynchronizationManager.getContext();
if (context == null) {
return null;
}
return context.getStepExecution();
}
}
|
final StepExecution stepExecution = getStepExecution();
FutureTask<O> task = new FutureTask<>(() -> {
if (stepExecution != null) {
StepSynchronizationManager.register(stepExecution);
}
try {
return delegate.process(item);
}
finally {
if (stepExecution != null) {
StepSynchronizationManager.close();
}
}
});
taskExecutor.execute(task);
return task;
| 461
| 131
| 592
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemWriter.java
|
AsyncItemWriter
|
write
|
class AsyncItemWriter<T> implements ItemStreamWriter<Future<T>>, InitializingBean {
private static final Log logger = LogFactory.getLog(AsyncItemWriter.class);
private ItemWriter<T> delegate;
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(delegate != null, "A delegate ItemWriter must be provided.");
}
/**
* @param delegate ItemWriter that does the actual writing of the Future results
*/
public void setDelegate(ItemWriter<T> delegate) {
this.delegate = delegate;
}
/**
* In the processing of the {@link java.util.concurrent.Future}s passed, nulls are
* <em>not</em> passed to the delegate since they are considered filtered out by the
* {@link org.springframework.batch.integration.async.AsyncItemProcessor}'s delegated
* {@link org.springframework.batch.item.ItemProcessor}. If the unwrapping of the
* {@link Future} results in an {@link ExecutionException}, that will be unwrapped and
* the cause will be thrown.
* @param items {@link java.util.concurrent.Future}s to be unwrapped and passed to the
* delegate
* @throws Exception The exception returned by the Future if one was thrown
*/
@Override
public void write(Chunk<? extends Future<T>> items) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
if (delegate instanceof ItemStream) {
((ItemStream) delegate).open(executionContext);
}
}
@Override
public void update(ExecutionContext executionContext) throws ItemStreamException {
if (delegate instanceof ItemStream) {
((ItemStream) delegate).update(executionContext);
}
}
@Override
public void close() throws ItemStreamException {
if (delegate instanceof ItemStream) {
((ItemStream) delegate).close();
}
}
}
|
List<T> list = new ArrayList<>();
for (Future<T> future : items) {
try {
T item = future.get();
if (item != null) {
list.add(item);
}
}
catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
logger.debug("An exception was thrown while processing an item", e);
throw (Exception) cause;
}
else {
throw e;
}
}
}
delegate.write(new Chunk<>(list));
| 499
| 170
| 669
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/StepExecutionInterceptor.java
|
StepExecutionInterceptor
|
preSend
|
class StepExecutionInterceptor implements ChannelInterceptor {
/**
* The name of the header
*/
public static final String STEP_EXECUTION = "stepExecution";
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {<FILL_FUNCTION_BODY>}
}
|
StepContext context = StepSynchronizationManager.getContext();
if (context == null) {
return message;
}
return MessageBuilder.fromMessage(message).setHeader(STEP_EXECUTION, context.getStepExecution()).build();
| 83
| 66
| 149
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkMessageChannelItemWriter.java
|
LocalState
|
pollChunkResponses
|
class LocalState {
private final AtomicInteger current = new AtomicInteger(-1);
private final AtomicInteger actual = new AtomicInteger();
private final AtomicInteger expected = new AtomicInteger();
private final AtomicInteger redelivered = new AtomicInteger();
private StepExecution stepExecution;
private final Queue<ChunkResponse> contributions = new LinkedBlockingQueue<>();
public int getExpecting() {
return expected.get() - actual.get();
}
public <T> ChunkRequest<T> getRequest(Chunk<? extends T> items) {
return new ChunkRequest<>(current.incrementAndGet(), items, getJobId(), createStepContribution());
}
public void open(int expectedValue, int actualValue) {
actual.set(actualValue);
expected.set(expectedValue);
}
public Collection<ChunkResponse> pollChunkResponses() {<FILL_FUNCTION_BODY>}
public void pushResponse(ChunkResponse stepContribution) {
synchronized (contributions) {
contributions.add(stepContribution);
}
}
public void incrementRedelivered() {
redelivered.incrementAndGet();
}
public void incrementActual() {
actual.incrementAndGet();
}
public void incrementExpected() {
expected.incrementAndGet();
}
public StepContribution createStepContribution() {
return stepExecution.createStepContribution();
}
public Long getJobId() {
return stepExecution.getJobExecution().getJobId();
}
public void setStepExecution(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
public void reset() {
expected.set(0);
actual.set(0);
}
}
|
Collection<ChunkResponse> set = new ArrayList<>();
synchronized (contributions) {
ChunkResponse item = contributions.poll();
while (item != null) {
set.add(item);
item = contributions.poll();
}
}
return set;
| 478
| 82
| 560
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandler.java
|
ChunkProcessorChunkHandler
|
process
|
class ChunkProcessorChunkHandler<S> implements ChunkHandler<S>, InitializingBean {
private static final Log logger = LogFactory.getLog(ChunkProcessorChunkHandler.class);
private ChunkProcessor<S> chunkProcessor;
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(chunkProcessor != null, "A ChunkProcessor must be provided");
}
/**
* Public setter for the {@link ChunkProcessor}.
* @param chunkProcessor the chunkProcessor to set
*/
public void setChunkProcessor(ChunkProcessor<S> chunkProcessor) {
this.chunkProcessor = chunkProcessor;
}
/**
*
* @see ChunkHandler#handleChunk(ChunkRequest)
*/
@Override
@ServiceActivator
public ChunkResponse handleChunk(ChunkRequest<S> chunkRequest) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Handling chunk: " + chunkRequest);
}
StepContribution stepContribution = chunkRequest.getStepContribution();
Throwable failure = process(chunkRequest, stepContribution);
if (failure != null) {
logger.debug("Failed chunk", failure);
return new ChunkResponse(false, chunkRequest.getSequence(), chunkRequest.getJobId(), stepContribution,
failure.getClass().getName() + ": " + failure.getMessage());
}
if (logger.isDebugEnabled()) {
logger.debug("Completed chunk handling with " + stepContribution);
}
return new ChunkResponse(true, chunkRequest.getSequence(), chunkRequest.getJobId(), stepContribution);
}
/**
* @param chunkRequest the current request
* @param stepContribution the step contribution to update
* @throws Exception if there is a fatal exception
*/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
private Throwable process(ChunkRequest<S> chunkRequest, StepContribution stepContribution) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Chunk chunk = chunkRequest.getItems();
Throwable failure = null;
try {
chunkProcessor.process(stepContribution, chunk);
}
catch (SkipLimitExceededException | NonSkippableReadException | SkipListenerFailedException | RetryException
| JobInterruptedException e) {
failure = e;
}
catch (Exception e) {
if (chunkProcessor instanceof FaultTolerantChunkProcessor<?, ?>) {
// try again...
throw e;
}
else {
failure = e;
}
}
return failure;
| 521
| 169
| 690
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkRequest.java
|
ChunkRequest
|
toString
|
class ChunkRequest<T> implements Serializable {
private static final long serialVersionUID = 1L;
private final long jobId;
private final Chunk<? extends T> items;
private final StepContribution stepContribution;
private final int sequence;
public ChunkRequest(int sequence, Chunk<? extends T> items, long jobId, StepContribution stepContribution) {
this.sequence = sequence;
this.items = items;
this.jobId = jobId;
this.stepContribution = stepContribution;
}
public long getJobId() {
return jobId;
}
public Chunk<? extends T> getItems() {
return items;
}
public int getSequence() {
return sequence;
}
/**
* @return the {@link StepContribution} for this chunk
*/
public StepContribution getStepContribution() {
return stepContribution;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getSimpleName() + ": jobId=" + jobId + ", sequence=" + sequence + ", contribution="
+ stepContribution + ", item count=" + items.size();
| 273
| 52
| 325
|
<no_super_class>
|
spring-projects_spring-batch
|
spring-batch/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkResponse.java
|
ChunkResponse
|
toString
|
class ChunkResponse implements Serializable {
private static final long serialVersionUID = 1L;
private final StepContribution stepContribution;
private final Long jobId;
private final boolean status;
private final String message;
private final boolean redelivered;
private final int sequence;
public ChunkResponse(int sequence, Long jobId, StepContribution stepContribution) {
this(true, sequence, jobId, stepContribution, null);
}
public ChunkResponse(boolean status, int sequence, Long jobId, StepContribution stepContribution) {
this(status, sequence, jobId, stepContribution, null);
}
public ChunkResponse(boolean status, int sequence, Long jobId, StepContribution stepContribution,
@Nullable String message) {
this(status, sequence, jobId, stepContribution, message, false);
}
public ChunkResponse(ChunkResponse input, boolean redelivered) {
this(input.status, input.sequence, input.jobId, input.stepContribution, input.message, redelivered);
}
public ChunkResponse(boolean status, int sequence, Long jobId, StepContribution stepContribution,
@Nullable String message, boolean redelivered) {
this.status = status;
this.sequence = sequence;
this.jobId = jobId;
this.stepContribution = stepContribution;
this.message = message;
this.redelivered = redelivered;
}
public StepContribution getStepContribution() {
return stepContribution;
}
public Long getJobId() {
return jobId;
}
public int getSequence() {
return sequence;
}
public boolean isSuccessful() {
return status;
}
public boolean isRedelivered() {
return redelivered;
}
public String getMessage() {
return message;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return getClass().getSimpleName() + ": jobId=" + jobId + ", sequence=" + sequence + ", stepContribution="
+ stepContribution + ", successful=" + status;
| 504
| 51
| 555
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.