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-4/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java | libraries-4/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java | package com.baeldung.mapdb;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
public class HelloBaeldungUnitTest {
@Test
public void givenInMemoryDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() {
DB db = DBMaker.memoryDB()
.make();
String welcomeMessageKey = "Welcome Message";
String welcomeMessageString = "Hello Baeldung!";
HTreeMap myMap = db.hashMap("myMap")
.createOrOpen();
myMap.put(welcomeMessageKey, welcomeMessageString);
String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey);
db.close();
assertEquals(welcomeMessageString, welcomeMessageFromDB);
}
@Test
public void givenInFileDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() {
DB db = DBMaker.fileDB("file.db")
.make();
String welcomeMessageKey = "Welcome Message";
String welcomeMessageString = "Hello Baeldung!";
HTreeMap myMap = db.hashMap("myMap")
.createOrOpen();
myMap.put(welcomeMessageKey, welcomeMessageString);
String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey);
db.close();
assertEquals(welcomeMessageString, welcomeMessageFromDB);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/aeron/AeronLiveTest.java | libraries-4/src/test/java/com/baeldung/aeron/AeronLiveTest.java | package com.baeldung.aeron;
import io.aeron.Aeron;
import io.aeron.driver.MediaDriver;
import org.junit.jupiter.api.Test;
public class AeronLiveTest {
@Test
void createAeronApi() {
try (MediaDriver mediaDriver = MediaDriver.launch()) {
System.out.println("Media driver: " + mediaDriver.aeronDirectoryName());
try (Aeron aeron = Aeron.connect()) {
System.out.println("Aeron connected: " + aeron);
}
}
}
@Test
void createEmbeddedAeronApi() {
try (MediaDriver mediaDriver = MediaDriver.launchEmbedded()) {
System.out.println("Media driver: " + mediaDriver.aeronDirectoryName());
Aeron.Context ctx = new Aeron.Context();
ctx.aeronDirectoryName(mediaDriver.aeronDirectoryName());
try (Aeron aeron = Aeron.connect(ctx)) {
System.out.println("Aeron connected: " + aeron);
}
}
}
@Test
void createMultipleAeronApi() {
try (MediaDriver mediaDriver = MediaDriver.launchEmbedded()) {
System.out.println("Media driver: " + mediaDriver.aeronDirectoryName());
Aeron aeron1 = null;
Aeron aeron2 = null;
try {
Aeron.Context ctx1 = new Aeron.Context();
ctx1.aeronDirectoryName(mediaDriver.aeronDirectoryName());
aeron1 = Aeron.connect(ctx1);
System.out.println("Aeron 1 connected: " + aeron1);
Aeron.Context ctx2 = new Aeron.Context();
ctx2.aeronDirectoryName(mediaDriver.aeronDirectoryName());
aeron2 = Aeron.connect(ctx2);
System.out.println("Aeron 2 connected: " + aeron2);
} finally {
if (aeron1 != null) {
aeron1.close();
}
if (aeron2 != null) {
aeron2.close();
}
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/aeron/MediaDriverLiveTest.java | libraries-4/src/test/java/com/baeldung/aeron/MediaDriverLiveTest.java | package com.baeldung.aeron;
import io.aeron.driver.MediaDriver;
import io.aeron.driver.ThreadingMode;
import org.agrona.concurrent.IdleStrategy;
import org.junit.jupiter.api.Test;
public class MediaDriverLiveTest {
@Test
void startDefaultMediaDriver() {
try (MediaDriver mediaDriver = MediaDriver.launch()) {
System.out.println("Media Driver: " + mediaDriver.aeronDirectoryName());
}
}
@Test
void startConfiguredMediaDriver() {
MediaDriver.Context context = new MediaDriver.Context();
context.threadingMode(ThreadingMode.SHARED);
try (MediaDriver mediaDriver = MediaDriver.launch(context)) {
System.out.println("Media Driver: " + mediaDriver.aeronDirectoryName());
}
}
@Test
void startDefaultEmbeddedMediaDriver() {
try (MediaDriver mediaDriver = MediaDriver.launchEmbedded()) {
System.out.println("Media Driver: " + mediaDriver.aeronDirectoryName());
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/aeron/SendReceiveLiveTest.java | libraries-4/src/test/java/com/baeldung/aeron/SendReceiveLiveTest.java | package com.baeldung.aeron;
import io.aeron.Aeron;
import io.aeron.CommonContext;
import io.aeron.ConcurrentPublication;
import io.aeron.Subscription;
import io.aeron.driver.MediaDriver;
import io.aeron.logbuffer.FragmentHandler;
import org.agrona.BufferUtil;
import org.agrona.concurrent.BackoffIdleStrategy;
import org.agrona.concurrent.IdleStrategy;
import org.agrona.concurrent.UnsafeBuffer;
import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
public class SendReceiveLiveTest {
private static final String CHANNEL = "aeron:udp?endpoint=localhost:20121";
private static final int STREAM = 1001;
@Test
void send() throws InterruptedException {
MediaDriver mediaDriver = MediaDriver.launchEmbedded();
try (Aeron aeron = Aeron.connect(new Aeron.Context().aeronDirectoryName(mediaDriver.aeronDirectoryName()))) {
ConcurrentPublication publication = aeron.addPublication(CHANNEL, STREAM);
while (!publication.isConnected()) {
TimeUnit.MILLISECONDS.sleep(100);
}
for (int i = 0; i < 10; ++i) {
String message = "Hello, World: " + i + " at " + System.currentTimeMillis();
UnsafeBuffer buffer = new UnsafeBuffer(BufferUtil.allocateDirectAligned(256, 64));
buffer.putStringWithoutLengthUtf8(0, message);
long offer = publication.offer(buffer, 0, message.length());
System.out.printf("Offered message <<%s>> with result %d%n", message, offer);
}
}
}
@Test
void receive() {
MediaDriver mediaDriver = MediaDriver.launchEmbedded();
try (Aeron aeron = Aeron.connect(new Aeron.Context().aeronDirectoryName(mediaDriver.aeronDirectoryName()))) {
Subscription subscription = aeron.addSubscription(CHANNEL, STREAM);
IdleStrategy idleStrategy = new BackoffIdleStrategy(100, 10,
TimeUnit.MICROSECONDS.toNanos(1), TimeUnit.MICROSECONDS.toNanos(100));
FragmentHandler fragmentHandler = (buffer, offset, length, header) ->
{
String data = buffer.getStringWithoutLengthUtf8(offset, length);
System.out.printf("Message to stream %d from session %d (%d@%d) <<%s>> at %d%n",
STREAM, header.sessionId(), length, offset, data, System.currentTimeMillis());
};
while (true) {
int fragmentsRead = subscription.poll(fragmentHandler, 10);
idleStrategy.idle(fragmentsRead);
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/githubapi/ClientLiveTest.java | libraries-4/src/test/java/com/baeldung/githubapi/ClientLiveTest.java | package com.baeldung.githubapi;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.kohsuke.github.GitHub;
import org.kohsuke.github.GitHubBuilder;
public class ClientLiveTest {
@Test
void whenWeCreateAnAnonynousClient_thenWeCanAccessTheGithubApi() throws IOException {
GitHub gitHub = GitHub.connectAnonymously();
String apiUri = gitHub.getApiUrl();
assertEquals("https://api.github.com", apiUri);
}
@Test
// Needs credentials configuring in environment variables or ~/.github.
void whenWeCreateADefaultClient_thenWeCanAccessTheGithubApi() throws IOException {
GitHub gitHub = GitHub.connect();
String apiUri = gitHub.getApiUrl();
assertEquals("https://api.github.com", apiUri);
}
@Test
// Needs credentials configuring
void whenWeCreateAClientWithProvidedCredentials_thenWeCanAccessTheGithubApi() throws IOException {
GitHub gitHub = new GitHubBuilder().withPassword("my_user", "my_password").build();
String apiUri = gitHub.getApiUrl();
assertEquals("https://api.github.com", apiUri);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/githubapi/UsersLiveTest.java | libraries-4/src/test/java/com/baeldung/githubapi/UsersLiveTest.java | package com.baeldung.githubapi;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import org.kohsuke.github.GHMyself;
import org.kohsuke.github.GHUser;
import org.kohsuke.github.GitHub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UsersLiveTest {
private static final Logger LOG = LoggerFactory.getLogger(UsersLiveTest.class);
@Test
// Needs credentials configuring in environment variables or ~/.github.
void whenWeAccessMyself_thenWeCanQueryUserDetails() throws IOException {
GitHub gitHub = GitHub.connect();
GHMyself myself = gitHub.getMyself();
LOG.info("Current users username: {}", myself.getLogin());
LOG.info("Current users email: {}", myself.getEmail());
}
@Test
void whenWeAccessAnotherUser_thenWeCanQueryUserDetails() throws IOException {
GitHub gitHub = GitHub.connectAnonymously();
GHUser user = gitHub.getUser("eugenp");
assertEquals("eugenp", user.getLogin());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/githubapi/RepositoryLiveTest.java | libraries-4/src/test/java/com/baeldung/githubapi/RepositoryLiveTest.java | package com.baeldung.githubapi;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import org.kohsuke.github.GHBranch;
import org.kohsuke.github.GHCommit;
import org.kohsuke.github.GHContent;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GHUser;
import org.kohsuke.github.GitHub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
public class RepositoryLiveTest {
private static final Logger LOG = LoggerFactory.getLogger(RepositoryLiveTest.class);
@Test
void whenWeListAUsersRepositories_thenWeCanAccessTheRepositories() throws IOException {
GitHub gitHub = GitHub.connectAnonymously();
GHUser user = gitHub.getUser("eugenp");
List<GHRepository> repositoriesList = user.listRepositories().toList();
assertThat(repositoriesList).isNotEmpty();
}
@Test
void whenWeIterateAUsersRepositories_thenWeCanAccessTheRepositories() throws IOException {
GitHub gitHub = GitHub.connectAnonymously();
GHUser user = gitHub.getUser("eugenp");
Set<String> names = new HashSet<>();
for (GHRepository ghRepository : user.listRepositories()) {
names.add(ghRepository.getName());
}
assertThat(names).isNotEmpty();
}
@Test
void whenWeDirectlyAccessAUsersRepository_thenWeCanQueryRepositoryDetails() throws IOException {
GitHub gitHub = GitHub.connectAnonymously();
GHUser user = gitHub.getUser("eugenp");
GHRepository repository = user.getRepository("tutorials");
assertEquals("tutorials", repository.getName());
assertEquals("eugenp/tutorials", repository.getFullName());
}
@Test
void whenWeDirectlyAccessARepository_thenWeCanQueryRepositoryDetails() throws IOException {
GitHub gitHub = GitHub.connectAnonymously();
GHRepository repository = gitHub.getRepository("eugenp/tutorials");
assertEquals("tutorials", repository.getName());
assertEquals("eugenp/tutorials", repository.getFullName());
}
@Test
void whenWeAccessARepositoryBranch_thenWeCanAccessCommitDetails() throws IOException {
GitHub gitHub = GitHub.connectAnonymously();
GHRepository repository = gitHub.getRepository("eugenp/tutorials");
String defaultBranch = repository.getDefaultBranch();
GHBranch branch = repository.getBranch(defaultBranch);
String branchHash = branch.getSHA1();
GHCommit commit = repository.getCommit(branchHash);
LOG.info("Commit message: {}", commit.getCommitShortInfo().getMessage());
}
@Test
void whenWeAccessARepositoryBranch_thenWeCanAccessFiles() throws IOException {
GitHub gitHub = GitHub.connectAnonymously();
GHRepository repository = gitHub.getRepository("eugenp/tutorials");
String defaultBranch = repository.getDefaultBranch();
GHContent file = repository.getFileContent("pom.xml", defaultBranch);
String fileContents = IOUtils.toString(file.read(), Charsets.UTF_8);
LOG.info("pom.xml file contents: {}", fileContents);
}
@Test
void whenWeAccessTheRepository_thenWeCanDirectlyAccessTheReadme() throws IOException {
GitHub gitHub = GitHub.connectAnonymously();
GHRepository repository = gitHub.getRepository("eugenp/tutorials");
GHContent readme = repository.getReadme();
String fileContents = IOUtils.toString(readme.read(), Charsets.UTF_8);
LOG.info("Readme file contents: {}", fileContents);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/lanterna/LowLevelLiveTest.java | libraries-4/src/test/java/com/baeldung/lanterna/LowLevelLiveTest.java | package com.baeldung.lanterna;
import org.junit.jupiter.api.Test;
import com.googlecode.lanterna.SGR;
import com.googlecode.lanterna.TextColor;
import com.googlecode.lanterna.input.KeyType;
import com.googlecode.lanterna.terminal.DefaultTerminalFactory;
import com.googlecode.lanterna.terminal.Terminal;
public class LowLevelLiveTest {
@Test
void whenPrintingCharacters_thenTheCharactersAppear() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
terminal.enterPrivateMode();
terminal.putCharacter('H');
terminal.putCharacter('e');
terminal.putCharacter('l');
terminal.putCharacter('l');
terminal.putCharacter('o');
terminal.flush();
Thread.sleep(15000);
terminal.exitPrivateMode();
}
}
@Test
void whenMovingTheCursor_thenCharactersAppearAtTheNewPosition() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
terminal.enterPrivateMode();
terminal.setCursorPosition(10, 10);
terminal.putCharacter('H');
terminal.putCharacter('e');
terminal.putCharacter('l');
terminal.putCharacter('l');
terminal.putCharacter('o');
terminal.setCursorPosition(11, 11);
terminal.putCharacter('W');
terminal.putCharacter('o');
terminal.putCharacter('r');
terminal.putCharacter('l');
terminal.putCharacter('d');
terminal.flush();
Thread.sleep(15000);
terminal.exitPrivateMode();
}
}
@Test
void whenQueryingTheTerminalSize_thenWeGetTheCorrectSize() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
terminal.enterPrivateMode();
var size = terminal.getTerminalSize();
System.out.println("Rows: " + size.getRows());
System.out.println("Columns: " + size.getColumns());
Thread.sleep(15000);
terminal.exitPrivateMode();
}
}
@Test
void whenSettingCharacterColours_thenTheCharactersUseThoseColours() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
terminal.enterPrivateMode();
terminal.setForegroundColor(TextColor.ANSI.RED);
terminal.putCharacter('H');
terminal.putCharacter('e');
terminal.putCharacter('l');
terminal.putCharacter('l');
terminal.putCharacter('o');
terminal.setForegroundColor(TextColor.ANSI.DEFAULT);
terminal.setBackgroundColor(TextColor.ANSI.BLUE);
terminal.putCharacter('W');
terminal.putCharacter('o');
terminal.putCharacter('r');
terminal.putCharacter('l');
terminal.putCharacter('d');
terminal.flush();
Thread.sleep(15000);
terminal.exitPrivateMode();
}
}
@Test
void whenSettingSGRAttributes_thenTheCharactersUseThoseColours() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
terminal.enterPrivateMode();
terminal.enableSGR(SGR.BOLD);
terminal.putCharacter('H');
terminal.putCharacter('e');
terminal.putCharacter('l');
terminal.putCharacter('l');
terminal.putCharacter('o');
terminal.disableSGR(SGR.BOLD);
terminal.enableSGR(SGR.UNDERLINE);
terminal.putCharacter('W');
terminal.putCharacter('o');
terminal.putCharacter('r');
terminal.putCharacter('l');
terminal.putCharacter('d');
terminal.resetColorAndSGR();
terminal.flush();
Thread.sleep(15000);
terminal.exitPrivateMode();
}
}
@Test
void whenReadingInput_thenTheInputIsProvided() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
terminal.enterPrivateMode();
while (true) {
var keystroke = terminal.readInput();
if (keystroke.getKeyType() == KeyType.Escape) {
break;
} else if (keystroke.getKeyType() == KeyType.Character) {
terminal.putCharacter(keystroke.getCharacter());
terminal.flush();
}
}
terminal.exitPrivateMode();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/lanterna/GuiLiveTest.java | libraries-4/src/test/java/com/baeldung/lanterna/GuiLiveTest.java | package com.baeldung.lanterna;
import java.util.Set;
import org.junit.jupiter.api.Test;
import com.googlecode.lanterna.gui2.BasicWindow;
import com.googlecode.lanterna.gui2.Button;
import com.googlecode.lanterna.gui2.Direction;
import com.googlecode.lanterna.gui2.Label;
import com.googlecode.lanterna.gui2.LinearLayout;
import com.googlecode.lanterna.gui2.MultiWindowTextGUI;
import com.googlecode.lanterna.gui2.Panel;
import com.googlecode.lanterna.gui2.TextBox;
import com.googlecode.lanterna.gui2.Window;
import com.googlecode.lanterna.gui2.dialogs.MessageDialogBuilder;
import com.googlecode.lanterna.screen.TerminalScreen;
import com.googlecode.lanterna.terminal.DefaultTerminalFactory;
import com.googlecode.lanterna.terminal.Terminal;
public class GuiLiveTest {
@Test
void whenStartingAGui_thenWeHaveAGui() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
try (var screen = new TerminalScreen(terminal)) {
screen.startScreen();
var gui = new MultiWindowTextGUI(screen);
gui.updateScreen();
Thread.sleep(5000);
}
}
}
@Test
void whenAddingAMessageDialog_thenTheWindowDisplays() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
try (var screen = new TerminalScreen(terminal)) {
screen.startScreen();
var gui = new MultiWindowTextGUI(screen);
var window = new MessageDialogBuilder()
.setTitle("Message Dialog")
.setText("Dialog Contents")
.build();
gui.addWindow(window);
gui.updateScreen();
Thread.sleep(5000);
}
}
}
@Test
void whenAddingABlankWindow_thenTheWindowDisplays() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
try (var screen = new TerminalScreen(terminal)) {
screen.startScreen();
var gui = new MultiWindowTextGUI(screen);
var window = new BasicWindow("Basic Window");
gui.addWindow(window);
gui.updateScreen();
Thread.sleep(5000);
}
}
}
@Test
void whenChangingTheWindowHints_thenTheWindowDisplaysAsDesired() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
try (var screen = new TerminalScreen(terminal)) {
screen.startScreen();
var gui = new MultiWindowTextGUI(screen);
var window = new BasicWindow("Basic Window");
window.setHints(Set.of(Window.Hint.CENTERED,
Window.Hint.NO_POST_RENDERING,
Window.Hint.EXPANDED));
gui.addWindow(window);
gui.updateScreen();
Thread.sleep(5000);
}
}
}
@Test
void whenAddingALabel_thenTheLabelDisplays() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
try (var screen = new TerminalScreen(terminal)) {
screen.startScreen();
var gui = new MultiWindowTextGUI(screen);
var window = new BasicWindow("Basic Window");
window.setComponent(new Label("This is a label"));
gui.addWindow(window);
gui.updateScreen();
Thread.sleep(5000);
}
}
}
@Test
void whenAddingMultipleLabels_thenTheLabelsAreDisplayedCorrectly() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
try (var screen = new TerminalScreen(terminal)) {
screen.startScreen();
var gui = new MultiWindowTextGUI(screen);
var window = new BasicWindow("Basic Window");
var innerPanel = new Panel(new LinearLayout(Direction.HORIZONTAL));
innerPanel.addComponent(new Label("Left"));
innerPanel.addComponent(new Label("Middle"));
innerPanel.addComponent(new Label("Right"));
var outerPanel = new Panel(new LinearLayout(Direction.VERTICAL));
outerPanel.addComponent(new Label("Top"));
outerPanel.addComponent(innerPanel);
outerPanel.addComponent(new Label("Bottom"));
window.setComponent(outerPanel);
gui.addWindow(window);
gui.updateScreen();
Thread.sleep(5000);
}
}
}
@Test
void whenAddingATextbox_thenTheTextboxCanBeTypedInto() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
try (var screen = new TerminalScreen(terminal)) {
screen.startScreen();
var gui = new MultiWindowTextGUI(screen);
var window = new BasicWindow("Basic Window");
var textbox = new TextBox();
var button = new Button("OK");
button.addListener((b) -> {
System.out.println(textbox.getText());
window.close();
});
var panel = new Panel(new LinearLayout(Direction.VERTICAL));
panel.addComponent(textbox);
panel.addComponent(button);
window.setComponent(panel);
gui.addWindow(window);
gui.updateScreen();
window.waitUntilClosed();
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/lanterna/ScreenLiveTest.java | libraries-4/src/test/java/com/baeldung/lanterna/ScreenLiveTest.java | package com.baeldung.lanterna;
import org.junit.jupiter.api.Test;
import com.googlecode.lanterna.SGR;
import com.googlecode.lanterna.TextCharacter;
import com.googlecode.lanterna.TextColor;
import com.googlecode.lanterna.screen.Screen;
import com.googlecode.lanterna.screen.TerminalScreen;
import com.googlecode.lanterna.terminal.DefaultTerminalFactory;
import com.googlecode.lanterna.terminal.Terminal;
public class ScreenLiveTest {
@Test
void whenWrappingATerminal_thenWeHaveAUsableScreen() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
try (var screen = new TerminalScreen(terminal)) {
screen.startScreen();
Thread.sleep(5000);
}
}
}
@Test
void whenCreatingAScreenDirectly_thenWeHaveAUsableScreen() throws Exception {
try (Screen screen = new DefaultTerminalFactory().createScreen()) {
screen.startScreen();
Thread.sleep(5000);
}
}
@Test
void whenDrawingACharacter_thenTheCharacterAppearsAsDesired() throws Exception {
try (Screen screen = new DefaultTerminalFactory().createScreen()) {
screen.startScreen();
screen.setCharacter(5, 5,
new TextCharacter('!',
TextColor.ANSI.RED, TextColor.ANSI.YELLOW_BRIGHT,
SGR.UNDERLINE, SGR.BOLD));
screen.refresh();
Thread.sleep(5000);
}
}
@Test
void whenDrawingAString_thenTheCharacterAppearsAsDesired() throws Exception {
try (Screen screen = new DefaultTerminalFactory().createScreen()) {
screen.startScreen();
var text = screen.newTextGraphics();
text.setForegroundColor(TextColor.ANSI.RED);
text.setBackgroundColor(TextColor.ANSI.YELLOW_BRIGHT);
text.putString(5, 5, "Hello");
text.putString(6, 6, "World!");
screen.refresh();
Thread.sleep(5000);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/lanterna/TerminalLiveTest.java | libraries-4/src/test/java/com/baeldung/lanterna/TerminalLiveTest.java | package com.baeldung.lanterna;
import org.junit.jupiter.api.Test;
import com.googlecode.lanterna.terminal.DefaultTerminalFactory;
import com.googlecode.lanterna.terminal.Terminal;
public class TerminalLiveTest {
@Test
void whenCreatingADefaultTerminal_thenATerminalIsCreated() throws Exception {
try (Terminal terminal = new DefaultTerminalFactory().createTerminal()) {
terminal.enterPrivateMode();
Thread.sleep(5000);
terminal.exitPrivateMode();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/classgraph/TestAnnotation.java | libraries-4/src/test/java/com/baeldung/classgraph/TestAnnotation.java | package com.baeldung.classgraph;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({TYPE, METHOD, FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
String value() default "";
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/classgraph/ClassWithAnnotation.java | libraries-4/src/test/java/com/baeldung/classgraph/ClassWithAnnotation.java | package com.baeldung.classgraph;
@TestAnnotation
public class ClassWithAnnotation {
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/classgraph/MethodWithAnnotation.java | libraries-4/src/test/java/com/baeldung/classgraph/MethodWithAnnotation.java | package com.baeldung.classgraph;
public class MethodWithAnnotation {
@TestAnnotation
public void service() {
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/classgraph/FieldWithAnnotation.java | libraries-4/src/test/java/com/baeldung/classgraph/FieldWithAnnotation.java | package com.baeldung.classgraph;
public class FieldWithAnnotation {
@TestAnnotation
private String s;
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/classgraph/ClassGraphUnitTest.java | libraries-4/src/test/java/com/baeldung/classgraph/ClassGraphUnitTest.java | package com.baeldung.classgraph;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.util.function.Consumer;
import org.junit.Test;
import io.github.classgraph.AnnotationInfo;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ClassInfoList;
import io.github.classgraph.Resource;
import io.github.classgraph.ResourceList;
import io.github.classgraph.ScanResult;
public class ClassGraphUnitTest {
@Test
public void whenClassAnnotationFilterIsDefined_thenTargetClassesCanBeFound() {
doTest(result -> {
ClassInfoList classInfos = result.getClassesWithAnnotation(TestAnnotation.class.getName());
assertThat(classInfos).extracting(ClassInfo::getName).contains(ClassWithAnnotation.class.getName());
});
}
@Test
public void whenMethodAnnotationFilterIsDefined_thenTargetClassesCanBeFound() {
doTest(result -> {
ClassInfoList classInfos = result.getClassesWithMethodAnnotation(TestAnnotation.class.getName());
assertThat(classInfos).extracting(ClassInfo::getName).contains(MethodWithAnnotation.class.getName());
});
}
@Test
public void whenMethodAnnotationValueFilterIsDefined_thenTargetClassesCanBeFound() {
doTest(result -> {
ClassInfoList classInfos = result.getClassesWithMethodAnnotation(TestAnnotation.class.getName());
ClassInfoList filteredClassInfos = classInfos.filter(classInfo -> {
return classInfo.getMethodInfo().stream().anyMatch(methodInfo -> {
AnnotationInfo annotationInfo = methodInfo.getAnnotationInfo(TestAnnotation.class.getName());
if (annotationInfo == null) {
return false;
}
return "web".equals(annotationInfo.getParameterValues().getValue("value"));
});
});
assertThat(filteredClassInfos)
.extracting(ClassInfo::getName)
.contains(MethodWithAnnotationParameterWeb.class.getName());
});
}
@Test
public void whenFieldAnnotationFilterIsDefined_thenTargetClassesCanBeFound() {
doTest(result -> {
ClassInfoList classInfos = result.getClassesWithFieldAnnotation(TestAnnotation.class.getName());
assertThat(classInfos).extracting(ClassInfo::getName).contains(FieldWithAnnotation.class.getName());
});
}
@Test
public void whenResourceIsUsed_thenItCanBeFoundAndLoaded() throws IOException {
try (ScanResult result = new ClassGraph().whitelistPaths("classgraph").scan()) {
ResourceList resources = result.getResourcesWithExtension("config");
assertThat(resources).extracting(Resource::getPath).containsOnly("classgraph/my.config");
assertThat(resources.get(0).getContentAsString()).isEqualTo("my data");
}
}
private void doTest(Consumer<ScanResult> checker) {
try (ScanResult result = new ClassGraph().enableAllInfo()
.whitelistPackages(getClass().getPackage().getName())
.scan())
{
checker.accept(result);
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/classgraph/MethodWithAnnotationParameterDao.java | libraries-4/src/test/java/com/baeldung/classgraph/MethodWithAnnotationParameterDao.java | package com.baeldung.classgraph;
public class MethodWithAnnotationParameterDao {
@TestAnnotation("dao")
public void service() {
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/classgraph/MethodWithAnnotationParameterWeb.java | libraries-4/src/test/java/com/baeldung/classgraph/MethodWithAnnotationParameterWeb.java | package com.baeldung.classgraph;
public class MethodWithAnnotationParameterWeb {
@TestAnnotation("web")
public void service() {
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/oshi/OSHIUnitTest.java | libraries-4/src/test/java/com/baeldung/oshi/OSHIUnitTest.java | package com.baeldung.oshi;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HWDiskStore;
import oshi.software.os.OperatingSystem;
import org.junit.jupiter.api.Test;
class OSHIUnitTest {
@Test
void givenSystem_whenUsingOSHI_thenExtractOSDetails() {
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
assertNotNull(os, "Operating System object should not be null");
assertNotNull(os.getFamily(), "OS Family should not be null");
assertNotNull(os.getVersionInfo(), "OS Version info should not be null");
assertTrue(os.getBitness() == 32 || os.getBitness() == 64, "OS Bitness should be 32 or 64");
}
@Test
void givenSystem_whenUsingOSHI_thenExtractSystemUptime() {
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
long uptime = os.getSystemUptime();
assertTrue(uptime >= 0, "System uptime should be non-negative");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
fail("Test interrupted");
}
long newUptime = os.getSystemUptime();
assertTrue(newUptime >= uptime, "Uptime should increase over time");
}
@Test
void givenSystem_whenUsingOSHI_thenExtractCPUDetails() {
SystemInfo si = new SystemInfo();
CentralProcessor processor = si.getHardware()
.getProcessor();
assertNotNull(processor, "Processor object should not be null");
assertTrue(processor.getPhysicalProcessorCount() > 0, "CPU must have at least one physical core");
assertTrue(processor.getLogicalProcessorCount() >= processor.getPhysicalProcessorCount(),
"Logical cores should be greater than or equal to physical cores");
}
@Test
void givenSystem_whenUsingOSHI_thenExtractCPULoad() throws InterruptedException {
SystemInfo si = new SystemInfo();
CentralProcessor processor = si.getHardware()
.getProcessor();
long[] prevTicks = processor.getSystemCpuLoadTicks();
TimeUnit.SECONDS.sleep(1);
double cpuLoad = processor.getSystemCpuLoadBetweenTicks(prevTicks) * 100;
assertTrue(cpuLoad >= 0 && cpuLoad <= 100, "CPU load should be between 0% and 100%");
}
@Test
void givenSystem_whenUsingOSHI_thenExtractMemoryDetails() {
SystemInfo si = new SystemInfo();
GlobalMemory memory = si.getHardware()
.getMemory();
assertTrue(memory.getTotal() > 0, "Total memory should be positive");
assertTrue(memory.getAvailable() >= 0, "Available memory should not be negative");
assertTrue(memory.getAvailable() <= memory.getTotal(), "Available memory should not exceed total memory");
}
@Test
void givenSystem_whenUsingOSHI_thenExtractDiskDetails() {
SystemInfo si = new SystemInfo();
List<HWDiskStore> diskStores = si.getHardware()
.getDiskStores();
assertFalse(diskStores.isEmpty(), "There should be at least one disk");
for (HWDiskStore disk : diskStores) {
assertNotNull(disk.getModel(), "Disk model should not be null");
assertTrue(disk.getSize() >= 0, "Disk size should be non-negative");
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/main/java/com/baeldung/crawler4j/ImageCrawlerController.java | libraries-4/src/main/java/com/baeldung/crawler4j/ImageCrawlerController.java | package com.baeldung.crawler4j;
import java.io.File;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class ImageCrawlerController {
public static void main(String[] args) throws Exception {
File crawlStorage = new File("src/test/resources/crawler4j");
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorage.getAbsolutePath());
config.setIncludeBinaryContentInCrawling(true);
config.setMaxPagesToFetch(500);
File saveDir = new File("src/test/resources/crawler4j");
int numCrawlers = 12;
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
controller.addSeed("https://www.baeldung.com/");
CrawlController.WebCrawlerFactory<ImageCrawler> factory = () -> new ImageCrawler(saveDir);
controller.start(factory, numCrawlers);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/main/java/com/baeldung/crawler4j/CrawlerStatistics.java | libraries-4/src/main/java/com/baeldung/crawler4j/CrawlerStatistics.java | package com.baeldung.crawler4j;
public class CrawlerStatistics {
private int processedPageCount = 0;
private int totalLinksCount = 0;
public void incrementProcessedPageCount() {
processedPageCount++;
}
public void incrementTotalLinksCount(int linksCount) {
totalLinksCount += linksCount;
}
public int getProcessedPageCount() {
return processedPageCount;
}
public int getTotalLinksCount() {
return totalLinksCount;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/main/java/com/baeldung/crawler4j/MultipleCrawlerController.java | libraries-4/src/main/java/com/baeldung/crawler4j/MultipleCrawlerController.java | package com.baeldung.crawler4j;
import java.io.File;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class MultipleCrawlerController {
public static void main(String[] args) throws Exception {
File crawlStorageBase = new File("src/test/resources/crawler4j");
CrawlConfig htmlConfig = new CrawlConfig();
CrawlConfig imageConfig = new CrawlConfig();
htmlConfig.setCrawlStorageFolder(new File(crawlStorageBase, "html").getAbsolutePath());
imageConfig.setCrawlStorageFolder(new File(crawlStorageBase, "image").getAbsolutePath());
imageConfig.setIncludeBinaryContentInCrawling(true);
htmlConfig.setMaxPagesToFetch(500);
imageConfig.setMaxPagesToFetch(1000);
PageFetcher pageFetcherHtml = new PageFetcher(htmlConfig);
PageFetcher pageFetcherImage = new PageFetcher(imageConfig);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcherHtml);
CrawlController htmlController = new CrawlController(htmlConfig, pageFetcherHtml, robotstxtServer);
CrawlController imageController = new CrawlController(imageConfig, pageFetcherImage, robotstxtServer);
htmlController.addSeed("https://www.baeldung.com/");
imageController.addSeed("https://www.baeldung.com/");
CrawlerStatistics stats = new CrawlerStatistics();
CrawlController.WebCrawlerFactory<HtmlCrawler> htmlFactory = () -> new HtmlCrawler(stats);
File saveDir = new File("src/test/resources/crawler4j");
CrawlController.WebCrawlerFactory<ImageCrawler> imageFactory = () -> new ImageCrawler(saveDir);
imageController.startNonBlocking(imageFactory, 7);
htmlController.startNonBlocking(htmlFactory, 10);
htmlController.waitUntilFinish();
System.out.printf("Crawled %d pages %n", stats.getProcessedPageCount());
System.out.printf("Total Number of outbound links = %d %n", stats.getTotalLinksCount());
imageController.waitUntilFinish();
System.out.printf("Image Crawler is finished.");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/main/java/com/baeldung/crawler4j/HtmlCrawler.java | libraries-4/src/main/java/com/baeldung/crawler4j/HtmlCrawler.java | package com.baeldung.crawler4j;
import java.util.Set;
import java.util.regex.Pattern;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
public class HtmlCrawler extends WebCrawler {
private final static Pattern EXCLUSIONS = Pattern.compile(".*(\\.(css|js|xml|gif|jpg|png|mp3|mp4|zip|gz|pdf))$");
private CrawlerStatistics stats;
public HtmlCrawler(CrawlerStatistics stats) {
this.stats = stats;
}
@Override
public boolean shouldVisit(Page referringPage, WebURL url) {
String urlString = url.getURL().toLowerCase();
return !EXCLUSIONS.matcher(urlString).matches()
&& urlString.startsWith("https://www.baeldung.com/");
}
@Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
stats.incrementProcessedPageCount();
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String title = htmlParseData.getTitle();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
Set<WebURL> links = htmlParseData.getOutgoingUrls();
stats.incrementTotalLinksCount(links.size());
System.out.printf("Page with title '%s' %n", title);
System.out.printf(" Text length: %d %n", text.length());
System.out.printf(" HTML length: %d %n", html.length());
System.out.printf(" %d outbound links %n", links.size());
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/main/java/com/baeldung/crawler4j/ImageCrawler.java | libraries-4/src/main/java/com/baeldung/crawler4j/ImageCrawler.java | package com.baeldung.crawler4j;
import java.io.File;
import java.util.regex.Pattern;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.BinaryParseData;
import edu.uci.ics.crawler4j.url.WebURL;
public class ImageCrawler extends WebCrawler {
private final static Pattern EXCLUSIONS = Pattern.compile(".*(\\.(css|js|xml|gif|png|mp3|mp4|zip|gz|pdf))$");
private static final Pattern IMG_PATTERNS = Pattern.compile(".*(\\.(jpg|jpeg))$");
private File saveDir;
public ImageCrawler(File saveDir) {
this.saveDir = saveDir;
}
@Override
public boolean shouldVisit(Page referringPage, WebURL url) {
String urlString = url.getURL().toLowerCase();
if (EXCLUSIONS.matcher(urlString).matches()) {
return false;
}
if (IMG_PATTERNS.matcher(urlString).matches()
|| urlString.startsWith("https://www.baeldung.com/")) {
return true;
}
return false;
}
@Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
if (IMG_PATTERNS.matcher(url).matches()
&& page.getParseData() instanceof BinaryParseData) {
String extension = url.substring(url.lastIndexOf("."));
int contentLength = page.getContentData().length;
System.out.printf("Extension is '%s' with content length %d %n", extension, contentLength);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/main/java/com/baeldung/crawler4j/HtmlCrawlerController.java | libraries-4/src/main/java/com/baeldung/crawler4j/HtmlCrawlerController.java | package com.baeldung.crawler4j;
import java.io.File;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class HtmlCrawlerController {
public static void main(String[] args) throws Exception {
File crawlStorage = new File("src/test/resources/crawler4j");
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorage.getAbsolutePath());
config.setMaxDepthOfCrawling(2);
int numCrawlers = 12;
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
controller.addSeed("https://www.baeldung.com/");
CrawlerStatistics stats = new CrawlerStatistics();
CrawlController.WebCrawlerFactory<HtmlCrawler> factory = () -> new HtmlCrawler(stats);
controller.start(factory, numCrawlers);
System.out.printf("Crawled %d pages %n", stats.getProcessedPageCount());
System.out.printf("Total Number of outbound links = %d %n", stats.getTotalLinksCount());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java | spring-di-4/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java | package com.baeldung.dependson.processor;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.dependson.config.TestConfig;
import com.baeldung.dependson.shared.File;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
public class FileProcessorIntegrationTest {
@Autowired
ApplicationContext context;
@Autowired
File file;
@Test
public void whenAllBeansCreated_FileTextEndsWithProcessed() {
context.getBean("fileProcessor");
assertTrue(file.getText().endsWith("processed"));
}
@Test(expected=BeanCreationException.class)
public void whenDependentBeanNotAvailable_ThrowsNoSuchBeanDefinitionException(){
context.getBean("dummyFileProcessor");
}
@Test(expected=BeanCreationException.class)
public void whenCircularDependency_ThrowsBeanCreationException(){
context.getBean("dummyFileReaderCircular");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/dependson/config/TestConfig.java | spring-di-4/src/test/java/com/baeldung/dependson/config/TestConfig.java | package com.baeldung.dependson.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import com.baeldung.dependson.file.processor.FileProcessor;
import com.baeldung.dependson.file.reader.FileReader;
import com.baeldung.dependson.file.writer.FileWriter;
import com.baeldung.dependson.shared.File;
@Configuration
@ComponentScan("com.baeldung.dependson")
public class TestConfig {
@Autowired
File file;
@Bean("fileProcessor")
@DependsOn({"fileReader","fileWriter"})
@Lazy
public FileProcessor fileProcessor(){
return new FileProcessor(file);
}
@Bean("fileReader")
public FileReader fileReader(){
return new FileReader(file);
}
@Bean("fileWriter")
public FileWriter fileWriter(){
return new FileWriter(file);
}
@Bean("dummyFileProcessor")
@DependsOn({"dummyfileWriter"})
@Lazy
public FileProcessor dummyFileProcessor(){
return new FileProcessor(file);
}
@Bean("dummyFileProcessorCircular")
@DependsOn({"dummyFileReaderCircular"})
@Lazy
public FileProcessor dummyFileProcessorCircular(){
return new FileProcessor(file);
}
@Bean("dummyFileReaderCircular")
@DependsOn({"dummyFileProcessorCircular"})
@Lazy
public FileReader dummyFileReaderCircular(){
return new FileReader(file);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/autowiremultipleimplementations/ConditionalDisabledUnitTest.java | spring-di-4/src/test/java/com/baeldung/autowiremultipleimplementations/ConditionalDisabledUnitTest.java | package com.baeldung.autowiremultipleimplementations;
import com.baeldung.autowiremultipleimplementations.candidates.GoodService;
import com.baeldung.autowiremultipleimplementations.candidates.GoodServiceE;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.junit.jupiter.api.Assertions.assertNull;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {GoodServiceE.class})
@TestPropertySource(properties = {"feature.toggle=disabled"})
public class ConditionalDisabledUnitTest {
@Autowired(required = false)
private GoodService goodService;
@Test
void testServiceWhenFeatureDisabled() {
assertNull(goodService, "GoodService should not be autowired when feature.toggle is disabled");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/autowiremultipleimplementations/ProfilesAutowireUnitTest.java | spring-di-4/src/test/java/com/baeldung/autowiremultipleimplementations/ProfilesAutowireUnitTest.java | package com.baeldung.autowiremultipleimplementations;
import com.baeldung.autowiremultipleimplementations.components.PrimaryAutowire;
import com.baeldung.autowiremultipleimplementations.candidates.*;
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.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {PrimaryAutowire.class, GoodServiceD.class, GoodServiceC.class,
GoodServiceB.class, GoodServiceA.class})
@ActiveProfiles("dev")
public class ProfilesAutowireUnitTest {
@Autowired
private GoodService goodService;
@Test
public void goodServiceDIsAutowiredCorrectly() {
assertNotNull(goodService, "GoodService should be autowired");
assertInstanceOf(GoodServiceD.class, goodService,
"Autowired GoodService should be an instance of GoodServiceD under 'dev' profile");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/autowiremultipleimplementations/PrimaryAutowireUnitTest.java | spring-di-4/src/test/java/com/baeldung/autowiremultipleimplementations/PrimaryAutowireUnitTest.java | package com.baeldung.autowiremultipleimplementations;
import com.baeldung.autowiremultipleimplementations.components.PrimaryAutowire;
import com.baeldung.autowiremultipleimplementations.candidates.GoodService;
import com.baeldung.autowiremultipleimplementations.candidates.GoodServiceA;
import com.baeldung.autowiremultipleimplementations.candidates.GoodServiceB;
import com.baeldung.autowiremultipleimplementations.candidates.GoodServiceC;
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.context.ApplicationContext;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(classes = {PrimaryAutowire.class, GoodServiceC.class, GoodServiceB.class, GoodServiceA.class})
@ExtendWith(SpringExtension.class)
public class PrimaryAutowireUnitTest {
@Autowired
private ApplicationContext context;
@Autowired
private PrimaryAutowire primaryAutowire;
@Test
public void whenPrimaryServiceInjected_thenItShouldBeGoodServiceC() {
GoodService injectedService = context.getBean(GoodService.class);
assertInstanceOf(GoodServiceC.class, injectedService);
String expectedMessage = "Hello from C!"; // GoodServiceC returns this message
String actualMessage = primaryAutowire.hello();
assertEquals(expectedMessage, actualMessage);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/autowiremultipleimplementations/ConditionalEnabledUnitTest.java | spring-di-4/src/test/java/com/baeldung/autowiremultipleimplementations/ConditionalEnabledUnitTest.java | package com.baeldung.autowiremultipleimplementations;
import com.baeldung.autowiremultipleimplementations.candidates.GoodService;
import com.baeldung.autowiremultipleimplementations.candidates.GoodServiceE;
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.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {GoodServiceE.class})
@TestPropertySource(properties = {"feature.toggle=enabled"})
public class ConditionalEnabledUnitTest {
@Autowired
private GoodService goodService;
@Test
void testServiceWhenFeatureEnabled() {
assertNotNull(goodService, "GoodService should be autowired when feature.toggle is enabled");
assertInstanceOf(GoodServiceE.class, goodService, "goodService should be an instance of GoodServiceE");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/autowiremultipleimplementations/CollectionsAutowireUnitTest.java | spring-di-4/src/test/java/com/baeldung/autowiremultipleimplementations/CollectionsAutowireUnitTest.java | package com.baeldung.autowiremultipleimplementations;
import com.baeldung.autowiremultipleimplementations.components.CollectionsAutowire;
import com.baeldung.autowiremultipleimplementations.candidates.*;
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.test.context.junit.jupiter.SpringExtension;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {CollectionsAutowire.class, GoodServiceD.class, GoodServiceC.class, GoodServiceB.class, GoodServiceA.class})
public class CollectionsAutowireUnitTest {
@Autowired
private CollectionsAutowire collectionsAutowire;
@Test
public void testSetAutowiring() throws NoSuchFieldException, IllegalAccessException {
Set<?> rawServices = (Set<?>) getPrivateField(collectionsAutowire, "goodServices");
assertNotNull(rawServices, "Set of GoodService should not be null");
assertFalse(rawServices.isEmpty(), "Set of GoodService should not be empty");
Set<GoodService> services = rawServices.stream()
.map(service -> (GoodService) service)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
// Check for all specific types
assertTrue(services.stream().anyMatch(s -> s instanceof GoodServiceA), "Should contain GoodServiceA");
assertTrue(services.stream().anyMatch(s -> s instanceof GoodServiceB), "Should contain GoodServiceB");
assertTrue(services.stream().anyMatch(s -> s instanceof GoodServiceC), "Should contain GoodServiceC");
String actualMessage = collectionsAutowire.hello();
assertTrue(actualMessage.contains("Hello from A!"), "Message should contain greeting from A");
assertTrue(actualMessage.contains("Hello from B!"), "Message should contain greeting from B");
assertTrue(actualMessage.contains("Hello from C!"), "Message should contain greeting from C");
}
@Test
public void testMapAutowiring() throws NoSuchFieldException, IllegalAccessException {
Map<?, ?> rawServiceMap = (Map<?, ?>) getPrivateField(collectionsAutowire, "goodServiceMap");
assertNotNull(rawServiceMap, "Map of GoodService should not be null");
assertFalse(rawServiceMap.isEmpty(), "Map of GoodService should not be empty");
Map<String, GoodService> serviceMap = rawServiceMap.entrySet().stream()
.collect(Collectors.toMap(
entry -> (String) entry.getKey(),
entry -> (GoodService) entry.getValue()
));
// Check keys and specific instances
assertTrue(serviceMap.containsKey("goodServiceA"), "Map should contain a key for GoodServiceA");
assertTrue(serviceMap.containsKey("goodServiceB"), "Map should contain a key for GoodServiceB");
assertTrue(serviceMap.containsKey("goodServiceC"), "Map should contain a key for GoodServiceC");
assertInstanceOf(GoodServiceA.class, serviceMap.get("goodServiceA"), "goodServiceA should be an instance of GoodServiceA");
assertInstanceOf(GoodServiceB.class, serviceMap.get("goodServiceB"), "goodServiceB should be an instance of GoodServiceB");
assertInstanceOf(GoodServiceC.class, serviceMap.get("goodServiceC"), "goodServiceC should be an instance of GoodServiceC");
}
private Object getPrivateField(Object object, String fieldName) throws NoSuchFieldException, IllegalAccessException {
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(object);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/autowiremultipleimplementations/QualifierAutowireUnitTest.java | spring-di-4/src/test/java/com/baeldung/autowiremultipleimplementations/QualifierAutowireUnitTest.java | package com.baeldung.autowiremultipleimplementations;
import com.baeldung.autowiremultipleimplementations.components.QualifierAutowire;
import com.baeldung.autowiremultipleimplementations.candidates.GoodService;
import com.baeldung.autowiremultipleimplementations.candidates.GoodServiceA;
import com.baeldung.autowiremultipleimplementations.candidates.GoodServiceB;
import com.baeldung.autowiremultipleimplementations.candidates.GoodServiceC;
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.test.context.junit.jupiter.SpringExtension;
import java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(classes = {QualifierAutowire.class, GoodServiceC.class, GoodServiceB.class, GoodServiceA.class})
@ExtendWith(SpringExtension.class)
public class QualifierAutowireUnitTest {
@Autowired
private QualifierAutowire qualifierAutowire;
@Test
public void testAutowiring() throws NoSuchFieldException, IllegalAccessException {
assertNotNull(qualifierAutowire, "QualifierAutowire should be autowired");
GoodService goodServiceA = getGoodServiceField("goodServiceA");
GoodService goodServiceB = getGoodServiceField("goodServiceB");
GoodService goodServiceC = getGoodServiceField("goodServiceC");
// Verify the types of the autowired services
assertInstanceOf(GoodServiceA.class, goodServiceA, "goodServiceA should be an instance of GoodServiceA");
assertInstanceOf(GoodServiceB.class, goodServiceB, "goodServiceB should be an instance of GoodServiceB");
assertInstanceOf(GoodServiceC.class, goodServiceC, "goodServiceC should be an instance of GoodServiceC");
// Check that the hello message is as expected
String expectedMessage = "Hello from A! Hello from B! Hello from C!";
String actualMessage = qualifierAutowire.hello();
assertEquals(expectedMessage, actualMessage, "Messages should be concatenated correctly from all services");
}
private GoodService getGoodServiceField(String fieldName) throws NoSuchFieldException, IllegalAccessException {
Field field = qualifierAutowire.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return (GoodService) field.get(qualifierAutowire);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/order/RatingRetrieverUnitTest.java | spring-di-4/src/test/java/com/baeldung/order/RatingRetrieverUnitTest.java | package com.baeldung.order;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class RatingRetrieverUnitTest {
@Configuration
@ComponentScan(basePackages = {"com.baeldung.order"})
static class ContextConfiguration {}
@Autowired
private List<Rating> ratings;
@Test
public void givenOrderOnComponents_whenInjected_thenAutowireByOrderValue() {
assertThat(ratings.get(0).getRating(), is(equalTo(1)));
assertThat(ratings.get(1).getRating(), is(equalTo(2)));
assertThat(ratings.get(2).getRating(), is(equalTo(3)));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/nullablebean/NullableXMLComponentUnitTest.java | spring-di-4/src/test/java/com/baeldung/nullablebean/NullableXMLComponentUnitTest.java | package com.baeldung.nullablebean;
import static org.junit.jupiter.api.Assertions.*;
import com.baeldung.nullablebean.nonrequired.NonRequiredConfiguration;
import com.baeldung.nullablebean.nonrequired.NonRequiredMainComponent;
import com.baeldung.nullablebean.nullablejava.NullableJavaConfiguration;
import com.baeldung.nullablebean.nullablejava.NullableMainComponent;
import com.baeldung.nullablebean.nullablespring.NullableConfiguration;
import com.baeldung.nullablebean.nullablespring.NullableSupplierConfiguration;
import com.baeldung.nullablebean.optionable.OptionableConfiguration;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class NullableXMLComponentUnitTest {
@Test
void givenContextWhenCreatingNullableMainComponentThenSubComponentIsNull() {
final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
NullableJavaConfiguration.class);
final NullableMainComponent bean = context.getBean(NullableMainComponent.class);
assertNull(bean.getSubComponent());
}
@Test
void givenNonRequiredContextWhenCreatingMainComponentThenSubComponentIsNull() {
final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
NonRequiredConfiguration.class);
final NonRequiredMainComponent bean = context.getBean(NonRequiredMainComponent.class);
assertNull(bean.getSubComponent());
}
@Test
void givenOptionableContextWhenCreatingMainComponentThenSubComponentIsNull() {
final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
OptionableConfiguration.class);
final MainComponent bean = context.getBean(MainComponent.class);
assertNull(bean.getSubComponent());
}
@Test
void givenNullableSupplierContextWhenCreatingMainComponentThenSubComponentIsNull() {
final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
NullableSupplierConfiguration.class);
final MainComponent bean = context.getBean(MainComponent.class);
assertNull(bean.getSubComponent());
}
@Test
void givenNullableContextWhenCreatingMainComponentThenSubComponentIsNull() {
assertThrows(UnsatisfiedDependencyException.class, () -> new AnnotationConfigApplicationContext(
NullableConfiguration.class));
}
@Test
void givenNullableXMLContextWhenCreatingMainComponentThenSubComponentIsNull() {
final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"nullable-application-context.xml");
final MainComponent bean = context.getBean(MainComponent.class);
assertNull(bean.getSubComponent());
}
@Test
void givenNullableSpELXMLContextWhenCreatingMainComponentThenSubComponentIsNull() {
final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"nullable-spel-application-context.xml");
final MainComponent bean = context.getBean(MainComponent.class);
assertNull(bean.getSubComponent());
}
@Test
void givenNullableSpELXMLContextWithNullablePropertiesWhenCreatingMainComponentThenSubComponentIsNull() {
final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"nullable-configurable-spel-application-context.xml");
final MainComponent bean = context.getBean(MainComponent.class);
assertNull(bean.getSubComponent());
}
@Test
void givenNullableSpELXMLContextWithNonNullablePropertiesWhenCreatingMainComponentThenSubComponentIsNull() {
final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"non-nullable-configurable-spel-application-context.xml");
final MainComponent bean = context.getBean(MainComponent.class);
assertNotNull(bean.getSubComponent());
}
@Test
void givenXMLContextWhenCreatingMainComponentThenSubComponentNotNull() {
final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"non-nullable-application-context.xml");
final MainComponent bean = context.getBean(MainComponent.class);
assertNotNull(bean.getSubComponent());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/registrypostprocessor/ApiClientConfigurationUnitTest.java | spring-di-4/src/test/java/com/baeldung/registrypostprocessor/ApiClientConfigurationUnitTest.java | package com.baeldung.registrypostprocessor;
import com.baeldung.registrypostprocessor.bean.ApiClient;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
@SpringBootTest(classes = RegistryPostProcessorApplication.class)
public class ApiClientConfigurationUnitTest {
@Autowired
private ApplicationContext context;
@Test
void givenBeansRegistered_whenConnect_thenConnected() {
ApiClient exampleClient = (ApiClient) context.getBean("apiClient_example");
Assertions.assertEquals("Connecting to example at https://api.example.com", exampleClient.getConnectionProperties());
ApiClient anotherExampleClient = (ApiClient) context.getBean("apiClient_anotherexample");
Assertions.assertEquals("Connecting to anotherexample at https://api.anotherexample.com", anotherExampleClient.getConnectionProperties());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/prototypebean/dynamicarguments/DynamicBeanUnitTest.java | spring-di-4/src/test/java/com/baeldung/prototypebean/dynamicarguments/DynamicBeanUnitTest.java | package com.baeldung.prototypebean.dynamicarguments;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import junit.framework.Assert;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = EmployeeConfig.class)
public class DynamicBeanUnitTest {
@Test
public void givenPrototypeBean_WhenFunction_ThenNewInstanceReturn() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(EmployeeConfig.class);
EmployeeBeanUsingFunction firstContext = context.getBean(EmployeeBeanUsingFunction.class);
EmployeeBeanUsingFunction secondContext = context.getBean(EmployeeBeanUsingFunction.class);
Employee firstInstance = firstContext.getEmployee("sachin");
Employee secondInstance = secondContext.getEmployee("kumar");
Assert.assertTrue(firstInstance != secondInstance);
}
@Test
public void givenPrototypeBean_WhenLookup_ThenNewInstanceReturn() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(EmployeeConfig.class);
EmployeeBeanUsingLookUp firstContext = context.getBean(EmployeeBeanUsingLookUp.class);
EmployeeBeanUsingLookUp secondContext = context.getBean(EmployeeBeanUsingLookUp.class);
Employee firstInstance = firstContext.getEmployee("sachin");
Employee secondInstance = secondContext.getEmployee("kumar");
Assert.assertTrue(firstInstance != secondInstance);
}
@Test
public void givenPrototypeBean_WhenObjectProvider_ThenNewInstanceReturn() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(EmployeeConfig.class);
EmployeeBeanUsingObjectProvider firstContext = context.getBean(EmployeeBeanUsingObjectProvider.class);
EmployeeBeanUsingObjectProvider secondContext = context.getBean(EmployeeBeanUsingObjectProvider.class);
Employee firstInstance = firstContext.getEmployee("sachin");
Employee secondInstance = secondContext.getEmployee("kumar");
Assert.assertTrue(firstInstance != secondInstance);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/test/java/com/baeldung/fieldinjection/EmailServiceUnitTest.java | spring-di-4/src/test/java/com/baeldung/fieldinjection/EmailServiceUnitTest.java | package com.baeldung.fieldinjection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class EmailServiceUnitTest {
private EmailValidator emailValidator;
private EmailService emailService;
@BeforeEach
public void setup() {
this.emailValidator = Mockito.mock(EmailValidator.class);
this.emailService = new EmailService(emailValidator);
}
@Test
void givenInvalidEmail_whenProcess_thenThrowException() {
String email = "testbaeldung.com";
when(emailValidator.isValid(email)).thenReturn(false);
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> emailService.process(email));
assertNotNull(exception);
assertEquals(EmailService.INVALID_EMAIL, exception.getMessage());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/dependson/DriverApplication.java | spring-di-4/src/main/java/com/baeldung/dependson/DriverApplication.java | package com.baeldung.dependson;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.baeldung.dependson.config.Config;
import com.baeldung.dependson.file.processor.FileProcessor;
public class DriverApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
ctx.getBean(FileProcessor.class);
ctx.close();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/dependson/file/writer/FileWriter.java | spring-di-4/src/main/java/com/baeldung/dependson/file/writer/FileWriter.java | package com.baeldung.dependson.file.writer;
import com.baeldung.dependson.shared.File;
public class FileWriter {
public FileWriter(File file){
file.setText("write");
}
public void writeFile(){}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/dependson/file/processor/FileProcessor.java | spring-di-4/src/main/java/com/baeldung/dependson/file/processor/FileProcessor.java | package com.baeldung.dependson.file.processor;
import org.springframework.beans.factory.annotation.Autowired;
import com.baeldung.dependson.file.reader.FileReader;
import com.baeldung.dependson.file.writer.FileWriter;
import com.baeldung.dependson.shared.File;
public class FileProcessor {
File file;
public FileProcessor(File file){
this.file = file;
if(file.getText().contains("write") && file.getText().contains("read")){
file.setText("processed");
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/dependson/file/reader/FileReader.java | spring-di-4/src/main/java/com/baeldung/dependson/file/reader/FileReader.java | package com.baeldung.dependson.file.reader;
import com.baeldung.dependson.shared.File;
public class FileReader {
public FileReader(File file) {
file.setText("read");
}
public void readFile() {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/dependson/config/Config.java | spring-di-4/src/main/java/com/baeldung/dependson/config/Config.java | package com.baeldung.dependson.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import com.baeldung.dependson.file.processor.FileProcessor;
import com.baeldung.dependson.file.reader.FileReader;
import com.baeldung.dependson.file.writer.FileWriter;
import com.baeldung.dependson.shared.File;
@Configuration
@ComponentScan("com.baeldung.dependson")
public class Config {
@Autowired
File file;
@Bean("fileProcessor")
@DependsOn({"fileReader","fileWriter"})
@Lazy
public FileProcessor fileProcessor(){
return new FileProcessor(file);
}
@Bean("fileReader")
public FileReader fileReader(){
return new FileReader(file);
}
@Bean("fileWriter")
public FileWriter fileWriter(){
return new FileWriter(file);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/dependson/shared/File.java | spring-di-4/src/main/java/com/baeldung/dependson/shared/File.java | package com.baeldung.dependson.shared;
import org.springframework.stereotype.Service;
@Service
public class File {
private String text = "";
public String getText() {
return text;
}
public void setText(String text) {
this.text = this.text+text;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/components/QualifierAutowire.java | spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/components/QualifierAutowire.java | package com.baeldung.autowiremultipleimplementations.components;
import com.baeldung.autowiremultipleimplementations.candidates.GoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class QualifierAutowire {
private final GoodService goodServiceA;
private final GoodService goodServiceB;
private final GoodService goodServiceC;
@Autowired
public QualifierAutowire(@Qualifier("goodServiceA-custom-name") GoodService niceServiceA,
@Qualifier("goodServiceB") GoodService niceServiceB,
GoodService goodServiceC) {
this.goodServiceA = niceServiceA;
this.goodServiceB = niceServiceB;
this.goodServiceC = goodServiceC;
}
public String hello() {
return goodServiceA.getHelloMessage() + " " +
goodServiceB.getHelloMessage() + " " +
goodServiceC.getHelloMessage();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/components/PrimaryAutowire.java | spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/components/PrimaryAutowire.java | package com.baeldung.autowiremultipleimplementations.components;
import com.baeldung.autowiremultipleimplementations.candidates.GoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class PrimaryAutowire {
private final GoodService goodService;
@Autowired
public PrimaryAutowire(GoodService goodService) {
this.goodService = goodService;
}
public String hello() {
return goodService.getHelloMessage();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/components/CollectionsAutowire.java | spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/components/CollectionsAutowire.java | package com.baeldung.autowiremultipleimplementations.components;
import com.baeldung.autowiremultipleimplementations.candidates.GoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.Set;
@Component
public class CollectionsAutowire {
private final Set<GoodService> goodServices;
private final Map<String, GoodService> goodServiceMap;
@Autowired
public CollectionsAutowire(Set<GoodService> goodServices, Map<String, GoodService> goodServiceMap) {
this.goodServices = goodServices;
this.goodServiceMap = goodServiceMap;
}
public String hello() {
return goodServices.stream()
.map(GoodService::getHelloMessage)
.reduce((a, b) -> a + " " + b)
.orElse("No services available");
}
public String helloMap() {
return goodServiceMap.values().stream()
.map(GoodService::getHelloMessage)
.reduce((a, b) -> a + " " + b)
.orElse("No services available");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/candidates/GoodServiceA.java | spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/candidates/GoodServiceA.java | package com.baeldung.autowiremultipleimplementations.candidates;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
@Service
@Profile("default")
@Qualifier("goodServiceA-custom-name")
@Order(3)
public class GoodServiceA implements GoodService {
@Override
public String getHelloMessage() {
return "Hello from A!";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/candidates/GoodServiceC.java | spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/candidates/GoodServiceC.java | package com.baeldung.autowiremultipleimplementations.candidates;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
@Primary
@Service
@Profile("default")
@Order(1)
public class GoodServiceC implements GoodService {
@Override
public String getHelloMessage() {
return "Hello from C!";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/candidates/GoodService.java | spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/candidates/GoodService.java | package com.baeldung.autowiremultipleimplementations.candidates;
public interface GoodService {
String getHelloMessage();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/candidates/GoodServiceD.java | spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/candidates/GoodServiceD.java | package com.baeldung.autowiremultipleimplementations.candidates;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@Service
@Profile("dev")
public class GoodServiceD implements GoodService {
public String getHelloMessage() {
return "Hello from D!";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/candidates/GoodServiceB.java | spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/candidates/GoodServiceB.java | package com.baeldung.autowiremultipleimplementations.candidates;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
@Service
@Profile("default")
@Order(2)
public class GoodServiceB implements GoodService {
@Override
public String getHelloMessage() {
return "Hello from B!";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/candidates/GoodServiceE.java | spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/candidates/GoodServiceE.java | package com.baeldung.autowiremultipleimplementations.candidates;
import com.baeldung.autowiremultipleimplementations.condition.OnFeatureEnabledCondition;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Service;
@Service
@Conditional(OnFeatureEnabledCondition.class)
public class GoodServiceE implements GoodService {
public String getHelloMessage() {
return "Hello from E!";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/condition/OnFeatureEnabledCondition.java | spring-di-4/src/main/java/com/baeldung/autowiremultipleimplementations/condition/OnFeatureEnabledCondition.java | package com.baeldung.autowiremultipleimplementations.condition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class OnFeatureEnabledCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String featureToggle = context.getEnvironment().getProperty("feature.toggle");
return "enabled".equalsIgnoreCase(featureToggle);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/order/Excellent.java | spring-di-4/src/main/java/com/baeldung/order/Excellent.java | package com.baeldung.order;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(1)
public class Excellent implements Rating {
@Override
public int getRating() {
return 1;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/order/Good.java | spring-di-4/src/main/java/com/baeldung/order/Good.java | package com.baeldung.order;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(2)
public class Good implements Rating {
@Override
public int getRating() {
return 2;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/order/Average.java | spring-di-4/src/main/java/com/baeldung/order/Average.java | package com.baeldung.order;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(Ordered.LOWEST_PRECEDENCE)
public class Average implements Rating {
@Override
public int getRating() {
return 3;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/order/Rating.java | spring-di-4/src/main/java/com/baeldung/order/Rating.java | package com.baeldung.order;
public interface Rating {
int getRating();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/nullablebean/MainComponent.java | spring-di-4/src/main/java/com/baeldung/nullablebean/MainComponent.java | package com.baeldung.nullablebean;
import org.springframework.stereotype.Component;
@Component
public class MainComponent {
private SubComponent subComponent;
public MainComponent(final SubComponent subComponent) {
this.subComponent = subComponent;
}
public SubComponent getSubComponent() {
return subComponent;
}
public void setSubComponent(final SubComponent subComponent) {
this.subComponent = subComponent;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/nullablebean/SubComponent.java | spring-di-4/src/main/java/com/baeldung/nullablebean/SubComponent.java | package com.baeldung.nullablebean;
import org.springframework.stereotype.Component;
@Component
public class SubComponent {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/nullablebean/nonrequired/NonRequiredMainComponent.java | spring-di-4/src/main/java/com/baeldung/nullablebean/nonrequired/NonRequiredMainComponent.java | package com.baeldung.nullablebean.nonrequired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class NonRequiredMainComponent {
@Autowired(required = false)
private NonRequiredSubComponent subComponent;
public NonRequiredSubComponent getSubComponent() {
return subComponent;
}
public void setSubComponent(final NonRequiredSubComponent subComponent) {
this.subComponent = subComponent;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/nullablebean/nonrequired/NonRequiredConfiguration.java | spring-di-4/src/main/java/com/baeldung/nullablebean/nonrequired/NonRequiredConfiguration.java | package com.baeldung.nullablebean.nonrequired;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
public class NonRequiredConfiguration {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/nullablebean/nonrequired/NonRequiredSubComponent.java | spring-di-4/src/main/java/com/baeldung/nullablebean/nonrequired/NonRequiredSubComponent.java | package com.baeldung.nullablebean.nonrequired;
public class NonRequiredSubComponent {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/nullablebean/nullablespring/NullableConfiguration.java | spring-di-4/src/main/java/com/baeldung/nullablebean/nullablespring/NullableConfiguration.java | package com.baeldung.nullablebean.nullablespring;
import com.baeldung.nullablebean.MainComponent;
import com.baeldung.nullablebean.SubComponent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class NullableConfiguration {
@Bean
public MainComponent mainComponent(SubComponent subComponent) {
return new MainComponent(subComponent);
}
@Bean
public SubComponent subComponent() {
return null;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/nullablebean/nullablespring/NullableSupplierConfiguration.java | spring-di-4/src/main/java/com/baeldung/nullablebean/nullablespring/NullableSupplierConfiguration.java | package com.baeldung.nullablebean.nullablespring;
import com.baeldung.nullablebean.MainComponent;
import com.baeldung.nullablebean.SubComponent;
import java.util.function.Supplier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class NullableSupplierConfiguration {
@Bean
public MainComponent mainComponent(Supplier<SubComponent> subComponentSupplier) {
return new MainComponent(subComponentSupplier.get());
}
@Bean
public Supplier<SubComponent> subComponentSupplier() {
return () -> null;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/nullablebean/optionable/OptionableConfiguration.java | spring-di-4/src/main/java/com/baeldung/nullablebean/optionable/OptionableConfiguration.java | package com.baeldung.nullablebean.optionable;
import com.baeldung.nullablebean.MainComponent;
import com.baeldung.nullablebean.SubComponent;
import java.util.Optional;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OptionableConfiguration {
@Bean
public MainComponent mainComponent(Optional<SubComponent> optionalSubComponent) {
return new MainComponent(optionalSubComponent.orElse(null));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/nullablebean/nullablejava/NullableMainComponent.java | spring-di-4/src/main/java/com/baeldung/nullablebean/nullablejava/NullableMainComponent.java | package com.baeldung.nullablebean.nullablejava;
import jakarta.annotation.Nullable;
import org.springframework.stereotype.Component;
@Component
public class NullableMainComponent {
private NullableSubComponent subComponent;
public NullableMainComponent(final @Nullable NullableSubComponent subComponent) {
this.subComponent = subComponent;
}
public NullableSubComponent getSubComponent() {
return subComponent;
}
public void setSubComponent(final NullableSubComponent subComponent) {
this.subComponent = subComponent;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/nullablebean/nullablejava/NullableJavaConfiguration.java | spring-di-4/src/main/java/com/baeldung/nullablebean/nullablejava/NullableJavaConfiguration.java | package com.baeldung.nullablebean.nullablejava;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class NullableJavaConfiguration {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/nullablebean/nullablejava/NullableSubComponent.java | spring-di-4/src/main/java/com/baeldung/nullablebean/nullablejava/NullableSubComponent.java | package com.baeldung.nullablebean.nullablejava;
public class NullableSubComponent {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/registrypostprocessor/RegistryPostProcessorApplication.java | spring-di-4/src/main/java/com/baeldung/registrypostprocessor/RegistryPostProcessorApplication.java | package com.baeldung.registrypostprocessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.ConfigurableEnvironment;
@SpringBootApplication
public class RegistryPostProcessorApplication {
public static void main(String[] args) {
SpringApplication.run(RegistryPostProcessorApplication.class, args);
}
@Bean
public ApiClientConfiguration apiClientConfiguration(ConfigurableEnvironment environment) {
return new ApiClientConfiguration(environment);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/registrypostprocessor/ApiClientConfiguration.java | spring-di-4/src/main/java/com/baeldung/registrypostprocessor/ApiClientConfiguration.java | package com.baeldung.registrypostprocessor;
import com.baeldung.registrypostprocessor.bean.ApiClient;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;
import java.util.HashMap;
import java.util.List;
public class ApiClientConfiguration implements BeanDefinitionRegistryPostProcessor {
private static final String API_CLIENT_BEAN_NAME = "apiClient_";
List<ApiClient> clients;
public ApiClientConfiguration(Environment environment) {
Binder binder = Binder.get(environment);
List<HashMap> properties = binder.bind("api.clients", Bindable.listOf(HashMap.class)).get();
clients = properties.stream().map(client -> new ApiClient(String.valueOf(client.get("name")),
String.valueOf(client.get("url")), String.valueOf(client.get("key")))).toList();
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
clients.forEach(client -> {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ApiClient.class);
builder.addPropertyValue("name", client.getName());
builder.addPropertyValue("url", client.getUrl());
builder.addPropertyValue("key", client.getKey());
registry.registerBeanDefinition(API_CLIENT_BEAN_NAME + client.getName(), builder.getBeanDefinition());
});
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/registrypostprocessor/bean/ApiClient.java | spring-di-4/src/main/java/com/baeldung/registrypostprocessor/bean/ApiClient.java | package com.baeldung.registrypostprocessor.bean;
public class ApiClient {
private String name;
private String url;
private String key;
public ApiClient(String name, String url, String key) {
this.name = name;
this.url = url;
this.key = key;
}
public ApiClient() {
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public String getKey() {
return key;
}
public String getConnectionProperties() {
return "Connecting to " + name + " at " + url;
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public void setKey(String key) {
this.key = key;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/prototypebean/dynamicarguments/Employee.java | spring-di-4/src/main/java/com/baeldung/prototypebean/dynamicarguments/Employee.java | package com.baeldung.prototypebean.dynamicarguments;
public class Employee {
private String name;
public Employee() {
}
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void printName() {
System.out.println(name);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/prototypebean/dynamicarguments/EmployeeConfig.java | spring-di-4/src/main/java/com/baeldung/prototypebean/dynamicarguments/EmployeeConfig.java | package com.baeldung.prototypebean.dynamicarguments;
import org.springframework.cglib.core.internal.Function;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
@ComponentScan(basePackages = { "com.baeldung.prototypebean.dynamicarguments" })
public class EmployeeConfig {
@Bean
@Scope(value = "prototype")
public Employee getEmployee(String name) {
return new Employee(name);
}
@Bean
public EmployeeBeanUsingObjectProvider employeeBeanUsingObjectProvider() {
return new EmployeeBeanUsingObjectProvider();
}
@Bean
public EmployeeBeanUsingObjectFactory employeeBeanUsingObjectFactory() {
return new EmployeeBeanUsingObjectFactory();
}
@Bean
public Function<String, Employee> beanFactory() {
return name -> getEmployee(name);
}
@Bean
public EmployeeBeanUsingFunction employeeBeanUsingFunction() {
return new EmployeeBeanUsingFunction();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/prototypebean/dynamicarguments/EmployeeBeanUsingLookUp.java | spring-di-4/src/main/java/com/baeldung/prototypebean/dynamicarguments/EmployeeBeanUsingLookUp.java | package com.baeldung.prototypebean.dynamicarguments;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;
@Component
public class EmployeeBeanUsingLookUp {
@Lookup
public Employee getEmployee(String arg) {
return null;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/prototypebean/dynamicarguments/EmployeeBeanUsingFunction.java | spring-di-4/src/main/java/com/baeldung/prototypebean/dynamicarguments/EmployeeBeanUsingFunction.java | package com.baeldung.prototypebean.dynamicarguments;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.internal.Function;
import org.springframework.stereotype.Component;
@Component
public class EmployeeBeanUsingFunction {
@Autowired
private Function<String, Employee> beanFactory;
public Employee getEmployee(String name) {
Employee employee = beanFactory.apply(name);
return employee;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/prototypebean/dynamicarguments/EmployeeBeanUsingObjectProvider.java | spring-di-4/src/main/java/com/baeldung/prototypebean/dynamicarguments/EmployeeBeanUsingObjectProvider.java | package com.baeldung.prototypebean.dynamicarguments;
import org.springframework.beans.factory.annotation.Autowired;
public class EmployeeBeanUsingObjectProvider {
@Autowired
private org.springframework.beans.factory.ObjectProvider<Employee> objectProvider;
public Employee getEmployee(String name) {
Employee employee = objectProvider.getObject(name);
return employee;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/prototypebean/dynamicarguments/EmployeeBeanUsingObjectFactory.java | spring-di-4/src/main/java/com/baeldung/prototypebean/dynamicarguments/EmployeeBeanUsingObjectFactory.java | package com.baeldung.prototypebean.dynamicarguments;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class EmployeeBeanUsingObjectFactory {
@Autowired
private ObjectFactory<Employee> employeeObjectFactory;
public Employee getEmployee() {
return employeeObjectFactory.getObject();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/fieldinjection/EmailValidator.java | spring-di-4/src/main/java/com/baeldung/fieldinjection/EmailValidator.java | package com.baeldung.fieldinjection;
import org.springframework.stereotype.Component;
import java.util.regex.Pattern;
@Component
public class EmailValidator {
private static final String REGEX_PATTERN = "^(.+)@(\\S+)$";
public boolean isValid(final String email) {
return Pattern.compile(REGEX_PATTERN)
.matcher(email)
.matches();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/fieldinjection/EmailService.java | spring-di-4/src/main/java/com/baeldung/fieldinjection/EmailService.java | package com.baeldung.fieldinjection;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
public static final String INVALID_EMAIL = "Invalid email";
private final EmailValidator emailValidator;
public EmailService(final EmailValidator emailValidator) {
this.emailValidator = emailValidator;
}
public void process(String email) {
if (!emailValidator.isValid(email)) {
throw new IllegalArgumentException(INVALID_EMAIL);
}
// ...
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/sampleabstract/LogRepository.java | spring-di-4/src/main/java/com/baeldung/sampleabstract/LogRepository.java | package com.baeldung.sampleabstract;
import org.springframework.stereotype.Component;
@Component
public class LogRepository {
@Override
public String toString() {
return "logRepository";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/sampleabstract/BasketballService.java | spring-di-4/src/main/java/com/baeldung/sampleabstract/BasketballService.java | package com.baeldung.sampleabstract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BasketballService extends BallService {
@Autowired
public BasketballService(RuleRepository ruleRepository) {
super(ruleRepository);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/sampleabstract/RuleRepository.java | spring-di-4/src/main/java/com/baeldung/sampleabstract/RuleRepository.java | package com.baeldung.sampleabstract;
import org.springframework.stereotype.Component;
@Component
public class RuleRepository {
@Override
public String toString() {
return "ruleRepository";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/sampleabstract/DemoApp.java | spring-di-4/src/main/java/com/baeldung/sampleabstract/DemoApp.java | package com.baeldung.sampleabstract;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.baeldung.sampleabstract")
public class DemoApp {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoApp.class);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-4/src/main/java/com/baeldung/sampleabstract/BallService.java | spring-di-4/src/main/java/com/baeldung/sampleabstract/BallService.java | package com.baeldung.sampleabstract;
import org.springframework.beans.factory.annotation.Autowired;
import jakarta.annotation.PostConstruct;
public abstract class BallService {
private RuleRepository ruleRepository;
private LogRepository logRepository;
public BallService(RuleRepository ruleRepository) {
this.ruleRepository = ruleRepository;
}
@Autowired
public final void setLogRepository(LogRepository logRepository) {
this.logRepository = logRepository;
}
@PostConstruct
public void afterInitialize() {
System.out.println(ruleRepository.toString());
System.out.println(logRepository.toString());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/atomix/src/test/java/com/atomix/exampletest/AtomixClientLiveTest.java | atomix/src/test/java/com/atomix/exampletest/AtomixClientLiveTest.java | package com.atomix.exampletest;
import io.atomix.AtomixClient;
import io.atomix.catalyst.transport.Address;
import io.atomix.catalyst.transport.netty.NettyTransport;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import static org.junit.Assert.assertEquals;
public class AtomixClientLiveTest {
private final AtomixClient client = AtomixClient.builder()
.withTransport(new NettyTransport())
.build();
@Test
public void whenBootstrap_thenShouldGet() throws InterruptedException, ExecutionException {
List<Address> cluster = Arrays.asList(
new Address("localhost", 8700),
new Address("localhsot", 8701));
String value = client.connect(cluster)
.thenRun(() -> System.out.println("Client Connected"))
.thenCompose(c -> client.getMap("map"))
.thenCompose(m -> m.get("bar"))
.thenApply(a -> (String) a)
.get();
assertEquals("Hello world!", value);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/atomix/src/main/java/com/atomix/example/BootstrapingCluster.java | atomix/src/main/java/com/atomix/example/BootstrapingCluster.java | package com.atomix.example;
import io.atomix.AtomixReplica;
import io.atomix.catalyst.transport.Address;
import io.atomix.catalyst.transport.netty.NettyTransport;
import io.atomix.copycat.server.storage.Storage;
import io.atomix.copycat.server.storage.StorageLevel;
import java.io.File;
import java.util.concurrent.CompletableFuture;
public class BootstrapingCluster {
public static void main(String[] args) {
Storage storage = Storage.builder()
.withDirectory(new File("log"))
.withStorageLevel(StorageLevel.DISK)
.build();
AtomixReplica replica = AtomixReplica.builder(new Address("localhost", 8700))
.withStorage(storage)
.withTransport(new NettyTransport())
.build();
CompletableFuture<AtomixReplica> completableFuture = replica.bootstrap();
completableFuture.join();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/atomix/src/main/java/com/atomix/example/OtherNodes.java | atomix/src/main/java/com/atomix/example/OtherNodes.java | package com.atomix.example;
import io.atomix.AtomixReplica;
import io.atomix.catalyst.transport.Address;
import io.atomix.catalyst.transport.netty.NettyTransport;
import io.atomix.concurrent.DistributedLock;
import io.atomix.copycat.server.storage.Storage;
import io.atomix.copycat.server.storage.StorageLevel;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class OtherNodes {
public static void main(String[] args) throws InterruptedException {
List<Address> cluster = Arrays
.asList(
new Address("localhost", 8700),
new Address("localhost", 8701),
new Address("localhost", 8702));
Storage storage = Storage.builder()
.withDirectory(new File("log"))
.withStorageLevel(StorageLevel.DISK)
.build();
AtomixReplica replica2 = AtomixReplica.builder(new Address("localhost", 8701))
.withStorage(storage)
.withTransport(new NettyTransport())
.build();
WorkerThread WT1 = new WorkerThread(replica2, cluster);
WT1.run();
AtomixReplica replica3 = AtomixReplica.builder(new Address("localhost", 8702))
.withStorage(storage)
.withTransport(new NettyTransport())
.build();
WorkerThread WT2 = new WorkerThread(replica3, cluster);
WT2.run();
Thread.sleep(6000);
DistributedLock lock = replica2.getLock("my-lock")
.join();
lock.lock()
.thenRun(() -> System.out.println("Acquired a lock"));
replica2.getMap("map")
.thenCompose(m -> m.put("bar", "Hello world!"))
.thenRun(() -> System.out.println("Value is set in Distributed Map"))
.join();
}
private static class WorkerThread extends Thread {
private AtomixReplica replica;
private List<Address> cluster;
WorkerThread(AtomixReplica replica, List<Address> cluster) {
this.replica = replica;
this.cluster = cluster;
}
public void run() {
replica.join(cluster)
.join();
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-io/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java | libraries-io/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java | package com.baeldung.java.io;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.util.FileSystemUtils;
public class JavaDirectoryDeleteUnitTest {
private static Path TEMP_DIRECTORY;
private static final String DIRECTORY_NAME = "toBeDeleted";
private static final List<String> ALL_LINES = Arrays.asList("This is line 1", "This is line 2", "This is line 3", "This is line 4", "This is line 5", "This is line 6");
@BeforeClass
public static void initializeTempDirectory() throws IOException {
TEMP_DIRECTORY = Files.createTempDirectory("tmpForJUnit");
}
@AfterClass
public static void cleanTempDirectory() throws IOException {
FileUtils.deleteDirectory(TEMP_DIRECTORY.toFile());
}
@Before
public void setupDirectory() throws IOException {
Path tempPathForEachTest = Files.createDirectory(TEMP_DIRECTORY.resolve(DIRECTORY_NAME));
// Create a directory structure
Files.write(tempPathForEachTest.resolve("file1.txt"), ALL_LINES.subList(0, 2));
Files.write(tempPathForEachTest.resolve("file2.txt"), ALL_LINES.subList(2, 4));
Files.createDirectories(tempPathForEachTest.resolve("Empty"));
Path aSubDir = Files.createDirectories(tempPathForEachTest.resolve("notEmpty"));
Files.write(aSubDir.resolve("file3.txt"), ALL_LINES.subList(3, 5));
Files.write(aSubDir.resolve("file4.txt"), ALL_LINES.subList(0, 3));
aSubDir = Files.createDirectories(aSubDir.resolve("anotherSubDirectory"));
Files.write(aSubDir.resolve("file5.txt"), ALL_LINES.subList(4, 5));
Files.write(aSubDir.resolve("file6.txt"), ALL_LINES.subList(0, 2));
}
@After
public void checkAndCleanupIfRequired() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
if (Files.exists(pathToBeDeleted)) {
FileUtils.deleteDirectory(pathToBeDeleted.toFile());
}
}
private boolean deleteDirectory(File directoryToBeDeleted) {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
return directoryToBeDeleted.delete();
}
@Test
public void givenDirectory_whenDeletedWithRecursion_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
boolean result = deleteDirectory(pathToBeDeleted.toFile());
assertTrue("Could not delete directory", result);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithCommonsIOFileUtils_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
FileUtils.deleteDirectory(pathToBeDeleted.toFile());
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithSpringFileSystemUtils_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
boolean result = FileSystemUtils.deleteRecursively(pathToBeDeleted.toFile());
assertTrue("Could not delete directory", result);
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithFilesWalk_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
try (Stream<Path> paths = Files.walk(pathToBeDeleted)) {
paths.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
}
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
@Test
public void givenDirectory_whenDeletedWithNIO2WalkFileTree_thenIsGone() throws IOException {
Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME);
Files.walkFileTree(pathToBeDeleted, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
assertFalse("Directory still exists", Files.exists(pathToBeDeleted));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-io/src/test/java/com/baeldung/java/io/remote/SftpFileTransferLiveTest.java | libraries-io/src/test/java/com/baeldung/java/io/remote/SftpFileTransferLiveTest.java | package com.baeldung.java.io.remote;
import java.io.IOException;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.VFS;
import org.junit.Test;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
public class SftpFileTransferLiveTest {
private final String remoteHost = "HOST_NAME_HERE";
private final String username = "USERNAME_HERE";
private final String password = "PASSWORD_HERE";
private final String localFile = "src/main/resources/input.txt";
private final String remoteFile = "welcome.txt";
private final String localDir = "src/main/resources/";
private final String remoteDir = "remote_sftp_test/";
private final String knownHostsFileLoc = "/Users/USERNAME/known_hosts_sample";
@Test
public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
channelSftp.put(localFile, remoteDir + "jschFile.txt");
channelSftp.exit();
}
@Test
public void whenDownloadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
channelSftp.get(remoteFile, localDir + "jschFile.txt");
channelSftp.exit();
}
@Test
public void whenUploadFileUsingSshj_thenSuccess() throws IOException {
SSHClient sshClient = setupSshj();
SFTPClient sftpClient = sshClient.newSFTPClient();
sftpClient.put(localFile, remoteDir + "sshjFile.txt");
sftpClient.close();
sshClient.disconnect();
}
@Test
public void whenDownloadFileUsingSshj_thenSuccess() throws IOException {
SSHClient sshClient = setupSshj();
SFTPClient sftpClient = sshClient.newSFTPClient();
sftpClient.get(remoteFile, localDir + "sshjFile.txt");
sftpClient.close();
sshClient.disconnect();
}
@Test
public void whenUploadFileUsingApacheVfs_thenSuccess() throws IOException {
FileSystemManager manager = VFS.getManager();
FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localFile);
FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFile.txt");
remote.copyFrom(local, Selectors.SELECT_SELF);
local.close();
remote.close();
}
@Test
public void whenDownloadFileUsingApacheVfs_thenSuccess() throws IOException {
FileSystemManager manager = VFS.getManager();
FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localDir + "vfsFile.txt");
FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteFile);
local.copyFrom(remote, Selectors.SELECT_SELF);
local.close();
remote.close();
}
// ====== ssh-keyscan -H -t rsa remoteHost >> known_hosts_sample
private ChannelSftp setupJsch() throws JSchException {
JSch jsch = new JSch();
jsch.setKnownHosts(knownHostsFileLoc);
Session jschSession = jsch.getSession(username, remoteHost);
jschSession.setPassword(password);
//jschSession.setConfig("StrictHostKeyChecking", "no");
jschSession.connect();
return (ChannelSftp) jschSession.openChannel("sftp");
}
private SSHClient setupSshj() throws IOException {
SSHClient client = new SSHClient();
client.addHostKeyVerifier(new PromiscuousVerifier());
client.connect(remoteHost);
client.authPassword(username, password);
client.useCompression();
return client;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-io/src/test/java/com/baeldung/java/io/pojotocsv/BeanToCsvUnitTest.java | libraries-io/src/test/java/com/baeldung/java/io/pojotocsv/BeanToCsvUnitTest.java | package com.baeldung.java.io.pojotocsv;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.io.BufferedReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class BeanToCsvUnitTest {
List<Application> applications = new ArrayList<>();
List<ApplicationWithAnnotation> applicationsWithAnnotation = new ArrayList<>();
@BeforeEach
public void beforeEach() {
applications = List.of(new Application("123", "Sam", 34, "2023-08-11"), new Application("456", "Tam", 44, "2023-02-11"), new Application("890", "Jam", 54, "2023-03-11"));
applicationsWithAnnotation = List.of(new ApplicationWithAnnotation("123", "Sam", 34, "2023-08-11"), new ApplicationWithAnnotation("456", "Tam", 44, "2023-02-11"), new ApplicationWithAnnotation("789", "Jam", 54, "2023-03-11"));
}
@Test
public void givenApplicationPOJO_whenUsingDefaultStrategy_thenReceiveCSVFormatWithAscendingOrderOfField() throws Exception {
BeanToCsv beanToCsv = new BeanToCsv();
beanToCsv.beanToCSVWithDefault(applications);
try (BufferedReader bufferedReader = Files.newBufferedReader(Path.of("src/main/resources/application.csv"))) {
List<String> content = bufferedReader.lines()
.toList();
assertThat(content.get(0)).isEqualTo("AGE,CREATED_AT,ID,NAME");
assertThat(content.get(1)).isEqualTo("34,2023-08-11,123,Sam");
assertThat(content.get(2)).isEqualTo("44,2023-02-11,456,Tam");
assertThat(content.get(3)).isEqualTo("54,2023-03-11,890,Jam");
}
}
@Test
public void givenApplicationPOJO_whenUsingCustomHeaderStrategy_thenReceiveCSVFormatWithCustomHeaders() throws Exception {
BeanToCsv beanToCsv = new BeanToCsv();
beanToCsv.beanToCSVWithCustomHeaderStrategy(applications);
try (BufferedReader bufferedReader = Files.newBufferedReader(Path.of("src/main/resources/application2.csv"))) {
List<String> content = bufferedReader.lines()
.toList();
assertThat(content.get(0)).isEqualTo("age,created_at,id,name");
assertThat(content.get(1)).isEqualTo("34,2023-08-11,123,Sam");
assertThat(content.get(2)).isEqualTo("44,2023-02-11,456,Tam");
assertThat(content.get(3)).isEqualTo("54,2023-03-11,890,Jam");
}
}
@Test
public void givenApplicationPOJOWithAnnotation_whenUsingCustomPositionStrategy_thenReceiveCSVFormatWithCustomPosition() throws Exception {
BeanToCsv beanToCsv = new BeanToCsv();
beanToCsv.beanToCSVWithCustomPositionStrategy(applicationsWithAnnotation);
try (BufferedReader bufferedReader = Files.newBufferedReader(Path.of("src/main/resources/application3.csv"))) {
List<String> content = bufferedReader.lines()
.toList();
assertThat(content.get(0)).isEqualTo("Sam,123,34,2023-08-11");
assertThat(content.get(1)).isEqualTo("Tam,456,44,2023-02-11");
assertThat(content.get(2)).isEqualTo("Jam,789,54,2023-03-11");
}
}
@Test
public void givenApplicationPOJOWithAnnotation_whenUsingCustomHeaderPositionStrategy_thenReceiveCSVFormatWithCustomHeaderPosition() throws Exception {
BeanToCsv beanToCsv = new BeanToCsv();
beanToCsv.beanToCSVWithCustomHeaderAndPositionStrategy(applicationsWithAnnotation);
try (BufferedReader bufferedReader = Files.newBufferedReader(Path.of("src/main/resources/application4.csv"))) {
List<String> content = bufferedReader.lines()
.toList();
assertThat(content.get(0)).isEqualTo("name,id,age,created_at");
assertThat(content.get(1)).isEqualTo("Sam,123,34,2023-08-11");
assertThat(content.get(2)).isEqualTo("Tam,456,44,2023-02-11");
assertThat(content.get(3)).isEqualTo("Jam,789,54,2023-03-11");
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-io/src/test/java/com/baeldung/java/io/jsch/SftpLiveTest.java | libraries-io/src/test/java/com/baeldung/java/io/jsch/SftpLiveTest.java | package com.baeldung.java.io.jsch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.file.Paths;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.MountableFile;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
@Testcontainers
public class SftpLiveTest {
private static final int SFTP_PORT = 22;
private static final String USERNAME = "foo";
private static final String PASSWORD = "pass";
// mobilistics/sftp is a Docker container for an SFTP server that reliably allows file upload and download.
// Unfortunately, atmoz/sftp intermittently doesn't allow writing to the server.
@Container
public static GenericContainer<?> sftpContainer = new GenericContainer<>("mobilistics/sftp:latest")
.withExposedPorts(SFTP_PORT)
.withEnv("USER", USERNAME)
.withEnv("PASS", PASSWORD)
.withCopyFileToContainer(
MountableFile.forHostPath(Paths.get("src/main/resources/input.txt")),
"/data/incoming/input.txt"
);
@Test
void whenGettingTheCurrentDirectory_thenTheCorrectValueIsReturned() throws Exception {
JSch jSch = new JSch();
Session session = jSch.getSession(USERNAME, sftpContainer.getHost(), sftpContainer.getMappedPort(SFTP_PORT));
session.setUserInfo(new SftpUserInfo());
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
assertEquals("/", sftp.pwd());
assertTrue(sftp.lpwd().endsWith("/libraries-io"));
}
@Test
void whenListingRemoteFiles_thenTheCorrectFilesAreReturned() throws Exception {
JSch jSch = new JSch();
Session session = jSch.getSession(USERNAME, sftpContainer.getHost(), sftpContainer.getMappedPort(SFTP_PORT));
session.setUserInfo(new SftpUserInfo());
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
List<ChannelSftp.LsEntry> remoteLs = sftp.ls(".");
assertEquals(3, remoteLs.size()); // ., ../ and incoming
ChannelSftp.LsEntry incoming = remoteLs.stream()
.filter(file -> file.getFilename()
.equals("incoming"))
.findFirst()
.get();
assertEquals("incoming", incoming.getFilename());
SftpATTRS attrs = incoming.getAttrs();
assertEquals("drwxr-xr-x", attrs.getPermissionsString());
}
@Test
void whenGettingFileStatus_thenTheCorrectValueIsReturned() throws Exception {
JSch jSch = new JSch();
Session session = jSch.getSession(USERNAME, sftpContainer.getHost(), sftpContainer.getMappedPort(SFTP_PORT));
session.setUserInfo(new SftpUserInfo());
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
SftpATTRS attrs = sftp.stat("incoming");
assertEquals("drwxr-xr-x", attrs.getPermissionsString());
}
@Test
void whenPuttingFiles_thenTheFilesAreCreatedOnTheServer() throws Exception {
JSch jSch = new JSch();
Session session = jSch.getSession(USERNAME, sftpContainer.getHost(), sftpContainer.getMappedPort(SFTP_PORT));
session.setUserInfo(new SftpUserInfo());
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
sftp.cd("incoming");
try (OutputStream outputStream = sftp.put("os.txt")) {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write("Hello, world!");
outputStreamWriter.close();
}
// Check the files exist
sftp.stat("os.txt");
}
@Test
void whenGettingAFile_thenTheFileContentsAreRetrieved() throws Exception {
JSch jSch = new JSch();
Session session = jSch.getSession(USERNAME, sftpContainer.getHost(), sftpContainer.getMappedPort(SFTP_PORT));
session.setUserInfo(new SftpUserInfo());
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
sftp.get("incoming/input.txt", baos);
assertEquals("This is a sample text content", new String(baos.toByteArray()));
}
private static class SftpUserInfo extends BaseUserInfo {
@Override
public String getPassword() {
return PASSWORD;
}
@Override
public boolean promptPassword(String message) {
return true;
}
@Override
public boolean promptYesNo(String message) {
if (message.startsWith("The authenticity of host")) {
return true;
}
return false;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-io/src/test/java/com/baeldung/java/io/jsch/ConnectLiveTest.java | libraries-io/src/test/java/com/baeldung/java/io/jsch/ConnectLiveTest.java | package com.baeldung.java.io.jsch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.MountableFile;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.JSchUnknownHostKeyException;
import com.jcraft.jsch.Session;
@Testcontainers
class ConnectLiveTest {
private static final int SFTP_PORT = 22;
private static final String USERNAME = "baeldung";
private static final String PASSWORD = "test";
private static final String DIRECTORY = "upload";
// atmoz/sftp is a Docker container for an SFTP server that can easily support password and key authentication.
@Container
public static GenericContainer<?> sftpContainer = new GenericContainer<>("atmoz/sftp:latest")
.withExposedPorts(SFTP_PORT)
.withCommand(USERNAME + ":" + PASSWORD + ":::" + DIRECTORY)
.withCopyFileToContainer(
MountableFile.forHostPath(Paths.get("src/test/resources/com/baeldung/java/io/jsch/nopassphrase/id_rsa.pub")),
"/home/" + USERNAME + "/.ssh/keys/id_rsa.pub"
)
.withCopyFileToContainer(
MountableFile.forHostPath(Paths.get("src/test/resources/com/baeldung/java/io/jsch/passphrase/id_rsa.pub")),
"/home/" + USERNAME + "/.ssh/keys/id_rsa2.pub"
);
@Test
void whenTheHostKeyIsUnknown_thenTheConnectionFails() throws Exception {
JSch jSch = new JSch();
Session session = jSch.getSession(USERNAME, sftpContainer.getHost(), sftpContainer.getMappedPort(SFTP_PORT));
session.setUserInfo(new BaseUserInfo() {});
assertThrows(JSchUnknownHostKeyException.class, () -> session.connect());
}
@Test
void whenNoAuthenticationIsProvided_thenTheConnectionFails() throws Exception {
JSch jSch = new JSch();
Session session = jSch.getSession(USERNAME, sftpContainer.getHost(), sftpContainer.getMappedPort(SFTP_PORT));
session.setUserInfo(new BaseUserInfo() {
@Override
public boolean promptYesNo(String message) {
if (message.startsWith("The authenticity of host")) {
return true;
}
return false;
}
});
JSchException exception = assertThrows(JSchException.class, () -> session.connect());
assertEquals("Auth cancel for methods 'publickey,password,keyboard-interactive'", exception.getMessage());
}
@Test
void whenPasswordAuthIsProvided_thenTheConnectionSucceeds() throws Exception {
JSch jSch = new JSch();
Session session = jSch.getSession(USERNAME, sftpContainer.getHost(), sftpContainer.getMappedPort(SFTP_PORT));
session.setUserInfo(new BaseUserInfo() {
@Override
public String getPassword() {
return PASSWORD;
}
@Override
public boolean promptPassword(String message) {
return true;
}
@Override
public boolean promptYesNo(String message) {
if (message.startsWith("The authenticity of host")) {
return true;
}
return false;
}
});
session.connect();
}
@Test
void givenAnOpenSSHKey_whenKeyAuthIsProvided_thenTheConnectionSucceeds() throws Exception {
JSch jSch = new JSch();
jSch.addIdentity("src/test/resources/com/baeldung/java/io/jsch/nopassphrase/id_rsa");
Session session = jSch.getSession(USERNAME, sftpContainer.getHost(), sftpContainer.getMappedPort(SFTP_PORT));
session.setUserInfo(new BaseUserInfo() {
@Override
public boolean promptYesNo(String message) {
if (message.startsWith("The authenticity of host")) {
return true;
}
return false;
}
});
session.connect();
}
@Test
void givenAPuttyKey_whenKeyAuthIsProvided_thenTheConnectionSucceeds() throws Exception {
JSch jSch = new JSch();
jSch.addIdentity("src/test/resources/com/baeldung/java/io/jsch/nopassphrase/id_rsa.ppk");
Session session = jSch.getSession(USERNAME, sftpContainer.getHost(), sftpContainer.getMappedPort(SFTP_PORT));
session.setUserInfo(new BaseUserInfo() {
@Override
public boolean promptYesNo(String message) {
if (message.startsWith("The authenticity of host")) {
return true;
}
return false;
}
});
session.connect();
}
@Test
void givenAnOpenSSHKeyWithPassphrase_whenKeyAuthIsProvided_thenTheConnectionSucceeds() throws Exception {
JSch jSch = new JSch();
jSch.addIdentity("src/test/resources/com/baeldung/java/io/jsch/passphrase/id_rsa");
Session session = jSch.getSession(USERNAME, sftpContainer.getHost(), sftpContainer.getMappedPort(SFTP_PORT));
session.setUserInfo(new BaseUserInfo() {
@Override
public String getPassphrase() {
return "te5tPa55word";
}
@Override
public boolean promptPassphrase(String message) {
return true;
}
@Override
public boolean promptYesNo(String message) {
if (message.startsWith("The authenticity of host")) {
return true;
}
return false;
}
});
session.connect();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-io/src/test/java/com/baeldung/java/io/jsch/BaseUserInfo.java | libraries-io/src/test/java/com/baeldung/java/io/jsch/BaseUserInfo.java | package com.baeldung.java.io.jsch;
import com.jcraft.jsch.UserInfo;
public class BaseUserInfo implements UserInfo {
@Override
public String getPassphrase() {
return null;
}
@Override
public String getPassword() {
return null;
}
@Override
public boolean promptPassword(String message) {
return false;
}
@Override
public boolean promptPassphrase(String message) {
return false;
}
@Override
public boolean promptYesNo(String message) {
return false;
}
@Override
public void showMessage(String message) {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-io/src/test/java/com/baeldung/java/io/accessemailwithimap/GmailAppLiveTest.java | libraries-io/src/test/java/com/baeldung/java/io/accessemailwithimap/GmailAppLiveTest.java | package com.baeldung.java.io.accessemailwithimap;
import jakarta.mail.Folder;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Store;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
class GmailAppLiveTest {
private static final Logger LOGGER = LoggerFactory.getLogger(GmailApp.class);
Store store = null;
Folder folder = null;
@BeforeEach
void setUp() throws MessagingException {
store = GmailApp.establishConnection();
folder = store.getFolder("inbox");
}
@AfterEach
void tearDown() throws MessagingException {
if (store != null) {
store.close();
}
if (folder != null && folder.isOpen()) {
folder.close(true);
}
}
@Test
void givenEmails_whenCountEmails_thenEmailsCounted() throws MessagingException {
GmailApp.emailCount(store);
}
@Test
void givenEmails_whenReadEmails_thenEmailsRead() throws MessagingException, IOException {
GmailApp.readEmails(store);
}
@Test
void givenEmails_whenSearchEmails_thenEmailsSearched() throws MessagingException {
GmailApp.searchEmails(store, "Google");
}
@Test
void givenEmails_whenLastEmailsIsUnread_thenEmailsRead() throws MessagingException, IOException {
GmailApp.markLatestUnreadAsRead(store);
}
@Test
void givenEmails_whenDeleting_thenEmailsDeleted() throws MessagingException {
GmailApp.deleteEmail(store);
}
@Test
void givenEmails_whenMoveEmails_thenEmailsMoved() throws MessagingException {
folder.open(Folder.READ_WRITE);
Message[] messages = folder.getMessages();
if (messages.length > 0) {
Message message = messages[0];
GmailApp.moveToFolder(store, message, "First");
}
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-io/src/main/java/com/baeldung/java/io/pojotocsv/CustomHeaderStrategy.java | libraries-io/src/main/java/com/baeldung/java/io/pojotocsv/CustomHeaderStrategy.java | package com.baeldung.java.io.pojotocsv;
import java.util.Arrays;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
public class CustomHeaderStrategy<T> extends HeaderColumnNameMappingStrategy<T> {
@Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
String[] header = super.generateHeader(bean);
return Arrays.stream(header)
.map(String::toLowerCase)
.toArray(String[]::new);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-io/src/main/java/com/baeldung/java/io/pojotocsv/ApplicationWithAnnotation.java | libraries-io/src/main/java/com/baeldung/java/io/pojotocsv/ApplicationWithAnnotation.java | package com.baeldung.java.io.pojotocsv;
import com.opencsv.bean.CsvBindByName;
import com.opencsv.bean.CsvBindByPosition;
public record ApplicationWithAnnotation(@CsvBindByName(column = "id", required = true) @CsvBindByPosition(position = 1) String id, @CsvBindByName(column = "name", required = true) @CsvBindByPosition(position = 0) String name,
@CsvBindByName(column = "age", required = true) @CsvBindByPosition(position = 2) Integer age, @CsvBindByName(column = "position", required = true) @CsvBindByPosition(position = 3) String created_at) {
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-io/src/main/java/com/baeldung/java/io/pojotocsv/BeanToCsv.java | libraries-io/src/main/java/com/baeldung/java/io/pojotocsv/BeanToCsv.java | package com.baeldung.java.io.pojotocsv;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
public class BeanToCsv {
public void beanToCSVWithDefault(List<Application> applications) throws Exception {
try (FileWriter writer = new FileWriter("src/main/resources/application.csv")) {
var builder = new StatefulBeanToCsvBuilder<Application>(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withSeparator(',')
.build();
builder.write(applications);
}
}
public void beanToCSVWithCustomHeaderStrategy(List<Application> applications) throws IOException, CsvRequiredFieldEmptyException, CsvDataTypeMismatchException {
try (FileWriter writer = new FileWriter("src/main/resources/application2.csv")) {
var mappingStrategy = new CustomHeaderStrategy<Application>();
mappingStrategy.setType(Application.class);
var builder = new StatefulBeanToCsvBuilder<Application>(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withMappingStrategy(mappingStrategy)
.build();
builder.write(applications);
}
}
public void beanToCSVWithCustomPositionStrategy(List<ApplicationWithAnnotation> applications) throws Exception {
try (FileWriter writer = new FileWriter("src/main/resources/application3.csv")) {
var builder = new StatefulBeanToCsvBuilder<ApplicationWithAnnotation>(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
builder.write(applications);
}
}
public void beanToCSVWithCustomHeaderAndPositionStrategy(List<ApplicationWithAnnotation> applications) throws IOException, CsvRequiredFieldEmptyException, CsvDataTypeMismatchException {
try (FileWriter writer = new FileWriter("src/main/resources/application4.csv")) {
var mappingStrategy = new CustomColumnPositionStrategy<ApplicationWithAnnotation>();
mappingStrategy.setType(ApplicationWithAnnotation.class);
var builder = new StatefulBeanToCsvBuilder<ApplicationWithAnnotation>(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withMappingStrategy(mappingStrategy)
.build();
builder.write(applications);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-io/src/main/java/com/baeldung/java/io/pojotocsv/CustomColumnPositionStrategy.java | libraries-io/src/main/java/com/baeldung/java/io/pojotocsv/CustomColumnPositionStrategy.java | package com.baeldung.java.io.pojotocsv;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
public class CustomColumnPositionStrategy<T> extends ColumnPositionMappingStrategy<T> {
@Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
super.generateHeader(bean);
return super.getColumnMapping();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-io/src/main/java/com/baeldung/java/io/pojotocsv/Application.java | libraries-io/src/main/java/com/baeldung/java/io/pojotocsv/Application.java | package com.baeldung.java.io.pojotocsv;
public record Application(String id, String name, Integer age, String created_at) {
}
| 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.