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/libraries-3/src/test/java/com/baeldung/failsafe/RateLimiterUnitTest.java | libraries-3/src/test/java/com/baeldung/failsafe/RateLimiterUnitTest.java | package com.baeldung.failsafe;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import dev.failsafe.Failsafe;
import dev.failsafe.FailsafeExecutor;
import dev.failsafe.RateLimitExceededException;
import dev.failsafe.RateLimiter;
public class RateLimiterUnitTest {
@Test
void lessThanWindow() {
RateLimiter<Object> rateLimiter = RateLimiter.burstyBuilder(10, Duration.ofSeconds(2))
.build();
FailsafeExecutor<Object> executor = Failsafe.with(rateLimiter);
for (int i = 0; i < 5; ++i) {
int expected = i;
assertEquals(expected, executor.get(() -> expected));
}
}
@Test
void moreThanWindow() {
RateLimiter<Object> rateLimiter = RateLimiter.burstyBuilder(10, Duration.ofSeconds(2))
.build();
FailsafeExecutor<Object> executor = Failsafe.with(rateLimiter);
for (int i = 0; i < 10; ++i) {
int expected = i;
assertEquals(expected, executor.get(() -> expected));
}
assertThrows(RateLimitExceededException.class, () -> executor.run(() -> {}));
}
@Test
void executedAfterBurstyWindow() throws InterruptedException {
RateLimiter<Object> rateLimiter = RateLimiter.burstyBuilder(10, Duration.ofSeconds(2)).build();
FailsafeExecutor<Object> executor = Failsafe.with(rateLimiter);
long start = System.currentTimeMillis();
for (int i = 0; i < 10; ++i) {
int expected = i;
System.out.println("Time " + i + ": " + (System.currentTimeMillis() - start));
assertEquals(expected, executor.get(() -> expected));
Thread.sleep(100);
}
// Wait for the entire window length
Thread.sleep(1000);
System.out.println("Time after: " + (System.currentTimeMillis() - start));
executor.run(() -> {});
}
@Test
void smoothWindow() throws InterruptedException {
RateLimiter<Object> rateLimiter = RateLimiter.smoothBuilder(10, Duration.ofSeconds(2)).build();
FailsafeExecutor<Object> executor = Failsafe.with(rateLimiter);
executor.run(() -> {});
Thread.sleep(200); // 1/10 of our 2 second window.
executor.run(() -> {});
// Wait less than 1/10 of our 2 second window.
assertThrows(RateLimitExceededException.class, () -> executor.run(() -> {}));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/test/java/com/baeldung/failsafe/BulkheadUnitTest.java | libraries-3/src/test/java/com/baeldung/failsafe/BulkheadUnitTest.java | package com.baeldung.failsafe;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import dev.failsafe.Bulkhead;
import dev.failsafe.BulkheadFullException;
import dev.failsafe.Failsafe;
public class BulkheadUnitTest {
@Test
void rejectExcessCalls() throws InterruptedException {
Bulkhead<Object> bulkhead = Bulkhead.builder(1).build();
Thread t = new Thread(() -> {
Failsafe.with(bulkhead).run(() -> Thread.sleep(500));
});
t.start();
// Ensure the thread has started.
Thread.sleep(100);
assertThrows(BulkheadFullException.class, () ->
Failsafe.with(bulkhead).run(() -> {})
);
t.join();
}
@Test
void waitForCapacity() throws InterruptedException {
Bulkhead<Object> bulkhead = Bulkhead.builder(1)
.withMaxWaitTime(Duration.ofMillis(1000))
.build();
Thread t = new Thread(() -> {
Failsafe.with(bulkhead).run(() -> Thread.sleep(500));
});
t.start();
// Ensure the thread has started.
Thread.sleep(100);
long start = System.currentTimeMillis();
Integer result = Failsafe.with(bulkhead).get(() -> 1);
long end = System.currentTimeMillis();
long duration = end - start;
assertEquals(1, result);
assertTrue(duration >= 400); // Our action time minus our startup pause.
assertTrue(duration <= 550); // Our action time plus a bit. Notably less than our timeout.
t.join();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/test/java/com/baeldung/failsafe/RetryUnitTest.java | libraries-3/src/test/java/com/baeldung/failsafe/RetryUnitTest.java | package com.baeldung.failsafe;
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.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import dev.failsafe.Failsafe;
import dev.failsafe.FailsafeException;
import dev.failsafe.RetryPolicy;
public class RetryUnitTest {
@Test
void defaultRetryTwice() {
RetryPolicy<Object> retryPolicy = RetryPolicy.builder().build();
AtomicInteger counter = new AtomicInteger(2);
Integer result = Failsafe.with(retryPolicy)
.get(() -> {
if (counter.decrementAndGet() > 0) {
throw new IOException("Something went wrong");
}
return 2;
});
assertEquals(0, counter.get());
assertEquals(2, result);
}
@Test
void defaultRetryFourTimes() {
RetryPolicy<Object> retryPolicy = RetryPolicy.builder().build();
AtomicInteger counter = new AtomicInteger(4);
FailsafeException exception = assertThrows(FailsafeException.class, () ->
Failsafe.with(retryPolicy)
.get(() -> {
if (counter.decrementAndGet() > 0) {
throw new IOException("Something went wrong");
}
return 2;
})
);
assertEquals(1, counter.get());
assertInstanceOf(IOException.class, exception.getCause());
assertEquals("Something went wrong", exception.getCause().getMessage());
}
@Test
void retryFourTimes() {
RetryPolicy<Object> retryPolicy = RetryPolicy.builder()
.withMaxAttempts(5)
.build();
AtomicInteger counter = new AtomicInteger(4);
Integer result = Failsafe.with(retryPolicy)
.get(() -> {
if (counter.decrementAndGet() > 0) {
throw new IOException("Something went wrong");
}
return 2;
});
assertEquals(0, counter.get());
assertEquals(2, result);
}
@Test
void retryWithDelay() {
RetryPolicy<Object> retryPolicy = RetryPolicy.builder()
.withDelay(Duration.ofMillis(250))
.build();
AtomicInteger counter = new AtomicInteger(2);
Integer result = Failsafe.with(retryPolicy)
.get(() -> {
System.out.println("Retrying: " + System.currentTimeMillis());
if (counter.decrementAndGet() > 0) {
throw new IOException("Something went wrong");
}
return 2;
});
assertEquals(0, counter.get());
assertEquals(2, result);
}
@Test
void retryWithBackoff() {
RetryPolicy<Object> retryPolicy = RetryPolicy.builder()
.withMaxAttempts(20)
.withBackoff(Duration.ofMillis(100), Duration.ofMillis(2000))
.build();
AtomicInteger counter = new AtomicInteger(10);
Integer result = Failsafe.with(retryPolicy)
.get(() -> {
System.out.println("Retrying: " + System.currentTimeMillis());
if (counter.decrementAndGet() > 0) {
throw new IOException("Something went wrong");
}
return 2;
});
assertEquals(0, counter.get());
assertEquals(2, result);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/test/java/com/baeldung/failsafe/TimeoutUnitTest.java | libraries-3/src/test/java/com/baeldung/failsafe/TimeoutUnitTest.java | package com.baeldung.failsafe;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import dev.failsafe.Failsafe;
import dev.failsafe.FailsafeException;
import dev.failsafe.Timeout;
public class TimeoutUnitTest {
@Test
void testTimeout() {
Timeout<Object> timeout = Timeout.builder(Duration.ofMillis(100)).build();
long start = System.currentTimeMillis();
assertThrows(FailsafeException.class, () ->
Failsafe.with(timeout)
.get(() -> {
Thread.sleep(250);
return 2;
})
);
long end = System.currentTimeMillis();
long duration = end - start;
assertTrue(duration >= 100); // Our timeout
assertTrue(duration <= 300); // 250ms plus a bit.
}
@Test
void testInterruption() {
Timeout<Object> timeout = Timeout.builder(Duration.ofMillis(100))
.withInterrupt()
.build();
long start = System.currentTimeMillis();
assertThrows(FailsafeException.class, () ->
Failsafe.with(timeout)
.get(() -> {
Thread.sleep(250);
return 2;
})
);
long end = System.currentTimeMillis();
long duration = end - start;
assertTrue(duration >= 100); // Our timeout
assertTrue(duration <= 150); // Our timeout plus a bit. Notably less than our task takes.
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/test/java/com/baeldung/yauaa/HomePageControllerIntegrationTest.java | libraries-3/src/test/java/com/baeldung/yauaa/HomePageControllerIntegrationTest.java | package com.baeldung.yauaa;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
@Import(UserAgentAnalyzerConfiguration.class)
@WebMvcTest(controllers = HomePageController.class)
class HomePageControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
private static final String SAFARI_MAC_OS_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15";
private static final String SAFARI_IOS_USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1";
@Test
void whenRequestFromLaptop_thenErrorScreenDisplayed() throws Exception {
mockMvc.perform(get("/mobile/home")
.header("User-Agent", SAFARI_MAC_OS_USER_AGENT))
.andExpect(view().name("error/open-in-mobile"))
.andExpect(status().isForbidden());
}
@Test
void whenRequestFromMobileDevice_thenHomePageDisplayed() throws Exception {
mockMvc.perform(get("/mobile/home")
.header("User-Agent", SAFARI_IOS_USER_AGENT))
.andExpect(view().name("/mobile-home"))
.andExpect(status().isOk());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/test/java/com/baeldung/jnats/NatsClientLiveTest.java | libraries-3/src/test/java/com/baeldung/jnats/NatsClientLiveTest.java | package com.baeldung.jnats;
import io.nats.client.*;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.*;
/**
* All the tests in this class require that a NATS server be running on localhost at the default port.
* See {@link <a href="https://docs.nats.io/nats-server/installation">Installing a NATS Server</a>}.
* <p>
* IMPORTANT: Awaitility.await is used to account for the real behavior
* that messages take some amount of time to go from being published
* to being received. This amount of time will vary depending on many factors including:
* <ul>
* <li>network latency</li>
* <li>server cluster configuration</li>
* <li>server computing power relative to the load of work</li>
* </ul>
* </p>
*/
public class NatsClientLiveTest {
private final static Logger log = LoggerFactory.getLogger(NatsClientLiveTest.class);
private static final int TIMEOUT_MILLIS = 200;
private static final int WAIT_AT_MOST_MILLIS = 300;
private static final int POLL_DELAY_MILLIS = 50;
private static Connection createConnection() throws IOException, InterruptedException {
return createConnection("nats://localhost:4222");
}
private static Connection createConnection(String uri) throws IOException, InterruptedException {
Options options = new Options.Builder().server(uri)
.connectionListener((connection, event) -> log.info("Connection Event: " + event))
.errorListener(new CustomErrorListener())
.build();
return Nats.connect(options);
}
public static Connection createConnectionWithReportNoResponders() throws IOException, InterruptedException {
return createConnectionWithReportNoResponders("nats://localhost:4222");
}
public static Connection createConnectionWithReportNoResponders(String uri) throws IOException, InterruptedException {
Options options = new Options.Builder().server(uri)
.connectionListener((connection, event) -> log.info("Connection Event: " + event))
.errorListener(new CustomErrorListener())
.reportNoResponders()
.build();
return Nats.connect(options);
}
private static String convertMessageDataBytesToString(Message message) {
return new String(message.getData(), StandardCharsets.UTF_8);
}
private static byte[] convertStringToBytes(String s) {
return s.getBytes(StandardCharsets.UTF_8);
}
static class CustomErrorListener implements ErrorListener {
@Override
public void errorOccurred(Connection conn, String error) {
log.error("Error Occurred: " + error);
}
@Override
public void exceptionOccurred(Connection conn, Exception exp) {
log.error("Exception Occurred: " + exp);
}
}
@Test
public void givenNoSubscribers_whenPublishingMessages_thenItCannotBeDeterminedIfMessageIsReceived() {
try (Connection natsConnection = createConnection()) {
natsConnection.publish("mySubject", convertStringToBytes("myData"));
} catch (Exception e) {
fail("There should not be an exception");
}
}
@Test
public void givenNoSubscribersAndReportNoResponders_whenRequestReply_thenReceiveNoResponders() {
try (Connection natsConnection = createConnectionWithReportNoResponders()) {
natsConnection.publish("noOneIsSubscribed", null);
CompletableFuture<Message> future = natsConnection.request("noOneIsSubscribed", null);
future.get(WAIT_AT_MOST_MILLIS, TimeUnit.MILLISECONDS);
fail("There should be an exception");
} catch (ExecutionException e) {
Throwable cause = e.getCause();
assertNotNull(cause);
assertInstanceOf(JetStreamStatusException.class, cause);
assertTrue(cause.getMessage()
.contains("503 No Responders Available For Request"));
} catch (InterruptedException | TimeoutException | IOException e) {
fail("There should not be one of these exceptions");
}
}
@Test
public void whenSubscribingSynchronouslyWithoutQueueGroups_thenEachSubscriptionShouldReceiveEachMessage() throws Exception {
try (Connection natsConnection = createConnection()) {
Subscription subscription1 = natsConnection.subscribe("mySubject");
Subscription subscription2 = natsConnection.subscribe("mySubject");
natsConnection.publish("mySubject", convertStringToBytes("data"));
assertNotNull(subscription1.nextMessage(TIMEOUT_MILLIS));
assertNotNull(subscription2.nextMessage(TIMEOUT_MILLIS));
subscription1.unsubscribe();
subscription2.unsubscribe();
}
}
@Test
public void whenSubscribingSynchronouslyWithQueueGroups_thenOnlyOneSubscriberInTheGroupShouldReceiveEachMessage() throws Exception {
try (Connection natsConnection = createConnection()) {
Subscription qSub1 = natsConnection.subscribe("mySubject", "myQueue");
Subscription qSub2 = natsConnection.subscribe("mySubject", "myQueue");
natsConnection.publish("mySubject", convertStringToBytes("data"));
List<Message> messages = new ArrayList<>();
Message message = qSub1.nextMessage(TIMEOUT_MILLIS);
if (message != null) {
messages.add(message);
}
message = qSub2.nextMessage(TIMEOUT_MILLIS);
if (message != null) {
messages.add(message);
}
assertEquals(1, messages.size());
qSub1.unsubscribe();
qSub2.unsubscribe();
}
}
@Test
public void whenSubscribingAsynchronouslyWithoutQueueGroups_thenEachMessageHandlerShouldReceiveEachMessage() throws Exception {
try (Connection natsConnection = createConnection()) {
List<Message> messages1 = new ArrayList<>();
List<Message> messages2 = new ArrayList<>();
Dispatcher dispatcher = natsConnection.createDispatcher();
Subscription subscription1 = dispatcher.subscribe("mySubject", messages1::add);
Subscription subscription2 = dispatcher.subscribe("mySubject", messages2::add);
natsConnection.publish("mySubject", convertStringToBytes("data1"));
natsConnection.publish("mySubject", convertStringToBytes("data2"));
// wait for messages to propagate.
Awaitility.await()
.atMost(WAIT_AT_MOST_MILLIS, TimeUnit.MILLISECONDS)
.pollDelay(POLL_DELAY_MILLIS, TimeUnit.MILLISECONDS)
.until(() -> messages1.size() + messages2.size() == 4);
assertEquals(2, messages1.size());
assertEquals(2, messages2.size());
dispatcher.unsubscribe(subscription1);
dispatcher.unsubscribe(subscription2);
}
}
@Test
public void whenSubscribingAsynchronouslyWithQueueGroups_thenOnlyOneMessageHandlerInTheGroupShouldReceiveEachMessage() throws Exception {
try (Connection natsConnection = createConnection()) {
List<Message> messages = new ArrayList<>();
Dispatcher dispatcher = natsConnection.createDispatcher();
Subscription qSub1 = dispatcher.subscribe("mySubject", "myQueue", messages::add);
Subscription qSub2 = dispatcher.subscribe("mySubject", "myQueue", messages::add);
natsConnection.publish("mySubject", convertStringToBytes("data"));
// wait for messages to propagate.
Awaitility.await()
.atMost(WAIT_AT_MOST_MILLIS, TimeUnit.MILLISECONDS)
.pollDelay(POLL_DELAY_MILLIS, TimeUnit.MILLISECONDS)
.until(() -> messages.size() == 1);
assertEquals(1, messages.size());
dispatcher.unsubscribe(qSub1);
dispatcher.unsubscribe(qSub2);
}
}
@Test
public void whenMessagesAreExchangedViaPublish_thenResponsesMustBeReceivedWithSecondarySubscription() throws Exception {
try (Connection natsConnection = createConnection()) {
Subscription replySideSubscription0 = natsConnection.subscribe("publishSubject");
Subscription replySideSubscription1 = natsConnection.subscribe("publishSubject");
Subscription publishSideSubscription = natsConnection.subscribe("replyToSubject");
natsConnection.publish("publishSubject", "replyToSubject", convertStringToBytes("Please respond!"));
Message message = replySideSubscription0.nextMessage(TIMEOUT_MILLIS);
assertNotNull(message, "No message!");
assertEquals("Please respond!", convertMessageDataBytesToString(message));
natsConnection.publish(message.getReplyTo(), convertStringToBytes("Message Received By Subscription 0"));
message = replySideSubscription1.nextMessage(TIMEOUT_MILLIS);
assertNotNull(message, "No message!");
assertEquals("Please respond!", convertMessageDataBytesToString(message));
natsConnection.publish(message.getReplyTo(), convertStringToBytes("Message Received By Subscription 1"));
int[] responsesFrom = new int[2];
message = publishSideSubscription.nextMessage(TIMEOUT_MILLIS);
assertNotNull(message, "No message!");
int replierIndex = extractReplierIndexFromMessageData(message);
responsesFrom[replierIndex]++;
message = publishSideSubscription.nextMessage(TIMEOUT_MILLIS);
assertNotNull(message, "No message!");
replierIndex = extractReplierIndexFromMessageData(message);
responsesFrom[replierIndex]++;
assertEquals(1, responsesFrom[0]);
assertEquals(1, responsesFrom[1]);
replySideSubscription0.unsubscribe();
replySideSubscription1.unsubscribe();
publishSideSubscription.unsubscribe();
}
}
private int extractReplierIndexFromMessageData(Message message) {
String messageData = convertMessageDataBytesToString(message);
assertTrue(messageData.contains("Message Received By Subscription"));
return messageData.endsWith("0") ? 0 : 1;
}
@Test
public void whenMessagesAreExchangedViaRequest_thenOnlyTheFirstResponseWillBeReceived() throws Exception {
try (Connection natsConnection = createConnection()) {
Subscription replySideSubscription1 = natsConnection.subscribe("requestSubject");
Subscription replySideSubscription2 = natsConnection.subscribe("requestSubject");
CompletableFuture<Message> future = natsConnection.request("requestSubject", convertStringToBytes("Please respond!"));
Message message = replySideSubscription1.nextMessage(TIMEOUT_MILLIS);
assertNotNull(message, "No message!");
assertEquals("Please respond!", convertMessageDataBytesToString(message));
natsConnection.publish(message.getReplyTo(), convertStringToBytes("Message Received From Subscription 1"));
message = replySideSubscription2.nextMessage(TIMEOUT_MILLIS);
assertNotNull(message, "No message!");
assertEquals("Please respond!", convertMessageDataBytesToString(message));
natsConnection.publish(message.getReplyTo(), convertStringToBytes("Message Received From Subscription 2"));
message = future.get(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
assertNotNull(message, "No message!");
assertEquals("Message Received From Subscription 1", convertMessageDataBytesToString(message));
replySideSubscription1.unsubscribe();
replySideSubscription2.unsubscribe();
}
}
@Test
public void whenMatchingWildCardsAreUsedInSubscriptions_thenSubscriptionsMustReceiveAllMatchingMessages() throws Exception {
try (Connection natsConnection = createConnection()) {
Subscription segmentStarSubscription = natsConnection.subscribe("segment.*");
natsConnection.publish("segment.another", convertStringToBytes("hello segment star sub"));
Message message = segmentStarSubscription.nextMessage(TIMEOUT_MILLIS);
assertNotNull(message, "No message!");
assertEquals("hello segment star sub", convertMessageDataBytesToString(message));
Subscription segmentGreaterSubscription = natsConnection.subscribe("segment.>");
natsConnection.publish("segment.one.two", convertStringToBytes("hello segment greater sub"));
message = segmentGreaterSubscription.nextMessage(TIMEOUT_MILLIS);
assertNotNull(message, "No message!");
assertEquals("hello segment greater sub", convertMessageDataBytesToString(message));
segmentStarSubscription.unsubscribe();
segmentGreaterSubscription.unsubscribe();
}
}
@Test
public void whenNonMatchingWildCardsAreUsedInSubscriptions_thenSubscriptionsMustNotReceiveNonMatchingMessages() throws Exception {
try (Connection natsConnection = createConnection()) {
Subscription starSubscription = natsConnection.subscribe("segment.*");
natsConnection.publish("segment.second.third", convertStringToBytes("hello there"));
Message message = starSubscription.nextMessage(TIMEOUT_MILLIS);
assertNull(message, "Got message!");
Subscription greaterSubscription = natsConnection.subscribe("segment.>");
natsConnection.publish("segment.second.third", convertStringToBytes("hello there"));
message = greaterSubscription.nextMessage(TIMEOUT_MILLIS);
assertNotNull(message, "No message!");
assertEquals("hello there", convertMessageDataBytesToString(message));
starSubscription.unsubscribe();
greaterSubscription.unsubscribe();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/sbe/MarketData.java | libraries-3/src/main/java/com/baeldung/sbe/MarketData.java | package com.baeldung.sbe;
import java.util.StringJoiner;
import com.baeldung.sbe.stub.Currency;
import com.baeldung.sbe.stub.Market;
public class MarketData {
private final int amount;
private final double price;
private final Market market;
private final Currency currency;
private final String symbol;
public MarketData(int amount, double price, Market market, Currency currency, String symbol) {
this.amount = amount;
this.price = price;
this.market = market;
this.currency = currency;
this.symbol = symbol;
}
public static class Builder {
private int amount;
public Builder amount(int amount) {
this.amount = amount;
return this;
}
private double price;
public Builder price(double price) {
this.price = price;
return this;
}
private Market market;
public Builder market(Market market) {
this.market = market;
return this;
}
private Currency currency;
public Builder currency(Currency currency) {
this.currency = currency;
return this;
}
private String symbol;
public Builder symbol(String symbol) {
this.symbol = symbol;
return this;
}
public MarketData build() {
return new MarketData(amount, price, market, currency, symbol);
}
}
public static Builder builder() {
return new Builder();
}
public int getAmount() {
return amount;
}
public double getPrice() {
return price;
}
public Market getMarket() {
return market;
}
public Currency getCurrency() {
return currency;
}
public String getSymbol() {
return symbol;
}
@Override
public String toString() {
return new StringJoiner(", ", MarketData.class.getSimpleName() + "[", "]").add("amount=" + amount)
.add("price=" + price)
.add("market=" + market)
.add("currency=" + currency)
.add("symbol='" + symbol + "'")
.toString();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/sbe/MarketDataSource.java | libraries-3/src/main/java/com/baeldung/sbe/MarketDataSource.java | package com.baeldung.sbe;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import com.baeldung.sbe.stub.Currency;
import com.baeldung.sbe.stub.Market;
public class MarketDataSource implements Iterator<MarketData> {
private final LinkedList<MarketData> dataQueue = new LinkedList<>();
public MarketDataSource() {
// adding some test data into queue
this.dataQueue.addAll(Arrays.asList(MarketData.builder()
.amount(1)
.market(Market.NASDAQ)
.symbol("AAPL")
.price(134.12)
.currency(Currency.USD)
.build(), MarketData.builder()
.amount(2)
.market(Market.NYSE)
.symbol("IBM")
.price(128.99)
.currency(Currency.USD)
.build(), MarketData.builder()
.amount(1)
.market(Market.NASDAQ)
.symbol("AXP")
.price(34.87)
.currency(Currency.EUR)
.build()));
}
@Override
public boolean hasNext() {
return !this.dataQueue.isEmpty();
}
@Override
public MarketData next() {
final MarketData data = this.dataQueue.pop();
this.dataQueue.add(data);
return data;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/sbe/MarketDataStreamServer.java | libraries-3/src/main/java/com/baeldung/sbe/MarketDataStreamServer.java | package com.baeldung.sbe;
import java.nio.ByteBuffer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MarketDataStreamServer {
private static final Logger log = LoggerFactory.getLogger(MarketDataStreamServer.class);
ByteBuffer buffer = ByteBuffer.allocate(128);
final AtomicLong writePos = new AtomicLong();
ScheduledExecutorService writerThread = Executors.newScheduledThreadPool(1);
ScheduledExecutorService readerThreadPool = Executors.newScheduledThreadPool(2);
private class Client {
final String name;
final ByteBuffer readOnlyBuffer;
final AtomicLong readPos = new AtomicLong();
Client(String name, ByteBuffer source) {
this.name = name;
this.readOnlyBuffer = source.asReadOnlyBuffer();
}
void readTradeData() {
while (readPos.get() < writePos.get()) {
try {
final int pos = this.readOnlyBuffer.position();
final MarketData data = MarketDataUtil.readAndDecode(this.readOnlyBuffer);
readPos.addAndGet(this.readOnlyBuffer.position() - pos);
log.info("<readTradeData> client: {}, read/write gap: {}, data: {}", name, writePos.get() - readPos.get(), data);
} catch (IndexOutOfBoundsException e) {
this.readOnlyBuffer.clear(); // ring buffer
} catch (Exception e) {
log.error("<readTradeData> cannot read from buffer {}", readOnlyBuffer);
}
}
if (this.readOnlyBuffer.remaining() == 0) {
this.readOnlyBuffer.clear(); // ring buffer
}
}
void read() {
readerThreadPool.scheduleAtFixedRate(this::readTradeData, 1, 1, TimeUnit.SECONDS);
}
}
private Client newClient(String name) {
return new Client(name, buffer);
}
private void writeTradeData(MarketData data) {
try {
final int writtenBytes = MarketDataUtil.encodeAndWrite(buffer, data);
writePos.addAndGet(writtenBytes);
log.info("<writeTradeData> buffer size remaining: %{}, data: {}", 100 * buffer.remaining() / buffer.capacity(), data);
} catch (IndexOutOfBoundsException e) {
buffer.clear(); // ring buffer
writeTradeData(data);
} catch (Exception e) {
log.error("<writeTradeData> cannot write into buffer {}", buffer);
}
}
private void run(MarketDataSource source) {
writerThread.scheduleAtFixedRate(() -> {
if (source.hasNext()) {
writeTradeData(source.next());
}
}, 1, 2, TimeUnit.SECONDS);
}
public static void main(String[] args) {
MarketDataStreamServer server = new MarketDataStreamServer();
Client client1 = server.newClient("client1");
client1.read();
Client client2 = server.newClient("client2");
client2.read();
server.run(new MarketDataSource());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/sbe/MarketDataUtil.java | libraries-3/src/main/java/com/baeldung/sbe/MarketDataUtil.java | package com.baeldung.sbe;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import org.agrona.concurrent.UnsafeBuffer;
import com.baeldung.sbe.stub.MessageHeaderDecoder;
import com.baeldung.sbe.stub.MessageHeaderEncoder;
import com.baeldung.sbe.stub.TradeDataDecoder;
import com.baeldung.sbe.stub.TradeDataEncoder;
public class MarketDataUtil {
public static int encodeAndWrite(ByteBuffer buffer, MarketData marketData) {
final int pos = buffer.position();
final UnsafeBuffer directBuffer = new UnsafeBuffer(buffer);
final MessageHeaderEncoder headerEncoder = new MessageHeaderEncoder();
final TradeDataEncoder dataEncoder = new TradeDataEncoder();
final BigDecimal priceDecimal = BigDecimal.valueOf(marketData.getPrice());
final int priceMantis = priceDecimal.scaleByPowerOfTen(priceDecimal.scale())
.intValue();
final int priceExponent = priceDecimal.scale() * -1;
final TradeDataEncoder encoder = dataEncoder.wrapAndApplyHeader(directBuffer, pos, headerEncoder);
encoder.amount(marketData.getAmount());
encoder.quote()
.market(marketData.getMarket())
.currency(marketData.getCurrency())
.symbol(marketData.getSymbol())
.price()
.mantissa(priceMantis)
.exponent((byte) priceExponent);
// set position
final int encodedLength = headerEncoder.encodedLength() + encoder.encodedLength();
buffer.position(pos + encodedLength);
return encodedLength;
}
public static MarketData readAndDecode(ByteBuffer buffer) {
final int pos = buffer.position();
final UnsafeBuffer directBuffer = new UnsafeBuffer(buffer);
final MessageHeaderDecoder headerDecoder = new MessageHeaderDecoder();
final TradeDataDecoder dataDecoder = new TradeDataDecoder();
dataDecoder.wrapAndApplyHeader(directBuffer, pos, headerDecoder);
// set position
final int encodedLength = headerDecoder.encodedLength() + dataDecoder.encodedLength();
buffer.position(pos + encodedLength);
final double price = BigDecimal.valueOf(dataDecoder.quote()
.price()
.mantissa())
.scaleByPowerOfTen(dataDecoder.quote()
.price()
.exponent())
.doubleValue();
return MarketData.builder()
.amount(dataDecoder.amount())
.symbol(dataDecoder.quote()
.symbol())
.market(dataDecoder.quote()
.market())
.currency(dataDecoder.quote()
.currency())
.price(price)
.build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/jfreechart/PieChartExample.java | libraries-3/src/main/java/com/baeldung/jfreechart/PieChartExample.java | package com.baeldung.jfreechart;
import javax.swing.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
public class PieChartExample {
public static void main(String[] args) {
// Create a dataset
DefaultPieDataset<String> dataset = new DefaultPieDataset<>();
dataset.setValue("January", 200);
dataset.setValue("February", 150);
dataset.setValue("March", 180);
// Create a chart using the dataset
JFreeChart chart = ChartFactory.createPieChart(
"Monthly Sales", // Chart title
dataset, // data
true, // include legend
true, // generate tool tips
false); // no URLs
// Display the chart
ChartPanel chartPanel = new ChartPanel(chart);
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setContentPane(chartPanel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/jfreechart/TimeSeriesChartExample.java | libraries-3/src/main/java/com/baeldung/jfreechart/TimeSeriesChartExample.java | package com.baeldung.jfreechart;
import javax.swing.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
public class TimeSeriesChartExample {
public static void main(String[] args) {
// Create a dataset
TimeSeries series = new TimeSeries("Monthly Sales");
series.add(new Month(1, 2024), 200);
series.add(new Month(2, 2024), 150);
series.add(new Month(3, 2024), 180);
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(series);
// Create a chart using the dataset
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Monthly Sales", // Chart title
"Date", // X-axis label
"Sales", // Y-axis label
dataset, // data
true, // legend
false, // tooltips
false); // no URLs
// Display the chart
ChartPanel chartPanel = new ChartPanel(chart);
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setContentPane(chartPanel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/jfreechart/LineChartExample.java | libraries-3/src/main/java/com/baeldung/jfreechart/LineChartExample.java | package com.baeldung.jfreechart;
import javax.swing.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;
public class LineChartExample {
public static void main(String[] args) {
// Create a dataset
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(200, "Sales", "January");
dataset.addValue(150, "Sales", "February");
dataset.addValue(180, "Sales", "March");
dataset.addValue(260, "Sales", "April");
dataset.addValue(300, "Sales", "May");
// Create a chart using the dataset
JFreeChart chart = ChartFactory.createLineChart(
"Monthly Sales", // Chart title
"Month", // X-axis label
"Sales", // Y-axis label
dataset); // data
// Display the chart
ChartPanel chartPanel = new ChartPanel(chart);
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setContentPane(chartPanel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/jfreechart/CombinationChartExample.java | libraries-3/src/main/java/com/baeldung/jfreechart/CombinationChartExample.java | package com.baeldung.jfreechart;
import javax.swing.*;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
public class CombinationChartExample {
public static void main(String[] args) {
// Create datasets
DefaultCategoryDataset lineDataset = new DefaultCategoryDataset();
lineDataset.addValue(200, "Sales", "January");
lineDataset.addValue(150, "Sales", "February");
lineDataset.addValue(180, "Sales", "March");
DefaultCategoryDataset barDataset = new DefaultCategoryDataset();
barDataset.addValue(400, "Profit", "January");
barDataset.addValue(300, "Profit", "February");
barDataset.addValue(250, "Profit", "March");
// Create a combination chart
CategoryPlot plot = new CategoryPlot();
plot.setDataset(0, lineDataset);
plot.setRenderer(0, new LineAndShapeRenderer());
plot.setDataset(1, barDataset);
plot.setRenderer(1, new BarRenderer());
plot.setDomainAxis(new CategoryAxis("Month"));
plot.setRangeAxis(new NumberAxis("Value"));
plot.setOrientation(PlotOrientation.VERTICAL);
plot.setRangeGridlinesVisible(true);
plot.setDomainGridlinesVisible(true);
JFreeChart chart = new JFreeChart(
"Monthly Sales and Profit", // chart title
null, // null means to use default font
plot, // combination chart as CategoryPlot
true); // legend
// Display the chart
ChartPanel chartPanel = new ChartPanel(chart);
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setContentPane(chartPanel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/jfreechart/BarChartExample.java | libraries-3/src/main/java/com/baeldung/jfreechart/BarChartExample.java | package com.baeldung.jfreechart;
import javax.swing.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;
public class BarChartExample {
public static void main(String[] args) {
// Create a dataset
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(200, "Sales", "January");
dataset.addValue(150, "Sales", "February");
dataset.addValue(180, "Sales", "March");
dataset.addValue(260, "Sales", "April");
dataset.addValue(300, "Sales", "May");
// Create a chart using the dataset
JFreeChart chart = ChartFactory.createBarChart(
"Monthly Sales", // Chart title
"Month", // X-axis label
"Sales", // Y-axis label
dataset); // data
// Display the chart
ChartPanel chartPanel = new ChartPanel(chart);
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setContentPane(chartPanel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/javers/Person.java | libraries-3/src/main/java/com/baeldung/javers/Person.java | package com.baeldung.javers;
public class Person {
private Integer id;
private String name;
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
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/libraries-3/src/main/java/com/baeldung/javers/Address.java | libraries-3/src/main/java/com/baeldung/javers/Address.java | package com.baeldung.javers;
public class Address {
private String country;
public Address(String country) {
this.country = country;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/javers/PersonWithAddress.java | libraries-3/src/main/java/com/baeldung/javers/PersonWithAddress.java | package com.baeldung.javers;
import java.util.List;
public class PersonWithAddress {
private Integer id;
private String name;
private List<Address> address;
public PersonWithAddress(Integer id, String name, List<Address> address) {
this.id = id;
this.name = name;
this.address = address;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/yauaa/UserAgentAttributeLoggingFilter.java | libraries-3/src/main/java/com/baeldung/yauaa/UserAgentAttributeLoggingFilter.java | package com.baeldung.yauaa;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import nl.basjes.parse.useragent.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;
@Component
public class UserAgentAttributeLoggingFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(UserAgentAttributeLoggingFilter.class);
private final UserAgentAnalyzer userAgentAnalyzer;
public UserAgentAttributeLoggingFilter(UserAgentAnalyzer userAgentAnalyzer) {
this.userAgentAnalyzer = userAgentAnalyzer;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String userAgentString = request.getHeader("User-Agent");
UserAgent userAgent = userAgentAnalyzer.parse(userAgentString);
userAgent
.getAvailableFieldNamesSorted()
.forEach(fieldName -> {
log.info("{}: {}", fieldName, userAgent.getValue(fieldName));
});
filterChain.doFilter(request, response);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/yauaa/HomePageController.java | libraries-3/src/main/java/com/baeldung/yauaa/HomePageController.java | package com.baeldung.yauaa;
import java.util.List;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.servlet.ModelAndView;
import nl.basjes.parse.useragent.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;
@Controller
public class HomePageController {
private static final List<String> SUPPORTED_DEVICES = List.of("Mobile", "Tablet", "Phone");
private final UserAgentAnalyzer userAgentAnalyzer;
public HomePageController(UserAgentAnalyzer userAgentAnalyzer) {
this.userAgentAnalyzer = userAgentAnalyzer;
}
@GetMapping("/mobile/home")
public ModelAndView homePage(@RequestHeader(HttpHeaders.USER_AGENT) String userAgentString) {
UserAgent userAgent = userAgentAnalyzer.parse(userAgentString);
String deviceClass = userAgent.getValue(UserAgent.DEVICE_CLASS);
boolean isMobileDevice = SUPPORTED_DEVICES.contains(deviceClass);
if (isMobileDevice) {
return new ModelAndView("/mobile-home");
}
return new ModelAndView("error/open-in-mobile", HttpStatus.FORBIDDEN);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/yauaa/UserAgentAnalyzerConfiguration.java | libraries-3/src/main/java/com/baeldung/yauaa/UserAgentAnalyzerConfiguration.java | package com.baeldung.yauaa;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import nl.basjes.parse.useragent.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;
@Configuration
public class UserAgentAnalyzerConfiguration {
private static final int CACHE_SIZE = 1000;
@Bean
public UserAgentAnalyzer userAgentAnalyzer() {
return UserAgentAnalyzer
.newBuilder()
.withCache(CACHE_SIZE)
.withField(UserAgent.DEVICE_CLASS)
.build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/yauaa/Application.java | libraries-3/src/main/java/com/baeldung/yauaa/Application.java | package com.baeldung.yauaa;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/nullaway/Person.java | libraries-3/src/main/java/com/baeldung/nullaway/Person.java | package com.baeldung.nullaway;
public class Person {
int age;
String name;
String email;
public Person(int age, String name, String email) {
super();
this.age = age;
this.name = name;
this.email = email;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [age=");
builder.append(age);
builder.append(", name=");
builder.append(name);
builder.append(", email=");
builder.append(email);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
return true;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java | libraries-3/src/main/java/com/baeldung/nullaway/NullAwayExample.java | package com.baeldung.nullaway;
public class NullAwayExample {
/*
* 1- NullAway will warn about yearsToRetirement method
* 2- Uncomment @Nullable in printAge and NullAway will warn about this method
* 3- Add a standard null check to be NullAway compliant
* 4- Build will be SUCCESS
*/
static Integer getAge(/*@Nullable*/ Person person) {
return person.getAge();
}
Integer yearsToRetirement() {
Person p = null;
// ... p never gets set correctly...
return 65 - getAge(p);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/lwjgl/src/main/java/com/baeldung/lwjgl/LWJGLApp.java | lwjgl/src/main/java/com/baeldung/lwjgl/LWJGLApp.java | package com.baeldung.lwjgl;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import java.nio.FloatBuffer;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.memAllocFloat;
import static org.lwjgl.system.MemoryUtil.memFree;
public class LWJGLApp {
private long window;
public static void main(String[] args) {
new LWJGLApp().run();
}
public void run() {
this.initializeGLFW();
this.createAndCenterWindow();
this.setupAndInitializeOpenGLContext();
this.renderTriangle();
}
private void initializeGLFW() {
if (!glfwInit()) {
throw new IllegalStateException("Unable to initialize GLFW");
}
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
}
private void createAndCenterWindow() {
window = glfwCreateWindow(500, 500, "LWJGL Triangle", 0, 0);
if (window == 0) {
throw new RuntimeException("Failed to create the GLFW window");
}
GLFWVidMode videoMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(
window,
(videoMode.width() - 500) / 2,
(videoMode.height() - 500) / 2
);
}
private void setupAndInitializeOpenGLContext() {
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwShowWindow(window);
GL.createCapabilities();
}
private void renderTriangle() {
float[] vertices = {
0.0f, 0.5f, 0.0f,
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f
};
FloatBuffer vertexBuffer = memAllocFloat(vertices.length);
vertexBuffer.put(vertices).flip();
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 1.0f, 0.0f);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertexBuffer);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableClientState(GL_VERTEX_ARRAY);
glfwSwapBuffers(window);
}
memFree(vertexBuffer);
glfwDestroyWindow(window);
glfwTerminate();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/language-interop/src/test/java/com/baeldung/language/interop/python/JavaPythonInteropUnitTest.java | language-interop/src/test/java/com/baeldung/language/interop/python/JavaPythonInteropUnitTest.java | package com.baeldung.language.interop.python;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.List;
import java.util.stream.Collectors;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleScriptContext;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.PumpStreamHandler;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.python.core.PyException;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class JavaPythonInteropUnitTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void givenPythonScript_whenPythonProcessInvoked_thenSuccess() throws Exception {
ProcessBuilder processBuilder = new ProcessBuilder("python", resolvePythonScriptPath("hello.py"));
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
List<String> results = readProcessOutput(process.getInputStream());
assertThat("Results should not be empty", results, is(not(empty())));
assertThat("Results should contain output of script: ", results, hasItem(containsString("Hello Baeldung Readers!!")));
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
}
@Test
public void givenPythonScriptEngineIsAvailable_whenScriptInvoked_thenOutputDisplayed() throws Exception {
StringWriter output = new StringWriter();
ScriptContext context = new SimpleScriptContext();
context.setWriter(output);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("python");
engine.eval(new FileReader(resolvePythonScriptPath("hello.py")), context);
assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", output.toString()
.trim());
}
@Test
public void givenPythonInterpreter_whenPrintExecuted_thenOutputDisplayed() {
try (PythonInterpreter pyInterp = new PythonInterpreter()) {
StringWriter output = new StringWriter();
pyInterp.setOut(output);
pyInterp.exec("print('Hello Baeldung Readers!!')");
assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", output.toString()
.trim());
}
}
@Test
public void givenPythonInterpreter_whenNumbersAdded_thenOutputDisplayed() {
try (PythonInterpreter pyInterp = new PythonInterpreter()) {
pyInterp.exec("x = 10+10");
PyObject x = pyInterp.get("x");
assertEquals("x: ", 20, x.asInt());
}
}
@Test
public void givenPythonInterpreter_whenErrorOccurs_thenExceptionIsThrown() {
thrown.expect(PyException.class);
thrown.expectMessage("ImportError: No module named syds");
try (PythonInterpreter pyInterp = new PythonInterpreter()) {
pyInterp.exec("import syds");
}
}
@Test
public void givenPythonScript_whenPythonProcessExecuted_thenSuccess() throws ExecuteException, IOException {
String line = "python " + resolvePythonScriptPath("hello.py");
CommandLine cmdLine = CommandLine.parse(line);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(streamHandler);
int exitCode = executor.execute(cmdLine);
assertEquals("No errors should be detected", 0, exitCode);
assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", outputStream.toString()
.trim());
}
private List<String> readProcessOutput(InputStream inputStream) throws IOException {
try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) {
return output.lines()
.collect(Collectors.toList());
}
}
private String resolvePythonScriptPath(String filename) {
File file = new File("src/test/resources/" + filename);
return file.getAbsolutePath();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/language-interop/src/main/java/com/baeldung/language/interop/python/ScriptEngineManagerUtils.java | language-interop/src/main/java/com/baeldung/language/interop/python/ScriptEngineManagerUtils.java | package com.baeldung.language.interop.python;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class ScriptEngineManagerUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(ScriptEngineManagerUtils.class);
private ScriptEngineManagerUtils() {
}
public static void listEngines() {
ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> engines = manager.getEngineFactories();
for (ScriptEngineFactory engine : engines) {
LOGGER.info("Engine name: {}", engine.getEngineName());
LOGGER.info("Version: {}", engine.getEngineVersion());
LOGGER.info("Language: {}", engine.getLanguageName());
LOGGER.info("Short Names:");
for (String names : engine.getNames()) {
LOGGER.info(names);
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/language-interop/scala-cli/hello-world/HelloWorld.java | language-interop/scala-cli/hello-world/HelloWorld.java | package com.baeldung;
public class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello, World!");
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/language-interop/scala-cli/jdk-config/Jdk21Sample.java | language-interop/scala-cli/jdk-config/Jdk21Sample.java | //> using jvm zulu:21
package com.baeldung;
record Greet(String name){};
public class Jdk21Sample {
public static void main(String args[]) {
var greet = new Greet("Baeldung!");
var greeting = "Hello, " + greet.name();
System.out.println(greeting);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/language-interop/scala-cli/deps/DependencyApp.java | language-interop/scala-cli/deps/DependencyApp.java | //> using dep com.google.code.gson:gson:2.8.9
import com.google.gson.JsonParser;
import com.google.gson.JsonElement;
public class DependencyApp {
public static void main(String args[]) {
String jsonString = "{\"country\": \"Germany\", \"language\": \"German\", \"currency\": \"Euro\"}";
var countryJson = JsonParser.parseString(jsonString);
var country = countryJson.getAsJsonObject().get("country").getAsString();
System.out.println("Selected country: " + country);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/language-interop/scala-cli/java-args/JavaArgs.java | language-interop/scala-cli/java-args/JavaArgs.java | //> using jvm 21
//> using javaOpt -Xmx2g, -DappName=baeldungApp, --enable-preview
//> using javaProp language=english, country=usa
//> using javacOpt --release 21 --enable-preview
public class JavaArgs {
public static void main(String[] args) {
String appName = System.getProperty("appName");
String language = System.getProperty("language");
String country = System.getProperty("country");
String combinedStr = STR."appName = \{ appName } , language = \{ language } and country = \{ country }";
System.out.println(combinedStr);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java | apache-cxf-modules/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java | package com.baeldung.cxf.introduction;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import javax.xml.namespace.QName;
import jakarta.xml.ws.Service;
import jakarta.xml.ws.soap.SOAPBinding;
import org.junit.Before;
import org.junit.Test;
public class StudentLiveTest {
private static QName SERVICE_NAME = new QName("http://introduction.cxf.baeldung.com/", "Baeldung");
private static QName PORT_NAME = new QName("http://introduction.cxf.baeldung.com/", "BaeldungPort");
private Service service;
private Baeldung baeldungProxy;
private BaeldungImpl baeldungImpl;
{
service = Service.create(SERVICE_NAME);
final String endpointAddress = "http://localhost:8080/baeldung";
service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
}
@Before
public void reinstantiateBaeldungInstances() {
baeldungImpl = new BaeldungImpl();
baeldungProxy = service.getPort(PORT_NAME, Baeldung.class);
}
@Test
public void whenUsingHelloMethod_thenCorrect() {
final String endpointResponse = baeldungProxy.hello("Baeldung");
final String localResponse = baeldungImpl.hello("Baeldung");
assertEquals(localResponse, endpointResponse);
}
@Test
public void whenUsingHelloStudentMethod_thenCorrect() {
final Student student = new StudentImpl("John Doe");
final String endpointResponse = baeldungProxy.helloStudent(student);
final String localResponse = baeldungImpl.helloStudent(student);
assertEquals(localResponse, endpointResponse);
}
@Test
public void usingGetStudentsMethod_thenCorrect() {
final Student student1 = new StudentImpl("Adam");
baeldungProxy.helloStudent(student1);
final Student student2 = new StudentImpl("Eve");
baeldungProxy.helloStudent(student2);
final Map<Integer, Student> students = baeldungProxy.getStudents();
assertEquals("Adam", students.get(1).getName());
assertEquals("Eve", students.get(2).getName());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java | apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java | package com.baeldung.cxf.introduction;
import jakarta.xml.bind.annotation.XmlType;
@XmlType(name = "Student")
public class StudentImpl implements Student {
private String name;
StudentImpl() {
}
public StudentImpl(String name) {
this.name = name;
}
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/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java | apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java | package com.baeldung.cxf.introduction;
import jakarta.xml.ws.Endpoint;
public class Server {
public static void main(String args[]) throws InterruptedException {
BaeldungImpl implementor = new BaeldungImpl();
String address = "http://localhost:8080/baeldung";
Endpoint.publish(address, implementor);
System.out.println("Server ready...");
Thread.sleep(60 * 1000);
System.out.println("Server exiting");
System.exit(0);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java | apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java | package com.baeldung.cxf.introduction;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlJavaTypeAdapter(StudentAdapter.class)
public interface Student {
public String getName();
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java | apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java | package com.baeldung.cxf.introduction;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
@XmlType(name = "StudentMap")
public class StudentMap {
private List<StudentEntry> entries = new ArrayList<StudentEntry>();
@XmlElement(nillable = false, name = "entry")
public List<StudentEntry> getEntries() {
return entries;
}
@XmlType(name = "StudentEntry")
public static class StudentEntry {
private Integer id;
private Student student;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setStudent(Student student) {
this.student = student;
}
public Student getStudent() {
return student;
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java | apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java | package com.baeldung.cxf.introduction;
import java.util.LinkedHashMap;
import java.util.Map;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
public class StudentMapAdapter extends XmlAdapter<StudentMap, Map<Integer, Student>> {
public StudentMap marshal(Map<Integer, Student> boundMap) throws Exception {
StudentMap valueMap = new StudentMap();
for (Map.Entry<Integer, Student> boundEntry : boundMap.entrySet()) {
StudentMap.StudentEntry valueEntry = new StudentMap.StudentEntry();
valueEntry.setStudent(boundEntry.getValue());
valueEntry.setId(boundEntry.getKey());
valueMap.getEntries().add(valueEntry);
}
return valueMap;
}
public Map<Integer, Student> unmarshal(StudentMap valueMap) throws Exception {
Map<Integer, Student> boundMap = new LinkedHashMap<Integer, Student>();
for (StudentMap.StudentEntry studentEntry : valueMap.getEntries()) {
boundMap.put(studentEntry.getId(), studentEntry.getStudent());
}
return boundMap;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java | apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java | package com.baeldung.cxf.introduction;
import java.util.LinkedHashMap;
import java.util.Map;
import jakarta.jws.WebService;
@WebService(endpointInterface = "com.baeldung.cxf.introduction.Baeldung")
public class BaeldungImpl implements Baeldung {
private Map<Integer, Student> students = new LinkedHashMap<Integer, Student>();
public String hello(String name) {
return "Hello " + name;
}
public String helloStudent(Student student) {
students.put(students.size() + 1, student);
return "Hello " + student.getName();
}
public Map<Integer, Student> getStudents() {
return students;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java | apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java | package com.baeldung.cxf.introduction;
import java.util.Map;
import jakarta.jws.WebService;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@WebService
public interface Baeldung {
public String hello(String name);
public String helloStudent(Student student);
@XmlJavaTypeAdapter(StudentMapAdapter.class)
public Map<Integer, Student> getStudents();
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java | apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java | package com.baeldung.cxf.introduction;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
public class StudentAdapter extends XmlAdapter<StudentImpl, Student> {
public StudentImpl marshal(Student student) throws Exception {
if (student instanceof StudentImpl) {
return (StudentImpl) student;
}
return new StudentImpl(student.getName());
}
public Student unmarshal(StudentImpl student) throws Exception {
return student;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungIntegrationTest.java | apache-cxf-modules/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungIntegrationTest.java | package com.baeldung.cxf.aegis;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.apache.cxf.aegis.AegisContext;
import org.apache.cxf.aegis.AegisReader;
import org.apache.cxf.aegis.AegisWriter;
import org.apache.cxf.aegis.type.AegisType;
public class BaeldungIntegrationTest {
private AegisContext context;
private String fileName = "baeldung.xml";
@Test
public void whenMarshalingAndUnmarshalingCourseRepo_thenCorrect() throws Exception {
initializeContext();
CourseRepo inputRepo = initCourseRepo();
marshalCourseRepo(inputRepo);
CourseRepo outputRepo = unmarshalCourseRepo();
Course restCourse = outputRepo.getCourses().get(1);
Course securityCourse = outputRepo.getCourses().get(2);
assertEquals("Welcome to Beldung!", outputRepo.getGreeting());
assertEquals("REST with Spring", restCourse.getName());
assertEquals(new Date(1234567890000L), restCourse.getEnrolmentDate());
assertNull(restCourse.getInstructor());
assertEquals("Learn Spring Security", securityCourse.getName());
assertEquals(new Date(1456789000000L), securityCourse.getEnrolmentDate());
assertNull(securityCourse.getInstructor());
}
private void initializeContext() {
context = new AegisContext();
Set<Type> rootClasses = new HashSet<Type>();
rootClasses.add(CourseRepo.class);
context.setRootClasses(rootClasses);
Map<Class<?>, String> beanImplementationMap = new HashMap<>();
beanImplementationMap.put(CourseRepoImpl.class, "CourseRepo");
context.setBeanImplementationMap(beanImplementationMap);
context.setWriteXsiTypes(true);
context.initialize();
}
private CourseRepoImpl initCourseRepo() {
Course restCourse = new Course();
restCourse.setId(1);
restCourse.setName("REST with Spring");
restCourse.setInstructor("Eugen");
restCourse.setEnrolmentDate(new Date(1234567890000L));
Course securityCourse = new Course();
securityCourse.setId(2);
securityCourse.setName("Learn Spring Security");
securityCourse.setInstructor("Eugen");
securityCourse.setEnrolmentDate(new Date(1456789000000L));
CourseRepoImpl courseRepo = new CourseRepoImpl();
courseRepo.setGreeting("Welcome to Beldung!");
courseRepo.addCourse(restCourse);
courseRepo.addCourse(securityCourse);
return courseRepo;
}
private void marshalCourseRepo(CourseRepo courseRepo) throws Exception {
AegisWriter<XMLStreamWriter> writer = context.createXMLStreamWriter();
AegisType aegisType = context.getTypeMapping().getType(CourseRepo.class);
final FileOutputStream stream = new FileOutputStream(fileName);
XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(stream);
writer.write(courseRepo, new QName("http://aegis.cxf.baeldung.com", "baeldung"), false, xmlWriter, aegisType);
xmlWriter.close();
stream.close();
}
private CourseRepo unmarshalCourseRepo() throws Exception {
AegisReader<XMLStreamReader> reader = context.createXMLStreamReader();
final FileInputStream stream = new FileInputStream(fileName);
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
CourseRepo courseRepo = (CourseRepo) reader.read(xmlReader, context.getTypeMapping().getType(CourseRepo.class));
xmlReader.close();
stream.close();
return courseRepo;
}
@After
public void cleanup(){
File testFile = new File(fileName);
if (testFile.exists()) {
testFile.deleteOnExit();
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-aegis/src/main/java/com/baeldung/cxf/aegis/Course.java | apache-cxf-modules/cxf-aegis/src/main/java/com/baeldung/cxf/aegis/Course.java | package com.baeldung.cxf.aegis;
import java.util.Date;
public class Course {
private int id;
private String name;
private String instructor;
private Date enrolmentDate;
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;
}
public String getInstructor() {
return instructor;
}
public void setInstructor(String instructor) {
this.instructor = instructor;
}
public Date getEnrolmentDate() {
return enrolmentDate;
}
public void setEnrolmentDate(Date enrolmentDate) {
this.enrolmentDate = enrolmentDate;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-aegis/src/main/java/com/baeldung/cxf/aegis/CourseRepo.java | apache-cxf-modules/cxf-aegis/src/main/java/com/baeldung/cxf/aegis/CourseRepo.java | package com.baeldung.cxf.aegis;
import java.util.Map;
public interface CourseRepo {
String getGreeting();
void setGreeting(String greeting);
Map<Integer, Course> getCourses();
void setCourses(Map<Integer, Course> courses);
void addCourse(Course course);
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-aegis/src/main/java/com/baeldung/cxf/aegis/CourseRepoImpl.java | apache-cxf-modules/cxf-aegis/src/main/java/com/baeldung/cxf/aegis/CourseRepoImpl.java | package com.baeldung.cxf.aegis;
import java.util.HashMap;
import java.util.Map;
public class CourseRepoImpl implements CourseRepo {
private String greeting;
private Map<Integer, Course> courses = new HashMap<>();
@Override
public String getGreeting() {
return greeting;
}
@Override
public void setGreeting(String greeting) {
this.greeting = greeting;
}
@Override
public Map<Integer, Course> getCourses() {
return courses;
}
@Override
public void setCourses(Map<Integer, Course> courses) {
this.courses = courses;
}
@Override
public void addCourse(Course course) {
courses.put(course.getId(), course);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentLiveTest.java | apache-cxf-modules/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentLiveTest.java | package com.baeldung.cxf.spring;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class StudentLiveTest {
private final ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class);
private final Baeldung baeldungProxy = (Baeldung) context.getBean("client");
@Test
public void whenUsingHelloMethod_thenCorrect() {
String response = baeldungProxy.hello("John Doe");
assertEquals("Hello John Doe!", response);
}
@Test
public void whenUsingRegisterMethod_thenCorrect() {
Student student1 = new Student("Adam");
Student student2 = new Student("Eve");
String student1Response = baeldungProxy.register(student1);
String student2Response = baeldungProxy.register(student2);
assertEquals("Adam is registered student number 1", student1Response);
assertEquals("Eve is registered student number 2", student2Response);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-spring/src/main/java/com/baeldung/cxf/spring/Student.java | apache-cxf-modules/cxf-spring/src/main/java/com/baeldung/cxf/spring/Student.java | package com.baeldung.cxf.spring;
public class Student {
private String name;
Student() {
}
public Student(String name) {
this.name = name;
}
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/apache-cxf-modules/cxf-spring/src/main/java/com/baeldung/cxf/spring/ServiceConfiguration.java | apache-cxf-modules/cxf-spring/src/main/java/com/baeldung/cxf/spring/ServiceConfiguration.java | package com.baeldung.cxf.spring;
import jakarta.xml.ws.Endpoint;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServiceConfiguration {
@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
return new SpringBus();
}
@Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(), new BaeldungImpl());
endpoint.publish("http://localhost:8081/services/baeldung");
return endpoint;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-spring/src/main/java/com/baeldung/cxf/spring/AppInitializer.java | apache-cxf-modules/cxf-spring/src/main/java/com/baeldung/cxf/spring/AppInitializer.java | package com.baeldung.cxf.spring;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRegistration;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
public class AppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(ServiceConfiguration.class);
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new CXFServlet());
dispatcher.addMapping("/services/*");
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-spring/src/main/java/com/baeldung/cxf/spring/ClientConfiguration.java | apache-cxf-modules/cxf-spring/src/main/java/com/baeldung/cxf/spring/ClientConfiguration.java | package com.baeldung.cxf.spring;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ClientConfiguration {
@Bean(name = "client")
public Object generateProxy() {
return proxyFactoryBean().create();
}
@Bean
public JaxWsProxyFactoryBean proxyFactoryBean() {
JaxWsProxyFactoryBean proxyFactory = new JaxWsProxyFactoryBean();
proxyFactory.setServiceClass(Baeldung.class);
proxyFactory.setAddress("http://localhost:8081/services/baeldung");
return proxyFactory;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-spring/src/main/java/com/baeldung/cxf/spring/BaeldungImpl.java | apache-cxf-modules/cxf-spring/src/main/java/com/baeldung/cxf/spring/BaeldungImpl.java | package com.baeldung.cxf.spring;
import jakarta.jws.WebService;
@WebService(endpointInterface = "com.baeldung.cxf.spring.Baeldung")
public class BaeldungImpl implements Baeldung {
private int counter;
public String hello(String name) {
return "Hello " + name + "!";
}
public String register(Student student) {
counter++;
return student.getName() + " is registered student number " + counter;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-spring/src/main/java/com/baeldung/cxf/spring/Baeldung.java | apache-cxf-modules/cxf-spring/src/main/java/com/baeldung/cxf/spring/Baeldung.java | package com.baeldung.cxf.spring;
import jakarta.jws.WebService;
@WebService
public interface Baeldung {
String hello(String name);
String register(Student student);
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java | apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java | package com.baeldung.sse.jaxrs.client;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.sse.InboundSseEvent;
import jakarta.ws.rs.sse.SseEventSource;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
public class SseClientBroadcastApp {
private static final String subscribeUrl = "http://localhost:9080/sse-jaxrs-server/sse/stock/subscribe";
public static void main(String... args) throws Exception {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(subscribeUrl);
try (final SseEventSource eventSource = SseEventSource.target(target)
.reconnectingEvery(5, TimeUnit.SECONDS)
.build()) {
eventSource.register(onEvent, onError, onComplete);
eventSource.open();
System.out.println("Wainting for incoming event ...");
//Consuming events for one hour
Thread.sleep(60 * 60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.close();
System.out.println("End");
}
// A new event is received
private static Consumer<InboundSseEvent> onEvent = (inboundSseEvent) -> {
String data = inboundSseEvent.readData();
System.out.println(data);
};
//Error
private static Consumer<Throwable> onError = (throwable) -> {
throwable.printStackTrace();
};
//Connection close and there is nothing to receive
private static Runnable onComplete = () -> {
System.out.println("Done!");
};
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java | apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java | package com.baeldung.sse.jaxrs.client;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.sse.InboundSseEvent;
import jakarta.ws.rs.sse.SseEventSource;
import java.util.function.Consumer;
public class SseClientApp {
private static final String url = "http://127.0.0.1:9080/sse-jaxrs-server/sse/stock/prices";
public static void main(String... args) throws Exception {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
try (SseEventSource eventSource = SseEventSource.target(target).build()) {
eventSource.register(onEvent, onError, onComplete);
eventSource.open();
//Consuming events for one hour
Thread.sleep(60 * 60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.close();
System.out.println("End");
}
// A new event is received
private static Consumer<InboundSseEvent> onEvent = (inboundSseEvent) -> {
String data = inboundSseEvent.readData();
System.out.println(data);
};
//Error
private static Consumer<Throwable> onError = (throwable) -> {
throwable.printStackTrace();
};
//Connection close and there is nothing to receive
private static Runnable onComplete = () -> {
System.out.println("Done!");
};
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java | apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java | package com.baeldung.sse.jaxrs;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.sse.OutboundSseEvent;
import jakarta.ws.rs.sse.Sse;
import jakarta.ws.rs.sse.SseBroadcaster;
import jakarta.ws.rs.sse.SseEventSink;
@ApplicationScoped
@Path("stock")
public class SseResource {
@Inject
private StockService stockService;
private Sse sse;
private SseBroadcaster sseBroadcaster;
private OutboundSseEvent.Builder eventBuilder;
@Context
public void setSse(Sse sse) {
this.sse = sse;
this.eventBuilder = sse.newEventBuilder();
this.sseBroadcaster = sse.newBroadcaster();
}
@GET
@Path("prices")
@Produces("text/event-stream")
public void getStockPrices(@Context SseEventSink sseEventSink,
@HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastReceivedId) {
int lastEventId = 1;
if (lastReceivedId != -1) {
lastEventId = ++lastReceivedId;
}
boolean running = true;
while (running) {
Stock stock = stockService.getNextTransaction(lastEventId);
if (stock != null) {
OutboundSseEvent sseEvent = this.eventBuilder
.name("stock")
.id(String.valueOf(lastEventId))
.mediaType(MediaType.APPLICATION_JSON_TYPE)
.data(Stock.class, stock)
.reconnectDelay(3000)
.comment("price change")
.build();
sseEventSink.send(sseEvent);
lastEventId++;
}
//Simulate connection close
if (lastEventId % 5 == 0) {
sseEventSink.close();
break;
}
try {
//Wait 5 seconds
Thread.sleep(5 * 1000);
} catch (InterruptedException ex) {
// ...
}
//Simulatae a while boucle break
running = lastEventId <= 2000;
}
sseEventSink.close();
}
@GET
@Path("subscribe")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void listen(@Context SseEventSink sseEventSink) {
sseEventSink.send(sse.newEvent("Welcome !"));
this.sseBroadcaster.register(sseEventSink);
sseEventSink.send(sse.newEvent("You are registred !"));
}
@GET
@Path("publish")
public void broadcast() {
Runnable r = new Runnable() {
@Override
public void run() {
int lastEventId = 0;
boolean running = true;
while (running) {
lastEventId++;
Stock stock = stockService.getNextTransaction(lastEventId);
if (stock != null) {
OutboundSseEvent sseEvent = eventBuilder
.name("stock")
.id(String.valueOf(lastEventId))
.mediaType(MediaType.APPLICATION_JSON_TYPE)
.data(Stock.class, stock)
.reconnectDelay(3000)
.comment("price change")
.build();
sseBroadcaster.broadcast(sseEvent);
}
try {
//Wait 5 seconds
Thread.currentThread().sleep(5 * 1000);
} catch (InterruptedException ex) {
// ...
}
//Simulatae a while boucle break
running = lastEventId <= 2000;
}
}
};
new Thread(r).start();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java | apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java | package com.baeldung.sse.jaxrs;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.Initialized;
import jakarta.enterprise.event.Event;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
@ApplicationScoped
@Named
public class StockService {
private static final BigDecimal UP = BigDecimal.valueOf(1.05f);
private static final BigDecimal DOWN = BigDecimal.valueOf(0.95f);
List<String> stockNames = Arrays.asList("GOOG", "IBM", "MS", "GOOG", "YAHO");
List<Stock> stocksDB = new ArrayList<>();
private AtomicInteger counter = new AtomicInteger(0);
public void init(@Observes @Initialized(ApplicationScoped.class) Object init) {
//Open price
System.out.println("@Start Init ...");
stockNames.forEach(stockName -> {
stocksDB.add(new Stock(counter.incrementAndGet(), stockName, generateOpenPrice(), LocalDateTime.now()));
});
Runnable runnable = new Runnable() {
@Override
public void run() {
//Simulate Change price and put every x seconds
while (true) {
int indx = new Random().nextInt(stockNames.size());
String stockName = stockNames.get(indx);
BigDecimal price = getLastPrice(stockName);
BigDecimal newprice = changePrice(price);
Stock stock = new Stock(counter.incrementAndGet(), stockName, newprice, LocalDateTime.now());
stocksDB.add(stock);
int r = new Random().nextInt(30);
try {
Thread.currentThread().sleep(r*1000);
} catch (InterruptedException ex) {
// ...
}
}
}
};
new Thread(runnable).start();
System.out.println("@End Init ...");
}
public Stock getNextTransaction(Integer lastEventId) {
return stocksDB.stream().filter(s -> s.getId().equals(lastEventId)).findFirst().orElse(null);
}
BigDecimal generateOpenPrice() {
float min = 70;
float max = 120;
return BigDecimal.valueOf(min + new Random().nextFloat() * (max - min)).setScale(4,RoundingMode.CEILING);
}
BigDecimal changePrice(BigDecimal price) {
return Math.random() >= 0.5 ? price.multiply(UP).setScale(4,RoundingMode.CEILING) : price.multiply(DOWN).setScale(4,RoundingMode.CEILING);
}
private BigDecimal getLastPrice(String stockName) {
return stocksDB.stream().filter(stock -> stock.getName().equals(stockName)).findFirst().get().getPrice();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java | apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java | package com.baeldung.sse.jaxrs;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
@ApplicationPath("sse")
public class AppConfig extends Application {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java | apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java | package com.baeldung.sse.jaxrs;
import java.math.BigDecimal;
import java.time.LocalDateTime;
public class Stock {
private Integer id;
private String name;
private BigDecimal price;
LocalDateTime dateTime;
public Stock(Integer id, String name, BigDecimal price, LocalDateTime dateTime) {
this.id = id;
this.name = name;
this.price = price;
this.dateTime = dateTime;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public LocalDateTime getDateTime() {
return dateTime;
}
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java | apache-cxf-modules/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java | package com.baeldung.cxf.jaxrs.implementation;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import com.ctc.wstx.shaded.msv_core.util.Uri;
import jakarta.xml.bind.JAXB;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class ServiceLiveTest {
private static final String BASE_URL = "http://localhost:8080/baeldung/courses/";
private static CloseableHttpClient client;
@BeforeClass
public static void createClient() {
client = HttpClients.createDefault();
}
@AfterClass
public static void closeClient() throws IOException {
client.close();
}
@Test
public void whenUpdateNonExistentCourse_thenReceiveNotFoundResponse() throws IOException {
final HttpPut httpPut = new HttpPut(BASE_URL + "3");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("non_existent_course.xml");
httpPut.setEntity(new InputStreamEntity(resourceStream));
httpPut.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPut);
assertEquals(404, response.getStatusLine().getStatusCode());
}
@Test
public void whenUpdateUnchangedCourse_thenReceiveNotModifiedResponse() throws IOException {
final HttpPut httpPut = new HttpPut(BASE_URL + "1");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("unchanged_course.xml");
httpPut.setEntity(new InputStreamEntity(resourceStream));
httpPut.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPut);
assertEquals(304, response.getStatusLine().getStatusCode());
}
@Test
public void whenUpdateValidCourse_thenReceiveOKResponse() throws IOException {
final HttpPut httpPut = new HttpPut(BASE_URL + "2");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("changed_course.xml");
httpPut.setEntity(new InputStreamEntity(resourceStream));
httpPut.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPut);
assertEquals(200, response.getStatusLine().getStatusCode());
final Course course = getCourse(2);
assertEquals(2, course.getId());
assertEquals("Apache CXF Support for RESTful", course.getName());
}
@Test
public void whenCreateConflictStudent_thenReceiveConflictResponse() throws IOException {
final HttpPost httpPost = new HttpPost(BASE_URL + "1/students");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("conflict_student.xml");
httpPost.setEntity(new InputStreamEntity(resourceStream));
httpPost.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPost);
assertEquals(409, response.getStatusLine().getStatusCode());
}
@Test
public void whenCreateValidStudent_thenReceiveOKResponse() throws IOException {
final HttpPost httpPost = new HttpPost(BASE_URL + "2/students");
final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("created_student.xml");
httpPost.setEntity(new InputStreamEntity(resourceStream));
httpPost.setHeader("Content-Type", "text/xml");
final HttpResponse response = client.execute(httpPost);
assertEquals(200, response.getStatusLine().getStatusCode());
final Student student = getStudent(2, 3);
assertEquals(3, student.getId());
assertEquals("Student C", student.getName());
}
@Test
public void whenDeleteInvalidStudent_thenReceiveNotFoundResponse() throws IOException {
final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/3");
final HttpResponse response = client.execute(httpDelete);
assertEquals(404, response.getStatusLine().getStatusCode());
}
@Test
public void whenDeleteValidStudent_thenReceiveOKResponse() throws IOException {
final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/1");
final HttpResponse response = client.execute(httpDelete);
assertEquals(200, response.getStatusLine().getStatusCode());
final Course course = getCourse(1);
assertEquals(1, course.getStudents().size());
assertEquals(2, course.getStudents().get(0).getId());
assertEquals("Student B", course.getStudents().get(0).getName());
}
private Course getCourse(int courseOrder) throws IOException {
final URL url;
try {
url = new URI(BASE_URL + courseOrder).toURL();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
final InputStream input = url.openStream();
return JAXB.unmarshal(new InputStreamReader(input), Course.class);
}
private Student getStudent(int courseOrder, int studentOrder) throws IOException {
final URL url;
try {
url = new URI(BASE_URL + courseOrder + "/students/" + studentOrder).toURL();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
final InputStream input = url.openStream();
return JAXB.unmarshal(new InputStreamReader(input), Student.class);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java | apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java | package com.baeldung.cxf.jaxrs.implementation;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Response;
import jakarta.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
@XmlRootElement(name = "Course")
public class Course {
private int id;
private String name;
private List<Student> students = new ArrayList<>();
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;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@GET
@Path("{studentId}")
public Student getStudent(@PathParam("studentId") int studentId) {
return findById(studentId);
}
@POST
public Response createStudent(Student student) {
for (Student element : students) {
if (element.getId() == student.getId()) {
return Response.status(Response.Status.CONFLICT).build();
}
}
students.add(student);
return Response.ok(student).build();
}
@DELETE
@Path("{studentId}")
public Response deleteStudent(@PathParam("studentId") int studentId) {
Student student = findById(studentId);
if (student == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
students.remove(student);
return Response.ok().build();
}
private Student findById(int id) {
for (Student student : students) {
if (student.getId() == id) {
return student;
}
}
return null;
}
@Override
public int hashCode() {
return id + name.hashCode();
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Course) && (id == ((Course) obj).getId()) && (name.equals(((Course) obj).getName()));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java | apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java | package com.baeldung.cxf.jaxrs.implementation;
import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Student")
public class Student {
private int id;
private String 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;
}
@Override
public int hashCode() {
return id + name.hashCode();
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Student) && (id == ((Student) obj).getId()) && (name.equals(((Student) obj).getName()));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java | apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java | package com.baeldung.cxf.jaxrs.implementation;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
public class RestfulServer {
public static void main(String args[]) throws Exception {
JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
factoryBean.setResourceClasses(CourseRepository.class);
factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository()));
factoryBean.setAddress("http://localhost:8080/");
Server server = factoryBean.create();
System.out.println("Server ready...");
Thread.sleep(60 * 1000);
System.out.println("Server exiting");
server.destroy();
System.exit(0);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java | apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java | package com.baeldung.cxf.jaxrs.implementation;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Path("baeldung")
@Produces("text/xml")
public class CourseRepository {
private Map<Integer, Course> courses = new HashMap<>();
{
Student student1 = new Student();
Student student2 = new Student();
student1.setId(1);
student1.setName("Student A");
student2.setId(2);
student2.setName("Student B");
List<Student> course1Students = new ArrayList<>();
course1Students.add(student1);
course1Students.add(student2);
Course course1 = new Course();
Course course2 = new Course();
course1.setId(1);
course1.setName("REST with Spring");
course1.setStudents(course1Students);
course2.setId(2);
course2.setName("Learn Spring Security");
courses.put(1, course1);
courses.put(2, course2);
}
@GET
@Path("courses/{courseId}")
public Course getCourse(@PathParam("courseId") int courseId) {
return findById(courseId);
}
@PUT
@Path("courses/{courseId}")
public Response updateCourse(@PathParam("courseId") int courseId, Course course) {
Course existingCourse = findById(courseId);
if (existingCourse == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
if (existingCourse.equals(course)) {
return Response.notModified().build();
}
courses.put(courseId, course);
return Response.ok().build();
}
@Path("courses/{courseId}/students")
public Course pathToStudent(@PathParam("courseId") int courseId) {
return findById(courseId);
}
private Course findById(int id) {
for (Map.Entry<Integer, Course> course : courses.entrySet()) {
if (course.getKey() == id) {
return course.getValue();
}
}
return null;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/tensorflow-java/src/test/java/com/baeldung/tensorflow/TensorflowGraphUnitTest.java | tensorflow-java/src/test/java/com/baeldung/tensorflow/TensorflowGraphUnitTest.java | package com.baeldung.tensorflow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import org.tensorflow.Graph;
public class TensorflowGraphUnitTest {
@Test
public void givenTensorflowGraphWhenRunInSessionReturnsExpectedResult() {
Graph graph = TensorflowGraph.createGraph();
Object result = TensorflowGraph.runGraph(graph, 3.0, 6.0);
assertEquals(21.0, result);
System.out.println(result);
graph.close();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/tensorflow-java/src/main/java/com/baeldung/tensorflow/TensorflowSavedModel.java | tensorflow-java/src/main/java/com/baeldung/tensorflow/TensorflowSavedModel.java | package com.baeldung.tensorflow;
import org.tensorflow.SavedModelBundle;
import org.tensorflow.Tensor;
public class TensorflowSavedModel {
public static void main(String[] args) {
SavedModelBundle model = SavedModelBundle.load("./model", "serve");
Tensor<Integer> tensor = model.session().runner().fetch("z").feed("x", Tensor.<Integer>create(3, Integer.class))
.feed("y", Tensor.<Integer>create(3, Integer.class)).run().get(0).expect(Integer.class);
System.out.println(tensor.intValue());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/tensorflow-java/src/main/java/com/baeldung/tensorflow/TensorflowGraph.java | tensorflow-java/src/main/java/com/baeldung/tensorflow/TensorflowGraph.java | package com.baeldung.tensorflow;
import org.tensorflow.DataType;
import org.tensorflow.Graph;
import org.tensorflow.Operation;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
public class TensorflowGraph {
public static Graph createGraph() {
Graph graph = new Graph();
Operation a = graph.opBuilder("Const", "a").setAttr("dtype", DataType.fromClass(Double.class))
.setAttr("value", Tensor.<Double>create(3.0, Double.class)).build();
Operation b = graph.opBuilder("Const", "b").setAttr("dtype", DataType.fromClass(Double.class))
.setAttr("value", Tensor.<Double>create(2.0, Double.class)).build();
Operation x = graph.opBuilder("Placeholder", "x").setAttr("dtype", DataType.fromClass(Double.class)).build();
Operation y = graph.opBuilder("Placeholder", "y").setAttr("dtype", DataType.fromClass(Double.class)).build();
Operation ax = graph.opBuilder("Mul", "ax").addInput(a.output(0)).addInput(x.output(0)).build();
Operation by = graph.opBuilder("Mul", "by").addInput(b.output(0)).addInput(y.output(0)).build();
graph.opBuilder("Add", "z").addInput(ax.output(0)).addInput(by.output(0)).build();
return graph;
}
public static Object runGraph(Graph graph, Double x, Double y) {
Object result;
try (Session sess = new Session(graph)) {
result = sess.runner().fetch("z").feed("x", Tensor.<Double>create(x, Double.class))
.feed("y", Tensor.<Double>create(y, Double.class)).run().get(0).expect(Double.class)
.doubleValue();
}
return result;
}
public static void main(String[] args) {
Graph graph = TensorflowGraph.createGraph();
Object result = TensorflowGraph.runGraph(graph, 3.0, 6.0);
System.out.println(result);
graph.close();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/ProductServletLiveTest.java | apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/ProductServletLiveTest.java | package com.baeldung.apache.velocity.servlet;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ProductServletLiveTest {
@Test
public void whenRequestUsingHttpClient_thenCorrectResponse() throws Exception {
HttpClient client = new DefaultHttpClient();
HttpGet method= new HttpGet("http://localhost:8080/");
HttpResponse httpResponse = client.execute(method);
assertEquals("Success", httpResponse.getHeaders("Template Returned")[0].getValue());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/LayoutServletLiveTest.java | apache-velocity/src/test/java/com/baeldung/apache/velocity/servlet/LayoutServletLiveTest.java | package com.baeldung.apache.velocity.servlet;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LayoutServletLiveTest {
@Test
public void whenRequestUsingHttpClient_thenCorrectResponse() throws Exception {
HttpClient client = new DefaultHttpClient();
HttpGet method= new HttpGet("http://localhost:8080/layout");
HttpResponse httpResponse = client.execute(method);
assertEquals("Success", httpResponse.getHeaders("Template Returned")[0].getValue());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-velocity/src/main/java/com/baeldung/apache/velocity/service/ProductService.java | apache-velocity/src/main/java/com/baeldung/apache/velocity/service/ProductService.java | package com.baeldung.apache.velocity.service;
import com.baeldung.apache.velocity.model.Product;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
public class ProductService {
Logger logger = LoggerFactory.getLogger(ProductService.class);
public List<Product> getProducts() {
logger.debug("Product service returning list of products");
return Arrays.asList(new Product("Laptop", 31000.00), new Product("Mobile", 16000.00),
new Product("Tablet", 15000.00), new Product("Camera", 23000.00));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-velocity/src/main/java/com/baeldung/apache/velocity/model/Product.java | apache-velocity/src/main/java/com/baeldung/apache/velocity/model/Product.java | package com.baeldung.apache.velocity.model;
public class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Product{" + "name='" + name + '\'' + ", price=" + price + '}';
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/ProductServlet.java | apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/ProductServlet.java | package com.baeldung.apache.velocity.servlet;
import com.baeldung.apache.velocity.model.Product;
import com.baeldung.apache.velocity.service.ProductService;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.VelocityViewServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
public class ProductServlet extends VelocityViewServlet {
ProductService service = new ProductService();
@Override
public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) {
Logger logger= LoggerFactory.getLogger(ProductServlet.class);
List<Product> products = service.getProducts();
context.put("products", products);
Template template = null;
try {
template = getTemplate("templates/index.vm");
response.setHeader("Template Returned", "Success");
} catch (Exception e) {
logger.error("Error while reading the template ", e);
}
return template;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/LayoutServlet.java | apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/LayoutServlet.java | package com.baeldung.apache.velocity.servlet;
import com.baeldung.apache.velocity.model.Product;
import com.baeldung.apache.velocity.service.ProductService;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.VelocityLayoutServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
public class LayoutServlet extends VelocityLayoutServlet {
ProductService service = new ProductService();
@Override
public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) {
Logger logger= LoggerFactory.getLogger(LayoutServlet.class);
List<Product> products = service.getProducts();
context.put("products", products);
Template template = null;
try {
template = getTemplate("templates/layoutdemo.vm");
response.setHeader("Template Returned", "Success");
} catch (Exception e) {
logger.error("Error while reading the template ",e);
}
return template;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/test/java/com/baeldung/disablingscheduledtasks/schedulingon/DelayedNotificationSchedulerIntegrationTest.java | spring-scheduling-2/src/test/java/com/baeldung/disablingscheduledtasks/schedulingon/DelayedNotificationSchedulerIntegrationTest.java | package com.baeldung.disablingscheduledtasks.schedulingon;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
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.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import com.baeldung.disablingscheduledtasks.DelayedNotificationScheduler;
import com.baeldung.disablingscheduledtasks.Notification;
import com.baeldung.disablingscheduledtasks.NotificationRepository;
import com.baeldung.disablingscheduledtasks.config.schedulingon.ApplicationConfig;
@SpringBootTest(
classes = { ApplicationConfig.class, SchedulerTestConfiguration.class },
properties = {
"notification.send.out.delay: 10",
"notification.send.out.initial.delay: 0"
}
)
public class DelayedNotificationSchedulerIntegrationTest {
@Autowired
private Clock testClock;
@Autowired
private NotificationRepository repository;
@Autowired
private DelayedNotificationScheduler scheduler;
@Test
public void whenTimeIsOverNotificationSendOutTime_thenItShouldBeSent() {
ZonedDateTime fiveMinutesAgo = ZonedDateTime.now(testClock).minusMinutes(5);
Notification notification = new Notification(fiveMinutesAgo);
repository.save(notification);
scheduler.attemptSendingOutDelayedNotifications();
Notification processedNotification = repository.findById(notification.getId());
assertTrue(processedNotification.isSentOut());
}
}
@TestConfiguration
class SchedulerTestConfiguration {
@Bean
@Primary
public Clock testClock() {
return Clock.fixed(Instant.parse("2024-03-10T10:15:30.00Z"), ZoneId.systemDefault());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/test/java/com/baeldung/disablingscheduledtasks/longinitialdelay/DelayedNotificationSchedulerIntegrationTest.java | spring-scheduling-2/src/test/java/com/baeldung/disablingscheduledtasks/longinitialdelay/DelayedNotificationSchedulerIntegrationTest.java | package com.baeldung.disablingscheduledtasks.longinitialdelay;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
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.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import com.baeldung.disablingscheduledtasks.DelayedNotificationScheduler;
import com.baeldung.disablingscheduledtasks.Notification;
import com.baeldung.disablingscheduledtasks.NotificationRepository;
import com.baeldung.disablingscheduledtasks.config.schedulingon.ApplicationConfig;
@SpringBootTest(
classes = { ApplicationConfig.class, SchedulerTestConfiguration.class },
properties = {
"notification.send.out.delay: 10",
"notification.send.out.initial.delay: 60000"
}
)
public class DelayedNotificationSchedulerIntegrationTest {
@Autowired
private Clock testClock;
@Autowired
private NotificationRepository repository;
@Autowired
private DelayedNotificationScheduler scheduler;
@Test
public void whenTimeIsOverNotificationSendOutTime_thenItShouldBeSent() {
ZonedDateTime fiveMinutesAgo = ZonedDateTime.now(testClock).minusMinutes(5);
Notification notification = new Notification(fiveMinutesAgo);
repository.save(notification);
scheduler.attemptSendingOutDelayedNotifications();
Notification processedNotification = repository.findById(notification.getId());
assertTrue(processedNotification.isSentOut());
}
}
@TestConfiguration
class SchedulerTestConfiguration {
@Bean
@Primary
public Clock testClock() {
return Clock.fixed(Instant.parse("2024-03-10T10:15:30.00Z"), ZoneId.systemDefault());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/test/java/com/baeldung/disablingscheduledtasks/disablewithproperty/DelayedNotificationSchedulerIntegrationTest.java | spring-scheduling-2/src/test/java/com/baeldung/disablingscheduledtasks/disablewithproperty/DelayedNotificationSchedulerIntegrationTest.java | package com.baeldung.disablingscheduledtasks.disablewithproperty;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
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.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import com.baeldung.disablingscheduledtasks.DelayedNotificationScheduler;
import com.baeldung.disablingscheduledtasks.Notification;
import com.baeldung.disablingscheduledtasks.NotificationRepository;
import com.baeldung.disablingscheduledtasks.config.disablewithproperty.ApplicationConfig;
import com.baeldung.disablingscheduledtasks.config.disablewithproperty.SchedulingConfig;
@SpringBootTest(
classes = { ApplicationConfig.class, SchedulingConfig.class, SchedulerTestConfiguration.class },
properties = {
"notification.send.out.delay: 10",
"notification.send.out.initial.delay: 0",
"scheduling.enabled: false"
}
)
public class DelayedNotificationSchedulerIntegrationTest {
@Autowired
private Clock testClock;
@Autowired
private NotificationRepository repository;
@Autowired
private DelayedNotificationScheduler scheduler;
@Test
public void whenTimeIsOverNotificationSendOutTime_thenItShouldBeSent() {
ZonedDateTime fiveMinutesAgo = ZonedDateTime.now(testClock).minusMinutes(5);
Notification notification = new Notification(fiveMinutesAgo);
repository.save(notification);
scheduler.attemptSendingOutDelayedNotifications();
Notification processedNotification = repository.findById(notification.getId());
assertTrue(processedNotification.isSentOut());
}
}
@TestConfiguration
class SchedulerTestConfiguration {
@Bean
@Primary
public Clock testClock() {
return Clock.fixed(Instant.parse("2024-03-10T10:15:30.00Z"), ZoneId.systemDefault());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/test/java/com/baeldung/disablingscheduledtasks/disablewithprofile/DelayedNotificationSchedulerIntegrationTest.java | spring-scheduling-2/src/test/java/com/baeldung/disablingscheduledtasks/disablewithprofile/DelayedNotificationSchedulerIntegrationTest.java | package com.baeldung.disablingscheduledtasks.disablewithprofile;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
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.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.test.context.ActiveProfiles;
import com.baeldung.disablingscheduledtasks.DelayedNotificationScheduler;
import com.baeldung.disablingscheduledtasks.Notification;
import com.baeldung.disablingscheduledtasks.NotificationRepository;
import com.baeldung.disablingscheduledtasks.config.disablewithprofile.ApplicationConfig;
import com.baeldung.disablingscheduledtasks.config.disablewithprofile.SchedulingConfig;
@SpringBootTest(
classes = { ApplicationConfig.class, SchedulingConfig.class, SchedulerTestConfiguration.class },
properties = {
"notification.send.out.delay: 10",
"notification.send.out.initial.delay: 0"
}
)
@ActiveProfiles("integrationTest")
public class DelayedNotificationSchedulerIntegrationTest {
@Autowired
private Clock testClock;
@Autowired
private NotificationRepository repository;
@Autowired
private DelayedNotificationScheduler scheduler;
@Test
public void whenTimeIsOverNotificationSendOutTime_thenItShouldBeSent() {
ZonedDateTime fiveMinutesAgo = ZonedDateTime.now(testClock).minusMinutes(5);
Notification notification = new Notification(fiveMinutesAgo);
repository.save(notification);
scheduler.attemptSendingOutDelayedNotifications();
Notification processedNotification = repository.findById(notification.getId());
assertTrue(processedNotification.isSentOut());
}
}
@TestConfiguration
class SchedulerTestConfiguration {
@Bean
@Primary
public Clock testClock() {
return Clock.fixed(Instant.parse("2024-03-10T10:15:30.00Z"), ZoneId.systemDefault());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/test/java/com/baeldung/scheduleonlyonce/ScheduleOnceServiceIntegrationTest.java | spring-scheduling-2/src/test/java/com/baeldung/scheduleonlyonce/ScheduleOnceServiceIntegrationTest.java | package com.baeldung.scheduleonlyonce;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.baeldung.scheduleonlyonce.service.ScheduleOnceService;
import com.baeldung.scheduleonlyonce.trigger.OneOffTrigger;
@SpringBootTest
class ScheduleOnceServiceIntegrationTest {
private static final long TIMEOUT = 5;
@Autowired
ScheduleOnceService scheduler;
@Test
void whenScheduledMethods_thenEachExecutesOnce() throws InterruptedException {
boolean executed = scheduler.getLatch()
.await(TIMEOUT, TimeUnit.SECONDS);
assertTrue(executed);
}
@Test
void whenScheduleAtInstant_thenExecutesOnce() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
scheduler.schedule(latch::countDown, aSecondFromNow());
boolean executed = latch.await(TIMEOUT, TimeUnit.SECONDS);
assertTrue(executed);
}
@Test
void whenScheduleAtIndefiniteRate_thenExecutesOnce() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
scheduler.scheduleAtIndefiniteRate(latch::countDown, aSecondFromNow());
boolean executed = latch.await(TIMEOUT, TimeUnit.SECONDS);
assertTrue(executed);
}
@Test
void whenScheduleWithRunOnceTrigger_thenExecutesOnce() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
scheduler.schedule(latch::countDown, new OneOffTrigger(aSecondFromNow()));
boolean executed = latch.await(TIMEOUT, TimeUnit.SECONDS);
assertTrue(executed);
}
private Instant aSecondFromNow() {
return Instant.now()
.plus(Duration.ofSeconds(1));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/NotificationService.java | spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/NotificationService.java | package com.baeldung.disablingscheduledtasks;
import java.time.Clock;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NotificationService {
private static final Logger logger = LoggerFactory.getLogger(NotificationService.class);
private NotificationRepository notificationRepository;
private Clock clock;
public NotificationService(NotificationRepository notificationRepository, Clock clock) {
this.notificationRepository = notificationRepository;
this.clock = clock;
}
public void sendOutDelayedNotifications() {
logger.info("Sending out delayed notifications");
List<Notification> notifications = notificationRepository.findAllAwaitingSendOut();
notifications.forEach(notification -> notification.sendOut(clock));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/Notification.java | spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/Notification.java | package com.baeldung.disablingscheduledtasks;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.util.UUID;
public class Notification {
private UUID id = UUID.randomUUID();
private boolean isSentOut = false;
private ZonedDateTime sendOutTime;
public Notification(ZonedDateTime sendOutTime) {
this.sendOutTime = sendOutTime;
}
public void sendOut(Clock clock) {
ZonedDateTime now = ZonedDateTime.now(clock);
if (now.isAfter(sendOutTime)) {
isSentOut = true;
}
}
public UUID getId() {
return id;
}
public boolean isSentOut() {
return isSentOut;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/DelayedNotificationScheduler.java | spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/DelayedNotificationScheduler.java | package com.baeldung.disablingscheduledtasks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
public class DelayedNotificationScheduler {
private static final Logger logger = LoggerFactory.getLogger(DelayedNotificationScheduler.class);
private NotificationService notificationService;
public DelayedNotificationScheduler(NotificationService notificationService) {
this.notificationService = notificationService;
}
@Scheduled(fixedDelayString = "${notification.send.out.delay}", initialDelayString = "${notification.send.out.initial.delay}")
public void attemptSendingOutDelayedNotifications() {
logger.info("Scheduled notifications send out attempt");
notificationService.sendOutDelayedNotifications();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/NotificationRepository.java | spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/NotificationRepository.java | package com.baeldung.disablingscheduledtasks;
import java.util.Collection;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.stream.Collectors;
public class NotificationRepository {
private Collection<Notification> notifications = new ConcurrentLinkedQueue<>();
public Notification findById(UUID notificationId) {
return notifications.stream()
.filter(n -> notificationId.equals(n.getId()))
.findFirst()
.orElseThrow(NoSuchElementException::new);
}
public List<Notification> findAllAwaitingSendOut() {
return notifications.stream()
.filter(notification -> !notification.isSentOut())
.collect(Collectors.toList());
}
public void save(Notification notification) {
notifications.add(notification);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/config/schedulingon/ApplicationConfig.java | spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/config/schedulingon/ApplicationConfig.java | package com.baeldung.disablingscheduledtasks.config.schedulingon;
import java.time.Clock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import com.baeldung.disablingscheduledtasks.DelayedNotificationScheduler;
import com.baeldung.disablingscheduledtasks.NotificationRepository;
import com.baeldung.disablingscheduledtasks.NotificationService;
@Configuration
@EnableScheduling
public class ApplicationConfig {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
@Bean
public NotificationRepository notificationRepository() {
return new NotificationRepository();
}
@Bean
public NotificationService notificationService(NotificationRepository notificationRepository, Clock clock) {
return new NotificationService(notificationRepository, clock);
}
@Bean
public DelayedNotificationScheduler delayedNotificationScheduler(NotificationService notificationService) {
return new DelayedNotificationScheduler(notificationService);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/config/disablewithproperty/SchedulingConfig.java | spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/config/disablewithproperty/SchedulingConfig.java | package com.baeldung.disablingscheduledtasks.config.disablewithproperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@ConditionalOnProperty(value = "scheduling.enabled", havingValue = "true", matchIfMissing = true)
public class SchedulingConfig {
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/config/disablewithproperty/ApplicationConfig.java | spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/config/disablewithproperty/ApplicationConfig.java | package com.baeldung.disablingscheduledtasks.config.disablewithproperty;
import java.time.Clock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baeldung.disablingscheduledtasks.DelayedNotificationScheduler;
import com.baeldung.disablingscheduledtasks.NotificationRepository;
import com.baeldung.disablingscheduledtasks.NotificationService;
@Configuration
public class ApplicationConfig {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
@Bean
public NotificationRepository notificationRepository() {
return new NotificationRepository();
}
@Bean
public NotificationService notificationService(NotificationRepository notificationRepository, Clock clock) {
return new NotificationService(notificationRepository, clock);
}
@Bean
public DelayedNotificationScheduler delayedNotificationScheduler(NotificationService notificationService) {
return new DelayedNotificationScheduler(notificationService);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/config/disablewithprofile/SchedulingConfig.java | spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/config/disablewithprofile/SchedulingConfig.java | package com.baeldung.disablingscheduledtasks.config.disablewithprofile;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@Profile("!integrationTest")
public class SchedulingConfig {
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/config/disablewithprofile/ApplicationConfig.java | spring-scheduling-2/src/main/java/com/baeldung/disablingscheduledtasks/config/disablewithprofile/ApplicationConfig.java | package com.baeldung.disablingscheduledtasks.config.disablewithprofile;
import java.time.Clock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baeldung.disablingscheduledtasks.DelayedNotificationScheduler;
import com.baeldung.disablingscheduledtasks.NotificationRepository;
import com.baeldung.disablingscheduledtasks.NotificationService;
@Configuration
public class ApplicationConfig {
@Bean
public Clock clock() {
return Clock.systemUTC();
}
@Bean
public NotificationRepository notificationRepository() {
return new NotificationRepository();
}
@Bean
public NotificationService notificationService(NotificationRepository notificationRepository, Clock clock) {
return new NotificationService(notificationRepository, clock);
}
@Bean
public DelayedNotificationScheduler delayedNotificationScheduler(NotificationService notificationService) {
return new DelayedNotificationScheduler(notificationService);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithExpression.java | spring-scheduling-2/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithExpression.java | package com.baeldung.scheduling.conditional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
public class ScheduledJobsWithExpression
{
private final static Logger LOG =
LoggerFactory.getLogger(ScheduledJobsWithExpression.class);
/**
* A scheduled job controlled via application property. The job always
* executes, but the logic inside is protected by a configurable boolean
* flag.
*/
@Scheduled(cron = "${jobs.cronSchedule:-}")
public void cleanTempDirectory() {
LOG.info("Cleaning temp directory via placeholder");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/scheduling/conditional/SchedulingApplication.java | spring-scheduling-2/src/main/java/com/baeldung/scheduling/conditional/SchedulingApplication.java | package com.baeldung.scheduling.conditional;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SchedulingApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingApplication.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithBoolean.java | spring-scheduling-2/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithBoolean.java | package com.baeldung.scheduling.conditional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
public class ScheduledJobsWithBoolean {
private final static Logger LOG = LoggerFactory.getLogger(ScheduledJobsWithBoolean.class);
@Value("${jobs.enabled:true}")
private boolean isEnabled;
/**
* A scheduled job controlled via application property. The job always
* executes, but the logic inside is protected by a configurable boolean
* flag.
*/
@Scheduled(fixedDelay = 60000)
public void cleanTempDirectory() {
if(isEnabled) {
LOG.info("Cleaning temp directory via boolean flag");
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/scheduling/conditional/ScheduleJobsByProfile.java | spring-scheduling-2/src/main/java/com/baeldung/scheduling/conditional/ScheduleJobsByProfile.java | package com.baeldung.scheduling.conditional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class ScheduleJobsByProfile {
private final static Logger LOG = LoggerFactory.getLogger(ScheduleJobsByProfile.class);
@Profile("prod")
@Bean
public ScheduledJob scheduledJob()
{
return new ScheduledJob("@Profile");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithConditional.java | spring-scheduling-2/src/main/java/com/baeldung/scheduling/conditional/ScheduledJobsWithConditional.java | package com.baeldung.scheduling.conditional;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ScheduledJobsWithConditional
{
/**
* This uses @ConditionalOnProperty to conditionally create a bean, which itself
* is a scheduled job.
* @return ScheduledJob
*/
@Bean
@ConditionalOnProperty(value = "jobs.enabled", matchIfMissing = true, havingValue = "true")
public ScheduledJob runMyCronTask() {
return new ScheduledJob("@ConditionalOnProperty");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/scheduling/conditional/ScheduledJob.java | spring-scheduling-2/src/main/java/com/baeldung/scheduling/conditional/ScheduledJob.java | package com.baeldung.scheduling.conditional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
public class ScheduledJob {
private String source;
public ScheduledJob(String source) {
this.source = source;
}
private final static Logger LOG = LoggerFactory.getLogger(ScheduledJob.class);
@Scheduled(fixedDelay = 60000)
public void cleanTempDir() {
LOG.info("Cleaning temp directory via {}", source);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/scheduleonlyonce/ScheduleOnylOnceApplication.java | spring-scheduling-2/src/main/java/com/baeldung/scheduleonlyonce/ScheduleOnylOnceApplication.java | package com.baeldung.scheduleonlyonce;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@SpringBootApplication
public class ScheduleOnylOnceApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(ScheduleOnylOnceApplication.class);
app.setWebApplicationType(WebApplicationType.NONE);
app.run(args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/scheduleonlyonce/service/ScheduleOnceService.java | spring-scheduling-2/src/main/java/com/baeldung/scheduleonlyonce/service/ScheduleOnceService.java | package com.baeldung.scheduleonlyonce.service;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.SimpleAsyncTaskScheduler;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;
@Component
public class ScheduleOnceService {
private static final long SCHEDULED_DELAY = 1000;
private TaskScheduler scheduler = new SimpleAsyncTaskScheduler();
private CountDownLatch latch = new CountDownLatch(2);
@Scheduled(initialDelay = SCHEDULED_DELAY, fixedDelay = Long.MAX_VALUE)
public void doTaskWithIndefiniteDelay() {
latch.countDown();
}
@Scheduled(initialDelay = SCHEDULED_DELAY)
public void doTaskWithInitialDelayOnly() {
latch.countDown();
}
public void schedule(Runnable task, Instant when) {
scheduler.schedule(task, when);
}
public void scheduleAtIndefiniteRate(Runnable task, Instant when) {
scheduler.scheduleAtFixedRate(task, when, Duration.ofMillis(Long.MAX_VALUE));
}
public void schedule(Runnable task, PeriodicTrigger trigger) {
scheduler.schedule(task, trigger);
}
public CountDownLatch getLatch() {
return latch;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-scheduling-2/src/main/java/com/baeldung/scheduleonlyonce/trigger/OneOffTrigger.java | spring-scheduling-2/src/main/java/com/baeldung/scheduleonlyonce/trigger/OneOffTrigger.java | package com.baeldung.scheduleonlyonce.trigger;
import java.time.Duration;
import java.time.Instant;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.support.PeriodicTrigger;
public class OneOffTrigger extends PeriodicTrigger {
public OneOffTrigger(Instant when) {
super(Duration.ofSeconds(0));
Duration difference = Duration.between(Instant.now(), when);
setInitialDelay(difference);
}
@Override
public Instant nextExecution(TriggerContext context) {
if (context.lastCompletion() == null) {
return super.nextExecution(context);
}
return null;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jeromq/src/test/java/com/baeldung/jeromq/PubSubLiveTest.java | jeromq/src/test/java/com/baeldung/jeromq/PubSubLiveTest.java | package com.baeldung.jeromq;
import org.junit.jupiter.api.Test;
import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class PubSubLiveTest {
@Test
public void singleSub() throws Exception {
Thread server = new Thread(() -> {
try (ZContext context = new ZContext()) {
ZMQ.Socket pub = context.createSocket(SocketType.PUB);
pub.bind("tcp://*:5555");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + " - Sending");
pub.send("Hello");
}
});
server.setName("server");
Thread client = new Thread(() -> {
try (ZContext context = new ZContext()) {
ZMQ.Socket sub = context.createSocket(SocketType.SUB);
sub.connect("tcp://localhost:5555");
System.out.println(Thread.currentThread().getName() + " - Connected");
sub.subscribe("".getBytes());
System.out.println(Thread.currentThread().getName() + " - Subscribed");
String message = sub.recvStr();
System.out.println(Thread.currentThread().getName() + " - " + message);
}
});
client.setName("client");
server.start();
client.start();
client.join();
server.join();
}
@Test
public void manySub() throws Exception {
Thread server = new Thread(() -> {
try (ZContext context = new ZContext()) {
ZMQ.Socket pub = context.createSocket(SocketType.PUB);
pub.bind("tcp://*:5555");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + " - Sending");
pub.send("Hello");
}
});
server.setName("server");
Set<Thread> clients = IntStream.range(0, 10)
.mapToObj(index -> {
Thread client = new Thread(() -> {
try (ZContext context = new ZContext()) {
ZMQ.Socket sub = context.createSocket(SocketType.SUB);
sub.connect("tcp://localhost:5555");
System.out.println(Thread.currentThread().getName() + " - Connected");
sub.subscribe("".getBytes());
System.out.println(Thread.currentThread().getName() + " - Subscribed");
String message = sub.recvStr();
System.out.println(Thread.currentThread().getName() + " - " + message);
}
});
client.setName("client-" + index);
return client;
})
.collect(Collectors.toSet());
server.start();
clients.forEach(Thread::start);
for (Thread client : clients) {
client.join();
}
server.join();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jeromq/src/test/java/com/baeldung/jeromq/DealerRouterLiveTest.java | jeromq/src/test/java/com/baeldung/jeromq/DealerRouterLiveTest.java | package com.baeldung.jeromq;
import org.junit.jupiter.api.Test;
import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class DealerRouterLiveTest {
@Test
public void single() throws Exception {
Thread brokerThread = new Thread(() -> {
try (ZContext context = new ZContext()) {
ZMQ.Socket broker = context.createSocket(SocketType.ROUTER);
broker.bind("tcp://*:5555");
String identity = broker.recvStr();
System.out.println(Thread.currentThread().getName() + " - Received identity " + identity);
broker.recv(0); // Envelope delimiter
System.out.println(Thread.currentThread().getName() + " - Received envelope");
String message = broker.recvStr(0); // Response from worker
System.out.println(Thread.currentThread().getName() + " - Received message " + message);
broker.sendMore(identity);
broker.sendMore("xxx");
broker.send("Hello back");
}
});
brokerThread.setName("broker");
Thread workerThread = new Thread(() -> {
try (ZContext context = new ZContext()) {
ZMQ.Socket worker = context.createSocket(SocketType.DEALER);
worker.setIdentity(Thread.currentThread().getName().getBytes(ZMQ.CHARSET));
worker.connect("tcp://localhost:5555");
System.out.println(Thread.currentThread().getName() + " - Connected");
worker.sendMore("");
worker.send("Hello " + Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName() + " - Sent Hello");
worker.recvStr(); // Envelope delimiter
System.out.println(Thread.currentThread().getName() + " - Received Envelope");
String workload = worker.recvStr();
System.out.println(Thread.currentThread().getName() + " - Received " + workload);
}
});
workerThread.setName("worker");
brokerThread.start();
workerThread.start();
workerThread.join();
brokerThread.join();
}
@Test
public void asynchronous() throws Exception {
Thread brokerThread = new Thread(() -> {
try (ZContext context = new ZContext()) {
ZMQ.Socket broker = context.createSocket(SocketType.ROUTER);
broker.bind("tcp://*:5555");
while (true) {
String identity = broker.recvStr(ZMQ.DONTWAIT);
System.out.println(Thread.currentThread().getName() + " - Received identity " + identity);
if (identity == null) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
} else {
broker.recv(0); // Envelope delimiter
System.out.println(Thread.currentThread().getName() + " - Received envelope");
String message = broker.recvStr(0); // Response from worker
System.out.println(Thread.currentThread().getName() + " - Received message " + message);
broker.sendMore(identity);
broker.sendMore("xxx");
broker.send("Hello back");
break;
}
}
}
});
brokerThread.setName("broker");
Thread workerThread = new Thread(() -> {
try (ZContext context = new ZContext()) {
ZMQ.Socket worker = context.createSocket(SocketType.DEALER);
worker.setIdentity(Thread.currentThread().getName().getBytes(ZMQ.CHARSET));
worker.connect("tcp://localhost:5555");
System.out.println(Thread.currentThread().getName() + " - Connected");
worker.sendMore("");
worker.send("Hello " + Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName() + " - Sent Hello");
worker.recvStr(); // Envelope delimiter
System.out.println(Thread.currentThread().getName() + " - Received Envelope");
String workload = worker.recvStr();
System.out.println(Thread.currentThread().getName() + " - Received " + workload);
}
});
workerThread.setName("worker");
brokerThread.start();
workerThread.start();
workerThread.join();
brokerThread.join();
}
@Test
public void many() throws Exception {
Thread brokerThread = new Thread(() -> {
try (ZContext context = new ZContext()) {
ZMQ.Socket broker = context.createSocket(SocketType.ROUTER);
broker.bind("tcp://*:5555");
while (!Thread.currentThread().isInterrupted()) {
String identity = broker.recvStr();
System.out.println(Thread.currentThread().getName() + " - Received identity " + identity);
broker.recv(0); // Envelope delimiter
String message = broker.recvStr(0); // Response from worker
System.out.println(Thread.currentThread().getName() + " - Received message " + message);
broker.sendMore(identity);
broker.sendMore("");
broker.send("Hello back to " + identity);
}
}
});
brokerThread.setName("broker");
Set<Thread> workers = IntStream.range(0, 10)
.mapToObj(index -> {
Thread workerThread = new Thread(() -> {
try (ZContext context = new ZContext()) {
ZMQ.Socket worker = context.createSocket(SocketType.DEALER);
worker.setIdentity(Thread.currentThread().getName().getBytes(ZMQ.CHARSET));
worker.connect("tcp://localhost:5555");
System.out.println(Thread.currentThread().getName() + " - Connected");
worker.sendMore("");
worker.send("Hello " + Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName() + " - Sent Hello");
worker.recvStr(); // Envelope delimiter
String workload = worker.recvStr();
System.out.println(Thread.currentThread().getName() + " - Received " + workload);
}
});
workerThread.setName("worker-" + index);
return workerThread;
})
.collect(Collectors.toSet());
brokerThread.start();
workers.forEach(Thread::start);
for (Thread worker : workers) {
worker.join();
}
brokerThread.interrupt();
}
@Test
public void threaded() throws Exception {
Thread brokerThread = new Thread(() -> {
try (ZContext context = new ZContext()) {
ZMQ.Socket broker = context.createSocket(SocketType.ROUTER);
broker.bind("tcp://*:5555");
ExecutorService threadPool = Executors.newFixedThreadPool(5);
Random rng = new Random();
while (!Thread.currentThread().isInterrupted()) {
String identity = broker.recvStr();
System.out.println(Thread.currentThread().getName() + " - Received identity " + identity);
broker.recv(0); // Envelope delimiter
String message = broker.recvStr(0); // Response from worker
System.out.println(Thread.currentThread().getName() + " - Received message " + message);
threadPool.submit(() -> {
try {
Thread.sleep(rng.nextInt(1000) + 1000 );
} catch (Exception e) {}
synchronized(broker) {
broker.sendMore(identity);
broker.sendMore("");
broker.send("Hello back to " + identity + " from " + Thread.currentThread().getName());
}
});
}
threadPool.shutdown();
}
});
brokerThread.setName("broker");
Set<Thread> workers = IntStream.range(0, 10)
.mapToObj(index -> {
Thread workerThread = new Thread(() -> {
try (ZContext context = new ZContext()) {
ZMQ.Socket worker = context.createSocket(SocketType.DEALER);
worker.setIdentity(Thread.currentThread().getName().getBytes(ZMQ.CHARSET));
worker.connect("tcp://localhost:5555");
System.out.println(Thread.currentThread().getName() + " - Connected");
worker.sendMore("");
worker.send("Hello " + Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName() + " - Sent Hello");
worker.recvStr(); // Envelope delimiter
String workload = worker.recvStr();
System.out.println(Thread.currentThread().getName() + " - Received " + workload);
}
});
workerThread.setName("worker-" + index);
return workerThread;
})
.collect(Collectors.toSet());
brokerThread.start();
workers.forEach(Thread::start);
for (Thread worker : workers) {
worker.join();
}
brokerThread.interrupt();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jeromq/src/test/java/com/baeldung/jeromq/RequestResponseLiveTest.java | jeromq/src/test/java/com/baeldung/jeromq/RequestResponseLiveTest.java | package com.baeldung.jeromq;
import org.junit.jupiter.api.Test;
import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class RequestResponseLiveTest {
@Test
public void requestResponse() throws Exception {
try (ZContext context = new ZContext()) {
Thread server = new Thread(() -> {
ZMQ.Socket socket = context.createSocket(SocketType.REP);
socket.bind("inproc://test");
while (!Thread.currentThread().isInterrupted()) {
byte[] reply = socket.recv(0);
System.out.println("Server Received " + ": [" + new String(reply, ZMQ.CHARSET) + "]");
String response = new String(reply, ZMQ.CHARSET) + ", world";
socket.send(response.getBytes(ZMQ.CHARSET), 0);
}
});
Thread client = new Thread(() -> {
ZMQ.Socket socket = context.createSocket(SocketType.REQ);
socket.connect("inproc://test");
for (int requestNbr = 0; requestNbr != 10; requestNbr++) {
String request = "Hello " + requestNbr;
System.out.println("Sending " + request);
socket.send(request.getBytes(ZMQ.CHARSET), 0);
byte[] reply = socket.recv(0);
System.out.println("Client Received " + new String(reply, ZMQ.CHARSET));
}
});
server.start();
client.start();
client.join();
server.interrupt();
}
}
@Test
public void manyRequestResponse() throws Exception {
try (ZContext context = new ZContext()) {
Thread server = new Thread(() -> {
ZMQ.Socket socket = context.createSocket(SocketType.REP);
socket.bind("tcp://*:5555");
while (!Thread.currentThread().isInterrupted()) {
byte[] reply = socket.recv(0);
System.out.println("Server Received " + ": [" + new String(reply, ZMQ.CHARSET) + "]");
String response = new String(reply, ZMQ.CHARSET) + ", world";
socket.send(response.getBytes(ZMQ.CHARSET), 0);
}
});
Set<Thread> clients = IntStream.range(0, 10).mapToObj(index ->
new Thread(() -> {
ZMQ.Socket socket = context.createSocket(SocketType.REQ);
socket.connect("tcp://localhost:5555");
for (int requestNbr = 0; requestNbr != 10; requestNbr++) {
String request = "Hello " + index + " - " + requestNbr;
System.out.println("Sending " + request);
socket.send(request.getBytes(ZMQ.CHARSET), 0);
byte[] reply = socket.recv(0);
System.out.println("Client " + index + " Received " + new String(reply, ZMQ.CHARSET));
}
})
).collect(Collectors.toSet());
server.start();
clients.forEach(Thread::start);
for (Thread client : clients) {
client.join();
}
server.interrupt();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit4IntegrationTest.java | spring-5-rest-docs/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit4IntegrationTest.java | package com.baeldung.restdocs;
import com.baeldung.restdocs.CrudInput;
import com.baeldung.restdocs.SpringRestDocsApplication;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Rule;
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.hateoas.MediaTypes;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.restdocs.constraints.ConstraintDescriptions;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.util.HashMap;
import java.util.Map;
import static java.util.Collections.singletonList;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.util.StringUtils.collectionToDelimitedString;
import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.pathParameters;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringRestDocsApplication.class)
public class ApiDocumentationJUnit4IntegrationTest {
@Rule
public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets");
@Autowired
private WebApplicationContext context;
@Autowired
private ObjectMapper objectMapper;
private MockMvc mockMvc;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
.build();
}
@Test
public void indexExample() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andDo(document("index-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links(linkWithRel("crud").description("The CRUD resource")), responseFields(subsectionWithPath("_links").description("Links to other resources")),
responseHeaders(headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`"))));
}
@Test
public void crudGetExample() throws Exception {
Map<String, Object> crud = new HashMap<>();
crud.put("id", 1L);
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getHeader("Location");
crud.put("tags", singletonList(tagLocation));
ConstraintDescriptions desc = new ConstraintDescriptions(CrudInput.class);
this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk())
.andDo(document("crud-get-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")),
fieldWithPath("title").description("The title of the input"), fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
@Test
public void crudCreateExample() throws Exception {
Map<String, Object> crud = new HashMap<>();
crud.put("id", 2L);
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getHeader("Location");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isCreated())
.andDo(document("crud-create-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input"), fieldWithPath("title").description("The title of the input"),
fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
@Test
public void crudDeleteExample() throws Exception {
this.mockMvc.perform(delete("/crud/{id}", 10))
.andExpect(status().isOk())
.andDo(document("crud-delete-example", pathParameters(parameterWithName("id").description("The id of the input to delete"))));
}
@Test
public void crudPatchExample() throws Exception {
Map<String, String> tag = new HashMap<>();
tag.put("name", "PATCH");
String tagLocation = this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(tag)))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getHeader("Location");
Map<String, Object> crud = new HashMap<>();
crud.put("title", "Sample Model Patch");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk());
}
@Test
public void crudPutExample() throws Exception {
Map<String, String> tag = new HashMap<>();
tag.put("name", "PUT");
String tagLocation = this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(tag)))
.andExpect(status().isAccepted())
.andReturn()
.getResponse()
.getHeader("Location");
Map<String, Object> crud = new HashMap<>();
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isAccepted());
}
@Test
public void contextLoads() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit5IntegrationTest.java | spring-5-rest-docs/src/test/java/com/baeldung/restdocs/ApiDocumentationJUnit5IntegrationTest.java | package com.baeldung.restdocs;
import static java.util.Collections.singletonList;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel;
import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.request.RequestDocumentation.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.util.StringUtils.collectionToDelimitedString;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.hateoas.MediaTypes;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.restdocs.constraints.ConstraintDescriptions;
import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.restdocs.CrudInput;
import com.baeldung.restdocs.SpringRestDocsApplication;
import com.fasterxml.jackson.databind.ObjectMapper;
@ExtendWith({ RestDocumentationExtension.class, SpringExtension.class })
@SpringBootTest(classes = SpringRestDocsApplication.class)
public class ApiDocumentationJUnit5IntegrationTest {
@Autowired
private ObjectMapper objectMapper;
private MockMvc mockMvc;
@BeforeEach
public void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.apply(documentationConfiguration(restDocumentation))
.alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
.build();
}
@Test
public void indexExample() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andDo(document("index-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links(linkWithRel("crud").description("The CRUD resource")), responseFields(subsectionWithPath("_links").description("Links to other resources")),
responseHeaders(headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`"))));
}
@Test
public void crudGetExample() throws Exception {
Map<String, Object> crud = new HashMap<>();
crud.put("id", 1L);
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
String tagLocation = this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getHeader("Location");
crud.put("tags", singletonList(tagLocation));
ConstraintDescriptions desc = new ConstraintDescriptions(CrudInput.class);
this.mockMvc.perform(get("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk())
.andDo(document("crud-get-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")),
fieldWithPath("title").description("The title of the input"), fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
@Test
public void crudCreateExample() throws Exception {
Map<String, Object> crud = new HashMap<>();
crud.put("id", 2L);
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
String tagLocation = this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getHeader("Location");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(post("/crud").contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isCreated())
.andDo(document("crud-create-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the input"), fieldWithPath("title").description("The title of the input"),
fieldWithPath("body").description("The body of the input"), fieldWithPath("tags").description("An array of tag resource URIs"))));
}
@Test
public void crudDeleteExample() throws Exception {
this.mockMvc.perform(delete("/crud/{id}", 10))
.andExpect(status().isOk())
.andDo(document("crud-delete-example", pathParameters(parameterWithName("id").description("The id of the input to delete"))));
}
@Test
public void crudPatchExample() throws Exception {
Map<String, String> tag = new HashMap<>();
tag.put("name", "PATCH");
String tagLocation = this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(tag)))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getHeader("Location");
Map<String, Object> crud = new HashMap<>();
crud.put("title", "Sample Model Patch");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(patch("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isOk());
}
@Test
public void crudPutExample() throws Exception {
Map<String, String> tag = new HashMap<>();
tag.put("name", "PUT");
String tagLocation = this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(tag)))
.andExpect(status().isAccepted())
.andReturn()
.getResponse()
.getHeader("Location");
Map<String, Object> crud = new HashMap<>();
crud.put("title", "Sample Model");
crud.put("body", "http://www.baeldung.com/");
crud.put("tags", singletonList(tagLocation));
this.mockMvc.perform(put("/crud/{id}", 10).contentType(MediaTypes.HAL_JSON)
.content(this.objectMapper.writeValueAsString(crud)))
.andExpect(status().isAccepted());
}
@Test
public void contextLoads() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/test/java/com/baeldung/queryparamdoc/BookControllerRestAssuredIntegrationTest.java | spring-5-rest-docs/src/test/java/com/baeldung/queryparamdoc/BookControllerRestAssuredIntegrationTest.java | package com.baeldung.queryparamdoc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.core.Is.is;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.queryParameters;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.restdocs.restassured.RestAssuredRestDocumentation;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
@AutoConfigureWebMvc
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class BookControllerRestAssuredIntegrationTest {
private RequestSpecification spec;
@BeforeEach
void setUp(RestDocumentationContextProvider restDocumentation, @LocalServerPort int port) {
this.spec = new RequestSpecBuilder().addFilter(RestAssuredRestDocumentation.documentationConfiguration(restDocumentation))
.setPort(port)
.build();
}
@Test
void smokeTest() {
assertThat(spec).isNotNull();
}
@Test
@WithMockUser
void givenEndpoint_whenSendGetRequest_thenSuccessfulResponse() {
RestAssured.given(this.spec).filter(RestAssuredRestDocumentation.document("users", queryParameters(
parameterWithName("page").description("The page to retrieve"))))
.when().get("/books?page=2")
.then().assertThat().statusCode(is(200));
}
} | 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.