This commit is contained in:
Ulisses Lima
2023-05-31 09:41:18 -03:00
193 changed files with 4021 additions and 1015 deletions
@@ -23,7 +23,7 @@ public class Graph {
adjVertices.get(src).add(dest);
}
public void dfsWithoutRecursion(int start) {
public boolean[] dfsWithoutRecursion(int start) {
Stack<Integer> stack = new Stack<Integer>();
boolean[] isVisited = new boolean[adjVertices.size()];
stack.push(start);
@@ -38,20 +38,22 @@ public class Graph {
}
}
}
return isVisited;
}
public void dfs(int start) {
public boolean[] dfs(int start) {
boolean[] isVisited = new boolean[adjVertices.size()];
dfsRecursive(start, isVisited);
return dfsRecursive(start, isVisited);
}
private void dfsRecursive(int current, boolean[] isVisited) {
private boolean[] dfsRecursive(int current, boolean[] isVisited) {
isVisited[current] = true;
visit(current);
for (int dest : adjVertices.get(current)) {
if (!isVisited[dest])
dfsRecursive(dest, isVisited);
}
return isVisited;
}
public List<Integer> topologicalSort(int start) {
@@ -1,7 +1,9 @@
package com.baeldung.algorithms.dfs;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
class GraphUnitTest {
@@ -9,9 +11,12 @@ class GraphUnitTest {
@Test
void givenDirectedGraph_whenDFS_thenPrintAllValues() {
Graph graph = createDirectedGraph();
graph.dfs(0);
System.out.println();
graph.dfsWithoutRecursion(0);
boolean[] visited;
visited = graph.dfs(0);
boolean[] expected = new boolean[]{true, true, true, true, true, true};
Assert.assertArrayEquals(expected, visited);
visited = graph.dfsWithoutRecursion(0);
Assert.assertArrayEquals(expected, visited);
}
@Test
@@ -19,6 +24,8 @@ class GraphUnitTest {
Graph graph = createDirectedGraph();
List<Integer> list = graph.topologicalSort(0);
System.out.println(list);
List<Integer> expected = Arrays.asList(0, 2, 1, 3, 4, 5);
Assert.assertEquals(expected, list);
}
private Graph createDirectedGraph() {
@@ -1,7 +1,7 @@
package com.baeldung.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
@@ -9,30 +9,36 @@ import java.util.concurrent.Future;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HttpAsyncClientLiveTest {
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.cookie.BasicCookieStore;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.cookie.BasicClientCookie;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
import org.apache.hc.core5.http.protocol.BasicHttpContext;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.reactor.IOReactorConfig;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
class HttpAsyncClientLiveTest {
private static final String HOST = "http://www.google.com";
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
@@ -48,23 +54,33 @@ public class HttpAsyncClientLiveTest {
// tests
@Test
public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
final HttpHost target = new HttpHost(HOST);
final SimpleHttpRequest request = SimpleRequestBuilder.get()
.setHttpHost(target)
.build();
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
final HttpGet request = new HttpGet(HOST);
final Future<HttpResponse> future = client.execute(request, null);
final Future<SimpleHttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(response.getCode(), equalTo(200));
client.close();
}
@Test
public void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception {
final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
final PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setConnectionManager(cm).build();
void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception {
final IOReactorConfig ioReactorConfig = IOReactorConfig
.custom()
.build();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setIOReactorConfig(ioReactorConfig)
.build();
client.start();
final String[] toGet = { "http://www.google.com/", "http://www.apache.org/", "http://www.bing.com/" };
@@ -85,36 +101,68 @@ public class HttpAsyncClientLiveTest {
}
@Test
public void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
final HttpHost proxy = new HttpHost("127.0.0.1", 8080);
final RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
final HttpGet request = new HttpGet(HOST_WITH_PROXY);
final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,HOST_WITH_PROXY);
request.setConfig(config);
final Future<HttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
final Future<SimpleHttpResponse> future = client.execute(request, new FutureCallback<>(){
@Override
public void completed(SimpleHttpResponse response) {
System.out.println("responseData");
}
@Override
public void failed(Exception ex) {
System.out.println("Error executing HTTP request: " + ex.getMessage());
}
@Override
public void cancelled() {
System.out.println("HTTP request execution cancelled");
}
});
final HttpResponse response = future.get();
assertThat(response.getCode(), equalTo(200));
client.close();
}
@Test
public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext).build();
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create()
.setSslContext(sslContext)
.build();
final PoolingAsyncClientConnectionManager cm = PoolingAsyncClientConnectionManagerBuilder.create()
.setTlsStrategy(tlsStrategy)
.build();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setConnectionManager(cm)
.build();
client.start();
final HttpGet request = new HttpGet(HOST_WITH_SSL);
final Future<HttpResponse> future = client.execute(request, null);
final SimpleHttpRequest request = new SimpleHttpRequest("GET",HOST_WITH_SSL);
final Future<SimpleHttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(response.getCode(), equalTo(200));
client.close();
}
@Test
public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234");
cookie.setDomain(COOKIE_DOMAIN);
@@ -122,29 +170,36 @@ public class HttpAsyncClientLiveTest {
cookieStore.addCookie(cookie);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
client.start();
final HttpGet request = new HttpGet(HOST_WITH_COOKIE);
final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,HOST_WITH_COOKIE);
final HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
final Future<HttpResponse> future = client.execute(request, localContext, null);
final Future<SimpleHttpResponse> future = client.execute(request, localContext, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(response.getCode(), equalTo(200));
client.close();
}
@Test
public void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
final CredentialsProvider provider = new BasicCredentialsProvider();
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
provider.setCredentials(AuthScope.ANY, creds);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build();
void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
final UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS.toCharArray());
credsProvider.setCredentials(new AuthScope(URL_SECURED_BY_BASIC_AUTHENTICATION, 80) ,credentials);
final CloseableHttpAsyncClient client = HttpAsyncClients
.custom()
.setDefaultCredentialsProvider(credsProvider).build();
final SimpleHttpRequest request = new SimpleHttpRequest("GET" ,URL_SECURED_BY_BASIC_AUTHENTICATION);
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
client.start();
final Future<HttpResponse> future = client.execute(request, null);
final Future<SimpleHttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(response.getCode(), equalTo(200));
client.close();
}
@@ -163,9 +218,9 @@ public class HttpAsyncClientLiveTest {
@Override
public void run() {
try {
final Future<HttpResponse> future = client.execute(request, context, null);
final Future<SimpleHttpResponse> future = client.execute(SimpleHttpRequest.copy(request), context, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(response.getCode(), equalTo(200));
} catch (final Exception ex) {
System.out.println(ex.getLocalizedMessage());
}
@@ -0,0 +1,174 @@
package com.baeldung.httpclient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.junit.jupiter.api.Test;
class HttpAsyncClientV4LiveTest {
private static final String HOST = "http://www.google.com";
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
private static final String HOST_WITH_PROXY = "http://httpbin.org/";
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";// "http://localhost:8080/spring-security-rest-basic-auth/api/foos/1";
private static final String DEFAULT_USER = "test";// "user1";
private static final String DEFAULT_PASS = "test";// "user1Pass";
private static final String HOST_WITH_COOKIE = "http://yuilibrary.com/yui/docs/cookie/cookie-simple-example.html"; // "http://github.com";
private static final String COOKIE_DOMAIN = ".yuilibrary.com"; // ".github.com";
private static final String COOKIE_NAME = "example"; // "JSESSIONID";
// tests
@Test
void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
final HttpGet request = new HttpGet(HOST);
final Future<HttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception {
final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
final PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setConnectionManager(cm).build();
client.start();
final String[] toGet = { "http://www.google.com/", "http://www.apache.org/", "http://www.bing.com/" };
final GetThread[] threads = new GetThread[toGet.length];
for (int i = 0; i < threads.length; i++) {
final HttpGet request = new HttpGet(toGet[i]);
threads[i] = new GetThread(client, request);
}
for (final GetThread thread : threads) {
thread.start();
}
for (final GetThread thread : threads) {
thread.join();
}
}
@Test
void whenUseProxyWithHttpClient_thenCorrect() throws Exception {
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
final HttpHost proxy = new HttpHost("127.0.0.1", 8080);
final RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
final HttpGet request = new HttpGet(HOST_WITH_PROXY);
request.setConfig(config);
final Future<HttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext).build();
client.start();
final HttpGet request = new HttpGet(HOST_WITH_SSL);
final Future<HttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234");
cookie.setDomain(COOKIE_DOMAIN);
cookie.setPath("/");
cookieStore.addCookie(cookie);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
client.start();
final HttpGet request = new HttpGet(HOST_WITH_COOKIE);
final HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
final Future<HttpResponse> future = client.execute(request, localContext, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
final CredentialsProvider provider = new BasicCredentialsProvider();
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
provider.setCredentials(AuthScope.ANY, creds);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build();
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
client.start();
final Future<HttpResponse> future = client.execute(request, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
static class GetThread extends Thread {
private final CloseableHttpAsyncClient client;
private final HttpContext context;
private final HttpGet request;
GetThread(final CloseableHttpAsyncClient client, final HttpGet request) {
this.client = client;
context = HttpClientContext.create();
this.request = request;
}
@Override
public void run() {
try {
final Future<HttpResponse> future = client.execute(request, context, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
} catch (final Exception ex) {
System.out.println(ex.getLocalizedMessage());
}
}
}
}
+1
View File
@@ -8,3 +8,4 @@ You can build the project from the command line using: *mvn clean install*, or i
### Relevant Articles:
- [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running)
- [Add Custom Headers to a Kafka Message](https://www.baeldung.com/java-kafka-custom-headers)
- [Get Last N Messages in Apache Kafka Topic](https://www.baeldung.com/java-apache-kafka-get-last-n-messages)
@@ -0,0 +1,81 @@
package com.baeldung.kafka.consumer;
import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.UUID;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConsumeFromBeginning {
private static Logger logger = LoggerFactory.getLogger(ConsumeFromBeginning.class);
private static String TOPIC = "baeldung";
private static int messagesInTopic = 10;
private static KafkaProducer<String, String> producer;
private static KafkaConsumer<String, String> consumer;
public static void main(String[] args) {
setup();
publishMessages();
consumeFromBeginning();
}
private static void consumeFromBeginning() {
consumer.subscribe(Arrays.asList(TOPIC));
ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(10));
for (ConsumerRecord<String, String> record : records) {
logger.info(record.value());
}
consumer.seekToBeginning(consumer.assignment());
records = consumer.poll(Duration.ofSeconds(10));
for (ConsumerRecord<String, String> record : records) {
logger.info(record.value());
}
}
private static void publishMessages() {
for (int i = 1; i <= messagesInTopic; i++) {
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, String.valueOf(i));
producer.send(record);
}
}
private static void setup() {
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
Properties consumerProperties = new Properties();
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID()
.toString());
producer = new KafkaProducer<>(producerProperties);
consumer = new KafkaConsumer<>(consumerProperties);
}
}
@@ -0,0 +1,106 @@
package com.baeldung.kafka.message;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MessageWithKey {
private static Logger logger = LoggerFactory.getLogger(MessageWithKey.class);
private static String TOPIC = "baeldung";
private static int PARTITIONS = 5;
private static short REPLICATION_FACTOR = 1;
private static String MESSAGE_KEY = "message-key";
private static Admin admin;
private static KafkaProducer<String, String> producer;
private static KafkaConsumer<String, String> consumer;
public static void main(String[] args) throws ExecutionException, InterruptedException {
setup();
publishMessagesWithoutKey();
consumeMessages();
publishMessagesWithKey();
consumeMessages();
}
private static void consumeMessages() {
consumer.subscribe(Arrays.asList(TOPIC));
ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(5));
for (ConsumerRecord<String, String> record : records) {
logger.info("Key : {}, Value : {}", record.key(), record.value());
}
}
private static void publishMessagesWithKey() throws ExecutionException, InterruptedException {
for (int i = 1; i <= 10; i++) {
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, MESSAGE_KEY, String.valueOf(i));
Future<RecordMetadata> future = producer.send(record);
RecordMetadata metadata = future.get();
logger.info(String.valueOf(metadata.partition()));
}
}
private static void publishMessagesWithoutKey() throws ExecutionException, InterruptedException {
for (int i = 1; i <= 10; i++) {
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, String.valueOf(i));
Future<RecordMetadata> future = producer.send(record);
RecordMetadata metadata = future.get();
logger.info(String.valueOf(metadata.partition()));
}
}
private static void setup() {
Properties adminProperties = new Properties();
adminProperties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
Properties consumerProperties = new Properties();
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID()
.toString());
admin = Admin.create(adminProperties);
producer = new KafkaProducer<>(producerProperties);
consumer = new KafkaConsumer<>(consumerProperties);
admin.createTopics(Collections.singleton(new NewTopic(TOPIC, PARTITIONS, REPLICATION_FACTOR)));
}
}
@@ -0,0 +1,109 @@
package com.baeldung.kafka.consumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
// This live test needs a Docker Daemon running so that a kafka container can be created
@Testcontainers
public class ConsumeFromBeginningLiveTest {
private static Logger logger = LoggerFactory.getLogger(ConsumeFromBeginningLiveTest.class);
private static String TOPIC = "baeldung";
private static int messagesInTopic = 10;
private static KafkaProducer<String, String> producer;
private static KafkaConsumer<String, String> consumer;
@Container
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
@BeforeAll
static void setup() {
KAFKA_CONTAINER.addExposedPort(9092);
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
Properties consumerProperties = new Properties();
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID()
.toString());
producer = new KafkaProducer<>(producerProperties);
consumer = new KafkaConsumer<>(consumerProperties);
}
private static void publishMessages() throws ExecutionException, InterruptedException {
for (int i = 1; i <= messagesInTopic; i++) {
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, String.valueOf(i));
producer.send(record)
.get();
}
}
@AfterAll
static void destroy() {
KAFKA_CONTAINER.stop();
}
@Test
void givenMessages_whenConsumedFromBeginning_thenCheckIfConsumedFromBeginning() throws ExecutionException, InterruptedException {
publishMessages();
consumer.subscribe(Arrays.asList(TOPIC));
ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(10));
int messageCount = 0;
for (ConsumerRecord<String, String> record : records) {
logger.info(record.value());
messageCount++;
}
assertEquals(messagesInTopic, messageCount);
consumer.seekToBeginning(consumer.assignment());
records = consumer.poll(Duration.ofSeconds(10));
messageCount = 0;
for (ConsumerRecord<String, String> record : records) {
logger.info(record.value());
messageCount++;
}
assertEquals(messagesInTopic, messageCount);
}
}
@@ -0,0 +1,130 @@
package com.baeldung.kafka.message;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
// This live test needs a Docker Daemon running so that a kafka container can be created
@Testcontainers
public class MessageWithKeyLiveTest {
private static String TOPIC = "baeldung";
private static int PARTITIONS = 5;
private static short REPLICATION_FACTOR = 1;
private static String MESSAGE_KEY = "message-key";
private static String MESSAGE_VALUE = "Hello World";
private static Admin admin;
private static KafkaProducer<String, String> producer;
private static KafkaConsumer<String, String> consumer;
@Container
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
@BeforeAll
static void setup() {
KAFKA_CONTAINER.addExposedPort(9092);
Properties adminProperties = new Properties();
adminProperties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
Properties consumerProperties = new Properties();
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, UUID.randomUUID()
.toString());
admin = Admin.create(adminProperties);
producer = new KafkaProducer<>(producerProperties);
consumer = new KafkaConsumer<>(consumerProperties);
admin.createTopics(Collections.singleton(new NewTopic(TOPIC, PARTITIONS, REPLICATION_FACTOR)));
}
@AfterAll
static void destroy() {
KAFKA_CONTAINER.stop();
}
@Test
void givenAMessageWithKey_whenPublishedToKafkaAndConsumed_thenCheckForKey() throws ExecutionException, InterruptedException {
ProducerRecord<String, String> producerRecord = new ProducerRecord<>(TOPIC, MESSAGE_KEY, MESSAGE_VALUE);
Future<RecordMetadata> future = producer.send(producerRecord);
RecordMetadata metadata = future.get();
assertNotNull(metadata);
consumer.subscribe(Arrays.asList(TOPIC));
ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(5));
for (ConsumerRecord<String, String> consumerRecord : records) {
assertEquals(MESSAGE_KEY, consumerRecord.key());
assertEquals(MESSAGE_VALUE, consumerRecord.value());
}
}
@Test
void givenAListOfMessageWithKeys_whenPublishedToKafka_thenCheckedIfPublishedToSamePartition() throws ExecutionException, InterruptedException {
boolean isSamePartition = true;
int partition = 0;
for (int i = 1; i <= 10; i++) {
ProducerRecord<String, String> producerRecord = new ProducerRecord<>(TOPIC, MESSAGE_KEY, MESSAGE_VALUE);
Future<RecordMetadata> future = producer.send(producerRecord);
RecordMetadata metadata = future.get();
assertNotNull(metadata);
if (i == 1) {
partition = metadata.partition();
} else {
if (partition != metadata.partition()) {
isSamePartition = false;
}
}
}
assertTrue(isSamePartition);
}
}
+2 -2
View File
@@ -20,5 +20,5 @@ Two scripts are included to easily start middleware using Docker matching the pr
- [Multi-Entity Aggregates in Axon](https://www.baeldung.com/java-axon-multi-entity-aggregates)
- [Snapshotting Aggregates in Axon](https://www.baeldung.com/axon-snapshotting-aggregates)
- [Dispatching Queries in Axon Framework](https://www.baeldung.com/axon-query-dispatching)
- [Persisting the Query Model](https://www.baeldung.com/persisting-the-query-model)
- [Using and testing Axon applications via REST](https://www.baeldung.com/using-and-testing-axon-applications-via-rest)
- [Persisting the Query Model](https://www.baeldung.com/axon-persisting-query-model)
- [Using and Testing Axon Applications via REST](https://www.baeldung.com/using-and-testing-axon-applications-via-rest)
@@ -4,4 +4,5 @@
### Relevant Articles:
- [Introduction to Roaring Bitmap](https://www.baeldung.com/java-roaring-bitmap-intro)
- [Creating Custom Iterator in Java](https://www.baeldung.com/java-creating-custom-iterator)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
@@ -6,3 +6,4 @@ This module contains articles about the Java List collection
- [Java List Interface](https://www.baeldung.com/java-list-interface)
- [Finding All Duplicates in a List in Java](https://www.baeldung.com/java-list-find-duplicates)
- [Moving Items Around in an Arraylist](https://www.baeldung.com/java-arraylist-move-items)
- [Check if a List Contains an Element From Another List in Java](https://www.baeldung.com/java-check-elements-between-lists)
@@ -1,65 +1,77 @@
package com.baeldung.arrayandlistperformance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class ArrayAndArrayListPerformance {
@Benchmark
public void arrayCreation() {
int[] array = new int[1000000];
}
@Benchmark
public void arrayListCreation() {
ArrayList<Integer> list = new ArrayList<>(1000000);
}
@Benchmark
public void arrayItemSetting() {
int[] array = new int[1000000];
array[0] = 10;
}
@Benchmark
public void arrayListItemSetting() {
ArrayList<Integer> list = new ArrayList<>(1000000);
list.add(0, 10);
}
@Benchmark
public void arrayItemRetrieval() {
int[] array = new int[1000000];
array[0] = 10;
int item = array[0];
}
@Benchmark
public void arrayListItemRetrieval() {
ArrayList<Integer> list = new ArrayList<>(1000000);
list.add(0, 10);
int item2 = list.get(0);
}
@Benchmark
public void arrayCloning() {
int[] array = new int[1000000];
int[] newArray = array.clone();
}
@Benchmark
public void arrayListCloning() {
ArrayList<Integer> list = new ArrayList<>(1000000);
ArrayList<Integer> newList = new ArrayList<>(list);
}
public static void main(String[] args) throws Exception {
org.openjdk.jmh.runner.Runner runner = new org.openjdk.jmh.runner.Runner(new OptionsBuilder()
.include(ArrayAndArrayListPerformance.class.getSimpleName())
.forks(1)
.build());
org.openjdk.jmh.runner.Runner runner = new org.openjdk.jmh.runner.Runner(new OptionsBuilder().include(ArrayAndArrayListPerformance.class.getSimpleName()).forks(1).build());
runner.run();
}
}
public static Integer[] array = Collections.nCopies(256, 1).toArray(new Integer[0]);
public static ArrayList<Integer> list = new ArrayList<Integer>(
Arrays.asList(array));
@Benchmark
public Integer[] arrayCreation() {
return new Integer[256];
}
@Benchmark
public ArrayList<Integer> arrayListCreation() {
return new ArrayList<>(256);
}
@Benchmark
public Integer[] arrayItemsSetting() {
for (int i = 0; i < 256; i++) {
array[i] = i;
}
return array;
}
@Benchmark
public ArrayList<Integer> arrayListItemsSetting() {
for (int i = 0; i < 256; i++) {
list.set(i,i);
}
return list;
}
@Benchmark
public void arrayItemsRetrieval(Blackhole blackhole) {
for (int i = 0; i < 256; i++) {
int item = array[i];
blackhole.consume(item);
}
}
@Benchmark
public void arrayListItemsRetrieval(Blackhole blackhole) {
for (int i = 0; i < 256; i++) {
int item = list.get(i);
blackhole.consume(item);
}
}
@Benchmark
public void arrayCloning(Blackhole blackhole) {
Integer[] newArray = array.clone();
blackhole.consume(newArray);
}
@Benchmark
public void arrayListCloning(Blackhole blackhole) {
ArrayList<Integer> newList = new ArrayList<>(list);
blackhole.consume(newList);
}
}
@@ -0,0 +1,92 @@
package com.baeldung.java.listwithdefault;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
public class ListWithDefaultValuesUnitTest {
private static final List<String> EXPECTED_LIST = Lists.newArrayList("new", "new", "new", "new", "new");
private static final Date DATE_EPOCH = Date.from(Instant.EPOCH);
private static final Date DATE_NOW = new Date();
static <T> List<T> newListWithDefault(T value, int size) {
List<T> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
list.add(value);
}
return list;
}
static <T> List<T> newListWithDefault2(Supplier<T> supplier, int size) {
List<T> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
list.add(supplier.get());
}
return list;
}
@Test
void whenUsingArraysFill_thenGetExpectedList() {
String[] strings = new String[5];
Arrays.fill(strings, "new");
List<String> result = Arrays.asList(strings);
assertEquals(EXPECTED_LIST, result);
//result is a fixed size list
assertThrows(UnsupportedOperationException.class, () -> result.add("a new string"));
assertThrows(UnsupportedOperationException.class, () -> result.remove(0));
//result's element can be "set"
result.set(2, "a new value");
assertEquals("a new value", result.get(2));
Date[] dates = new Date[2];
Arrays.fill(dates, Date.from(Instant.EPOCH));
List<Date> dateList = Arrays.asList(dates);
assertEquals(Lists.newArrayList(DATE_EPOCH, DATE_EPOCH), dateList);
dateList.get(0)
.setTime(DATE_NOW.getTime());
assertEquals(Lists.newArrayList(DATE_NOW, DATE_NOW), dateList);
}
@Test
void whenUsingNewListWithDefault_thenGetExpectedList() {
List<String> result = newListWithDefault("new", 5);
assertEquals(EXPECTED_LIST, result);
List<Integer> intList = newListWithDefault(42, 3);
assertEquals(Lists.newArrayList(42, 42, 42), intList);
List<Date> dateList = newListWithDefault(Date.from(Instant.EPOCH), 2);
assertEquals(Lists.newArrayList(DATE_EPOCH, DATE_EPOCH), dateList);
dateList.get(0)
.setTime(DATE_NOW.getTime());
assertEquals(Lists.newArrayList(DATE_NOW, DATE_NOW), dateList);
}
@Test
void whenUsingNewListWithDefault2_thenGetExpectedList() {
List<String> result = newListWithDefault2(() -> "new", 5);
assertEquals(EXPECTED_LIST, result);
List<Integer> intList = newListWithDefault2(() -> 42, 3);
assertEquals(Lists.newArrayList(42, 42, 42), intList);
List<Date> dateList = newListWithDefault2(() -> Date.from(Instant.EPOCH), 2);
assertEquals(Lists.newArrayList(DATE_EPOCH, DATE_EPOCH), dateList);
dateList.get(0)
.setTime(DATE_NOW.getTime());
assertEquals(Lists.newArrayList(DATE_NOW, DATE_EPOCH), dateList);
}
}
@@ -17,16 +17,7 @@ import java.util.HashMap;
import java.util.Map;
public class MapToJsonUnitTest {
final TypeAdapter<JsonElement> strictAdapter = new Gson().getAdapter(JsonElement.class);
public boolean isValid(String json) {
try {
strictAdapter.fromJson(json);
} catch (JsonSyntaxException | IOException e) {
return false;
}
return true;
}
String originalJsonData = "{\"CS\":\"Post1\",\"Linux\":\"Post1\",\"Kotlin\":\"Post1\"}";
@Test
public void given_HashMapData_whenUsingJackson_thenConvertToJson() throws JsonProcessingException {
@@ -36,7 +27,7 @@ public class MapToJsonUnitTest {
data.put("Kotlin", "Post1");
ObjectMapper objectMapper = new ObjectMapper();
String jacksonData = objectMapper.writeValueAsString(data);
Assertions.assertTrue(isValid(jacksonData));
Assertions.assertEquals(originalJsonData,jacksonData);
}
@Test
@@ -49,7 +40,7 @@ public class MapToJsonUnitTest {
Type typeObject = new TypeToken<HashMap>() {
}.getType();
String gsonData = gson.toJson(data, typeObject);
Assertions.assertTrue(isValid(gsonData));
Assertions.assertEquals(originalJsonData,gsonData);
}
@Test
@@ -60,6 +51,6 @@ public class MapToJsonUnitTest {
data.put("Kotlin", "Post1");
JSONObject jsonObject = new JSONObject(data);
String orgJsonData = jsonObject.toString();
Assertions.assertTrue(isValid(orgJsonData));
Assertions.assertEquals(originalJsonData,orgJsonData);
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ This module contains articles about core Java input and output (IO)
- [Simulate touch Command in Java](https://www.baeldung.com/java-simulate-touch-command)
- [SequenceInputStream Class in Java](https://www.baeldung.com/java-sequenceinputstream)
- [Read a File Into a Map in Java](https://www.baeldung.com/java-read-file-into-map)
- [Read User Input Until a Condition is Met](https://www.baeldung.com/java-read-input-until-condition)
- [Read User Input Until a Condition Is Met](https://www.baeldung.com/java-read-input-until-condition)
- [Java Scanner.skip method with examples](https://www.baeldung.com/java-scanner-skip)
- [Generate the MD5 Checksum for a File in Java](https://www.baeldung.com/java-md5-checksum-file)
- [Getting the Filename From a String Containing an Absolute File Path](https://www.baeldung.com/java-filename-full-path)
@@ -10,3 +10,5 @@ This module contains articles about core Java input/output(IO) APIs.
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line)
- [Storing Java Scanner Input in an Array](https://www.baeldung.com/java-store-scanner-input-in-array)
- [How to Take Input as String With Spaces in Java Using Scanner?](https://www.baeldung.com/java-scanner-input-with-spaces)
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
@@ -99,9 +99,6 @@
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<junit-jupiter-version>5.2.0</junit-jupiter-version>
</properties>
<build>
<finalName>core-java-io-apis-2</finalName>
<resources>
@@ -111,5 +108,7 @@
</resource>
</resources>
</build>
<properties>
<junit-jupiter-version>5.9.3</junit-jupiter-version>
</properties>
</project>
@@ -0,0 +1,58 @@
package com.baeldung.scanner;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class ScannerNoSuchElementException {
public static String readFileV1(String pathname) throws IOException {
Path pathFile = Paths.get(pathname);
if (Files.notExists(pathFile)) {
return "";
}
try (Scanner scanner = new Scanner(pathFile)) {
return scanner.nextLine();
}
}
public static String readFileV2(String pathname) throws IOException {
Path pathFile = Paths.get(pathname);
if (Files.notExists(pathFile)) {
return "";
}
try (Scanner scanner = new Scanner(pathFile)) {
return scanner.hasNextLine() ? scanner.nextLine() : "";
}
}
public static String readFileV3(String pathname) throws IOException {
Path pathFile = Paths.get(pathname);
if (Files.notExists(pathFile) || Files.size(pathFile) == 0) {
return "";
}
try (Scanner scanner = new Scanner(pathFile)) {
return scanner.nextLine();
}
}
public static String readFileV4(String pathname) throws IOException {
Path pathFile = Paths.get(pathname);
if (Files.notExists(pathFile)) {
return "";
}
try (Scanner scanner = new Scanner(pathFile)) {
return scanner.nextLine();
} catch (NoSuchElementException exception) {
return "";
}
}
}
@@ -0,0 +1,94 @@
package com.baeldung.outputtofile;
import static org.junit.jupiter.api.Assertions.assertLinesMatch;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import com.google.common.collect.Lists;
class DualPrintStream extends PrintStream {
private final PrintStream second;
public DualPrintStream(OutputStream main, PrintStream second) {
super(main);
this.second = second;
}
@Override
public void close() {
super.close();
second.close();
}
@Override
public void flush() {
super.flush();
second.flush();
}
@Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
second.write(buf, off, len);
}
@Override
public void write(int b) {
super.write(b);
second.write(b);
}
@Override
public void write(byte[] b) throws IOException {
super.write(b);
second.write(b);
}
}
public class ConsoleOutputToFileUnitTest {
// @formatter:off
private final static List<String> OUTPUT_LINES = Lists.newArrayList(
"I came",
"I saw",
"I conquered");
// @formatter:on
@Test
void whenReplacingSystemOutPrintStreamWithFileOutputStream_thenOutputsGoToFile(@TempDir Path tempDir) throws IOException {
PrintStream originalOut = System.out;
Path outputFilePath = tempDir.resolve("file-output.txt");
PrintStream out = new PrintStream(Files.newOutputStream(outputFilePath), true);
System.setOut(out);
OUTPUT_LINES.forEach(line -> System.out.println(line));
assertTrue(outputFilePath.toFile()
.exists(), "The file exists");
assertLinesMatch(OUTPUT_LINES, Files.readAllLines(outputFilePath));
System.setOut(originalOut);
}
@Test
void whenUsingDualPrintStream_thenOutputsGoToConsoleAndFile(@TempDir Path tempDir) throws IOException {
PrintStream originalOut = System.out;
Path outputFilePath = tempDir.resolve("dual-output.txt");
DualPrintStream dualOut = new DualPrintStream(Files.newOutputStream(outputFilePath), System.out);
System.setOut(dualOut);
OUTPUT_LINES.forEach(line -> System.out.println(line));
assertTrue(outputFilePath.toFile()
.exists(), "The file exists");
assertLinesMatch(OUTPUT_LINES, Files.readAllLines(outputFilePath));
System.setOut(originalOut);
}
}
@@ -0,0 +1,97 @@
package com.baeldung.scanner;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
public class InputWithSpacesUnitTest {
@Test
void whenValuesContainSpaces_thenNextBreaksTheValue() {
String input = new StringBuilder().append("Michael Jackson\n")
.append("He was the 'King of Pop'.\n")
.toString();
Scanner sc = new Scanner(input);
String name = sc.next();
String description = sc.next();
assertEquals("Michael", name);
assertEquals("Jackson", description);
}
@Test
void whenOneValuePerLineUsingNextLine_thenGetExpectedResult() {
String input = new StringBuilder().append("Michael Jackson\n")
.append("He was the 'King of Pop'.\n")
.toString();
Scanner sc = new Scanner(input);
String name = sc.nextLine();
String description = sc.nextLine();
assertEquals("Michael Jackson", name);
assertEquals("He was the 'King of Pop'.", description);
}
@Test
void whenOneValuePerLineUsingNewLineAsDelimiter_thenGetExpectedResult() {
String input = new StringBuilder().append("Michael Jackson\n")
.append("He was the 'King of Pop'.\n")
.toString();
Scanner sc = new Scanner(input);
sc.useDelimiter("\\n");
String name = sc.next();
String description = sc.next();
assertEquals("Michael Jackson", name);
assertEquals("He was the 'King of Pop'.", description);
}
@Test
void whenValuesAreSeparatedByCommaUsingSplit_thenGetExpectedResult() {
String input = "Michael Jackson, Whitney Houston, John Lennon\n";
Scanner sc = new Scanner(input);
String[] names = sc.nextLine()
.split(", ");
assertArrayEquals(new String[] { "Michael Jackson", "Whitney Houston", "John Lennon" }, names);
}
@Test
void whenValuesAreSeparatedByCommaSettingDelimiterWithoutNewline_thenGetExpectedResult() {
String input = new StringBuilder().append("Michael Jackson, Whitney Houston, John Lennon\n")
.append("Elvis Presley\n")
.toString();
Scanner sc = new Scanner(input);
sc.useDelimiter(", ");
List<String> names = new ArrayList<>();
while (sc.hasNext()) {
names.add(sc.next());
}
//assertEquals(Lists.newArrayList("Michael Jackson", "Whitney Houston", "John Lennon", "Elvis Presley"), names); <-- Fail
assertEquals(3, names.size());
assertEquals("John Lennon\nElvis Presley\n", names.get(2));
}
@Test
void whenValuesAreSeparatedByCommaSettingDelimiter_thenGetExpectedResult() {
String input = new StringBuilder().append("Michael Jackson, Whitney Houston, John Lennon\n")
.append("Elvis Presley\n")
.toString();
Scanner sc = new Scanner(input);
sc.useDelimiter(", |\\n");
List<String> names = new ArrayList<>();
while (sc.hasNext()) {
names.add(sc.next());
}
assertEquals(Lists.newArrayList("Michael Jackson", "Whitney Houston", "John Lennon", "Elvis Presley"), names);
}
}
@@ -0,0 +1,51 @@
package com.baeldung.scanner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Scanner;
import org.junit.jupiter.api.Test;
class NextVsNextLineUnitTest {
@Test
void givenInput_whenUsingNextMethod_thenReturnToken() {
String input = "Hello world";
try (Scanner scanner = new Scanner(input)) {
assertEquals("Hello", scanner.next());
assertEquals("world", scanner.next());
}
}
@Test
void givenInput_whenUsingNextMethodWithCustomDelimiter_thenReturnToken() {
String input = "Hello :world";
try (Scanner scanner = new Scanner(input)) {
scanner.useDelimiter(":");
assertEquals("Hello ", scanner.next());
assertEquals("world", scanner.next());
}
}
@Test
void givenInput_whenUsingNextLineMethod_thenReturnEntireLine() {
String input = "Hello world\nWelcome to baeldung.com";
try (Scanner scanner = new Scanner(input)) {
assertEquals("Hello world", scanner.nextLine());
assertEquals("Welcome to baeldung.com", scanner.nextLine());
}
}
@Test
void givenInput_whenUsingNextLineWithCustomDelimiter_thenIgnoreDelimiter() {
String input = "Hello:world\nWelcome:to baeldung.com";
try (Scanner scanner = new Scanner(input)) {
scanner.useDelimiter(":");
assertEquals("Hello:world", scanner.nextLine());
assertEquals("Welcome:to baeldung.com", scanner.nextLine());
}
}
}
@@ -0,0 +1,43 @@
package com.baeldung.scanner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.Test;
class ScannerNoSuchElementExceptionUnitTest {
@Test
void givenEmptyFile_whenUsingReadFileV1_thenThrowException() {
Exception exception = assertThrows(NoSuchElementException.class, () -> {
ScannerNoSuchElementException.readFileV1("src/test/resources/emptyFile.txt");
});
assertEquals("No line found", exception.getMessage());
}
@Test
void givenEmptyFile_whenUsingReadFileV2_thenSuccess() throws IOException {
String emptyLine = ScannerNoSuchElementException.readFileV2("src/test/resources/emptyFile.txt");
assertEquals("", emptyLine);
}
@Test
void givenEmptyFile_whenUsingReadFileV3_thenSuccess() throws IOException {
String emptyLine = ScannerNoSuchElementException.readFileV3("src/test/resources/emptyFile.txt");
assertEquals("", emptyLine);
}
@Test
void givenEmptyFile_whenUsingReadFileV4_thenSuccess() throws IOException {
String emptyLine = ScannerNoSuchElementException.readFileV4("src/test/resources/emptyFile.txt");
assertEquals("", emptyLine);
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ This module contains articles about core features in the Java language
- [The Java final Keyword – Impact on Performance](https://www.baeldung.com/java-final-performance)
- [The package-info.java File](https://www.baeldung.com/java-package-info)
- [What are Compile-time Constants in Java?](https://www.baeldung.com/java-compile-time-constants)
- [What Are Compile-Time Constants in Java?](https://www.baeldung.com/java-compile-time-constants)
- [Java Objects.hash() vs Objects.hashCode()](https://www.baeldung.com/java-objects-hash-vs-objects-hashcode)
- [Referencing a Method in Javadoc Comments](https://www.baeldung.com/java-method-in-javadoc)
- [Tiered Compilation in JVM](https://www.baeldung.com/jvm-tiered-compilation)
@@ -16,7 +16,7 @@ class Voucher {
return true;
if (!(o instanceof Voucher))
return false;
Voucher other = (Voucher)o;
Voucher other = (Voucher) o;
boolean valueEquals = (this.value == null && other.value == null)
|| (this.value != null && this.value.equals(other.value));
boolean storeEquals = (this.store == null && other.store == null)
@@ -13,15 +13,25 @@ public class MoneyUnitTest {
Money expenses = new Money(55, "USD");
assertTrue(income.equals(expenses));
assertTrue(expenses.equals(income));
}
@Test
public void givenMoneyAndWrongVoucherInstances_whenEquals_thenReturnValuesArentSymmetric() {
Money money = new Money(42, "USD");
WrongVoucher voucher = new WrongVoucher(42, "USD", "Amazon");
assertFalse(voucher.equals(money));
assertTrue(money.equals(voucher));
}
@Test
public void givenMoneyAndVoucherInstances_whenEquals_thenReturnValuesArentSymmetric() {
Money cash = new Money(42, "USD");
WrongVoucher voucher = new WrongVoucher(42, "USD", "Amazon");
Money money = new Money(42, "USD");
Voucher voucher = new Voucher(42, "USD", "Amazon");
assertFalse(voucher.equals(cash));
assertTrue(cash.equals(voucher));
assertFalse(voucher.equals(money));
assertFalse(money.equals(voucher));
}
}
@@ -11,6 +11,6 @@ This module contains articles about types in Java
- [Iterating over Enum Values in Java](https://www.baeldung.com/java-enum-iteration)
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
- [Determine if an Object is of Primitive Type](https://www.baeldung.com/java-object-primitive-type)
- [Determine if an Object Is of Primitive Type](https://www.baeldung.com/java-object-primitive-type)
- [Extending Enums in Java](https://www.baeldung.com/java-extending-enums)
- [Java Class File Naming Conventions](https://www.baeldung.com/java-class-file-naming)
+1 -1
View File
@@ -13,5 +13,5 @@ This module contains articles about core Java non-blocking input and output (IO)
- [Java – Path vs File](https://www.baeldung.com/java-path-vs-file)
- [What Is the Difference Between NIO and NIO.2?](https://www.baeldung.com/java-nio-vs-nio-2)
- [Guide to ByteBuffer](https://www.baeldung.com/java-bytebuffer)
- [Find Files that Match Wildcard Strings in Java](https://www.baeldung.com/java-files-match-wildcard-strings)
- [Find Files That Match Wildcard Strings in Java](https://www.baeldung.com/java-files-match-wildcard-strings)
- [[<-- Prev]](/core-java-modules/core-java-nio)
@@ -7,5 +7,5 @@
- [Make Division of Two Integers Result in a Float](https://www.baeldung.com/java-integer-division-float-result)
- [Creating Random Numbers With No Duplicates in Java](https://www.baeldung.com/java-unique-random-numbers)
- [Multiply a BigDecimal by an Integer in Java](https://www.baeldung.com/java-bigdecimal-multiply-integer)
- [Check if an Integer Value is null or Zero in Java](https://www.baeldung.com/java-check-integer-null-or-zero)
- [Check if an Integer Value Is Null or Zero in Java](https://www.baeldung.com/java-check-integer-null-or-zero)
- [Return Absolute Difference of Two Integers in Java](https://www.baeldung.com/java-absolute-difference-of-two-integers)

Some files were not shown because too many files have changed in this diff Show More