repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/workflows/dapr-workflows/src/main/java/com/baeldung/dapr/workflow/model/RideWorkflowRequest.java | workflows/dapr-workflows/src/main/java/com/baeldung/dapr/workflow/model/RideWorkflowRequest.java | package com.baeldung.dapr.workflow.model;
import com.baeldung.dapr.pubsub.model.RideRequest;
public class RideWorkflowRequest {
private String rideId;
private RideRequest rideRequest;
private String driverId;
private String workflowInstanceId;
public RideWorkflowRequest() {
}
public RideWorkflowRequest(String rideId, RideRequest rideRequest, String driverId, String workflowInstanceId) {
this.rideId = rideId;
this.rideRequest = rideRequest;
this.driverId = driverId;
this.workflowInstanceId = workflowInstanceId;
}
public String getRideId() {
return rideId;
}
public void setRideId(String rideId) {
this.rideId = rideId;
}
public RideRequest getRideRequest() {
return rideRequest;
}
public void setRideRequest(RideRequest rideRequest) {
this.rideRequest = rideRequest;
}
public String getDriverId() {
return driverId;
}
public void setDriverId(String driverId) {
this.driverId = driverId;
}
public String getWorkflowInstanceId() {
return workflowInstanceId;
}
public void setWorkflowInstanceId(String workflowInstanceId) {
this.workflowInstanceId = workflowInstanceId;
}
@Override
public String toString() {
return "RideWorkflowRequest{" + "rideId='" + rideId + '\'' + ", rideRequest=" + rideRequest + ", driverId='" + driverId + '\'' + ", workflowInstanceId='" + workflowInstanceId + '\'' + '}';
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/workflows/dapr-workflows/src/main/java/com/baeldung/dapr/workflow/model/RideWorkflowStatus.java | workflows/dapr-workflows/src/main/java/com/baeldung/dapr/workflow/model/RideWorkflowStatus.java | package com.baeldung.dapr.workflow.model;
public record RideWorkflowStatus(String rideId, String status, String message) {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-open-telemetry/otel-collector/trivia-service/src/test/java/com/baeldung/TriviaServiceUnitTest.java | libraries-open-telemetry/otel-collector/trivia-service/src/test/java/com/baeldung/TriviaServiceUnitTest.java | package com.baeldung;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertEquals;
import io.opentelemetry.context.propagation.TextMapPropagator;
import io.opentelemetry.context.Context;
class TriviaServiceUnitTest {
@Mock
private OkHttpClient mockHttpClient;
@Mock
private okhttp3.Call mockHttpCall;
@Mock
private Response mockHttpResponse;
@Mock
private ResponseBody mockHttpResponseBody;
private TriviaService triviaService;
private String wordServiceUrl;
@Mock
private TextMapPropagator mockTextMapPropagator;
@Mock
private Context mockContext;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
triviaService = new TriviaService(mockHttpClient, mockTextMapPropagator);
wordServiceUrl = "https://localhost:8081/api/words/random";
}
@Test
void whenRequestingAWordFromSource_thenReturnAWordWithDefinition() throws IOException {
String responseBody = "{\"meaning\":\"Fluent or persuasive in speaking or writing.\",\"word\":\"eloquent\"}";
when(mockHttpClient.newCall(any(Request.class))).thenReturn(mockHttpCall);
when(mockHttpCall.execute()).thenReturn(mockHttpResponse);
when(mockHttpResponse.isSuccessful()).thenReturn(true);
when(mockHttpResponse.body()).thenReturn(mockHttpResponseBody);
when(mockHttpResponseBody.string()).thenReturn(responseBody);
when(mockHttpResponse.code()).thenReturn(200);
WordResponse result = triviaService.requestWordFromSource(mockContext, wordServiceUrl);
assertEquals(responseBody, result.wordWithDefinition());
assertEquals(200, result.httpResponseCode());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-open-telemetry/otel-collector/trivia-service/src/main/java/com/baeldung/TriviaService.java | libraries-open-telemetry/otel-collector/trivia-service/src/main/java/com/baeldung/TriviaService.java | package com.baeldung;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import io.opentelemetry.context.propagation.TextMapPropagator;
import io.opentelemetry.context.Context;
public class TriviaService {
private final OkHttpClient client;
private TextMapPropagator textMapPropagator;
public TriviaService(OkHttpClient client, TextMapPropagator textMapPropagator) {
this.client = client;
this.textMapPropagator = textMapPropagator;
}
public WordResponse requestWordFromSource(Context context, String wordServiceUrl) throws IOException {
Request request = new Request.Builder()
.url(wordServiceUrl)
.build();
Request.Builder requestBuilder = request.newBuilder();
textMapPropagator.inject(context, requestBuilder, Request.Builder::addHeader);
okhttp3.Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected service call error: " + response);
}
return new WordResponse(response.body().string(), response.code());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-open-telemetry/otel-collector/trivia-service/src/main/java/com/baeldung/TriviaResource.java | libraries-open-telemetry/otel-collector/trivia-service/src/main/java/com/baeldung/TriviaResource.java | package com.baeldung;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import okhttp3.OkHttpClient;
import java.io.IOException;
import java.time.Instant;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.StatusCode;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.context.Scope;
import io.opentelemetry.context.Context;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
@Path("/trivia")
public class TriviaResource {
Logger logger = LogManager.getLogger(TriviaResource.class);
private final Tracer tracer;
private final Meter meter;
private TriviaService triviaService;
private final LongCounter httpRequestCounter;
static final String OTEL_SERVICE_NAME = "trivia-service";
static final String WORD_SERVICE_URL = "http://127.0.0.1:8081/api/words/random";
public TriviaResource() {
TelemetryConfig telemetryConfig = TelemetryConfig.getInstance();
this.tracer = telemetryConfig.getOpenTelemetry().getTracer(OTEL_SERVICE_NAME, "0.0.1-SNAPSHOT");
this.meter = telemetryConfig.getOpenTelemetry().getMeter(OTEL_SERVICE_NAME);
var textMapPropagator = telemetryConfig.getOpenTelemetry().getPropagators().getTextMapPropagator();
this.triviaService = new TriviaService(new OkHttpClient(), textMapPropagator);
this.httpRequestCounter = meter.counterBuilder("http.request.count")
.setDescription("Counts the number of HTTP requests")
.setUnit("1")
.build();
}
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response retrieveCard() {
httpRequestCounter.add(1, Attributes.builder().put("endpoint", "/trivia").build());
Span span = tracer.spanBuilder("retreive_card")
.setAttribute("http.method", "GET")
.setAttribute("http.url", WORD_SERVICE_URL)
.setSpanKind(SpanKind.CLIENT).startSpan();
try (Scope scope = span.makeCurrent()) {
Instant start = Instant.now();
span.addEvent("http.request.word-api", start);
WordResponse wordResponse = triviaService.requestWordFromSource(Context.current().with(span), WORD_SERVICE_URL);
span.setAttribute("http.status_code", wordResponse.httpResponseCode());
logger.info("word-api response payload: {}", wordResponse.wordWithDefinition());
return Response.ok(wordResponse.wordWithDefinition()).build();
} catch(IOException exception) {
span.setStatus(StatusCode.ERROR, "Error retreiving info from dictionary service");
span.recordException(exception);
logger.error("Error while calling dictionary service", exception);
return Response.noContent().build();
} finally {
span.end();
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-open-telemetry/otel-collector/trivia-service/src/main/java/com/baeldung/TelemetryConfig.java | libraries-open-telemetry/otel-collector/trivia-service/src/main/java/com/baeldung/TelemetryConfig.java | package com.baeldung;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator;
import io.opentelemetry.context.propagation.ContextPropagators;
import io.opentelemetry.context.propagation.TextMapPropagator;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.metrics.export.MetricExporter;
import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader;
import io.opentelemetry.sdk.metrics.export.MetricReader;
import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor;
import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.logs.LogRecordProcessor;
import io.opentelemetry.sdk.logs.SdkLoggerProvider;
import io.opentelemetry.sdk.logs.export.LogRecordExporter;
import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter;
import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter;
import io.opentelemetry.instrumentation.log4j.appender.v2_17.OpenTelemetryAppender;
import java.util.concurrent.TimeUnit;
public class TelemetryConfig {
private static final String OTLP_TRACES_ENDPOINT = "http://telemetry-collector:4318/v1/traces";
private static final String OTLP_METRICS_ENDPOINT = "http://telemetry-collector:4318/v1/metrics";
private static final String OTLP_LOGS_ENDPOINT = "http://telemetry-collector:4317";
private static TelemetryConfig telemetryConfig;
private final OpenTelemetry openTelemetry;
private TelemetryConfig() {
Resource resource = Resource.getDefault()
.toBuilder()
.put(AttributeKey.stringKey("service.name"), "trivia-service")
.put(AttributeKey.stringKey("service.version"), "1.0-SNAPSHOT")
.build();
// Tracing setup
SpanExporter spanExporter = OtlpHttpSpanExporter.builder().setEndpoint(OTLP_TRACES_ENDPOINT).build();
SdkTracerProvider tracerProvider = SdkTracerProvider.builder()
.setResource(resource)
.addSpanProcessor(SimpleSpanProcessor.create(spanExporter))
.build();
// Metrics setup
MetricExporter metricExporter = OtlpHttpMetricExporter.builder().setEndpoint(OTLP_METRICS_ENDPOINT).build();
MetricReader metricReader = PeriodicMetricReader.builder(metricExporter)
.setInterval(30, TimeUnit.SECONDS)
.build();
SdkMeterProvider meterProvider = SdkMeterProvider.builder()
.setResource(resource)
.registerMetricReader(metricReader)
.build();
// Logging setup
LogRecordExporter logRecordExporter = OtlpGrpcLogRecordExporter.builder().setEndpoint(OTLP_LOGS_ENDPOINT).build();
LogRecordProcessor logRecordProcessor = BatchLogRecordProcessor.builder(logRecordExporter).build();
SdkLoggerProvider sdkLoggerProvider = SdkLoggerProvider.builder()
.setResource(resource)
.addLogRecordProcessor(logRecordProcessor).build();
openTelemetry = OpenTelemetrySdk.builder()
.setMeterProvider(meterProvider)
.setTracerProvider(tracerProvider)
.setLoggerProvider(sdkLoggerProvider)
.setPropagators(ContextPropagators.create(TextMapPropagator.composite(W3CTraceContextPropagator.getInstance(), W3CBaggagePropagator.getInstance())))
.buildAndRegisterGlobal();
//OpenTelemetryAppender in log4j configuration and install
OpenTelemetryAppender.install(openTelemetry);
}
public OpenTelemetry getOpenTelemetry() {
return openTelemetry;
}
public static TelemetryConfig getInstance() {
if (telemetryConfig == null) {
telemetryConfig = new TelemetryConfig();
}
return telemetryConfig;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-open-telemetry/otel-collector/trivia-service/src/main/java/com/baeldung/WordResponse.java | libraries-open-telemetry/otel-collector/trivia-service/src/main/java/com/baeldung/WordResponse.java | package com.baeldung;
public record WordResponse(String wordWithDefinition, int httpResponseCode) {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-open-telemetry/otel-collector/trivia-service/src/main/java/com/baeldung/AppConfig.java | libraries-open-telemetry/otel-collector/trivia-service/src/main/java/com/baeldung/AppConfig.java | package com.baeldung;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
@ApplicationPath("/api")
public class AppConfig extends Application {
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-open-telemetry/otel-collector/dictionary-service/src/test/java/com/baeldung/DictionaryServiceUnitTest.java | libraries-open-telemetry/otel-collector/dictionary-service/src/test/java/com/baeldung/DictionaryServiceUnitTest.java | package com.baeldung;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DictionaryServiceUnitTest {
private DictionaryService dictionaryService;
@BeforeEach
void setUp() {
dictionaryService = new DictionaryService();
}
@Test
void whenGeneratingAKnownWord_thenReturnMeaning() {
String word = "serendipity";
String meaning = dictionaryService.getWordMeaning(word);
assertEquals("The occurrence and development of events by chance in a happy or beneficial way.", meaning);
}
@Test
void whenGeneratingAnUnknownWord_thenReturnErrorMessage() {
String word = "unknownWord";
String meaning = dictionaryService.getWordMeaning(word);
assertEquals("Meaning not found.", meaning);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-open-telemetry/otel-collector/dictionary-service/src/main/java/com/baeldung/DictionaryServiceApplication.java | libraries-open-telemetry/otel-collector/dictionary-service/src/main/java/com/baeldung/DictionaryServiceApplication.java | package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DictionaryServiceApplication {
public static void main(String[] args) {
SpringApplication.run(DictionaryServiceApplication.class, args);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-open-telemetry/otel-collector/dictionary-service/src/main/java/com/baeldung/DictionaryService.java | libraries-open-telemetry/otel-collector/dictionary-service/src/main/java/com/baeldung/DictionaryService.java | package com.baeldung;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Service
public class DictionaryService {
private static final Logger logger = LoggerFactory.getLogger(DictionaryService.class);
static final Map<String, String> dictionary = new HashMap<>();
static {
dictionary.put("serendipity", "The occurrence and development of events by chance in a happy or beneficial way.");
dictionary.put("eloquent", "Fluent or persuasive in speaking or writing.");
dictionary.put("quintessential", "Representing the most perfect or typical example of a quality or class.");
dictionary.put("resilient", "Able to withstand or recover quickly from difficult conditions.");
dictionary.put("peregrinate", "To travel or wander from place to place, especially on foot.");
dictionary.put("susurrus", "A whispering or rustling sound, like that of leaves or the wind.");
dictionary.put("quixotic", "Extremely idealistic, unrealistic, and impractical.");
dictionary.put("lacuna", "An unfilled space or gap; a missing portion in a manuscript or text.");
dictionary.put("ephemeral", "Lasting for a very short time; transient.");
dictionary.put("syzygy", "The alignment of three celestial bodies in a straight line, commonly the Earth, Moon, and Sun.");
dictionary.put("pusillanimous", "Showing a lack of courage or determination; timid.");
dictionary.put("mellifluous", "(of a voice or words) Sweet or musical; pleasant to hear.");
dictionary.put("defenestration", "The act of throwing someone out of a window.");
dictionary.put("pulchritudinous", "Having great physical beauty or appeal.");
}
private final Random random = new Random();
public String getRandomWord() {
try {
// Randomly pause for a duration between 1 and 5 seconds
int delay = 1000 + random.nextInt(4000);
logger.info("Mandatory pause period of {} milliseconds", delay);
Thread.sleep(delay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
Object[] words = dictionary.keySet().toArray();
return (String) words[random.nextInt(words.length)];
}
public String getWordMeaning(String word) {
return dictionary.getOrDefault(word, "Meaning not found.");
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-open-telemetry/otel-collector/dictionary-service/src/main/java/com/baeldung/DictionaryController.java | libraries-open-telemetry/otel-collector/dictionary-service/src/main/java/com/baeldung/DictionaryController.java | package com.baeldung;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.context.Scope;
import io.opentelemetry.context.Context;
@RestController
@RequestMapping("/api/words")
public class DictionaryController {
private static final Logger logger = LoggerFactory.getLogger(DictionaryController.class);
private final DictionaryService dictionaryService;
@Autowired
OpenTelemetry openTelemetry;
public DictionaryController(DictionaryService dictionaryService) {
this.dictionaryService = dictionaryService;
}
@GetMapping("/random")
public Map<String, String> getRandomWord() {
Map<String, String> response = new HashMap<>();
Tracer tracer = openTelemetry.getTracer("dictionary-service-application");
Span span = tracer.spanBuilder("get_word")
.setParent(Context.current().with(Span.current()))
.startSpan();
try (Scope scope = span.makeCurrent()) {
logger.info("Processing received request for a random word");
String word = dictionaryService.getRandomWord();
String meaning = dictionaryService.getWordMeaning(word);
logger.info("Generated result: {} , {}", word, meaning);
response.put("word", word);
response.put("meaning", meaning);
} catch(Exception exception ) {
span.recordException(exception);
} finally {
span.end();
}
return response;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-open-telemetry/otel-collector/dictionary-service/src/main/java/com/baeldung/OtelConfiguration.java | libraries-open-telemetry/otel-collector/dictionary-service/src/main/java/com/baeldung/OtelConfiguration.java | package com.baeldung;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.OpenTelemetry;
@Configuration
public class OtelConfiguration {
@Bean
public OpenTelemetry openTelemetry() {
return GlobalOpenTelemetry.get();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/test/java/com/baeldung/batch/CompositeItemReaderUnitTest.java | spring-batch-2/src/test/java/com/baeldung/batch/CompositeItemReaderUnitTest.java | package com.baeldung.batch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.math.BigDecimal;
import java.util.Arrays;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStreamReader;
import org.springframework.batch.item.support.CompositeItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import com.baeldung.batch.model.Product;
@SpringBootTest
@EnableAutoConfiguration
@ContextConfiguration(classes = { CompositeItemReaderConfig.class })
public class CompositeItemReaderUnitTest {
@Autowired
private CompositeItemReader<Product> compositeReader;
@Autowired
private JdbcTemplate jdbcTemplate;
@BeforeEach
public void setUp() {
jdbcTemplate.update("DELETE FROM products");
jdbcTemplate.update("INSERT INTO products (productid, productname, stock, price) VALUES (?, ?, ?, ?)",
102, "Banana", 30, 1.49);
}
@Test
public void givenTwoReaders_whenRead_thenProcessProductsInOrder() throws Exception {
StepExecution stepExecution = new StepExecution("testStep", new JobExecution(1L, new JobParameters()), 1L);
ExecutionContext executionContext = stepExecution.getExecutionContext();
compositeReader.open(executionContext);
Product product1 = compositeReader.read();
assertNotNull(product1);
assertEquals(101, product1.getProductId());
assertEquals("Apple", product1.getProductName());
Product product2 = compositeReader.read();
assertNotNull(product2);
assertEquals(102, product2.getProductId());
assertEquals("Banana", product2.getProductName());
}
@Test
public void givenMultipleReader_whenOneReaderReturnNull_thenProcessDataFromNextReader() throws Exception {
ItemStreamReader<Product> emptyReader = mock(ItemStreamReader.class);
when(emptyReader.read()).thenReturn(null);
ItemStreamReader<Product> validReader = mock(ItemStreamReader.class);
when(validReader.read()).thenReturn(new Product(103L, "Cherry", 20, BigDecimal.valueOf(2.99)), null);
CompositeItemReader<Product> compositeReader = new CompositeItemReader<>(Arrays.asList(emptyReader, validReader));
Product product = compositeReader.read();
assertNotNull(product);
assertEquals(103, product.getProductId());
assertEquals("Cherry", product.getProductName());
}
@Test
public void givenEmptyReaders_whenRead_thenReturnNull() throws Exception {
ItemStreamReader<Product> emptyReader = mock(ItemStreamReader.class);
when(emptyReader.read()).thenReturn(null);
CompositeItemReader<Product> compositeReader = new CompositeItemReader<>(Arrays.asList(emptyReader, emptyReader));
Product product = compositeReader.read();
assertNull(product);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/test/java/com/baeldung/batch/SpringBatchRetryIntegrationTest.java | spring-batch-2/src/test/java/com/baeldung/batch/SpringBatchRetryIntegrationTest.java | package com.baeldung.batch;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobInstance;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.core.io.FileSystemResource;
import org.springframework.test.context.ContextConfiguration;
@SpringBatchTest
@EnableAutoConfiguration
@ContextConfiguration(classes = { SpringBatchRetryConfig.class })
public class SpringBatchRetryIntegrationTest {
private static final String TEST_OUTPUT = "xml/retryOutput.xml";
private static final String EXPECTED_OUTPUT = "src/test/resources/output/batchRetry/retryOutput.xml";
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@MockBean
private CloseableHttpClient closeableHttpClient;
@Mock
private CloseableHttpResponse httpResponse;
@Test
public void whenEndpointAlwaysFail_thenJobFails() throws Exception {
when(closeableHttpClient.execute(any()))
.thenThrow(new ConnectTimeoutException("Endpoint is down"));
JobExecution jobExecution = jobLauncherTestUtils.launchJob(defaultJobParameters());
JobInstance actualJobInstance = jobExecution.getJobInstance();
ExitStatus actualJobExitStatus = jobExecution.getExitStatus();
assertEquals("retryBatchJob", actualJobInstance.getJobName());
assertEquals("FAILED", actualJobExitStatus.getExitCode());
assertThat(actualJobExitStatus.getExitDescription(), containsString("org.apache.http.conn.ConnectTimeoutException"));
}
@Test
public void whenEndpointFailsTwicePasses3rdTime_thenSuccess() throws Exception {
FileSystemResource expectedResult = new FileSystemResource(EXPECTED_OUTPUT);
FileSystemResource actualResult = new FileSystemResource(TEST_OUTPUT);
//fails for first two calls and passes third time onwards
when(httpResponse.getEntity())
.thenReturn(new StringEntity("{ \"age\":10, \"postCode\":\"430222\" }"));
when(closeableHttpClient.execute(any()))
.thenThrow(new ConnectTimeoutException("Timeout count 1"))
.thenThrow(new ConnectTimeoutException("Timeout count 2"))
.thenReturn(httpResponse);
JobExecution jobExecution = jobLauncherTestUtils.launchJob(defaultJobParameters());
JobInstance actualJobInstance = jobExecution.getJobInstance();
ExitStatus actualJobExitStatus = jobExecution.getExitStatus();
assertEquals("retryBatchJob", actualJobInstance.getJobName());
assertEquals("COMPLETED", actualJobExitStatus.getExitCode());
org.assertj.core.api.Assertions.assertThat(actualResult.getFile()).hasSameTextualContentAs(expectedResult.getFile());
}
private JobParameters defaultJobParameters() {
JobParametersBuilder paramsBuilder = new JobParametersBuilder();
paramsBuilder.addString("jobID", String.valueOf(System.currentTimeMillis()));
return paramsBuilder.toJobParameters();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/test/java/com/baeldung/dataloaderbatchprocessing/DataLoaderUnitTest.java | spring-batch-2/src/test/java/com/baeldung/dataloaderbatchprocessing/DataLoaderUnitTest.java | package com.baeldung.dataloaderbatchprocessing;
import com.baeldung.dataloaderbatchprocessing.entity.User;
import com.baeldung.dataloaderbatchprocessing.repository.UserRepository;
import com.baeldung.dataloaderbatchprocessing.service.UserService;
import org.dataloader.DataLoader;
import org.dataloader.DataLoaderRegistry;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.SpyBean;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
@SpringBootTest(classes = DataLoaderApp.class)
class UserDataLoaderIntegrationTest {
@Autowired
private UserRepository userRepository;
@SpyBean
private UserService userService;
private DataLoader<String, User> userDataLoader;
@BeforeEach
void setUp() {
userRepository.deleteAll();
User user1 = new User("101", "User_101");
User user2 = new User("102", "User_102");
User user3 = new User("103", "User_103");
userRepository.saveAll(Arrays.asList(user1, user2, user3));
userDataLoader = new DataLoader<>(userService::getUsersByIds);
DataLoaderRegistry registry = new DataLoaderRegistry();
registry.register("userDataLoader", userDataLoader);
}
@Test
void whenLoadingUsers_thenBatchLoaderIsInvokedAndResultsReturned() {
CompletableFuture<User> userFuture1 = userDataLoader.load("101");
CompletableFuture<User> userFuture2 = userDataLoader.load("102");
CompletableFuture<User> userFuture3 = userDataLoader.load("103");
userDataLoader.dispatchAndJoin();
verify(userService, times(1)).getUsersByIds(anyList());
assertThat(userFuture1.join().getName()).isEqualTo("User_101");
assertThat(userFuture2.join().getName()).isEqualTo("User_102");
assertThat(userFuture3.join().getName()).isEqualTo("User_103");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/test/java/com/baeldung/restartjob/RestartJobBatchAppIntegrationTest.java | spring-batch-2/src/test/java/com/baeldung/restartjob/RestartJobBatchAppIntegrationTest.java | package com.baeldung.restartjob;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.junit.jupiter.api.Test;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
@SpringBootTest(classes = {RestartJobBatchApp.class, BatchConfig.class},
properties = {"job.autorun.enabled=false"})
@Import(RestartJobBatchAppIntegrationTest.TestConfig.class)
public class RestartJobBatchAppIntegrationTest {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Autowired
private BatchConfig.RestartItemProcessor itemProcessor;
@TestConfiguration
static class TestConfig {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job job;
@Bean
public JobLauncherTestUtils jobLauncherTestUtils() {
JobLauncherTestUtils jobLauncherTestUtils = new JobLauncherTestUtils();
jobLauncherTestUtils.setJobLauncher(jobLauncher);
jobLauncherTestUtils.setJob(job);
return jobLauncherTestUtils;
}
}
private final Resource inputFile = new ClassPathResource("data.csv");
@Test
public void givenItems_whenFailed_thenRestartFromFailure() throws Exception {
// Given
createTestFile("Item1\nItem2\nItem3\nItem4");
JobParameters jobParameters = new JobParametersBuilder()
.addLong("time", System.currentTimeMillis())
.toJobParameters();
// When
JobExecution firstExecution = jobLauncherTestUtils.launchJob(jobParameters);
assertEquals(BatchStatus.FAILED, firstExecution.getStatus());
Long executionId = firstExecution.getId();
itemProcessor.setFailOnItem3(false);
// Then
JobExecution restartedExecution = jobLauncherTestUtils.launchJob(jobParameters);
assertEquals(BatchStatus.COMPLETED, restartedExecution.getStatus());
assertEquals(
firstExecution.getJobInstance().getInstanceId(),
restartedExecution.getJobInstance().getInstanceId()
);
}
private void createTestFile(String content) throws IOException {
Path tempFile = Files.createTempFile("test-data", ".csv");
Files.write(tempFile, content.getBytes());
Files.copy(tempFile, inputFile.getFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/test/java/com/baeldung/conditionalflow/DeciderJobIntegrationTest.java | spring-batch-2/src/test/java/com/baeldung/conditionalflow/DeciderJobIntegrationTest.java | package com.baeldung.conditionalflow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collection;
import java.util.Iterator;
import com.baeldung.conditionalflow.config.NumberInfoConfig;
import org.junit.jupiter.api.Test;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.test.context.ContextConfiguration;
@SpringBatchTest
@EnableAutoConfiguration
@ContextConfiguration(classes = { NumberInfoConfig.class })
public class DeciderJobIntegrationTest {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Test
public void givenNumberGeneratorDecider_whenDeciderRuns_thenStatusIsNotify() throws Exception {
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
Collection<StepExecution> actualStepExecutions = jobExecution.getStepExecutions();
ExitStatus actualJobExitStatus = jobExecution.getExitStatus();
assertEquals("COMPLETED", actualJobExitStatus.getExitCode());
assertEquals(2, actualStepExecutions.size());
boolean notifyStepDidRun = false;
Iterator<StepExecution> iterator = actualStepExecutions.iterator();
while (iterator.hasNext() && !notifyStepDidRun) {
if (iterator.next()
.getStepName()
.equals("Notify step")) {
notifyStepDidRun = true;
}
}
assertTrue(notifyStepDidRun);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/test/java/com/baeldung/conditionalflow/model/NumberInfoUnitTest.java | spring-batch-2/src/test/java/com/baeldung/conditionalflow/model/NumberInfoUnitTest.java | package com.baeldung.conditionalflow.model;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
class NumberInfoUnitTest {
@Test
void givenPositive_whenFrom_isPositive() {
assertTrue(NumberInfo.from(1)
.isPositive());
assertTrue(NumberInfo.from(11)
.isPositive());
assertFalse(NumberInfo.from(0)
.isPositive());
}
@Test
void givenNegative_whenFrom_isNegative() {
assertFalse(NumberInfo.from(-1)
.isPositive());
assertFalse(NumberInfo.from(-10)
.isPositive());
}
@Test
void givenEven_whenFrom_isEven() {
assertTrue(NumberInfo.from(0)
.isEven());
assertTrue(NumberInfo.from(-2)
.isEven());
assertTrue(NumberInfo.from(2)
.isEven());
assertTrue(NumberInfo.from(-22)
.isEven());
assertTrue(NumberInfo.from(22)
.isEven());
}
@Test
void givenOdd_whenFrom_isOdd() {
assertFalse(NumberInfo.from(1)
.isEven());
assertFalse(NumberInfo.from(-1)
.isEven());
assertFalse(NumberInfo.from(13)
.isEven());
assertFalse(NumberInfo.from(-13)
.isEven());
assertFalse(NumberInfo.from(31)
.isEven());
assertFalse(NumberInfo.from(-51)
.isEven());
}
@Test
void giveGeneratedInt_whenFrom_isNumberFromGenerator() {
for (int i = -100; i < 100; i++) {
assertEquals(i, NumberInfo.from(i)
.getNumber());
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/test/java/com/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java | spring-batch-2/src/test/java/com/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java | package com.baeldung.conditionalflow.step;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.baeldung.conditionalflow.model.NumberInfo;
import org.junit.jupiter.api.Test;
class NumberInfoClassifierUnitTest {
@Test
void givenNumberInfo_whenProcess_thenConvertsToInteger() throws Exception {
NumberInfoClassifier nic = new NumberInfoClassifier();
assertEquals(Integer.valueOf(4), nic.process(NumberInfo.from(4)));
assertEquals(Integer.valueOf(-4), nic.process(NumberInfo.from(-4)));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/test/java/com/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java | spring-batch-2/src/test/java/com/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java | package com.baeldung.conditionalflow.step;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import com.baeldung.conditionalflow.model.NumberInfo;
import org.junit.jupiter.api.Test;
public class NumberInfoGeneratorUnitTest {
@Test
public void givenArray_whenGenerator_correctOrderAndValue() {
int[] numbers = new int[] { 1, -2, 4, -10 };
NumberInfoGenerator numberGenerator = new NumberInfoGenerator(numbers);
assertEquals(new NumberInfo(numbers[0]), numberGenerator.read());
assertEquals(new NumberInfo(numbers[1]), numberGenerator.read());
assertEquals(new NumberInfo(numbers[2]), numberGenerator.read());
assertEquals(new NumberInfo(numbers[3]), numberGenerator.read());
assertNull(numberGenerator.read());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/test/java/com/baeldung/multiprocessorandwriter/BatchJobIntegrationTest.java | spring-batch-2/src/test/java/com/baeldung/multiprocessorandwriter/BatchJobIntegrationTest.java | package com.baeldung.multiprocessorandwriter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStreamReader;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import com.baeldung.multiprocessorandwriter.config.BatchConfig;
import com.baeldung.multiprocessorandwriter.model.Customer;
import com.baeldung.multiprocessorandwriter.processor.CustomerProcessorRouter;
@SpringBootTest
@EnableAutoConfiguration
@ContextConfiguration(classes = { BatchConfig.class, JpaTestConfig.class})
@TestPropertySource(locations = "classpath:application-test.properties")
@Import(BatchJobIntegrationTest.TestConfig.class)
public class BatchJobIntegrationTest {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@TestConfiguration
static class TestConfig {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job job;
@Bean
public JobLauncherTestUtils jobLauncherTestUtils() {
JobLauncherTestUtils jobLauncherTestUtils = new JobLauncherTestUtils();
jobLauncherTestUtils.setJobLauncher(jobLauncher);
jobLauncherTestUtils.setJob(job);
return jobLauncherTestUtils;
}
}
@Autowired
private DataSource dataSource;
private Path outputFile;
@BeforeEach
public void setup() throws IOException {
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
try (ResultSet rs = metaData.getTables(null, null, "BATCH_JOB_INSTANCE", null)) {
if (!rs.next()) {
ScriptUtils.executeSqlScript(connection, new ClassPathResource("org/springframework/batch/core/schema-h2.sql"));
} else {
System.out.println("Spring Batch tables already exist. Skipping schema creation.");
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
outputFile = Paths.get("output/processed_customers.txt");
Files.deleteIfExists(outputFile); // clean output file before test
}
@Test
public void givenTypeA_whenProcess_thenNameIsUppercaseAndEmailPrefixedWithA() throws Exception {
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<Customer> dbCustomers = jdbcTemplate.query(
"SELECT id, name, email, type FROM customer WHERE type = 'A'",
(rs, rowNum) -> new Customer(
rs.getLong("id"),
rs.getString("name"),
rs.getString("email"),
rs.getString("type"))
);
assertFalse(dbCustomers.isEmpty());
dbCustomers.forEach(c -> {
assertEquals(c.getName(), c.getName().toUpperCase());
assertTrue(c.getEmail().startsWith("A_"));
});
}
@Test
public void givenTypeB_whenProcess_thenNameIsLowercaseAndEmailPrefixedWithB() throws Exception {
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
assertTrue(Files.exists(outputFile));
List<String> lines = Files.readAllLines(outputFile);
boolean hasTypeB = lines.stream().anyMatch(line -> line.endsWith(",B"));
assertTrue(hasTypeB);
lines.forEach(line -> {
String[] parts = line.split(",");
if ("B".equals(parts[3])) {
assertEquals(parts[1], parts[1].toLowerCase());
assertTrue(parts[2].startsWith("B_"));
}
});
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/test/java/com/baeldung/multiprocessorandwriter/JpaTestConfig.java | spring-batch-2/src/test/java/com/baeldung/multiprocessorandwriter/JpaTestConfig.java | package com.baeldung.multiprocessorandwriter;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import jakarta.persistence.EntityManagerFactory;
@Configuration
public class JpaTestConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
emf.setPackagesToScan("com.baeldung.multiprocessorandwriter.model"); // your entity package here
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Map<String, Object> props = new HashMap<>();
props.put("hibernate.hbm2ddl.auto", "create-drop"); // creates schema for tests
emf.setJpaPropertyMap(props);
return emf;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
return new JpaTransactionManager(emf);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/test/java/com/baeldung/springbatch/SpringBatchLiveTest.java | spring-batch-2/src/test/java/com/baeldung/springbatch/SpringBatchLiveTest.java | package com.baeldung.springbatch.jobs;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.batch.core.Job;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class SpringBatchLiveTest {
@Autowired
private Job jobOne;
@Autowired
private Job jobTwo;
@Autowired
private SequentialJobsConfig sequentialJobsConfig;
@Autowired
private DynamicJobService dynamicJobService;
@Test
void givenJobDefinitions_whenJobsLoaded_thenJobNamesShouldMatch() {
assertNotNull(jobOne, "jobOne should be defined");
assertEquals("jobOne", jobOne.getName());
assertNotNull(jobTwo, "jobTwo should be defined");
assertEquals("jobTwo", jobTwo.getName());
}
@Test
void givenSequentialJobs_whenExecuted_thenJobsRunInOrder() {
assertDoesNotThrow(() -> sequentialJobsConfig.runJobsSequentially(), "Sequential job execution should execute");
}
@Test
void givenJobData_whenJobsCreated_thenJobsRunSuccessfully() throws Exception {
Map<String, List<String>> jobsData = new HashMap<>();
jobsData.put("chunkJob1", Arrays.asList("data1", "data2", "data3"));
jobsData.put("chunkJob2", Arrays.asList("data4", "data5", "data6"));
assertDoesNotThrow(() -> dynamicJobService.createAndRunJob(jobsData), "Dynamic job creation and execution should run successfully");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/batch/CompositeItemReaderConfig.java | spring-batch-2/src/main/java/com/baeldung/batch/CompositeItemReaderConfig.java | package com.baeldung.batch;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.batch.item.database.builder.JdbcCursorItemReaderBuilder;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.support.CompositeItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.Arrays;
import com.baeldung.batch.model.Product;
@Configuration
@EnableBatchProcessing
public class CompositeItemReaderConfig {
@Bean
public DataSource dataSource() {
return DataSourceBuilder.create()
.driverClassName("org.h2.Driver")
.url("jdbc:h2:mem:batchdb;DB_CLOSE_DELAY=-1;")
.username("sa")
.password("")
.build();
}
@Bean
public FlatFileItemReader<Product> fileReader() {
return new FlatFileItemReaderBuilder<Product>()
.name("fileReader")
.resource(new ClassPathResource("products.csv"))
.delimited()
.names("productId", "productName", "stock", "price")
.linesToSkip(1)
.targetType(Product.class)
.build();
}
@Bean
public JdbcCursorItemReader<Product> dbReader() {
return new JdbcCursorItemReaderBuilder<Product>()
.name("dbReader")
.dataSource(dataSource())
.sql("SELECT productid, productname, stock, price FROM products")
.rowMapper((rs, rowNum) -> new Product(
rs.getLong("productid"),
rs.getString("productname"),
rs.getInt("stock"),
rs.getBigDecimal("price")
))
.build();
}
@Bean
public CompositeItemReader<Product> compositeReader() {
return new CompositeItemReader<>(Arrays.asList(fileReader(), dbReader()));
}
@Bean
public ItemWriter<Product> productWriter() {
return items -> {
for (Product product : items) {
System.out.println("Writing product: " + product);
}
};
}
@Bean
public Step step(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("compositeReader") ItemReader<Product> compositeReader, ItemWriter<Product> productWriter) {
return new StepBuilder("productStep", jobRepository)
.<Product, Product>chunk(10, transactionManager)
.reader(compositeReader)
.writer(productWriter)
.build();
}
@Bean
public Job productJob(JobRepository jobRepository, Step step) {
return new JobBuilder("productJob", jobRepository)
.start(step)
.build();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/batch/SpringBatchRetryConfig.java | spring-batch-2/src/main/java/com/baeldung/batch/SpringBatchRetryConfig.java | package com.baeldung.batch;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.xml.StaxEventItemWriter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.WritableResource;
import org.springframework.dao.DeadlockLoserDataAccessException;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.transaction.PlatformTransactionManager;
import com.baeldung.batch.model.Transaction;
import com.baeldung.batch.service.RecordFieldSetMapper;
import com.baeldung.batch.service.RetryItemProcessor;
@Configuration
public class SpringBatchRetryConfig {
private static final String[] tokens = { "username", "userid", "transactiondate", "amount" };
private static final int TWO_SECONDS = 2000;
@Value("input/recordRetry.csv")
private Resource inputCsv;
@Value("file:xml/retryOutput.xml")
private WritableResource outputXml;
public ItemReader<Transaction> itemReader(Resource inputData) {
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
tokenizer.setNames(tokens);
DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<>();
lineMapper.setLineTokenizer(tokenizer);
lineMapper.setFieldSetMapper(new RecordFieldSetMapper());
FlatFileItemReader<Transaction> reader = new FlatFileItemReader<>();
reader.setResource(inputData);
reader.setLinesToSkip(1);
reader.setLineMapper(lineMapper);
return reader;
}
@Bean
public CloseableHttpClient closeableHttpClient() {
final RequestConfig config = RequestConfig.custom()
.setConnectTimeout(TWO_SECONDS)
.build();
return HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
@Bean
public ItemProcessor<Transaction, Transaction> retryItemProcessor() {
return new RetryItemProcessor();
}
@Bean
public ItemWriter<Transaction> itemWriter(Marshaller marshaller) {
StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<>();
itemWriter.setMarshaller(marshaller);
itemWriter.setRootTagName("transactionRecord");
itemWriter.setResource(outputXml);
return itemWriter;
}
@Bean
public Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Transaction.class);
return marshaller;
}
@Bean
public Step retryStep(
JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("retryItemProcessor") ItemProcessor<Transaction, Transaction> processor,
ItemWriter<Transaction> writer) {
return new StepBuilder("retryStep", jobRepository)
.<Transaction, Transaction>chunk(10, transactionManager)
.reader(itemReader(inputCsv))
.processor(processor)
.writer(writer)
.faultTolerant()
.retryLimit(3)
.retry(ConnectTimeoutException.class)
.retry(DeadlockLoserDataAccessException.class)
.build();
}
@Bean(name = "retryBatchJob")
public Job retryJob(JobRepository jobRepository, @Qualifier("retryStep") Step retryStep) {
return new JobBuilder("retryBatchJob", jobRepository)
.start(retryStep)
.build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java | spring-batch-2/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java | package com.baeldung.batch.service;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import com.baeldung.batch.model.Transaction;
public class RecordFieldSetMapper implements FieldSetMapper<Transaction> {
public Transaction mapFieldSet(FieldSet fieldSet) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyy");
Transaction transaction = new Transaction();
// you can either use the indices or custom names
// I personally prefer the custom names easy for debugging and
// validating the pipelines
transaction.setUsername(fieldSet.readString("username"));
transaction.setUserId(fieldSet.readInt("userid"));
transaction.setAmount(fieldSet.readDouble(3));
// Converting the date
String dateString = fieldSet.readString(2);
transaction.setTransactionDate(LocalDate.parse(dateString, formatter).atStartOfDay());
return transaction;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/batch/service/RetryItemProcessor.java | spring-batch-2/src/main/java/com/baeldung/batch/service/RetryItemProcessor.java | package com.baeldung.batch.service;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import com.baeldung.batch.model.Transaction;
public class RetryItemProcessor implements ItemProcessor<Transaction, Transaction> {
private static final Logger LOGGER = LoggerFactory.getLogger(RetryItemProcessor.class);
@Autowired
private CloseableHttpClient closeableHttpClient;
@Override
public Transaction process(Transaction transaction) throws Exception {
LOGGER.info("Attempting to process user with id={}", transaction.getUserId());
HttpResponse response = fetchMoreUserDetails(transaction.getUserId());
//parse user's age and postCode from response and update transaction
String result = EntityUtils.toString(response.getEntity());
JSONObject userObject = new JSONObject(result);
transaction.setAge(Integer.parseInt(userObject.getString("age")));
transaction.setPostCode(userObject.getString("postCode"));
return transaction;
}
private HttpResponse fetchMoreUserDetails(int id) throws Exception {
final HttpGet request = new HttpGet("http://www.baeldung.com:81/user/" + id);
return closeableHttpClient.execute(request);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/batch/service/adapter/LocalDateTimeAdapter.java | spring-batch-2/src/main/java/com/baeldung/batch/service/adapter/LocalDateTimeAdapter.java | package com.baeldung.batch.service.adapter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
public class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> {
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT);
public LocalDateTime unmarshal(String v) throws Exception {
return LocalDateTime.parse(v, DATE_TIME_FORMATTER);
}
public String marshal(LocalDateTime v) throws Exception {
return DATE_TIME_FORMATTER.format(v);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/batch/model/Product.java | spring-batch-2/src/main/java/com/baeldung/batch/model/Product.java | package com.baeldung.batch.model;
import java.math.BigDecimal;
import jakarta.persistence.*;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "productid")
private Long productId;
@Column(name = "productname")
private String productName;
@Column(name = "stock")
private Integer stock;
@Column(name = "price")
private BigDecimal price;
public Product() {
}
public Product(Long productId, String productName, Integer stock, BigDecimal price) {
this.productId = productId;
this.productName = productName;
this.stock = stock;
this.price = price;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/batch/model/Transaction.java | spring-batch-2/src/main/java/com/baeldung/batch/model/Transaction.java | package com.baeldung.batch.model;
import java.time.LocalDateTime;
import com.baeldung.batch.service.adapter.LocalDateTimeAdapter;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@SuppressWarnings("restriction")
@XmlRootElement(name = "transactionRecord")
public class Transaction {
private String username;
private int userId;
private int age;
private String postCode;
private LocalDateTime transactionDate;
private double amount;
/* getters and setters for the attributes */
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@XmlJavaTypeAdapter(LocalDateTimeAdapter.class)
public LocalDateTime getTransactionDate() {
return transactionDate;
}
public void setTransactionDate(LocalDateTime transactionDate) {
this.transactionDate = transactionDate;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
@Override
public String toString() {
return "Transaction [username=" + username + ", userId=" + userId + ", age=" + age + ", postCode=" + postCode + ", transactionDate=" + transactionDate + ", amount=" + amount + "]";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/dataloaderbatchprocessing/DataLoaderApp.java | spring-batch-2/src/main/java/com/baeldung/dataloaderbatchprocessing/DataLoaderApp.java | package com.baeldung.dataloaderbatchprocessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DataLoaderApp {
public static void main(String[] args) {
SpringApplication.run(DataLoaderApp.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/dataloaderbatchprocessing/UserDataLoader.java | spring-batch-2/src/main/java/com/baeldung/dataloaderbatchprocessing/UserDataLoader.java | package com.baeldung.dataloaderbatchprocessing;
import org.dataloader.BatchLoader;
import org.dataloader.DataLoader;
import org.dataloader.DataLoaderFactory;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.stream.Collectors;
import com.baeldung.dataloaderbatchprocessing.entity.User;
import com.baeldung.dataloaderbatchprocessing.service.UserService;
@Component
public class UserDataLoader {
private final UserService userService;
public UserDataLoader(UserService userService) {
this.userService = userService;
}
public DataLoader<String, User> createUserLoader() {
BatchLoader<String, User> userBatchLoader = ids -> {
return userService.getUsersByIds(ids)
.thenApply(users -> {
Map<String, User> userMap = users.stream()
.collect(Collectors.toMap(User::getId, user -> user));
return ids.stream()
.map(userMap::get)
.collect(Collectors.toList());
});
};
return DataLoaderFactory.newDataLoader(userBatchLoader);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/dataloaderbatchprocessing/service/UserService.java | spring-batch-2/src/main/java/com/baeldung/dataloaderbatchprocessing/service/UserService.java | package com.baeldung.dataloaderbatchprocessing.service;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import com.baeldung.dataloaderbatchprocessing.entity.User;
import com.baeldung.dataloaderbatchprocessing.repository.UserRepository;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public CompletableFuture<List<User>> getUsersByIds(List<String> ids) {
return CompletableFuture.supplyAsync(() -> userRepository.findAllById(ids));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/dataloaderbatchprocessing/repository/UserRepository.java | spring-batch-2/src/main/java/com/baeldung/dataloaderbatchprocessing/repository/UserRepository.java | package com.baeldung.dataloaderbatchprocessing.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.baeldung.dataloaderbatchprocessing.entity.User;
public interface UserRepository extends JpaRepository<User, String> {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/dataloaderbatchprocessing/entity/User.java | spring-batch-2/src/main/java/com/baeldung/dataloaderbatchprocessing/entity/User.java | package com.baeldung.dataloaderbatchprocessing.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Entity
@Table(name = "users")
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class User {
@Id
private String id;
private String name;
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/restartjob/RestartJobBatchApp.java | spring-batch-2/src/main/java/com/baeldung/restartjob/RestartJobBatchApp.java | package com.baeldung.restartjob;
import java.util.List;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobInstance;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class RestartJobBatchApp {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(RestartJobBatchApp.class);
app.setAdditionalProfiles("restart");
app.run(args);
}
@Bean
@ConditionalOnProperty(prefix = "job.autorun", name = "enabled", havingValue = "true", matchIfMissing = true)
CommandLineRunner run(JobLauncher jobLauncher, Job job, JobExplorer jobExplorer,
JobOperator jobOperator, BatchConfig.RestartItemProcessor itemProcessor) {
return args -> {
JobParameters jobParameters = new JobParametersBuilder()
.addString("jobId", "test-job-" + System.currentTimeMillis())
.toJobParameters();
List<JobInstance> instances = jobExplorer.getJobInstances("simpleJob", 0, 1);
if (!instances.isEmpty()) {
JobInstance lastInstance = instances.get(0);
List<JobExecution> executions = jobExplorer.getJobExecutions(lastInstance);
if (!executions.isEmpty()) {
JobExecution lastExecution = executions.get(0);
if (lastExecution.getStatus() == BatchStatus.FAILED) {
System.out.println("Restarting failed job execution with ID: " + lastExecution.getId());
itemProcessor.setFailOnItem3(false);
JobExecution restartedExecution = jobLauncher.run(job, jobParameters);
// final Long restartId = jobOperator.restart(lastExecution.getId());
// final JobExecution restartedExecution = jobExplorer.getJobExecution(restartedExecution);
System.out.println("Restarted job status: " + restartedExecution.getStatus());
return;
}
}
}
System.out.println("Starting new job execution...");
JobExecution jobExecution = jobLauncher.run(job, jobParameters);
System.out.println("Job started with status: " + jobExecution.getStatus());
};
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/restartjob/BatchConfig.java | spring-batch-2/src/main/java/com/baeldung/restartjob/BatchConfig.java | package com.baeldung.restartjob;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.PassThroughLineMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
public class BatchConfig {
@Bean
public Job simpleJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new JobBuilder("simpleJob", jobRepository)
.start(step1(jobRepository, transactionManager))
.build();
}
@Bean
public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("step1", jobRepository)
.<String, String>chunk(2, transactionManager)
.reader(flatFileItemReader())
.processor(itemProcessor())
.writer(itemWriter())
.build();
}
@Bean
@StepScope
public FlatFileItemReader<String> flatFileItemReader() {
return new FlatFileItemReaderBuilder<String>()
.name("itemReader")
.resource(new ClassPathResource("data.csv"))
.lineMapper(new PassThroughLineMapper())
.saveState(true)
.build();
}
@Bean
public RestartItemProcessor itemProcessor() {
return new RestartItemProcessor();
}
@Bean
public ItemWriter<String> itemWriter() {
return items -> {
System.out.println("Writing items:");
for (String item : items) {
System.out.println("- " + item);
}
};
}
static class RestartItemProcessor implements ItemProcessor<String, String> {
private boolean failOnItem3 = true;
public void setFailOnItem3(boolean failOnItem3) {
this.failOnItem3 = failOnItem3;
}
@Override
public String process(String item) throws Exception {
System.out.println("Processing: " + item + " (failOnItem3=" + failOnItem3 + ")");
if (failOnItem3 && item.equals("Item3")) {
throw new RuntimeException("Simulated failure on Item3");
}
return "PROCESSED " + item;
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/conditionalflow/ConditionalFlowApplication.java | spring-batch-2/src/main/java/com/baeldung/conditionalflow/ConditionalFlowApplication.java | package com.baeldung.conditionalflow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConditionalFlowApplication implements CommandLineRunner {
private static Logger logger = LoggerFactory.getLogger(ConditionalFlowApplication.class);
public static void main(String[] args) {
SpringApplication.run(ConditionalFlowApplication.class, args);
}
@Override
public void run(String... args) {
logger.info("Running conditional flow application...");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/conditionalflow/NumberInfoDecider.java | spring-batch-2/src/main/java/com/baeldung/conditionalflow/NumberInfoDecider.java | package com.baeldung.conditionalflow;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.job.flow.FlowExecutionStatus;
import org.springframework.batch.core.job.flow.JobExecutionDecider;
public class NumberInfoDecider implements JobExecutionDecider {
public static final String NOTIFY = "NOTIFY";
public static final String QUIET = "QUIET";
/**
* Method that determines notification status of job
* @return true if notifications should be sent.
*/
private boolean shouldNotify() {
return true;
}
@Override
public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) {
if (shouldNotify()) {
return new FlowExecutionStatus(NOTIFY);
} else {
return new FlowExecutionStatus(QUIET);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/conditionalflow/model/NumberInfo.java | spring-batch-2/src/main/java/com/baeldung/conditionalflow/model/NumberInfo.java | package com.baeldung.conditionalflow.model;
import java.util.Objects;
public class NumberInfo {
private int number;
public NumberInfo(int number) {
this.number = number;
}
public static NumberInfo from(int number) {
return new NumberInfo(number);
}
public boolean isPositive() {
return number > 0;
}
public boolean isEven() {
return number % 2 == 0;
}
public int getNumber() {
return number;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
NumberInfo that = (NumberInfo) o;
return number == that.number;
}
@Override
public int hashCode() {
return Objects.hash(number);
}
@Override
public String toString() {
return "NumberInfo{" + "number=" + number + '}';
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/conditionalflow/step/PrependingStdoutWriter.java | spring-batch-2/src/main/java/com/baeldung/conditionalflow/step/PrependingStdoutWriter.java | package com.baeldung.conditionalflow.step;
import org.springframework.batch.item.Chunk;
import org.springframework.batch.item.ItemWriter;
public class PrependingStdoutWriter<T> implements ItemWriter<T> {
private String prependText;
public PrependingStdoutWriter(String prependText) {
this.prependText = prependText;
}
@Override
public void write(Chunk<? extends T> chunk) {
for (T listItem : chunk) {
System.out.println(prependText + " " + listItem.toString());
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/conditionalflow/step/NumberInfoGenerator.java | spring-batch-2/src/main/java/com/baeldung/conditionalflow/step/NumberInfoGenerator.java | package com.baeldung.conditionalflow.step;
import com.baeldung.conditionalflow.model.NumberInfo;
import org.springframework.batch.item.ItemReader;
public class NumberInfoGenerator implements ItemReader<NumberInfo> {
private int[] values;
private int counter;
public NumberInfoGenerator(int[] values) {
this.values = values;
counter = 0;
}
@Override
public NumberInfo read() {
if (counter == values.length) {
return null;
} else {
return new NumberInfo(values[counter++]);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/conditionalflow/step/NotifierTasklet.java | spring-batch-2/src/main/java/com/baeldung/conditionalflow/step/NotifierTasklet.java | package com.baeldung.conditionalflow.step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
public class NotifierTasklet implements Tasklet {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) {
System.err.println("[" + chunkContext.getStepContext().getJobName() + "] contains interesting data!!");
return RepeatStatus.FINISHED;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java | spring-batch-2/src/main/java/com/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java | package com.baeldung.conditionalflow.step;
import com.baeldung.conditionalflow.model.NumberInfo;
import org.springframework.batch.core.listener.ItemListenerSupport;
import org.springframework.batch.item.ItemProcessor;
public class NumberInfoClassifierWithDecider extends ItemListenerSupport<NumberInfo, Integer> implements ItemProcessor<NumberInfo, Integer> {
@Override
public Integer process(NumberInfo numberInfo) {
return Integer.valueOf(numberInfo.getNumber());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/conditionalflow/step/NumberInfoClassifier.java | spring-batch-2/src/main/java/com/baeldung/conditionalflow/step/NumberInfoClassifier.java | package com.baeldung.conditionalflow.step;
import static com.baeldung.conditionalflow.NumberInfoDecider.NOTIFY;
import static com.baeldung.conditionalflow.NumberInfoDecider.QUIET;
import com.baeldung.conditionalflow.model.NumberInfo;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.core.listener.ItemListenerSupport;
import org.springframework.batch.item.ItemProcessor;
public class NumberInfoClassifier extends ItemListenerSupport<NumberInfo, Integer>
implements ItemProcessor<NumberInfo, Integer> {
private StepExecution stepExecution;
@BeforeStep
public void beforeStep(StepExecution stepExecution) {
this.stepExecution = stepExecution;
this.stepExecution.setExitStatus(new ExitStatus(QUIET));
}
@Override
public void afterProcess(NumberInfo item, Integer result) {
super.afterProcess(item, result);
if (item.isPositive()) {
stepExecution.setExitStatus(new ExitStatus(NOTIFY));
}
}
@Override
public Integer process(NumberInfo numberInfo) {
return numberInfo.getNumber();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/conditionalflow/config/NumberInfoConfig.java | spring-batch-2/src/main/java/com/baeldung/conditionalflow/config/NumberInfoConfig.java | package com.baeldung.conditionalflow.config;
import static com.baeldung.conditionalflow.NumberInfoDecider.NOTIFY;
import javax.sql.DataSource;
import com.baeldung.conditionalflow.NumberInfoDecider;
import com.baeldung.conditionalflow.model.NumberInfo;
import com.baeldung.conditionalflow.step.NotifierTasklet;
import com.baeldung.conditionalflow.step.NumberInfoClassifier;
import com.baeldung.conditionalflow.step.NumberInfoClassifierWithDecider;
import com.baeldung.conditionalflow.step.NumberInfoGenerator;
import com.baeldung.conditionalflow.step.PrependingStdoutWriter;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.TaskExecutorJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
@EnableBatchProcessing
public class NumberInfoConfig {
@Bean
@Qualifier("NotificationStep")
public Step notificationStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("Notify step", jobRepository)
.tasklet(new NotifierTasklet(), transactionManager)
.build();
}
public Step numberGeneratorStep(JobRepository jobRepositories, PlatformTransactionManager transactionManager, int[] values, String prepend) {
return new StepBuilder("Number generator", jobRepositories)
.<NumberInfo, Integer> chunk(1, transactionManager)
.reader(new NumberInfoGenerator(values))
.processor(new NumberInfoClassifier())
.writer(new PrependingStdoutWriter<>(prepend))
.build();
}
public Step numberGeneratorStepDecider(JobRepository jobRepositories, PlatformTransactionManager transactionManager, int[] values, String prepend) {
return new StepBuilder("Number generator decider", jobRepositories)
.<NumberInfo, Integer> chunk(1, transactionManager)
.reader(new NumberInfoGenerator(values))
.processor(new NumberInfoClassifierWithDecider())
.writer(new PrependingStdoutWriter<>(prepend))
.build();
}
@Bean
@Qualifier("first_job")
public Job numberGeneratorNonNotifierJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("NotificationStep") Step notificationStep) {
int[] nonNotifierData = { -1, -2, -3 };
Step step = numberGeneratorStep(jobRepository, transactionManager, nonNotifierData, "First Dataset Processor");
return new JobBuilder("Number generator - first dataset", jobRepository)
.start(step)
.on(NOTIFY)
.to(notificationStep)
.from(step)
.on("*")
.stop()
.end()
.build();
}
@Bean
@Qualifier("second_job")
public Job numberGeneratorNotifierJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("NotificationStep") Step notificationStep) {
int[] billableData = { 11, -2, -3 };
Step dataProviderStep = numberGeneratorStep(jobRepository, transactionManager, billableData, "Second Dataset Processor");
return new JobBuilder("Number generator - second dataset", jobRepository)
.start(dataProviderStep)
.on(NOTIFY)
.to(notificationStep)
.end()
.build();
}
@Bean
@Qualifier("third_job")
@Primary
public Job numberGeneratorNotifierJobWithDecider(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("NotificationStep") Step notificationStep) {
int[] billableData = { 11, -2, -3 };
Step dataProviderStep = numberGeneratorStepDecider(jobRepository, transactionManager, billableData, "Third Dataset Processor");
return new JobBuilder("Number generator - third dataset", jobRepository)
.start(dataProviderStep)
.next(new NumberInfoDecider())
.on(NOTIFY)
.to(notificationStep)
.end()
.build();
}
@Bean(name = "jobRepository")
public JobRepository getJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource());
factory.setTransactionManager(getTransactionManager());
// JobRepositoryFactoryBean's methods Throws Generic Exception,
// it would have been better to have a specific one
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean(name = "dataSource")
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql")
.addScript("classpath:org/springframework/batch/core/schema-h2.sql")
.build();
}
@Bean(name = "transactionManager")
public PlatformTransactionManager getTransactionManager() {
return new ResourcelessTransactionManager();
}
@Bean(name = "jobLauncher")
public JobLauncher getJobLauncher() throws Exception {
TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher();
// SimpleJobLauncher's methods Throws Generic Exception,
// it would have been better to have a specific one
jobLauncher.setJobRepository(getJobRepository());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/multiprocessorandwriter/BatchApp.java | spring-batch-2/src/main/java/com/baeldung/multiprocessorandwriter/BatchApp.java | package com.baeldung.multiprocessorandwriter;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class BatchApp {
public static void main(String[] args) {
SpringApplication.run(BatchApp.class, args);
}
@Bean
CommandLineRunner run(JobLauncher jobLauncher, Job job) {
return args -> {
JobParameters parameters = new JobParametersBuilder().addLong("startAt", System.currentTimeMillis())
.toJobParameters();
jobLauncher.run(job, parameters);
};
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/multiprocessorandwriter/model/Customer.java | spring-batch-2/src/main/java/com/baeldung/multiprocessorandwriter/model/Customer.java | package com.baeldung.multiprocessorandwriter.model;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Customer {
@Id
private Long id;
private String name;
private String email;
private String type;
public Customer() {}
public Customer(Long id, String name, String email, String type) {
this.id = id;
this.name = name;
this.email = email;
this.type = type;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/multiprocessorandwriter/processor/TypeAProcessor.java | spring-batch-2/src/main/java/com/baeldung/multiprocessorandwriter/processor/TypeAProcessor.java | package com.baeldung.multiprocessorandwriter.processor;
import org.springframework.batch.item.ItemProcessor;
import com.baeldung.multiprocessorandwriter.model.Customer;
public class TypeAProcessor implements ItemProcessor<Customer, Customer> {
@Override
public Customer process(Customer customer) {
customer.setName(customer.getName().toUpperCase());
customer.setEmail("A_" + customer.getEmail());
return customer;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/multiprocessorandwriter/processor/CustomerProcessorRouter.java | spring-batch-2/src/main/java/com/baeldung/multiprocessorandwriter/processor/CustomerProcessorRouter.java | package com.baeldung.multiprocessorandwriter.processor;
import org.springframework.batch.item.ItemProcessor;
import com.baeldung.multiprocessorandwriter.model.Customer;
public class CustomerProcessorRouter implements ItemProcessor<Customer, Customer> {
private final TypeAProcessor typeAProcessor;
private final TypeBProcessor typeBProcessor;
public CustomerProcessorRouter(TypeAProcessor typeAProcessor,
TypeBProcessor typeBProcessor) {
this.typeAProcessor = typeAProcessor;
this.typeBProcessor = typeBProcessor;
}
@Override
public Customer process(Customer customer) throws Exception {
if ("A".equals(customer.getType())) {
return typeAProcessor.process(customer);
} else if ("B".equals(customer.getType())) {
return typeBProcessor.process(customer);
}
return customer;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/multiprocessorandwriter/processor/TypeBProcessor.java | spring-batch-2/src/main/java/com/baeldung/multiprocessorandwriter/processor/TypeBProcessor.java | package com.baeldung.multiprocessorandwriter.processor;
import org.springframework.batch.item.ItemProcessor;
import com.baeldung.multiprocessorandwriter.model.Customer;
public class TypeBProcessor implements ItemProcessor<Customer, Customer> {
@Override
public Customer process(Customer customer) {
customer.setName(customer.getName().toLowerCase());
customer.setEmail("B_" + customer.getEmail());
return customer;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/multiprocessorandwriter/config/BatchConfig.java | spring-batch-2/src/main/java/com/baeldung/multiprocessorandwriter/config/BatchConfig.java | package com.baeldung.multiprocessorandwriter.config;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.JpaItemWriter;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.item.database.builder.JpaItemWriterBuilder;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.builder.FlatFileItemWriterBuilder;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.support.CompositeItemWriter;
import org.springframework.batch.item.support.builder.CompositeItemWriterBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import com.baeldung.multiprocessorandwriter.model.Customer;
import com.baeldung.multiprocessorandwriter.processor.CustomerProcessorRouter;
import com.baeldung.multiprocessorandwriter.processor.TypeAProcessor;
import com.baeldung.multiprocessorandwriter.processor.TypeBProcessor;
import jakarta.persistence.EntityManagerFactory;
@Configuration
@EnableBatchProcessing
public class BatchConfig {
@Bean
public FlatFileItemReader<Customer> customerReader() {
return new FlatFileItemReaderBuilder<Customer>().name("customerItemReader")
.resource(new ClassPathResource("customers.csv"))
.delimited()
.names("id", "name", "email", "type")
.linesToSkip(1)
.fieldSetMapper(new BeanWrapperFieldSetMapper<>() {{
setTargetType(Customer.class);
}})
.build();
}
@Bean
public TypeAProcessor typeAProcessor() {
return new TypeAProcessor();
}
@Bean
public TypeBProcessor typeBProcessor() {
return new TypeBProcessor();
}
@Bean
public CustomerProcessorRouter processorRouter(TypeAProcessor typeAProcessor, TypeBProcessor typeBProcessor) {
return new CustomerProcessorRouter(typeAProcessor, typeBProcessor);
}
@Bean
public JpaItemWriter<Customer> jpaDBWriter(EntityManagerFactory entityManagerFactory) {
JpaItemWriter<Customer> writer = new JpaItemWriter<>();
writer.setEntityManagerFactory(entityManagerFactory);
return writer;
}
@Bean
public FlatFileItemWriter<Customer> fileWriter() {
return new FlatFileItemWriterBuilder<Customer>().name("customerItemWriter")
.resource(new FileSystemResource("output/processed_customers.txt"))
.delimited()
.delimiter(",")
.names("id", "name", "email", "type")
.build();
}
@Bean
public CompositeItemWriter<Customer> compositeWriter(JpaItemWriter<Customer> jpaDBWriter, FlatFileItemWriter<Customer> fileWriter) {
return new CompositeItemWriterBuilder<Customer>().delegates(List.of(jpaDBWriter, fileWriter))
.build();
}
@Bean
public Step processCustomersStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, FlatFileItemReader<Customer> reader,
CustomerProcessorRouter processorRouter, CompositeItemWriter<Customer> compositeWriter) {
return new StepBuilder("processCustomersStep", jobRepository).<Customer, Customer> chunk(10, transactionManager)
.reader(reader)
.processor(processorRouter)
.writer(compositeWriter)
.build();
}
@Bean
public Job processCustomersJob(JobRepository jobRepository, Step processCustomersStep) {
return new JobBuilder("customerProcessingJob", jobRepository).start(processCustomersStep)
.build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/ParallelJobService.java | spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/ParallelJobService.java | package com.baeldung.springbatch.jobs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.stereotype.Component;
@Component
public class ParallelJobService {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job jobOne;
@Autowired
private Job jobTwo;
public void runJobsInParallel() {
SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
taskExecutor.execute(() -> {
try {
jobLauncher.run(jobOne, new JobParametersBuilder().addString("ID", "Parallel 1")
.toJobParameters());
} catch (Exception e) {
e.printStackTrace();
}
});
taskExecutor.execute(() -> {
try {
jobLauncher.run(jobTwo, new JobParametersBuilder().addString("ID", "Parallel 2")
.toJobParameters());
} catch (Exception e) {
e.printStackTrace();
}
});
taskExecutor.close();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/SequentialJobsConfig.java | spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/SequentialJobsConfig.java | package com.baeldung.springbatch.jobs;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SequentialJobsConfig {
@Autowired
private Job jobOne;
@Autowired
private Job jobTwo;
@Autowired
private JobLauncher jobLauncher;
public void runJobsSequentially() {
JobParameters jobParameters = new JobParametersBuilder().addString("ID", "Sequential 1")
.toJobParameters();
JobParameters jobParameters2 = new JobParametersBuilder().addString("ID", "Sequential 2")
.toJobParameters();
// Run jobs one after another
try {
jobLauncher.run(jobOne, jobParameters);
jobLauncher.run(jobTwo, jobParameters2);
} catch (Exception e) {
// handle exception
e.printStackTrace();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/JobsConfig.java | spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/JobsConfig.java | package com.baeldung.springbatch.jobs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
public class JobsConfig {
private static final Logger log = LoggerFactory.getLogger(SequentialJobsConfig.class);
@Bean
public Job jobOne(JobRepository jobRepository, Step stepOne) {
return new JobBuilder("jobOne", jobRepository).start(stepOne)
.build();
}
@Bean
public Step stepOne(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("stepOne", jobRepository).tasklet((contribution, chunkContext) -> {
log.info("Hello");
return RepeatStatus.FINISHED;
}, transactionManager)
.build();
}
@Bean
public Job jobTwo(JobRepository jobRepository, Step stepTwo) {
return new JobBuilder("jobTwo", jobRepository).start(stepTwo)
.build();
}
@Bean
public Step stepTwo(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("stepTwo", jobRepository).tasklet((contribution, chunkContext) -> {
log.info("World");
return RepeatStatus.FINISHED;
}, transactionManager)
.build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/ScheduledJobs.java | spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/ScheduledJobs.java | package com.baeldung.springbatch.jobs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Configuration
@EnableScheduling
public class ScheduledJobs {
private static final Logger log = LoggerFactory.getLogger(SequentialJobsConfig.class);
@Autowired
private Job jobOne;
@Autowired
private Job jobTwo;
@Autowired
private JobLauncher jobLauncher;
@Scheduled(cron = "0 */1 * * * *") // Run every minutes
public void runJob1() throws Exception {
JobParameters jobParameters = new JobParametersBuilder().addString("ID", "Scheduled 1")
.toJobParameters();
jobLauncher.run(jobOne, jobParameters);
}
@Scheduled(fixedRate = 1000 * 60 * 3) // Run every 3 minutes
public void runJob2() throws Exception {
JobParameters jobParameters = new JobParametersBuilder().addString("ID", "Scheduled 2")
.toJobParameters();
jobLauncher.run(jobTwo, jobParameters);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/DynamicJobService.java | spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/DynamicJobService.java | package com.baeldung.springbatch.jobs;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
@Service
public class DynamicJobService {
private final JobRepository jobRepository;
private final JobLauncher jobLauncher;
private final PlatformTransactionManager transactionManager;
public DynamicJobService(JobRepository jobRepository, JobLauncher jobLauncher, PlatformTransactionManager transactionManager) {
this.jobRepository = jobRepository;
this.jobLauncher = jobLauncher;
this.transactionManager = transactionManager;
}
public void createAndRunJob(Map<String, List<String>> jobsData) throws Exception {
List<Job> jobs = new ArrayList<>();
// Create chunk-oriented jobs
for (Map.Entry<String, List<String>> entry : jobsData.entrySet()) {
if (entry.getValue() instanceof List) {
jobs.add(createJob(entry.getKey(), entry.getValue()));
}
}
// Run all jobs
for (Job job : jobs) {
JobParameters jobParameters = new JobParametersBuilder().addString("jobID", String.valueOf(System.currentTimeMillis()))
.toJobParameters();
jobLauncher.run(job, jobParameters);
}
}
private Job createJob(String jobName, List<String> data) {
return new JobBuilder(jobName, jobRepository).start(createStep(data))
.build();
}
private Step createStep(List<String> data) {
return new StepBuilder("step", jobRepository).<String, String> chunk(10, transactionManager)
.reader(new ListItemReader<>(data))
.processor(item -> item.toUpperCase())
.writer(items -> items.forEach(System.out::println))
.build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/BatchConfig.java | spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/BatchConfig.java | package com.baeldung.springbatch.jobs;
import javax.sql.DataSource;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
@Configuration
@EnableBatchProcessing
public class BatchConfig {
@Bean
public DataSource dataSource() {
return DataSourceBuilder.create()
.driverClassName("org.h2.Driver")
.url("jdbc:h2:mem:batchdb;DB_CLOSE_DELAY=-1;")
.username("sa")
.password("")
.build();
}
@Bean
public DatabasePopulator databasePopulator(DataSource dataSource) {
ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.addScript(new ClassPathResource("org/springframework/batch/core/schema-h2.sql"));
populator.setContinueOnError(false);
populator.execute(dataSource);
return populator;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/quartz/QuartzJobOne.java | spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/quartz/QuartzJobOne.java | package com.baeldung.springbatch.jobs.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class QuartzJobOne implements Job {
private static final Logger log = LoggerFactory.getLogger(QuartzJobOne.class);
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try {
log.info("Job One is executing from quartz");
} catch (Exception e) {
log.error("Error executing Job One: {}", e.getMessage(), e);
throw new JobExecutionException(e);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/quartz/QuartzJobTwo.java | spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/quartz/QuartzJobTwo.java | package com.baeldung.springbatch.jobs.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class QuartzJobTwo implements Job {
private static final Logger log = LoggerFactory.getLogger(QuartzJobOne.class);
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try {
log.info("Job Two is executing from quartz");
} catch (Exception e) {
log.error("Error executing Job Two: {}", e.getMessage(), e);
throw new JobExecutionException(e);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/quartz/QuartzConfig.java | spring-batch-2/src/main/java/com/baeldung/springbatch/jobs/quartz/QuartzConfig.java | package com.baeldung.springbatch.jobs.quartz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import static org.quartz.JobBuilder.newJob;
import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
@Configuration
public class QuartzConfig {
@Autowired
private Job quartzJobOne;
@Autowired
private Job quartzJobTwo;
@Bean
public JobDetail job1Detail() {
return JobBuilder.newJob()
.ofType(quartzJobOne.getClass())
.withIdentity("quartzJobOne", "group1")
.storeDurably()
.build();
}
@Bean
public JobDetail job2Detail() {
return JobBuilder.newJob()
.ofType(quartzJobTwo.getClass())
.withIdentity("quartzJobTwo", "group1")
.storeDurably()
.build();
}
@Bean
public Trigger job1Trigger(JobDetail job1Detail) {
return TriggerBuilder.newTrigger()
.forJob(job1Detail)
.withIdentity("quartzJobOneTrigger", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
.build();
}
@Bean
public Trigger job2Trigger(JobDetail job2Detail) {
return TriggerBuilder.newTrigger()
.forJob(job2Detail)
.withIdentity("quartzJobTwoTrigger", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("0/15 * * * * ?"))
.build();
}
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
schedulerFactory.setJobDetails(job1Detail(), job2Detail());
schedulerFactory.setTriggers(job1Trigger(job1Detail()), job2Trigger(job2Detail()));
return schedulerFactory;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/vertx/src/test/java/com/baeldung/RestServiceVerticleUnitTest.java | vertx-modules/vertx/src/test/java/com/baeldung/RestServiceVerticleUnitTest.java | package com.baeldung;
import java.io.IOException;
import java.net.ServerSocket;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.baeldung.rest.RestServiceVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
@RunWith(VertxUnitRunner.class)
public class RestServiceVerticleUnitTest {
private Vertx vertx;
private int port = 8081;
@BeforeClass
public static void beforeClass() {
}
@Before
public void setup(TestContext testContext) throws IOException {
vertx = Vertx.vertx();
// Pick an available and random
ServerSocket socket = new ServerSocket(0);
port = socket.getLocalPort();
socket.close();
DeploymentOptions options = new DeploymentOptions().setConfig(new JsonObject().put("http.port", port));
vertx.deployVerticle(RestServiceVerticle.class.getName(), options, testContext.asyncAssertSuccess());
}
@After
public void tearDown(TestContext testContext) {
vertx.close(testContext.asyncAssertSuccess());
}
@Test
public void givenId_whenReceivedArticle_thenSuccess(TestContext testContext) {
final Async async = testContext.async();
vertx.createHttpClient()
.getNow(port, "localhost", "/api/baeldung/articles/article/12345", response -> {
response.handler(responseBody -> {
testContext.assertTrue(responseBody.toString()
.contains("\"id\" : \"12345\""));
async.complete();
});
});
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/vertx/src/test/java/com/baeldung/SimpleServerVerticleUnitTest.java | vertx-modules/vertx/src/test/java/com/baeldung/SimpleServerVerticleUnitTest.java | package com.baeldung;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import java.io.IOException;
import java.net.ServerSocket;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(VertxUnitRunner.class)
public class SimpleServerVerticleUnitTest {
private Vertx vertx;
private int port = 8081;
@Before
public void setup(TestContext testContext) throws IOException {
vertx = Vertx.vertx();
// Pick an available and random
ServerSocket socket = new ServerSocket(0);
port = socket.getLocalPort();
socket.close();
DeploymentOptions options = new DeploymentOptions().setConfig(new JsonObject().put("http.port", port));
vertx.deployVerticle(SimpleServerVerticle.class.getName(), options, testContext.asyncAssertSuccess());
}
@After
public void tearDown(TestContext testContext) {
vertx.close(testContext.asyncAssertSuccess());
}
@Test
public void whenReceivedResponse_thenSuccess(TestContext testContext) {
final Async async = testContext.async();
vertx.createHttpClient()
.getNow(port, "localhost", "/", response -> response.handler(responseBody -> {
testContext.assertTrue(responseBody.toString()
.contains("Welcome"));
async.complete();
}));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/vertx/src/main/java/com/baeldung/SimpleServerVerticle.java | vertx-modules/vertx/src/main/java/com/baeldung/SimpleServerVerticle.java | package com.baeldung;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
public class SimpleServerVerticle extends AbstractVerticle {
@Override
public void start(Future<Void> future) {
vertx.createHttpServer()
.requestHandler(
r -> r.response().end("Welcome to Vert.x Intro"))
.listen(config().getInteger("http.port", 8080), result -> {
if (result.succeeded()) {
future.complete();
} else {
future.fail(result.cause());
}
});
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/vertx/src/main/java/com/baeldung/HelloVerticle.java | vertx-modules/vertx/src/main/java/com/baeldung/HelloVerticle.java | package com.baeldung;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
public class HelloVerticle extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(HelloVerticle.class);
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new HelloVerticle());
}
@Override
public void start(Future<Void> future) {
LOGGER.info("Welcome to Vertx");
}
@Override
public void stop() {
LOGGER.info("Shutting down application");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/vertx/src/main/java/com/baeldung/model/Article.java | vertx-modules/vertx/src/main/java/com/baeldung/model/Article.java | package com.baeldung.model;
public class Article {
private String id;
private String content;
private String author;
private String datePublished;
private int wordCount;
public Article(String id, String content, String author, String datePublished, int wordCount) {
super();
this.id = id;
this.content = content;
this.author = author;
this.datePublished = datePublished;
this.wordCount = wordCount;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDatePublished() {
return datePublished;
}
public void setDatePublished(String datePublished) {
this.datePublished = datePublished;
}
public int getWordCount() {
return wordCount;
}
public void setWordCount(int wordCount) {
this.wordCount = wordCount;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/vertx/src/main/java/com/baeldung/rest/RestServiceVerticle.java | vertx-modules/vertx/src/main/java/com/baeldung/rest/RestServiceVerticle.java | package com.baeldung.rest;
import com.baeldung.model.Article;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.json.Json;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
public class RestServiceVerticle extends AbstractVerticle {
@Override
public void start(Future<Void> future) {
Router router = Router.router(vertx);
router.get("/api/baeldung/articles/article/:id")
.handler(this::getArticles);
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(config().getInteger("http.port", 8080), result -> {
if (result.succeeded()) {
future.complete();
} else {
future.fail(result.cause());
}
});
}
private void getArticles(RoutingContext routingContext) {
String articleId = routingContext.request()
.getParam("id");
Article article = new Article(articleId, "This is an intro to vertx", "baeldung", "01-02-2017", 1578);
routingContext.response()
.putHeader("content-type", "application/json")
.setStatusCode(200)
.end(Json.encodePrettily(article));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/vertx-and-rxjava/src/test/java/com/baeldung/weather/VertxWithRxJavaIntegrationTest.java | vertx-modules/vertx-and-rxjava/src/test/java/com/baeldung/weather/VertxWithRxJavaIntegrationTest.java | package com.baeldung.weather;
import io.reactivex.Flowable;
import io.reactivex.functions.Function;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.core.buffer.Buffer;
import io.vertx.reactivex.core.file.FileSystem;
import io.vertx.reactivex.core.http.HttpClient;
import io.vertx.reactivex.core.http.HttpClientResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.ZonedDateTime;
import static com.baeldung.weather.MetaWeatherClient.getDataByPlaceId;
import static com.baeldung.weather.MetaWeatherClient.searchByCityName;
public class VertxWithRxJavaIntegrationTest {
private Vertx vertx;
private HttpClient httpClient;
private FileSystem fileSystem;
private static Logger log = LoggerFactory.getLogger(VertxWithRxJavaIntegrationTest.class);
@Before
public void setUp() {
vertx = Vertx.vertx();
httpClient = vertx.createHttpClient();
fileSystem = vertx.fileSystem();
}
@After
public void tearDown() {
vertx.close();
}
@Test
public void shouldDisplayLightLenghts() throws InterruptedException {
// read the file that contains one city name per line
fileSystem
.rxReadFile("cities.txt").toFlowable()
.doOnNext(buffer -> log.debug("File buffer ---\n{}\n---", buffer))
.flatMap(buffer -> Flowable.fromArray(buffer.toString().split("\\r?\\n")))
.doOnNext(city -> log.debug("City from file: '{}'", city))
.filter(city -> !city.startsWith("#"))
.doOnNext(city -> log.debug("City that survived filtering: '{}'", city))
.flatMap(city -> searchByCityName(httpClient, city))
.flatMap(HttpClientResponse::toFlowable)
.doOnNext(buffer -> log.debug("JSON of city detail: '{}'", buffer))
.map(extractingWoeid())
.flatMap(cityId -> getDataByPlaceId(httpClient, cityId))
.flatMap(toBufferFlowable())
.doOnNext(buffer -> log.debug("JSON of place detail: '{}'", buffer))
.map(Buffer::toJsonObject)
.map(toCityAndDayLength())
.subscribe(System.out::println, Throwable::printStackTrace);
Thread.sleep(20000); // enough to give time to complete the execution
}
private static Function<HttpClientResponse, Publisher<? extends Buffer>> toBufferFlowable() {
return response -> response
.toObservable()
.reduce(
Buffer.buffer(),
Buffer::appendBuffer).toFlowable();
}
private static Function<Buffer, Long> extractingWoeid() {
return cityBuffer -> cityBuffer
.toJsonArray()
.getJsonObject(0)
.getLong("woeid");
}
private static Function<JsonObject, CityAndDayLength> toCityAndDayLength() {
return json -> {
ZonedDateTime sunRise = ZonedDateTime.parse(json.getString("sun_rise"));
ZonedDateTime sunSet = ZonedDateTime.parse(json.getString("sun_set"));
String cityName = json.getString("title");
return new CityAndDayLength(
cityName, sunSet.toEpochSecond() - sunRise.toEpochSecond());
};
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/vertx-and-rxjava/src/test/java/com/baeldung/weather/MetaWeatherClient.java | vertx-modules/vertx-and-rxjava/src/test/java/com/baeldung/weather/MetaWeatherClient.java | package com.baeldung.weather;
import io.reactivex.Flowable;
import io.vertx.core.http.RequestOptions;
import io.vertx.reactivex.core.http.HttpClient;
import io.vertx.reactivex.core.http.HttpClientRequest;
import io.vertx.reactivex.core.http.HttpClientResponse;
import static java.lang.String.format;
class MetaWeatherClient {
private static RequestOptions metawether = new RequestOptions()
.setHost("www.metaweather.com")
.setPort(443)
.setSsl(true);
/**
* @return A flowable backed by vertx that automatically sends an HTTP request at soon as the first subscription is received.
*/
private static Flowable<HttpClientResponse> autoPerformingReq(HttpClient httpClient, String uri) {
HttpClientRequest req = httpClient.get(new RequestOptions(metawether).setURI(uri));
return req.toFlowable()
.doOnSubscribe(subscription -> req.end());
}
static Flowable<HttpClientResponse> searchByCityName(HttpClient httpClient, String cityName) {
HttpClientRequest req = httpClient.get(
new RequestOptions()
.setHost("www.metaweather.com")
.setPort(443)
.setSsl(true)
.setURI(format("/api/location/search/?query=%s", cityName)));
return req
.toFlowable()
.doOnSubscribe(subscription -> req.end());
}
static Flowable<HttpClientResponse> getDataByPlaceId(HttpClient httpClient, long placeId) {
return autoPerformingReq(
httpClient,
format("/api/location/%s/", placeId));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/vertx-and-rxjava/src/test/java/com/baeldung/weather/CityAndDayLength.java | vertx-modules/vertx-and-rxjava/src/test/java/com/baeldung/weather/CityAndDayLength.java | package com.baeldung.weather;
import java.text.MessageFormat;
class CityAndDayLength {
private final String city;
private final double dayLengthInHours;
CityAndDayLength(String city, long dayLengthInSeconds) {
this.city = city;
this.dayLengthInHours = dayLengthInSeconds / (60.0 * 60.0);
}
@Override
public String toString() {
return MessageFormat.format("In {0} there are {1,number,#0.0} hours of light.", city, dayLengthInHours);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/spring-vertx/src/test/java/com/baeldung/SpringContextTest.java | vertx-modules/spring-vertx/src/test/java/com/baeldung/SpringContextTest.java | package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.vertxspring.VertxSpringApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = VertxSpringApplication.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/spring-vertx/src/test/java/com/baeldung/vertxspring/VertxSpringApplicationIntegrationTest.java | vertx-modules/spring-vertx/src/test/java/com/baeldung/vertxspring/VertxSpringApplicationIntegrationTest.java | package com.baeldung.vertxspring;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class VertxSpringApplicationIntegrationTest {
@Autowired
private Integer port;
private TestRestTemplate restTemplate = new TestRestTemplate();
@Test
public void givenUrl_whenReceivedArticles_thenSuccess() throws InterruptedException {
ResponseEntity<String> responseEntity = restTemplate
.getForEntity("http://localhost:" + port + "/api/baeldung/articles", String.class);
assertEquals(200, responseEntity.getStatusCodeValue());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/VertxSpringApplication.java | vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/VertxSpringApplication.java | package com.baeldung.vertxspring;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.baeldung.vertxspring.verticles.ServerVerticle;
import com.baeldung.vertxspring.verticles.ArticleRecipientVerticle;
import io.vertx.core.Vertx;
@SpringBootApplication
@Configuration
@EnableJpaRepositories("com.baeldung.vertxspring.repository")
@EntityScan("com.baeldung.vertxspring.entity")
@ComponentScan(basePackages = { "com.baeldung" })
public class VertxSpringApplication {
@Autowired
private ServerVerticle serverVerticle;
@Autowired
private ArticleRecipientVerticle serviceVerticle;
public static void main(String[] args) {
SpringApplication.run(VertxSpringApplication.class, args);
}
@PostConstruct
public void deployVerticle() {
final Vertx vertx = Vertx.vertx();
vertx.deployVerticle(serverVerticle);
vertx.deployVerticle(serviceVerticle);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/util/DbBootstrap.java | vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/util/DbBootstrap.java | package com.baeldung.vertxspring.util;
import java.util.Random;
import java.util.UUID;
import java.util.stream.IntStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.baeldung.vertxspring.entity.Article;
import com.baeldung.vertxspring.repository.ArticleRepository;
@Component
public class DbBootstrap implements CommandLineRunner {
@Autowired
private ArticleRepository articleRepository;
@Override
public void run(String... arg0) throws Exception {
IntStream.range(0, 10)
.forEach(count -> this.articleRepository.save(new Article(new Random().nextLong(), UUID.randomUUID()
.toString())));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/service/ArticleService.java | vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/service/ArticleService.java | package com.baeldung.vertxspring.service;
import com.baeldung.vertxspring.entity.Article;
import com.baeldung.vertxspring.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ArticleService {
@Autowired
private ArticleRepository articleRepository;
public List<Article> getAllArticle() {
return articleRepository.findAll();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/repository/ArticleRepository.java | vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/repository/ArticleRepository.java | package com.baeldung.vertxspring.repository;
import com.baeldung.vertxspring.entity.Article;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ArticleRepository extends JpaRepository<Article, Long> {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/entity/Article.java | vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/entity/Article.java | package com.baeldung.vertxspring.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.springframework.data.annotation.PersistenceConstructor;
@Entity
public class Article {
@Id
private Long id;
private String article;
private Article() {
}
@PersistenceConstructor
public Article(Long id, String article) {
super();
this.id = id;
this.article = article;
}
@Override
public String toString() {
return "Article [id=" + id + ", article=" + article + "]";
}
public Long getArticleId() {
return id;
}
public void setArticleId(Long id) {
this.id = id;
}
public String getArticle() {
return article;
}
public void setArticle(String article) {
this.article = article;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/config/PortConfiguration.java | vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/config/PortConfiguration.java | package com.baeldung.vertxspring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import java.io.IOException;
import java.net.ServerSocket;
@Configuration
public class PortConfiguration {
private static final int DEFAULT_PORT = 8069;
@Profile("default")
@Bean
public Integer defaultPort() {
return DEFAULT_PORT;
}
@Profile("test")
@Bean
public Integer randomPort() {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
} catch (IOException e) {
return DEFAULT_PORT;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/verticles/ServerVerticle.java | vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/verticles/ServerVerticle.java | package com.baeldung.vertxspring.verticles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.vertx.core.AbstractVerticle;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
@Component
public class ServerVerticle extends AbstractVerticle {
@Autowired
private Integer defaultPort;
private void getAllArticlesHandler(RoutingContext routingContext) {
vertx.eventBus()
.<String>send(ArticleRecipientVerticle.GET_ALL_ARTICLES, "", result -> {
if (result.succeeded()) {
routingContext.response()
.putHeader("content-type", "application/json")
.setStatusCode(200)
.end(result.result()
.body());
} else {
routingContext.response()
.setStatusCode(500)
.end();
}
});
}
@Override
public void start() throws Exception {
super.start();
Router router = Router.router(vertx);
router.get("/api/baeldung/articles")
.handler(this::getAllArticlesHandler);
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(config().getInteger("http.port", defaultPort));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/verticles/ArticleRecipientVerticle.java | vertx-modules/spring-vertx/src/main/java/com/baeldung/vertxspring/verticles/ArticleRecipientVerticle.java | package com.baeldung.vertxspring.verticles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.baeldung.vertxspring.service.ArticleService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.Json;
@Component
public class ArticleRecipientVerticle extends AbstractVerticle {
public static final String GET_ALL_ARTICLES = "get.articles.all";
private final ObjectMapper mapper = Json.mapper;
@Autowired
private ArticleService articleService;
@Override
public void start() throws Exception {
super.start();
vertx.eventBus()
.<String>consumer(GET_ALL_ARTICLES)
.handler(getAllArticleService(articleService));
}
private Handler<Message<String>> getAllArticleService(ArticleService service) {
return msg -> vertx.<String>executeBlocking(future -> {
try {
future.complete(mapper.writeValueAsString(service.getAllArticle()));
} catch (JsonProcessingException e) {
System.out.println("Failed to serialize result");
future.fail(e);
}
}, result -> {
if (result.succeeded()) {
msg.reply(result.result());
} else {
msg.reply(result.cause()
.toString());
}
});
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/rome/src/main/java/com/baeldung/rome/RSSRomeExample.java | web-modules/rome/src/main/java/com/baeldung/rome/RSSRomeExample.java | package com.baeldung.rome;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.sun.syndication.feed.synd.SyndCategory;
import com.sun.syndication.feed.synd.SyndCategoryImpl;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.SyndFeedOutput;
import com.sun.syndication.io.XmlReader;
public class RSSRomeExample {
public static void main(String[] args) throws IOException, FeedException, URISyntaxException {
SyndFeed feed = createFeed();
addEntryToFeed(feed);
publishFeed(feed);
readFeed();
}
private static SyndFeed createFeed() {
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_1.0");
feed.setTitle("Test title");
feed.setLink("http://www.somelink.com");
feed.setDescription("Basic description");
return feed;
}
private static void addEntryToFeed(SyndFeed feed) {
SyndEntry entry = new SyndEntryImpl();
entry.setTitle("Entry title");
entry.setLink("http://www.somelink.com/entry1");
addDescriptionToEntry(entry);
addCategoryToEntry(entry);
feed.setEntries(Arrays.asList(entry));
}
private static void addDescriptionToEntry(SyndEntry entry) {
SyndContent description = new SyndContentImpl();
description.setType("text/html");
description.setValue("First entry");
entry.setDescription(description);
}
private static void addCategoryToEntry(SyndEntry entry) {
List<SyndCategory> categories = new ArrayList<>();
SyndCategory category = new SyndCategoryImpl();
category.setName("Sophisticated category");
categories.add(category);
entry.setCategories(categories);
}
private static void publishFeed(SyndFeed feed) throws IOException, FeedException {
Writer writer = new FileWriter("xyz.txt");
SyndFeedOutput syndFeedOutput = new SyndFeedOutput();
syndFeedOutput.output(feed, writer);
writer.close();
}
private static SyndFeed readFeed() throws IOException, FeedException, URISyntaxException {
URL feedSource = new URI("http://rssblog.whatisrss.com/feed/").toURL();
SyndFeedInput input = new SyndFeedInput();
return input.build(new XmlReader(feedSource));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/test/java/com/baeldung/jersey/https/JerseyHttpsClientManualTest.java | web-modules/jersey-2/src/test/java/com/baeldung/jersey/https/JerseyHttpsClientManualTest.java | package com.baeldung.jersey.https;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.nio.file.Paths;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.SSLContext;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.Response;
/**
* 1. run {@code gen-keys.sh api.service} to generate server certificate/stores
* 2. specify system properties with the directory of the certificates and password
* 3. create api.service entries for 127.0.0.1 in /etc/hosts
* 4. run this class
*/
class JerseyHttpsClientManualTest {
static final String MOCK_HOST = "api.service";
static final String CERTS_DIR = System.getProperty("certs.dir");
static final String PASSWORD = System.getProperty("certs.password");
WireMockServer api;
void setup(boolean mTls) {
api = mockHttpsServer(mTls);
api.stubFor(get(urlEqualTo("/test")).willReturn(aResponse().withHeader("Content-Type", "text/plain")
.withStatus(200)
.withBody("ok")));
api.start();
System.out.println(">> Mock server started on HTTPS port: " + api.httpsPort());
}
@AfterEach
void teardown() {
if (api != null) {
api.stop();
}
}
@Test
void whenUsingJVMParameters_thenCorrectCertificateUsed() {
setup(false);
System.setProperty("javax.net.ssl.trustStore", CERTS_DIR + "/trust." + MOCK_HOST + ".p12");
System.setProperty("javax.net.ssl.trustStorePassword", PASSWORD);
Response response = ClientBuilder.newClient().target(String.format("https://%s:%d/test", api.getOptions().bindAddress(), api.httpsPort()))
.request()
.get();
assertEquals(200, response.getStatus());
}
@Test
void whenUsingCustomSSLContext_thenCorrectCertificateUsed() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
setup(false);
SSLContext sslContext = SSLContextBuilder.create()
.loadTrustMaterial(Paths.get(CERTS_DIR + "/trust." + MOCK_HOST + ".p12"), PASSWORD.toCharArray())
.build();
Client client = ClientBuilder.newBuilder()
.sslContext(sslContext)
.build();
Response response = client.target(String.format("https://%s:%d/test", api.getOptions().bindAddress(), api.httpsPort()))
.request()
.get();
assertEquals(200, response.getStatus());
}
@Test
void whenUsingMutualTLS_thenCorrectCertificateUsed() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
setup(true);
char[] password = PASSWORD.toCharArray();
SSLContext sslContext = SSLContextBuilder.create()
.loadTrustMaterial(Paths.get(CERTS_DIR + "/trust." + MOCK_HOST + ".p12"), password)
.loadKeyMaterial(Paths.get(CERTS_DIR + "/client." + MOCK_HOST + ".p12"), password, password)
.build();
Client client = ClientBuilder.newBuilder()
.sslContext(sslContext)
.build();
Response response = client.target(String.format("https://%s:%d/test", api.getOptions().bindAddress(), api.httpsPort()))
.request()
.get();
assertEquals(200, response.getStatus());
}
private static WireMockServer mockHttpsServer(boolean mTls) {
WireMockConfiguration config = WireMockConfiguration.options()
.bindAddress(MOCK_HOST)
.dynamicPort()
.dynamicHttpsPort()
.keystorePath(CERTS_DIR + "/server." + MOCK_HOST + ".p12")
.keystorePassword(PASSWORD)
.keyManagerPassword(PASSWORD);
if (mTls) {
config.trustStorePath(CERTS_DIR + "/trust." + MOCK_HOST + ".p12")
.trustStorePassword(PASSWORD)
.needClientAuth(true);
}
return new WireMockServer(config);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/test/java/com/baeldung/jersey/serverlogging/JerseyServerLoggingIntegrationTest.java | web-modules/jersey-2/src/test/java/com/baeldung/jersey/serverlogging/JerseyServerLoggingIntegrationTest.java | package com.baeldung.jersey.serverlogging;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.net.URI;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.Response;
class JerseyServerLoggingIntegrationTest {
private static HttpServer server;
private static final URI BASE_URI = URI.create("http://localhost:8080/api");
@BeforeAll
static void setup() {
server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, new JerseyServerLoggingApp());
}
@AfterAll
static void teardown() {
server.shutdownNow();
}
@Test
void whenRequestMadeWithLoggingFilter_thenCustomLogsAreWritten() {
Logger logger = (Logger) LoggerFactory.getLogger(CustomServerLoggingFilter.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
logger.addAppender(listAppender);
listAppender.list.clear();
Response response = ClientBuilder.newClient()
.target(BASE_URI + "/logging")
.request()
.get();
assertEquals(200, response.getStatus());
boolean requestLogFound = listAppender.list.stream()
.anyMatch(event -> event.getFormattedMessage().contains("Incoming request: GET http://localhost:8080/api/logging"));
boolean responseLogFound = listAppender.list.stream()
.anyMatch(event -> event.getFormattedMessage().contains("Outgoing response: GET http://localhost:8080/api/logging - Status 200"));
assertEquals(true, requestLogFound, "Request log not found");
assertEquals(true, responseLogFound, "Response log not found");
logger.detachAppender(listAppender);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/test/java/com/baeldung/jersey/response/XMLResponseUnitTest.java | web-modules/jersey-2/src/test/java/com/baeldung/jersey/response/XMLResponseUnitTest.java | package com.baeldung.jersey.response;
import com.baeldung.jersey.model.Product;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@DisplayName("XMLResponse Tests")
class XMLResponseUnitTest {
@Mock private Client client;
@Mock private WebTarget webTarget;
@Mock private Invocation.Builder builder;
@Mock private Response response;
@Mock private Logger logger;
private XMLResponse xmlResponse;
private static final String BASE_URL = "https://api.example.com/product";
@BeforeEach
void setUp() {
xmlResponse = new XMLResponse(client, logger, BASE_URL);
// Common mock setup
when(client.target(anyString())).thenReturn(webTarget);
when(webTarget.request(MediaType.APPLICATION_XML)).thenReturn(builder);
when(builder.post(any(Entity.class))).thenReturn(response);
}
@Test
@DisplayName("Should successfully fetch product data")
void givenValidProductId_whenFetchingProductData_thenReturnProduct() {
// Given
String validXml = "<product><id>1</id><name>Test Product</name></product>";
when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
when(response.readEntity(InputStream.class))
.thenReturn(new ByteArrayInputStream(validXml.getBytes()));
// When
Product product = xmlResponse.fetchProductData(1);
// Then
assertNotNull(product);
assertEquals(1, product.getId());
assertEquals("Test Product", product.getName());
verify(response).close();
}
@Test
@DisplayName("Should handle non-200 response")
void givenNon200Response_whenFetchingProductData_thenReturnNull() {
// Given
when(response.getStatus()).thenReturn(Response.Status.BAD_REQUEST.getStatusCode());
// When
Product product = xmlResponse.fetchProductData(1);
// Then
assertNull(product);
verify(logger).error(eq("Failed to get product data. Status: {}"), eq(400));
verify(response).close();
}
@Test
@DisplayName("Should handle unmarshalling error")
void givenInvalidXmlResponse_whenFetchingProductData_thenReturnNull() {
// Given
String invalidXml = "<invalid><data></data></invalid>";
when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
when(response.readEntity(InputStream.class))
.thenReturn(new ByteArrayInputStream(invalidXml.getBytes()));
// When
Product product = xmlResponse.fetchProductData(1);
// Then
assertNull(product);
verify(logger).error(eq("Error unmarshalling product data"), any(JAXBException.class));
verify(response).close();
}
@Test
@DisplayName("Should handle exception during processing")
void givenExceptionDuringProcessing_whenFetchingProductData_thenReturnNull() {
// Given
when(response.getStatus()).thenThrow(new RuntimeException("Test exception"));
// When
Product product = xmlResponse.fetchProductData(1);
// Then
assertNull(product);
verify(logger).error(eq("Error processing product data"), any(RuntimeException.class));
verify(response).close();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/test/java/com/baeldung/jersey/response/GenericRestResponseUnitTest.java | web-modules/jersey-2/src/test/java/com/baeldung/jersey/response/GenericRestResponseUnitTest.java | package com.baeldung.jersey.response;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@DisplayName("GenericRestResponse Tests")
public class GenericRestResponseUnitTest {
@Mock private Client client;
@Mock private WebTarget webTarget;
@Mock private Response response;
@Mock private Invocation.Builder builder;
@Mock private Logger logger;
private GenericRestResponse genericRestResponse;
private static final String TEST_URL = "https://api.example.com/data";
private static final String TEST_PAYLOAD = "{\"name\":\"John Doe\",\"email\":\"john.doe@example.com\"}";
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
genericRestResponse = new GenericRestResponse(client, logger);
// Common mock setup
when(client.target(TEST_URL)).thenReturn(webTarget);
when(webTarget.request(MediaType.APPLICATION_JSON)).thenReturn(builder);
when(builder.post(any(Entity.class))).thenReturn(response);
}
@Test
@DisplayName("Should successfully process OK response")
void givenOkResponse_whenSendingRequest_thenShouldSuccessfullyProcess() {
// Given
String expectedResponse = "{\"status\":\"success\"}";
when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
when(response.readEntity(String.class)).thenReturn(expectedResponse);
// When
genericRestResponse.sendRequest(TEST_URL, TEST_PAYLOAD);
// Then
verify(logger).info(contains(expectedResponse));
verify(response).close();
verify(client).close();
}
@Test
@DisplayName("Should handle failed response")
void givenFailedResponse_whenSendingRequest_thenShouldHandleFailedResponse() {
// Given
when(response.getStatus()).thenReturn(Response.Status.BAD_REQUEST.getStatusCode());
// When
genericRestResponse.sendRequest(TEST_URL, TEST_PAYLOAD);
// Then
verify(logger).error("Failed to get a successful response");
verify(response).close();
verify(client).close();
}
@Test
@DisplayName("Given runtime exception, when sending request, then handle exception appropriately")
void givenRuntimeException_whenSendingRequest_thenHandleException() {
// Given
RuntimeException testException = new RuntimeException("Test exception");
when(response.getStatus()).thenThrow(testException);
// When
genericRestResponse.sendRequest(TEST_URL, TEST_PAYLOAD);
// Then
verify(logger).error(eq("Error processing response"), eq(testException));
verify(response).close();
verify(client).close();
}
@Test
@DisplayName("Given empty response body, when sending request, then process empty response")
void givenEmptyResponseBody_whenSendingRequest_thenProcessEmptyResponse() {
// Given
when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
when(response.readEntity(String.class)).thenReturn("");
// When
genericRestResponse.sendRequest(TEST_URL, TEST_PAYLOAD);
// Then
verify(logger).info(contains(""));
verify(response).close();
verify(client).close();
}
@Test
@DisplayName("Should handle malformed response")
void givenOkResponse_whenMalformedResponse_thenShouldHandle() {
// Given
when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
when(response.readEntity(String.class)).thenThrow(new RuntimeException("Malformed response"));
// When
genericRestResponse.sendRequest(TEST_URL, TEST_PAYLOAD);
// Then
verify(logger).error(eq("Error processing response"), any(RuntimeException.class));
verify(response).close();
verify(client).close();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/test/java/com/baeldung/jersey/response/JsonResponseUnitTest.java | web-modules/jersey-2/src/test/java/com/baeldung/jersey/response/JsonResponseUnitTest.java | package com.baeldung.jersey.response;
import com.baeldung.jersey.model.User;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.Logger;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@DisplayName("JsonResponse Tests")
class JsonResponseUnitTest {
@Mock private Client client;
@Mock private WebTarget webTarget;
@Mock private Invocation.Builder builder;
@Mock private Response response;
@Mock private Logger logger;
private JsonResponse jsonResponse;
private static final String BASE_URL = "https://api.example.com/user";
@BeforeEach
void setUp() {
jsonResponse = new JsonResponse(client, logger, BASE_URL);
// Common mock setup
when(client.target(anyString())).thenReturn(webTarget);
when(webTarget.request(MediaType.APPLICATION_JSON)).thenReturn(builder);
when(builder.post(any(Entity.class))).thenReturn(response);
}
@Test
@DisplayName("Should successfully fetch user data")
void givenValidUserId_whenFetchingUserData_thenReturnUser() {
// Given
User expectedUser = new User(1, "John Doe");
when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode());
when(response.readEntity(User.class)).thenReturn(expectedUser);
// When
User actualUser = jsonResponse.fetchUserData(1);
// Then
assertNotNull(actualUser);
assertEquals(expectedUser.getId(), actualUser.getId());
assertEquals(expectedUser.getName(), actualUser.getName());
verify(response).close();
}
@Test
@DisplayName("Should handle non-200 response")
void givenNon200Response_whenFetchingUserData_thenReturnNull() {
// Given
when(response.getStatus()).thenReturn(Response.Status.BAD_REQUEST.getStatusCode());
// When
User user = jsonResponse.fetchUserData(1);
// Then
assertNull(user);
verify(logger).error(eq("Failed to get user data. Status: {}"), eq(400));
verify(response).close();
}
@Test
@DisplayName("Should handle exception during processing")
void givenExceptionDuringProcessing_whenFetchingUserData_thenReturnNull() {
// Given
when(response.getStatus()).thenThrow(new RuntimeException("Test exception"));
// When
User user = jsonResponse.fetchUserData(1);
// Then
assertNull(user);
verify(logger).error(eq("Error processing user data"), any(RuntimeException.class));
verify(response).close();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/test/java/com/baeldung/jersey/jackson/CustomObjectMapperUnitTest.java | web-modules/jersey-2/src/test/java/com/baeldung/jersey/jackson/CustomObjectMapperUnitTest.java | package com.baeldung.jersey.jackson;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.jersey.jackson.mapper.ConditionalObjectMapperResolver;
import com.baeldung.jersey.jackson.model.InternalApiMessage;
import com.baeldung.jersey.jackson.model.Message;
import com.baeldung.jersey.jackson.model.PublicApiMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CustomObjectMapperUnitTest {
private ObjectMapper defaultMapper;
private ObjectMapper publicApiMapper;
private ObjectMapper internalApiMapper;
@BeforeEach
void setUp() {
ConditionalObjectMapperResolver resolver = new ConditionalObjectMapperResolver();
publicApiMapper = resolver.getContext(PublicApiMessage.class);
internalApiMapper = resolver.getContext(InternalApiMessage.class);
defaultMapper = resolver.getContext(Message.class);
}
@Test
void givenPublicApiMessage_whenSerialized_thenOmitsSensitiveFieldAndNulls() throws Exception {
PublicApiMessage message = new PublicApiMessage("Public Hello!", LocalDate.of(2025, 8, 23), null);
String json = publicApiMapper.writeValueAsString(message);
assertTrue(json.contains("text"));
assertTrue(json.contains("date"));
assertFalse(json.contains("sensitiveField"), "sensitiveField should not appear");
assertFalse(json.contains("null"), "Null values should be excluded");
}
@Test
void givenInternalApiMessageWithEmptyMetadata_whenSerialized_thenIncludesEmptyArraysButNoNulls() throws Exception {
InternalApiMessage message = new InternalApiMessage("Internal Hello!", LocalDate.of(2025, 8, 23), "debug-123", new ArrayList<>());
String json = internalApiMapper.writeValueAsString(message);
assertTrue(json.contains("debugInfo"));
assertFalse(json.contains("null"), "Null values should be excluded");
assertFalse(json.contains("metadata"), "Empty metadata list should be excluded");
}
@Test
void givenInternalApiMessageWithNonEmptyMetadata_whenSerialized_thenMetadataIsIncluded() throws Exception {
InternalApiMessage message = new InternalApiMessage("Internal Hello!", LocalDate.of(2025, 8, 23), "debug-123", Arrays.asList("meta1"));
String json = internalApiMapper.writeValueAsString(message);
assertTrue(json.contains("metadata"), "Non-empty metadata should be serialized");
}
@Test
void givenDefaultMessage_whenSerialized_thenIncludesOptionalFieldAndMetadata() throws Exception {
Message message = new Message("Default Hello!", LocalDate.of(2025, 8, 23), "optional");
message.metadata = new ArrayList<>();
String json = defaultMapper.writeValueAsString(message);
assertTrue(json.contains("metadata"));
assertTrue(json.contains("optionalField") || json.contains("optional"), "Optional field should be included");
}
@Test
void givenMessageWithDate_whenSerialized_thenDateIsInIso8601Format() throws Exception {
Message message = new Message("Date Test", LocalDate.of(2025, 9, 2), "optional");
String json = defaultMapper.writeValueAsString(message);
assertTrue(json.contains("2025-09-02"), "Date should be serialized in ISO-8601 format");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/test/java/com/baeldung/jersey/timeout/JerseyClientTimeoutIntegrationTest.java | web-modules/jersey-2/src/test/java/com/baeldung/jersey/timeout/JerseyClientTimeoutIntegrationTest.java | package com.baeldung.jersey.timeout;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.URI;
import org.glassfish.grizzly.http.server.HttpServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import com.baeldung.jersey.timeout.client.JerseyTimeoutClient;
import com.baeldung.jersey.timeout.server.JerseyTimeoutServerApp;
import jakarta.ws.rs.ProcessingException;
class JerseyClientTimeoutIntegrationTest {
private static final String CONNECT_TIMED_OUT = "Connect timed out";
private static final String READ_TIMED_OUT = "Read timed out";
private static final URI BASE = JerseyTimeoutServerApp.BASE_URI;
private static final String CORRECT_ENDPOINT = BASE + "/timeout";
private static final String INCORRECT_ENDPOINT = BASE.toString()
.replace(BASE.getHost(), "10.255.255.1");
private static HttpServer server;
private JerseyTimeoutClient readTimeoutClient = new JerseyTimeoutClient(CORRECT_ENDPOINT);
private JerseyTimeoutClient connectTimeoutClient = new JerseyTimeoutClient(INCORRECT_ENDPOINT);
@BeforeAll
static void beforeAllTests() throws IOException {
server = JerseyTimeoutServerApp.start();
}
@AfterAll
static void afterAllTests() {
server.shutdownNow();
}
private void assertTimeout(String message, Executable executable) {
ProcessingException exception = assertThrows(ProcessingException.class, executable);
Throwable cause = exception.getCause();
assertInstanceOf(SocketTimeoutException.class, cause);
assertEquals(message, cause.getMessage());
}
@Test
void givenCorrectEndpoint_whenClientBuilderAndSlowServer_thenReadTimeout() {
assertTimeout(READ_TIMED_OUT, readTimeoutClient::viaClientBuilder);
}
@Test
void givenIncorrectEndpoint_whenClientBuilder_thenConnectTimeout() {
assertTimeout(CONNECT_TIMED_OUT, connectTimeoutClient::viaClientBuilder);
}
@Test
void givenCorrectEndpoint_whenClientConfigAndSlowServer_thenReadTimeout() {
assertTimeout(READ_TIMED_OUT, readTimeoutClient::viaClientConfig);
}
@Test
void givenIncorrectEndpoint_whenClientConfig_thenConnectTimeout() {
assertTimeout(CONNECT_TIMED_OUT, connectTimeoutClient::viaClientConfig);
}
@Test
void givenCorrectEndpoint_whenClientPropertyAndSlowServer_thenReadTimeout() {
assertTimeout(READ_TIMED_OUT, readTimeoutClient::viaClientProperty);
}
@Test
void givenIncorrectEndpoint_whenClientProperty_thenConnectTimeout() {
assertTimeout(CONNECT_TIMED_OUT, connectTimeoutClient::viaClientProperty);
}
@Test
void givenCorrectEndpoint_whenRequestPropertyAndSlowServer_thenReadTimeout() {
assertTimeout(READ_TIMED_OUT, readTimeoutClient::viaRequestProperty);
}
@Test
void givenIncorrectEndpoint_whenRequestProperty_thenConnectTimeout() {
assertTimeout(CONNECT_TIMED_OUT, connectTimeoutClient::viaRequestProperty);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/model/Product.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/model/Product.java | package com.baeldung.jersey.model;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Product {
private int id;
private String name;
@XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/model/User.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/model/User.java | package com.baeldung.jersey.model;
public class User {
private int id;
private String name;
public User() {
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/serverlogging/JerseyServerLoggingApp.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/serverlogging/JerseyServerLoggingApp.java | package com.baeldung.jersey.serverlogging;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.glassfish.jersey.logging.LoggingFeature;
import org.glassfish.jersey.server.ResourceConfig;
public class JerseyServerLoggingApp extends ResourceConfig {
public JerseyServerLoggingApp() {
register(LoggingResource.class);
register(new LoggingFeature(
Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME),
Level.INFO,
LoggingFeature.Verbosity.PAYLOAD_ANY,
8192));
register(CustomServerLoggingFilter.class);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/serverlogging/LoggingResource.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/serverlogging/LoggingResource.java | package com.baeldung.jersey.serverlogging;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
@Path("/logging")
public class LoggingResource {
@GET
public String get() {
return "Hello";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/serverlogging/CustomServerLoggingFilter.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/serverlogging/CustomServerLoggingFilter.java | package com.baeldung.jersey.serverlogging;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import jakarta.ws.rs.ext.Provider;
@Provider
public class CustomServerLoggingFilter implements ContainerRequestFilter, ContainerResponseFilter {
private static final Logger LOG = LoggerFactory.getLogger(CustomServerLoggingFilter.class);
@Override
public void filter(ContainerRequestContext requestContext) {
LOG.info("Incoming request: {} {}", requestContext.getMethod(), requestContext.getUriInfo()
.getRequestUri());
LOG.info("Request headers: {}", requestContext.getHeaders());
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
LOG.info("Outgoing response: {} {} - Status {}", requestContext.getMethod(), requestContext.getUriInfo()
.getRequestUri(), responseContext.getStatus());
LOG.info("Response headers: {}", responseContext.getHeaders());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/server/EmbeddedJerseyServer.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/server/EmbeddedJerseyServer.java | package com.baeldung.jersey.server;
import java.io.IOException;
import java.net.URI;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EmbeddedJerseyServer {
private static final Logger logger = LoggerFactory.getLogger(EmbeddedJerseyServer.class);
private EmbeddedJerseyServer() {
}
public static HttpServer start(URI url, ResourceConfig config) throws IOException {
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create(url.toString()), config, false);
Runtime.getRuntime()
.addShutdownHook(new Thread(server::shutdownNow));
server.start();
logger.info("server available at {}", url);
return server;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/response/GenericRestResponse.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/response/GenericRestResponse.java | package com.baeldung.jersey.response;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GenericRestResponse {
private final Logger logger;
private final Client client;
public GenericRestResponse(Client client, Logger logger) {
this.client = client;
this.logger = logger;
}
public GenericRestResponse() {
this(ClientBuilder.newClient(), LoggerFactory.getLogger(GenericRestResponse.class));
}
public void sendRequest(String url, String jsonPayload) {
WebTarget target = client.target(url);
Response response = target.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(jsonPayload, MediaType.APPLICATION_JSON));
try {
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
String responseBody = response.readEntity(String.class);
logger.info("Response Body: " + responseBody);
} else {
logger.error("Failed to get a successful response");
}
} catch (RuntimeException e) {
logger.error("Error processing response", e);
} finally {
response.close();
client.close();
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/response/JsonResponse.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/response/JsonResponse.java | package com.baeldung.jersey.response;
import com.baeldung.jersey.model.User;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.slf4j.Logger;
public class JsonResponse {
private final Logger logger;
private final Client client;
private final String baseUrl;
public JsonResponse(Client client, Logger logger, String baseUrl) {
this.client = client;
this.logger = logger;
this.baseUrl = baseUrl;
}
public User fetchUserData(int userId) {
WebTarget target = client.target(baseUrl);
String jsonPayload = String.format("{\"id\":%d}", userId);
try (Response response = target.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(jsonPayload, MediaType.APPLICATION_JSON))) {
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
return response.readEntity(User.class);
} else {
logger.error("Failed to get user data. Status: {}", response.getStatus());
return null;
}
} catch (Exception e) {
logger.error("Error processing user data", e);
return null;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/response/XMLResponse.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/response/XMLResponse.java | package com.baeldung.jersey.response;
import com.baeldung.jersey.model.Product;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import org.slf4j.Logger;
import java.io.InputStream;
public class XMLResponse {
private final Logger logger;
private final Client client;
private final String baseUrl;
public XMLResponse(Client client, Logger logger, String baseUrl) {
this.client = client;
this.logger = logger;
this.baseUrl = baseUrl;
}
public Product fetchProductData(int productId) {
WebTarget target = client.target(baseUrl);
String xmlPayload = String.format("<product><id>%d</id></product>", productId);
try (Response response = target.request(MediaType.APPLICATION_XML)
.post(Entity.entity(xmlPayload, MediaType.APPLICATION_XML))) {
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
JAXBContext jaxbContext = JAXBContext.newInstance(Product.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
return (Product) unmarshaller.unmarshal(response.readEntity(InputStream.class));
} else {
logger.error("Failed to get product data. Status: {}", response.getStatus());
return null;
}
} catch (JAXBException e) {
logger.error("Error unmarshalling product data", e);
return null;
} catch (Exception e) {
logger.error("Error processing product data", e);
return null;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/model/Message.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/model/Message.java | package com.baeldung.jersey.jackson.model;
import java.time.LocalDate;
import java.util.List;
public class Message {
public String text;
public LocalDate date;
public String optionalField;
public List<String> metadata;
public Message(String text, LocalDate date, String optionalField) {
this.text = text;
this.date = date;
this.optionalField = optionalField;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/model/PublicApiMessage.java | web-modules/jersey-2/src/main/java/com/baeldung/jersey/jackson/model/PublicApiMessage.java | package com.baeldung.jersey.jackson.model;
import java.time.LocalDate;
import com.baeldung.jersey.jackson.annotation.PublicApi;
@PublicApi
public class PublicApiMessage {
public String text;
public LocalDate date;
public String sensitiveField;
public PublicApiMessage(String text, LocalDate date, String sensitiveField) {
this.text = text;
this.date = date;
this.sensitiveField = sensitiveField;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.