Merge branch 'master' into BAEL-6818-check-value-exists-json-array

This commit is contained in:
Sam Gardner 2023-08-22 10:05:00 +01:00
commit 418b65de46
327 changed files with 10693 additions and 2511 deletions

5
.gitignore vendored
View File

@ -124,4 +124,7 @@ devDb*.db
*.xjb
#neo4j
persistence-modules/neo4j/data/**
persistence-modules/neo4j/data/**
/deep-shallow-copy/.mvn/wrapper
/deep-shallow-copy/mvnw
/deep-shallow-copy/mvnw.cmd

View File

@ -0,0 +1,19 @@
package com.baeldung.algorithms.latlondistance;
public class EquirectangularApproximation {
private static final int EARTH_RADIUS = 6371; // Approx Earth radius in KM
public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double lon1Rad = Math.toRadians(lon1);
double lon2Rad = Math.toRadians(lon2);
double x = (lon2Rad - lon1Rad) * Math.cos((lat1Rad + lat2Rad) / 2);
double y = (lat2Rad - lat1Rad);
double distance = Math.sqrt(x * x + y * y) * EARTH_RADIUS;
return distance;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.algorithms.latlondistance;
public class HaversineDistance {
private static final int EARTH_RADIUS = 6371; // Approx Earth radius in KM
public static double calculateDistance(double startLat, double startLong,
double endLat, double endLong) {
double dLat = Math.toRadians((endLat - startLat));
double dLong = Math.toRadians((endLong - startLong));
startLat = Math.toRadians(startLat);
endLat = Math.toRadians(endLat);
double a = haversine(dLat) + Math.cos(startLat) * Math.cos(endLat) * haversine(dLong);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return EARTH_RADIUS * c;
}
public static double haversine(double val) {
return Math.pow(Math.sin(val / 2), 2);
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.algorithms.latlondistance;
public class VincentyDistance {
// Constants for WGS84 ellipsoid model of Earth
private static final double SEMI_MAJOR_AXIS_MT = 6378137;
private static final double SEMI_MINOR_AXIS_MT = 6356752.314245;
private static final double FLATTENING = 1 / 298.257223563;
private static final double ERROR_TOLERANCE = 1e-12;
public static double calculateDistance(double latitude1, double longitude1, double latitude2, double longitude2) {
double U1 = Math.atan((1 - FLATTENING) * Math.tan(Math.toRadians(latitude1)));
double U2 = Math.atan((1 - FLATTENING) * Math.tan(Math.toRadians(latitude2)));
double sinU1 = Math.sin(U1);
double cosU1 = Math.cos(U1);
double sinU2 = Math.sin(U2);
double cosU2 = Math.cos(U2);
double longitudeDifference = Math.toRadians(longitude2 - longitude1);
double previousLongitudeDifference;
double sinSigma, cosSigma, sigma, sinAlpha, cosSqAlpha, cos2SigmaM;
do {
sinSigma = Math.sqrt(Math.pow(cosU2 * Math.sin(longitudeDifference), 2) +
Math.pow(cosU1 * sinU2 - sinU1 * cosU2 * Math.cos(longitudeDifference), 2));
cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * Math.cos(longitudeDifference);
sigma = Math.atan2(sinSigma, cosSigma);
sinAlpha = cosU1 * cosU2 * Math.sin(longitudeDifference) / sinSigma;
cosSqAlpha = 1 - Math.pow(sinAlpha, 2);
cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
if (Double.isNaN(cos2SigmaM)) {
cos2SigmaM = 0;
}
previousLongitudeDifference = longitudeDifference;
double C = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 * cosSqAlpha));
longitudeDifference = Math.toRadians(longitude2 - longitude1) + (1 - C) * FLATTENING * sinAlpha *
(sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * Math.pow(cos2SigmaM, 2))));
} while (Math.abs(longitudeDifference - previousLongitudeDifference) > ERROR_TOLERANCE);
double uSq = cosSqAlpha * (Math.pow(SEMI_MAJOR_AXIS_MT, 2) - Math.pow(SEMI_MINOR_AXIS_MT, 2)) / Math.pow(SEMI_MINOR_AXIS_MT, 2);
double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
double deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * Math.pow(cos2SigmaM, 2)) -
B / 6 * cos2SigmaM * (-3 + 4 * Math.pow(sinSigma, 2)) * (-3 + 4 * Math.pow(cos2SigmaM, 2))));
double distanceMt = SEMI_MINOR_AXIS_MT * A * (sigma - deltaSigma);
return distanceMt / 1000;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.latlondistance;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
class GeoDistanceUnitTest {
@Test
public void testCalculateDistance() {
double lat1 = 40.714268; // New York
double lon1 = -74.005974;
double lat2 = 34.0522; // Los Angeles
double lon2 = -118.2437;
double equirectangularDistance = EquirectangularApproximation.calculateDistance(lat1, lon1, lat2, lon2);
double haversineDistance = HaversineDistance.calculateDistance(lat1, lon1, lat2, lon2);
double vincentyDistance = VincentyDistance.calculateDistance(lat1, lon1, lat2, lon2);
double expectedDistance = 3944;
assertTrue(Math.abs(equirectangularDistance - expectedDistance) < 100);
assertTrue(Math.abs(haversineDistance - expectedDistance) < 10);
assertTrue(Math.abs(vincentyDistance - expectedDistance) < 0.5);
}
}

View File

@ -1,36 +1,43 @@
package com.baeldung.tlsversion;
import javax.net.ssl.SSLSocket;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import javax.net.ssl.SSLSocket;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.TlsConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.ssl.TLS;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.util.Timeout;
public class ClientTlsVersionExamples {
public static CloseableHttpClient setViaSocketFactory() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
SSLContexts.createDefault(),
new String[] { "TLSv1.2", "TLSv1.3" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setDefaultTlsConfig(TlsConfig.custom()
.setHandshakeTimeout(Timeout.ofSeconds(30))
.setSupportedProtocols(TLS.V_1_2, TLS.V_1_3)
.build())
.build();
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
return HttpClients.custom()
.setConnectionManager(cm)
.build();
}
public static CloseableHttpClient setTlsVersionPerConnection() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.createDefault()) {
@Override
protected void prepareSocket(SSLSocket socket) {
String hostname = socket.getInetAddress().getHostName();
String hostname = socket.getInetAddress()
.getHostName();
if (hostname.endsWith("internal.system.com")) {
socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" });
} else {
@ -39,7 +46,14 @@ public class ClientTlsVersionExamples {
}
};
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
HttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslsf)
.build();
return HttpClients.custom()
.setConnectionManager(connManager)
.build();
}
// To configure the TLS versions for the client, set the https.protocols system property during runtime.
@ -47,15 +61,11 @@ public class ClientTlsVersionExamples {
public static CloseableHttpClient setViaSystemProperties() {
return HttpClients.createSystem();
// Alternatively:
// return HttpClients.custom().useSystemProperties().build();
//return HttpClients.custom().useSystemProperties().build();
}
public static void main(String[] args) throws IOException {
// Alternatively:
// CloseableHttpClient httpClient = setTlsVersionPerConnection();
// CloseableHttpClient httpClient = setViaSystemProperties();
try (CloseableHttpClient httpClient = setViaSocketFactory();
CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
try (CloseableHttpClient httpClient = setViaSocketFactory(); CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);

View File

@ -1,29 +1,5 @@
package com.baeldung.httpclient.advancedconfig;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.apache.http.HttpHeaders;
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.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
@ -34,6 +10,30 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.hc.client5.http.auth.AuthCache;
import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.CredentialsProvider;
import org.apache.hc.client5.http.auth.StandardAuthScheme;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.auth.BasicAuthCache;
import org.apache.hc.client5.http.impl.auth.BasicScheme;
import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.junit.Rule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class HttpClientAdvancedConfigurationIntegrationTest {
@Rule
@ -59,7 +59,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpClient.execute(httpGet);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
assertEquals(response.getCode(), 200);
}
@Test
@ -82,7 +82,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpClient.execute(httpPost);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
assertEquals(response.getCode(), 200);
}
@ -107,7 +107,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
HttpResponse response = httpclient.execute(httpGet);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
assertEquals(response.getCode(), 200);
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
@ -125,14 +125,12 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
// Client credentials
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxy),
new UsernamePasswordCredentials("username_admin", "secret_password"));
CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
.add(new AuthScope(proxy), "username_admin", "secret_password".toCharArray())
.build();
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(proxy, basicAuth);
@ -149,10 +147,11 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
//when
final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
httpGet.setHeader("Authorization", StandardAuthScheme.BASIC);
HttpResponse response = httpclient.execute(httpGet, context);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
assertEquals(response.getCode(), 200);
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}

View File

@ -0,0 +1,64 @@
package com.baeldung.tlsversion;
import javax.net.ssl.SSLSocket;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class ClientTlsVersionExamples {
public static CloseableHttpClient setViaSocketFactory() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
SSLContexts.createDefault(),
new String[] { "TLSv1.2", "TLSv1.3" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
public static CloseableHttpClient setTlsVersionPerConnection() {
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.createDefault()) {
@Override
protected void prepareSocket(SSLSocket socket) {
String hostname = socket.getInetAddress().getHostName();
if (hostname.endsWith("internal.system.com")) {
socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" });
} else {
socket.setEnabledProtocols(new String[] { "TLSv1.3" });
}
}
};
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
// To configure the TLS versions for the client, set the https.protocols system property during runtime.
// For example: java -Dhttps.protocols=TLSv1.1,TLSv1.2,TLSv1.3 -jar webClient.jar
public static CloseableHttpClient setViaSystemProperties() {
return HttpClients.createSystem();
// Alternatively:
// return HttpClients.custom().useSystemProperties().build();
}
public static void main(String[] args) throws IOException {
// Alternatively:
// CloseableHttpClient httpClient = setTlsVersionPerConnection();
// CloseableHttpClient httpClient = setViaSystemProperties();
try (CloseableHttpClient httpClient = setViaSocketFactory();
CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}
}
}

View File

@ -0,0 +1,161 @@
package com.baeldung.httpclient.advancedconfig;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.apache.http.HttpHeaders;
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.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static org.junit.Assert.assertEquals;
public class HttpClientAdvancedConfigurationIntegrationTest {
@Rule
public WireMockRule serviceMock = new WireMockRule(8089);
@Rule
public WireMockRule proxyMock = new WireMockRule(8090);
@Test
public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException {
//given
String userAgent = "BaeldungAgent/1.0";
serviceMock.stubFor(get(urlEqualTo("/detail"))
.withHeader("User-Agent", equalTo(userAgent))
.willReturn(aResponse()
.withStatus(200)));
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://localhost:8089/detail");
httpGet.setHeader(HttpHeaders.USER_AGENT, userAgent);
//when
HttpResponse response = httpClient.execute(httpGet);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
}
@Test
public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException {
//given
String xmlBody = "<xml><id>1</id></xml>";
serviceMock.stubFor(post(urlEqualTo("/person"))
.withHeader("Content-Type", equalTo("application/xml"))
.withRequestBody(equalTo(xmlBody))
.willReturn(aResponse()
.withStatus(200)));
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8089/person");
httpPost.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlBody);
httpPost.setEntity(xmlEntity);
//when
HttpResponse response = httpClient.execute(httpPost);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
}
@Test
public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
//given
proxyMock.stubFor(get(urlMatching(".*"))
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
serviceMock.stubFor(get(urlEqualTo("/private"))
.willReturn(aResponse().withStatus(200)));
HttpHost proxy = new HttpHost("localhost", 8090);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
HttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
//when
final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
HttpResponse response = httpclient.execute(httpGet);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
@Test
public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException {
//given
proxyMock.stubFor(get(urlMatching("/private"))
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
serviceMock.stubFor(get(urlEqualTo("/private"))
.willReturn(aResponse().withStatus(200)));
HttpHost proxy = new HttpHost("localhost", 8090);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
// Client credentials
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxy),
new UsernamePasswordCredentials("username_admin", "secret_password"));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(proxy, basicAuth);
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
context.setAuthCache(authCache);
HttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.setDefaultCredentialsProvider(credentialsProvider)
.build();
//when
final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
HttpResponse response = httpclient.execute(httpGet, context);
//then
assertEquals(response.getStatusLine().getStatusCode(), 200);
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
}

View File

@ -12,3 +12,4 @@ You can build the project from the command line using: *mvn clean install*, or i
- [Is a Key Required as Part of Sending Messages to Kafka?](https://www.baeldung.com/java-kafka-message-key)
- [Read Data From the Beginning Using Kafka Consumer API](https://www.baeldung.com/java-kafka-consumer-api-read)
- [Get Partition Count for a Topic in Kafka](https://www.baeldung.com/java-kafka-partition-count-topic)
- [bootstrap-server in Kafka Configuration](https://www.baeldung.com/java-kafka-bootstrap-server)

View File

@ -0,0 +1,39 @@
package com.baeldung.kafka.consumer;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.serialization.LongDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
public class SimpleConsumerWithBootStrapServers {
public static void main(String[] args) {
try(final Consumer<Long, String> consumer = createConsumer()) {
ConsumerRecords<Long, String> records = consumer.poll(Duration.ofMinutes(1));
for(ConsumerRecord<Long, String> record : records) {
System.out.println(record.value());
}
}
}
private static Consumer<Long, String> createConsumer() {
final Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
"localhost:9092,another-host.com:29092");
props.put(ConsumerConfig.GROUP_ID_CONFIG,
"MySampleConsumer");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
LongDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class.getName());
// Create the consumer using props.
final Consumer<Long, String> consumer = new KafkaConsumer<Long, String>(props);
// Subscribe to the topic.
consumer.subscribe(Arrays.asList("samples"));
return consumer;
}
}

View File

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-libraries-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apache-libraries-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation.validation-api.version}</version>
</dependency>
</dependencies>
<properties>
<javax.validation.validation-api.version>2.0.1.Final</javax.validation.validation-api.version>
</properties>
</project>

View File

@ -0,0 +1,18 @@
package com.baeldung.xslt;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
public class XSLTProcessor {
public static void transformXMLUsingXSLT(String inputXMLPath, String xsltPath, String outputHTMLPath) throws TransformerException {
Source xmlSource = new StreamSource(new File(inputXMLPath));
Source xsltSource = new StreamSource(new File(xsltPath));
Result output = new StreamResult(new File(outputHTMLPath));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(xsltSource);
transformer.transform(xmlSource, output);
}
}

View File

@ -0,0 +1,47 @@
{
"type":"record",
"name":"AvroHttpRequest",
"namespace":"com.baeldung.avro.model",
"fields":[
{
"name":"requestTime",
"type":"long"
},
{
"name":"clientIdentifier",
"type":{
"type":"record",
"name":"ClientIdentifier",
"fields":[
{
"name":"hostName",
"type":"string"
},
{
"name":"ipAddress",
"type":"string"
}
]
}
},
{
"name":"employeeNames",
"type":{
"type":"array",
"items":"string"
},
"default":null
},
{
"name":"active",
"type":{
"type":"enum",
"name":"Active",
"symbols":[
"YES",
"NO"
]
}
}
]
}

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="org.apache.meecrowave" level="warn">
<AppenderRef ref="Console"/>
</Logger>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

View File

@ -1,10 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %msg%n</pattern>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="debug">
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,29 @@
package com.baeldung.xslt;
import org.junit.jupiter.api.Test;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class XSLTProcessorUnitTest {
@Test
public void givenValidInputAndStylesheet_whenTransformingXML_thenOutputHTMLCreated() throws TransformerException, IOException {
// Given
String inputXMLPath = "src/test/resources/input.xml";
String xsltPath = "src/test/resources/stylesheet.xslt";
String outputHTMLPath = "src/test/resources/output.html";
XSLTProcessor.transformXMLUsingXSLT(inputXMLPath, xsltPath, outputHTMLPath);
Path outputFile = Paths.get(outputHTMLPath);
assertTrue(Files.exists(outputFile));
}
}

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<person gender="male">
<name>John Doe</name>
<age>30</age>
</person>
<person gender="female">
<name>Jane Smith</name>
<age>25</age>
</person>
</root>

View File

@ -0,0 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<p>Male person: John Doe, Age: 30</p>
<p>Female person: Jane Smith, Age: 25</p>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="person[@gender='male']">
<xsl:element name="p">
<xsl:text>Male person: </xsl:text>
<xsl:value-of select="name"/>
<xsl:text>, Age: </xsl:text>
<xsl:value-of select="age"/>
</xsl:element>
</xsl:template>
<xsl:template match="person[@gender='female']">
<xsl:element name="p">
<xsl:text>Female person: </xsl:text>
<xsl:value-of select="name"/>
<xsl:text>, Age: </xsl:text>
<xsl:value-of select="age"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>

View File

@ -13,4 +13,5 @@ This module contains articles about Apache POI.
- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)
- [Set the Date Format Using Apache POI](https://www.baeldung.com/java-apache-poi-date-format)
- [Replacing Variables in a Document Template with Java](https://www.baeldung.com/java-replace-pattern-word-document-doc-docx)
- [Lock Header Rows With Apache POI](https://www.baeldung.com/java-apache-poi-lock-header-rows)
- More articles: [[<-- prev]](../apache-poi)

View File

@ -0,0 +1,19 @@
package com.baeldung.poi.excel.locksheet;
import org.apache.poi.ss.usermodel.*;
public class LockSheet {
public void lockFirstRow(Sheet sheet) {
sheet.createFreezePane(0, 1);
}
public void lockTwoRows(Sheet sheet) {
sheet.createFreezePane(0, 2);
}
public void lockFirstColumn(Sheet sheet) {
sheet.createFreezePane(1, 0);
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.poi.excel.locksheet;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.*;
class LockSheetUnitTest {
private LockSheet lockSheet;
private Workbook workbook;
private Sheet sheet;
@BeforeEach
void setup() {
workbook = new XSSFWorkbook();
sheet = workbook.createSheet();
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("row 1 col 1");
row.createCell(1).setCellValue("row 1 col 2");
row = sheet.createRow(1);
row.createCell(0).setCellValue("row 2 col 1");
row.createCell(1).setCellValue("row 2 col 2");
lockSheet = new LockSheet();
}
@AfterEach
void cleanup() throws IOException {
workbook.close();
}
@Test
void whenLockFirstRow_thenFirstRowIsLocked() {
lockSheet.lockFirstRow(sheet);
assertEquals(sheet.getPaneInformation().getHorizontalSplitPosition(), 1);
}
@Test
void whenLockTwoRows_thenTwoRowsAreLocked() {
lockSheet.lockTwoRows(sheet);
assertEquals(sheet.getPaneInformation().getHorizontalSplitPosition(), 2);
}
@Test
void whenLockFirstColumn_thenFirstColumnIsLocked() {
lockSheet.lockFirstColumn(sheet);
assertEquals(sheet.getPaneInformation().getVerticalSplitPosition(), 1);
}
}

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>aws-s3-update-object</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>aws-s3-update-object</name>
<description>Project demonstrating overwriting of S3 objects</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>${aws-java-sdk-version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<aws-java-sdk-version>1.12.523</aws-java-sdk-version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
package com.baeldung.awss3updateobject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AwsS3UpdateObjectApplication {
public static void main(String[] args) {
SpringApplication.run(AwsS3UpdateObjectApplication.class, args);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.awss3updateobject.controller;
import com.baeldung.awss3updateobject.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("api/v1/file")
public class FileController {
@Autowired
FileService fileService;
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile multipartFile) throws Exception {
return this.fileService.uploadFile(multipartFile);
}
@PostMapping("/update")
public String updateFile(@RequestParam("file") MultipartFile multipartFile, @RequestParam("filePath") String exitingFilePath) throws Exception {
return this.fileService.updateFile(multipartFile, exitingFilePath);
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.awss3updateobject.service;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
@Service
public class FileService {
private static final Logger logger = LoggerFactory.getLogger(FileService.class);
public AmazonS3 amazonS3;
@Value("${aws.s3bucket}")
public String awsS3Bucket;
@PostConstruct
private void init(){
AWSCredentials credentials = new BasicAWSCredentials(
"AWS AccessKey",
"AWS secretKey"
);
this.amazonS3 = AmazonS3ClientBuilder.standard()
.withRegion(Regions.fromName("us-east-1"))
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
}
public String uploadFile(MultipartFile multipartFile) throws Exception {
String key = "/documents/" + multipartFile.getOriginalFilename();
return this.uploadDocument(this.awsS3Bucket, key, multipartFile);
}
public String updateFile(MultipartFile multipartFile, String key) throws Exception {
return this.uploadDocument(this.awsS3Bucket, key, multipartFile);
}
private String uploadDocument(String s3bucket, String key, MultipartFile multipartFile) throws Exception {
try {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(multipartFile.getContentType());
Map<String, String> attributes = new HashMap<>();
attributes.put("document-content-size", String.valueOf(multipartFile.getSize()));
metadata.setUserMetadata(attributes);
InputStream documentStream = multipartFile.getInputStream();
PutObjectResult putObjectResult = this.amazonS3.putObject(new PutObjectRequest(s3bucket, key, documentStream, metadata));
S3Object s3Object = this.amazonS3.getObject(s3bucket, key);
logger.info("Last Modified: " + s3Object.getObjectMetadata().getLastModified());
return key;
} catch (AmazonS3Exception ex) {
if (ex.getErrorCode().equalsIgnoreCase("NoSuchBucket")) {
String msg = String.format("No bucket found with name %s", s3bucket);
throw new Exception(msg);
} else if (ex.getErrorCode().equalsIgnoreCase("AccessDenied")) {
String msg = String.format("Access denied to S3 bucket %s", s3bucket);
throw new Exception(msg);
}
throw ex;
} catch (IOException ex) {
String msg = String.format("Error saving file %s to AWS S3 bucket %s", key, s3bucket);
throw new Exception(msg);
}
}
}

View File

@ -0,0 +1 @@
aws.s3bucket=baeldung-documents;

View File

@ -0,0 +1,62 @@
package com.baeldung.awss3updateobject.controller;
import com.baeldung.awss3updateobject.service.FileService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.multipart.MultipartFile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
public class FileControllerUnitTest {
private MockMvc mockMvc;
@Mock
private FileService fileService;
@InjectMocks
private FileController fileController;
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(fileController).build();
}
@Test
public void givenValidMultipartFile_whenUploadedViaEndpoint_thenCorrectPathIsReturned() throws Exception {
MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt", "text/plain", "sample file content".getBytes());
String expectedResult = "File Uploaded Successfully";
when(fileService.uploadFile(multipartFile)).thenReturn(expectedResult);
mockMvc.perform(multipart("/api/v1/file/upload").file(multipartFile))
.andExpect(status().isOk())
.andExpect(content().string(expectedResult));
}
@Test
public void givenValidMultipartFileAndExistingPath_whenUpdatedViaEndpoint_thenSamePathIsReturned() throws Exception {
MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt", "text/plain", "updated file content".getBytes());
String filePath = "some/path/to/file";
String expectedResult = "File Updated Successfully";
when(fileService.updateFile(multipartFile, filePath)).thenReturn(expectedResult);
mockMvc.perform(multipart("/api/v1/file/update")
.file(multipartFile)
.param("filePath", filePath))
.andExpect(status().isOk())
.andExpect(content().string(expectedResult));
}
}

View File

@ -0,0 +1,99 @@
package com.baeldung.awss3updateobject.service;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
public class FileServiceUnitTest {
@Mock
private AmazonS3 amazonS3;
@Mock
private MultipartFile multipartFile;
@InjectMocks
private FileService fileService;
@BeforeEach
public void setup() {
MockitoAnnotations.openMocks(this);
fileService = new FileService();
fileService.awsS3Bucket = "test-bucket";
fileService.amazonS3 = amazonS3;
}
@Test
public void givenValidFile_whenUploaded_thenKeyMatchesDocumentPath() throws Exception {
when(multipartFile.getName()).thenReturn("testFile");
when(multipartFile.getOriginalFilename()).thenReturn("testFile");
when(multipartFile.getContentType()).thenReturn("application/pdf");
when(multipartFile.getSize()).thenReturn(1024L);
when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class));
S3Object s3Object = new S3Object();
when(amazonS3.putObject(any())).thenReturn(null);
when(amazonS3.getObject(anyString(), anyString())).thenReturn(s3Object);
String key = fileService.uploadFile(multipartFile);
assertEquals("/documents/testFile", key);
}
@Test
public void givenValidFile_whenUploadFailsDueToNoBucket_thenExceptionIsThrown() throws Exception {
when(multipartFile.getName()).thenReturn("testFile");
when(multipartFile.getOriginalFilename()).thenReturn("testFile");
when(multipartFile.getContentType()).thenReturn("application/pdf");
when(multipartFile.getSize()).thenReturn(1024L);
when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class));
AmazonS3Exception exception = new AmazonS3Exception("Test exception");
exception.setErrorCode("NoSuchBucket");
when(amazonS3.putObject(any(PutObjectRequest.class))).thenThrow(exception);
assertThrows(Exception.class, () -> fileService.uploadFile(multipartFile));
}
@Test
public void givenExistingFile_whenUpdated_thenSameKeyIsReturned() throws Exception {
when(multipartFile.getName()).thenReturn("testFile");
when(multipartFile.getContentType()).thenReturn("application/pdf");
when(multipartFile.getSize()).thenReturn(1024L);
when(multipartFile.getInputStream()).thenReturn(mock(InputStream.class));
S3Object s3Object = new S3Object();
when(amazonS3.putObject(any(PutObjectRequest.class))).thenReturn(null);
when(amazonS3.getObject(anyString(), anyString())).thenReturn(s3Object);
String key = "/documents/existingFile";
String resultKey = fileService.updateFile(multipartFile, key);
assertEquals(key, resultKey);
}
@Test
public void givenFileWithIOException_whenUpdated_thenExceptionIsThrown() throws Exception {
when(multipartFile.getName()).thenReturn("testFile");
when(multipartFile.getContentType()).thenReturn("application/pdf");
when(multipartFile.getSize()).thenReturn(1024L);
when(multipartFile.getInputStream()).thenThrow(new IOException("Test IO Exception"));
assertThrows(Exception.class, () -> fileService.updateFile(multipartFile, "/documents/existingFile"));
}
}

View File

@ -1,2 +0,0 @@
## Relevant Articles
- [Listing All AWS S3 Objects in a Bucket Using Java](https://www.baeldung.com/java-aws-s3-list-bucket-objects)

View File

@ -1,50 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.s3</groupId>
<artifactId>aws-s3-v2</artifactId>
<version>1.0-SNAPSHOT</version>
<name>aws-s3-v2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>aws-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<aws.java.sdk.version>2.20.52</aws.java.sdk.version>
<maven.compiler.plugin.version>3.6.1</maven.compiler.plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
<version>${aws.java.sdk.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,22 +0,0 @@
package com.baeldung.s3.listobjects;
import software.amazon.awssdk.regions.Region;
public class Main {
private static String AWS_BUCKET = "baeldung-tutorial-s3";
public static Region AWS_REGION = Region.EU_CENTRAL_1;
public static void main(String[] args) {
S3Service s3Service = new S3Service(AWS_REGION);
s3Service.putObject(AWS_BUCKET, FileGenerator.generateFiles(1000, 1));
s3Service.listBuckets();
s3Service.listObjectsInBucket(AWS_BUCKET);
s3Service.listAllObjectsInBucket(AWS_BUCKET);
s3Service.listAllObjectsInBucketPaginated(AWS_BUCKET, 500);
s3Service.listAllObjectsInBucketPaginatedWithPrefix(AWS_BUCKET, 500, "backup/");
s3Service.cleanup();
}
}

View File

@ -1,129 +0,0 @@
package com.baeldung.s3.listobjects;
import java.util.List;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
class S3Service {
private S3Client s3Client;
public S3Service(Region awsRegion) {
init(awsRegion);
}
public S3Service(S3Client s3Client) {
this.s3Client = s3Client;
}
public void init(Region awsRegion) {
this.s3Client = S3Client.builder()
.region(awsRegion)
.credentialsProvider(ProfileCredentialsProvider.create("default"))
.build();
}
public void listObjectsInBucket(String bucketName) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.build();
ListObjectsV2Response listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request);
List<S3Object> contents = listObjectsV2Response.contents();
System.out.println("Number of objects in the bucket: " + contents.stream().count());
contents.stream().forEach(System.out::println);
}
public void listAllObjectsInBucket(String bucketName) {
String nextContinuationToken = null;
long totalObjects = 0;
do {
ListObjectsV2Request.Builder requestBuilder = ListObjectsV2Request.builder()
.bucket(bucketName)
.continuationToken(nextContinuationToken);
ListObjectsV2Response response = s3Client.listObjectsV2(requestBuilder.build());
nextContinuationToken = response.nextContinuationToken();
totalObjects += response.contents().stream()
.peek(System.out::println)
.reduce(0, (subtotal, element) -> subtotal + 1, Integer::sum);
} while (nextContinuationToken != null);
System.out.println("Number of objects in the bucket: " + totalObjects);
}
public void listAllObjectsInBucketPaginated(String bucketName, int pageSize) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(pageSize) // Set the maxKeys parameter to control the page size
.build();
ListObjectsV2Iterable listObjectsV2Iterable = s3Client.listObjectsV2Paginator(listObjectsV2Request);
long totalObjects = 0;
for (ListObjectsV2Response page : listObjectsV2Iterable) {
long retrievedPageSize = page.contents().stream()
.peek(System.out::println)
.reduce(0, (subtotal, element) -> subtotal + 1, Integer::sum);
totalObjects += retrievedPageSize;
System.out.println("Page size: " + retrievedPageSize);
}
System.out.println("Total objects in the bucket: " + totalObjects);
}
public void listAllObjectsInBucketPaginatedWithPrefix(String bucketName, int pageSize, String prefix) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(pageSize) // Set the maxKeys parameter to control the page size
.prefix(prefix)
.build();
ListObjectsV2Iterable listObjectsV2Iterable = s3Client.listObjectsV2Paginator(listObjectsV2Request);
long totalObjects = 0;
for (ListObjectsV2Response page : listObjectsV2Iterable) {
long retrievedPageSize = page.contents().stream()
.peek(System.out::println)
.reduce(0, (subtotal, element) -> subtotal + 1, Integer::sum);
totalObjects += retrievedPageSize;
System.out.println("Page size: " + retrievedPageSize);
}
System.out.println("Total objects in the bucket: " + totalObjects);
}
public void listBuckets() {
// List all buckets
ListBucketsResponse listBucketsResponse = s3Client.listBuckets();
// Display the bucket names
List<Bucket> buckets = listBucketsResponse.buckets();
System.out.println("Buckets:");
for (Bucket bucket : buckets) {
System.out.println(bucket.name());
}
}
public void putObject(String bucketName, List<File> files) {
try {
files.stream().forEach(file -> {
s3Client.putObject(PutObjectRequest.builder().bucket(bucketName).key(file.getName()).build(),
RequestBody.fromByteBuffer(file.getContent()));
System.out.println("Uploaded file: " + file.getName());
});
} catch (S3Exception e) {
System.err.println("Upload failed");
e.printStackTrace();
}
}
public void cleanup() {
this.s3Client.close();
}
}

View File

@ -8,3 +8,4 @@ This module contains articles about Simple Storage Service (S3) on AWS
- [Multipart Uploads in Amazon S3 with Java](https://www.baeldung.com/aws-s3-multipart-upload)
- [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3)
- [Check if a Specified Key Exists in a Given S3 Bucket Using Java](https://www.baeldung.com/java-aws-s3-check-specified-key-exists)
- [Listing All AWS S3 Objects in a Bucket Using Java](https://www.baeldung.com/java-aws-s3-list-bucket-objects)

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>aws-s3</artifactId>
<version>0.1.0-SNAPSHOT</version>
@ -16,10 +16,11 @@
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>${aws-java-sdk.version}</version>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
<version>${aws.java.sdk.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
@ -60,6 +61,7 @@
</build>
<properties>
<aws.java.sdk.version>2.20.52</aws.java.sdk.version>
<commons-codec-version>1.10.L001</commons-codec-version>
<jets3t-version>0.9.4.0006L</jets3t-version>
</properties>

View File

@ -1,42 +0,0 @@
package com.baeldung.s3;
import org.apache.http.HttpStatus;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
public class AWSS3ObjectUtils {
private AmazonS3 s3Client;
public AWSS3ObjectUtils(AmazonS3 s3client) {
this.s3Client = s3client;
}
public boolean doesObjectExistByDefaultMethod(String bucket, String key) {
return s3Client.doesObjectExist(bucket, key);
}
public boolean doesObjectExistByListObjects(String bucket, String key) {
return s3Client.listObjects(bucket)
.getObjectSummaries()
.stream()
.filter(s3ObjectSummary -> s3ObjectSummary.getKey()
.equals(key))
.findFirst()
.isPresent();
}
public boolean doesObjectExistByMetaData(String bucket, String key) {
try {
s3Client.getObjectMetadata(bucket, key);
return true;
} catch (AmazonServiceException e) {
if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
return false;
} else {
throw e;
}
}
}
}

View File

@ -1,93 +0,0 @@
package com.baeldung.s3;
import java.io.File;
import java.net.URL;
import java.util.List;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.CopyObjectResult;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.model.DeleteObjectsResult;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
public class AWSS3Service {
private final AmazonS3 s3client;
public AWSS3Service() {
this(new AmazonS3Client() {
});
}
public AWSS3Service(AmazonS3 s3client) {
this.s3client = s3client;
}
//is bucket exist?
public boolean doesBucketExist(String bucketName) {
return s3client.doesBucketExist(bucketName);
}
//create a bucket
public Bucket createBucket(String bucketName) {
return s3client.createBucket(bucketName);
}
//list all buckets
public List<Bucket> listBuckets() {
return s3client.listBuckets();
}
//delete a bucket
public void deleteBucket(String bucketName) {
s3client.deleteBucket(bucketName);
}
//uploading object
public PutObjectResult putObject(String bucketName, String key, File file) {
return s3client.putObject(bucketName, key, file);
}
//uploading object and getting url
public URL getObjectURL(String bucketName, String key, File file) {
s3client.putObject(bucketName, key, file);
return s3client.getUrl(bucketName, key);
}
//listing objects
public ObjectListing listObjects(String bucketName) {
return s3client.listObjects(bucketName);
}
//get an object
public S3Object getObject(String bucketName, String objectKey) {
return s3client.getObject(bucketName, objectKey);
}
//copying an object
public CopyObjectResult copyObject(
String sourceBucketName,
String sourceKey,
String destinationBucketName,
String destinationKey
) {
return s3client.copyObject(
sourceBucketName,
sourceKey,
destinationBucketName,
destinationKey
);
}
//deleting an object
public void deleteObject(String bucketName, String objectKey) {
s3client.deleteObject(bucketName, objectKey);
}
//deleting multiple Objects
public DeleteObjectsResult deleteObjects(DeleteObjectsRequest delObjReq) {
return s3client.deleteObjects(delObjReq);
}
}

View File

@ -1,21 +1,21 @@
package com.baeldung.s3.listobjects;
import java.nio.ByteBuffer;
public class File {
private String name;
private ByteBuffer content;
public File(String name, ByteBuffer content) {
this.name = name;
this.content = content;
}
public String getName() {
return name;
}
public ByteBuffer getContent() {
return content;
}
}
package com.baeldung.s3;
import java.nio.ByteBuffer;
public class File {
private String name;
private ByteBuffer content;
public File(String name, ByteBuffer content) {
this.name = name;
this.content = content;
}
public String getName() {
return name;
}
public ByteBuffer getContent() {
return content;
}
}

View File

@ -1,27 +1,27 @@
package com.baeldung.s3.listobjects;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class FileGenerator {
public static List<File> generateFiles(int fileCount, int fileSize) {
List<File> files = new ArrayList<>();
for (int i = 0; i < fileCount; i++) {
String fileName = "file_" + i + ".txt";
ByteBuffer fileContent = generateRandomBytes(fileSize);
files.add(new File(fileName, fileContent));
}
return files;
}
private static ByteBuffer generateRandomBytes(int size) {
byte[] array = new byte[size];
new Random().nextBytes(array);
return ByteBuffer.wrap(array);
}
}
package com.baeldung.s3;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class FileGenerator {
public static List<File> generateFiles(int fileCount, int fileSize) {
List<File> files = new ArrayList<>();
for (int i = 0; i < fileCount; i++) {
String fileName = "file_" + i + ".txt";
ByteBuffer fileContent = generateRandomBytes(fileSize);
files.add(new File(fileName, fileContent));
}
return files;
}
private static ByteBuffer generateRandomBytes(int size) {
byte[] array = new byte[size];
new Random().nextBytes(array);
return ByteBuffer.wrap(array);
}
}

View File

@ -1,56 +1,101 @@
package com.baeldung.s3;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.Upload;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.*;
import java.io.File;
import java.util.concurrent.Executors;
public class MultipartUpload {
public static void main(String[] args) throws Exception {
public static void main(String[] args) {
String existingBucketName = "baeldung-bucket";
String keyName = "my-picture.jpg";
String filePath = "documents/my-picture.jpg";
AmazonS3 amazonS3 = AmazonS3ClientBuilder
.standard()
.withCredentials(new DefaultAWSCredentialsProviderChain())
.withRegion(Regions.DEFAULT_REGION)
.build();
ProfileCredentialsProvider credentialsProvider = ProfileCredentialsProvider.create();
Region region = Region.US_EAST_1;
S3Client s3 = S3Client.builder()
.region(region)
.credentialsProvider(credentialsProvider)
.build();
int maxUploadThreads = 5;
// Initiate a multipart upload
CreateMultipartUploadRequest createRequest = CreateMultipartUploadRequest.builder()
.bucket(existingBucketName)
.key(keyName)
.build();
TransferManager tm = TransferManagerBuilder
.standard()
.withS3Client(amazonS3)
.withMultipartUploadThreshold((long) (5 * 1024 * 1024))
.withExecutorFactory(() -> Executors.newFixedThreadPool(maxUploadThreads))
.build();
CreateMultipartUploadResponse createResponse = s3.createMultipartUpload(createRequest);
ProgressListener progressListener =
progressEvent -> System.out.println("Transferred bytes: " + progressEvent.getBytesTransferred());
String uploadId = createResponse.uploadId();
PutObjectRequest request = new PutObjectRequest(existingBucketName, keyName, new File(filePath));
// Prepare the parts to be uploaded
List<CompletedPart> completedParts = new ArrayList<>();
int partNumber = 1;
ByteBuffer buffer = ByteBuffer.allocate(5 * 1024 * 1024); // Set your preferred part size (5 MB in this example)
request.setGeneralProgressListener(progressListener);
// Read the file and upload each part
try (RandomAccessFile file = new RandomAccessFile(filePath, "r")) {
long fileSize = file.length();
long position = 0;
Upload upload = tm.upload(request);
while (position < fileSize) {
file.seek(position);
int bytesRead = file.getChannel().read(buffer);
try {
upload.waitForCompletion();
System.out.println("Upload complete.");
} catch (AmazonClientException e) {
System.out.println("Error occurred while uploading file");
buffer.flip();
UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
.bucket(existingBucketName)
.key(keyName)
.uploadId(uploadId)
.partNumber(partNumber)
.contentLength((long) bytesRead)
.build();
UploadPartResponse response = s3.uploadPart(uploadPartRequest, RequestBody.fromByteBuffer(buffer));
completedParts.add(CompletedPart.builder()
.partNumber(partNumber)
.eTag(response.eTag())
.build());
buffer.clear();
position += bytesRead;
partNumber++;
}
} catch (IOException e) {
e.printStackTrace();
}
// Complete the multipart upload
CompletedMultipartUpload completedUpload = CompletedMultipartUpload.builder()
.parts(completedParts)
.build();
CompleteMultipartUploadRequest completeRequest = CompleteMultipartUploadRequest.builder()
.bucket(existingBucketName)
.key(keyName)
.uploadId(uploadId)
.multipartUpload(completedUpload)
.build();
CompleteMultipartUploadResponse completeResponse = s3.completeMultipartUpload(completeRequest);
// Print the object's URL
String objectUrl = s3.utilities().getUrl(GetUrlRequest.builder()
.bucket(existingBucketName)
.key(keyName)
.build())
.toExternalForm();
System.out.println("Uploaded object URL: " + objectUrl);
}
}

View File

@ -1,104 +1,69 @@
package com.baeldung.s3;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import software.amazon.awssdk.regions.Region;
public class S3Application {
private static final AWSCredentials credentials;
private static String bucketName;
private static String AWS_BUCKET = "baeldung-tutorial-s3";
public static Region AWS_REGION = Region.EU_CENTRAL_1;
static {
//put your accesskey and secretkey here
credentials = new BasicAWSCredentials(
"<AWS accesskey>",
"<AWS secretkey>"
);
}
public static void main(String[] args) throws IOException {
//set-up the client
AmazonS3 s3client = AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_EAST_2)
.build();
AWSS3Service awsService = new AWSS3Service(s3client);
bucketName = "baeldung-bucket";
public static void main(String[] args) {
S3Service s3Service = new S3Service(AWS_REGION);
//creating a bucket
if(awsService.doesBucketExist(bucketName)) {
s3Service.createBucket(AWS_BUCKET);
//check if a bucket exists
if(s3Service.doesBucketExist(AWS_BUCKET)) {
System.out.println("Bucket name is not available."
+ " Try again with a different Bucket name.");
+ " Try again with a different Bucket name.");
return;
}
awsService.createBucket(bucketName);
//list all the buckets
for(Bucket s : awsService.listBuckets() ) {
System.out.println(s.getName());
}
//deleting bucket
awsService.deleteBucket("baeldung-bucket-test2");
//uploading object
awsService.putObject(
bucketName,
"Document/hello.txt",
new File("/Users/user/Document/hello.txt")
);
//uploading object and getting url
awsService.getObjectURL(bucketName, "Document/hello.txt", new File("/Users/user/Document/hello.txt"));
s3Service.putObjects(AWS_BUCKET, FileGenerator.generateFiles(1000, 1));
//list all the buckets
s3Service.listBuckets();
s3Service.listObjectsInBucket(AWS_BUCKET);
s3Service.listAllObjectsInBucket(AWS_BUCKET);
s3Service.listAllObjectsInBucketPaginated(AWS_BUCKET, 500);
s3Service.listAllObjectsInBucketPaginatedWithPrefix(AWS_BUCKET, 500, "backup/");
//deleting bucket
s3Service.deleteBucket("baeldung-bucket-test2");
//uploading object
s3Service.putObject(
AWS_BUCKET,
"Document/hello.txt",
new File("/Users/user/Document/hello.txt")
);
//listing objects
ObjectListing objectListing = awsService.listObjects(bucketName);
for(S3ObjectSummary os : objectListing.getObjectSummaries()) {
System.out.println(os.getKey());
}
s3Service.listObjects(AWS_BUCKET);
//downloading an object
S3Object s3object = awsService.getObject(bucketName, "Document/hello.txt");
S3ObjectInputStream inputStream = s3object.getObjectContent();
FileUtils.copyInputStreamToFile(inputStream, new File("/Users/user/Desktop/hello.txt"));
s3Service.getObject(AWS_BUCKET, "Document/hello.txt");
//copying an object
awsService.copyObject(
"baeldung-bucket",
"picture/pic.png",
"baeldung-bucket2",
"Document/picture.png"
s3Service.copyObject(
"baeldung-bucket",
"picture/pic.png",
"baeldung-bucket2",
"Document/picture.png"
);
//deleting an object
awsService.deleteObject(bucketName, "Document/hello.txt");
s3Service.deleteObject(AWS_BUCKET, "Document/hello.txt");
//deleting multiple objects
String objkeyArr[] = {
"Document/hello2.txt",
"Document/picture.png"
};
DeleteObjectsRequest delObjReq = new DeleteObjectsRequest("baeldung-bucket")
.withKeys(objkeyArr);
awsService.deleteObjects(delObjReq);
List<String> objKeyList = List.of("Document/hello2.txt", "Document/picture.png");
s3Service.deleteObjects(AWS_BUCKET, objKeyList);
}
}

View File

@ -0,0 +1,323 @@
package com.baeldung.s3;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.Bucket;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.Delete;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
class S3Service {
private S3Client s3Client;
public S3Service(Region awsRegion) {
init(awsRegion);
}
public S3Service(S3Client s3Client) {
this.s3Client = s3Client;
}
public void init(Region awsRegion) {
this.s3Client = S3Client.builder()
.region(awsRegion)
.credentialsProvider(ProfileCredentialsProvider.create("default"))
.build();
}
//is bucket exist?
public boolean doesBucketExist(String bucketName) {
HeadBucketRequest headBucketRequest = HeadBucketRequest.builder()
.bucket(bucketName)
.build();
try {
s3Client.headBucket(headBucketRequest);
return true;
} catch (NoSuchBucketException e) {
return false;
}
}
//create a bucket
public void createBucket(String bucketName) {
CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
.bucket(bucketName)
.build();
s3Client.createBucket(bucketRequest);
}
//delete a bucket
public void deleteBucket(String bucketName) {
try {
DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder()
.bucket(bucketName)
.build();
s3Client.deleteBucket(deleteBucketRequest);
System.out.println("Successfully deleted bucket : " + bucketName);
} catch (S3Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
//uploading object
public PutObjectResponse putObject(String bucketName, String key, java.io.File file) {
PutObjectRequest request = PutObjectRequest.builder()
.bucket(bucketName)
.key(key)
.build();
return s3Client.putObject(request, Path.of(file.toURI()) );
}
//listing objects
public void listObjects(String bucketName) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.build();
ListObjectsV2Response listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request);
for(S3Object os : listObjectsV2Response.contents()) {
System.out.println(os.key());
}
}
//get an object
public void getObject(String bucketName, String objectKey) {
try {
GetObjectRequest objectRequest = GetObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
ResponseBytes<GetObjectResponse> responseResponseBytes = s3Client.getObjectAsBytes(objectRequest);
byte[] data = responseResponseBytes.asByteArray();
// Write the data to a local file.
java.io.File myFile = new java.io.File("/Users/user/Desktop/hello.txt" );
OutputStream os = new FileOutputStream(myFile);
os.write(data);
System.out.println("Successfully obtained bytes from an S3 object");
os.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
//copying an object
public CopyObjectResponse copyObject(
String sourceBucketName,
String sourceKey,
String destinationBucketName,
String destinationKey
) {
CopyObjectRequest copyObjectRequest = CopyObjectRequest.builder()
.sourceBucket(sourceBucketName)
.sourceKey(sourceKey)
.destinationBucket(destinationBucketName)
.destinationKey(destinationKey)
.build();
return s3Client.copyObject(copyObjectRequest);
}
//deleting an object
public void deleteObject(String bucketName, String objectKey) {
DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
s3Client.deleteObject(deleteObjectRequest);
}
//deleting multiple Objects
public void deleteObjects(String bucketName, List<String> keys ) {
ArrayList<ObjectIdentifier> toDelete = new ArrayList<>();
for(String objKey : keys) {
toDelete.add(ObjectIdentifier.builder()
.key(objKey)
.build());
}
DeleteObjectsRequest deleteObjectRequest = DeleteObjectsRequest.builder()
.bucket(bucketName)
.delete(Delete.builder()
.objects(toDelete).build())
.build();
s3Client.deleteObjects(deleteObjectRequest);
}
public boolean doesObjectExistByListObjects(String bucketName, String key) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.build();
ListObjectsV2Response listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request);
return listObjectsV2Response.contents()
.stream()
.filter(s3ObjectSummary -> s3ObjectSummary.getValueForField("key", String.class)
.equals(key))
.findFirst()
.isPresent();
}
public boolean doesObjectExistByDefaultMethod(String bucket, String key) {
try {
HeadObjectRequest headObjectRequest = HeadObjectRequest.builder()
.bucket(bucket)
.key(key)
.build();
s3Client.headObject(headObjectRequest);
System.out.println("Object exists");
return true;
} catch (S3Exception e) {
if (e.statusCode() == 404) {
System.out.println("Object does not exist");
return false;
} else {
throw e;
}
}
}
public void listBuckets() {
// List all buckets
ListBucketsResponse listBucketsResponse = s3Client.listBuckets();
// Display the bucket names
List<Bucket> buckets = listBucketsResponse.buckets();
System.out.println("Buckets:");
for (Bucket bucket : buckets) {
System.out.println(bucket.name());
}
}
public void listObjectsInBucket(String bucketName) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.build();
ListObjectsV2Response listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request);
List<S3Object> contents = listObjectsV2Response.contents();
System.out.println("Number of objects in the bucket: " + contents.stream().count());
contents.stream().forEach(System.out::println);
}
public void listAllObjectsInBucket(String bucketName) {
String nextContinuationToken = null;
long totalObjects = 0;
do {
ListObjectsV2Request.Builder requestBuilder = ListObjectsV2Request.builder()
.bucket(bucketName)
.continuationToken(nextContinuationToken);
ListObjectsV2Response response = s3Client.listObjectsV2(requestBuilder.build());
nextContinuationToken = response.nextContinuationToken();
totalObjects += response.contents().stream()
.peek(System.out::println)
.reduce(0, (subtotal, element) -> subtotal + 1, Integer::sum);
} while (nextContinuationToken != null);
System.out.println("Number of objects in the bucket: " + totalObjects);
}
public void listAllObjectsInBucketPaginated(String bucketName, int pageSize) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(pageSize) // Set the maxKeys parameter to control the page size
.build();
ListObjectsV2Iterable listObjectsV2Iterable = s3Client.listObjectsV2Paginator(listObjectsV2Request);
long totalObjects = 0;
for (ListObjectsV2Response page : listObjectsV2Iterable) {
long retrievedPageSize = page.contents().stream()
.peek(System.out::println)
.reduce(0, (subtotal, element) -> subtotal + 1, Integer::sum);
totalObjects += retrievedPageSize;
System.out.println("Page size: " + retrievedPageSize);
}
System.out.println("Total objects in the bucket: " + totalObjects);
}
public void listAllObjectsInBucketPaginatedWithPrefix(String bucketName, int pageSize, String prefix) {
ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(pageSize) // Set the maxKeys parameter to control the page size
.prefix(prefix)
.build();
ListObjectsV2Iterable listObjectsV2Iterable = s3Client.listObjectsV2Paginator(listObjectsV2Request);
long totalObjects = 0;
for (ListObjectsV2Response page : listObjectsV2Iterable) {
long retrievedPageSize = page.contents().stream()
.peek(System.out::println)
.reduce(0, (subtotal, element) -> subtotal + 1, Integer::sum);
totalObjects += retrievedPageSize;
System.out.println("Page size: " + retrievedPageSize);
}
System.out.println("Total objects in the bucket: " + totalObjects);
}
public void putObjects(String bucketName, List<File> files) {
try {
files.stream().forEach(file -> {
s3Client.putObject(PutObjectRequest.builder().bucket(bucketName).key(file.getName()).build(),
RequestBody.fromByteBuffer(file.getContent()));
System.out.println("Uploaded file: " + file.getName());
});
} catch (S3Exception e) {
System.err.println("Upload failed");
e.printStackTrace();
}
}
public void cleanup() {
this.s3Client.close();
}
}

View File

@ -10,4 +10,7 @@
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<!-- Change the log level for software.amazon.awssdk -->
<logger name="software.amazon.awssdk" level="info" />
</configuration>

View File

@ -1,5 +1,13 @@
package com.baeldung.jets3t;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
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 org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -10,8 +18,8 @@ import org.jets3t.service.model.S3Bucket;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.model.StorageObject;
import org.jets3t.service.security.AWSCredentials;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.*;
import java.nio.file.Files;
@ -19,14 +27,13 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class JetS3tLiveTest {
private Log log = LogFactory.getLog(JetS3tLiveTest.class);
private final Log log = LogFactory.getLog(JetS3tLiveTest.class);
private static final String BucketName = "baeldung-barfoo";
private static final String TestString = "test string";
@ -35,7 +42,7 @@ public class JetS3tLiveTest {
private static S3Service s3Service;
@BeforeClass
@BeforeAll
public static void connectS3() throws Exception {
// Replace with your keys
@ -50,7 +57,7 @@ public class JetS3tLiveTest {
}
@Test
public void givenCreate_AndDeleteBucket_CountGoesUpThenDown() throws Exception {
void givenCreate_AndDeleteBucket_CountGoesUpThenDown() throws Exception {
// List buckets, get a count
S3Bucket[] myBuckets = s3Service.listAllBuckets();
@ -89,7 +96,7 @@ public class JetS3tLiveTest {
}
@Test
public void givenString_Uploaded_StringInfoIsAvailable() throws Exception {
void givenString_Uploaded_StringInfoIsAvailable() throws Exception {
// Create a bucket
S3Bucket bucket = createBucket();
@ -120,7 +127,7 @@ public class JetS3tLiveTest {
}
@Test
public void givenStringUploaded_StringIsDownloaded() throws Exception {
void givenStringUploaded_StringIsDownloaded() throws Exception {
// Get a bucket
S3Bucket bucket = createBucket();
@ -135,7 +142,7 @@ public class JetS3tLiveTest {
String downloadedString = new BufferedReader(new InputStreamReader(stringObject.getDataInputStream())).lines().collect(Collectors.joining("\n"));
// Verify
assertTrue(TestString.equals(downloadedString));
assertEquals(TestString, downloadedString);
// Clean up for next test
@ -144,7 +151,7 @@ public class JetS3tLiveTest {
}
@Test
public void givenBinaryFileUploaded_FileIsDownloaded() throws Exception {
void givenBinaryFileUploaded_FileIsDownloaded() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
@ -169,7 +176,7 @@ public class JetS3tLiveTest {
// Get hashes and compare
String origMD5 = getFileMD5("src/test/resources/test.jpg");
String newMD5 = getFileMD5("src/test/resources/newtest.jpg");
assertTrue(origMD5.equals(newMD5));
assertEquals(origMD5, newMD5);
// Clean up
deleteObject("test.jpg");
@ -186,7 +193,7 @@ public class JetS3tLiveTest {
@Test
public void givenStreamDataUploaded_StreamDataIsDownloaded() throws Exception {
void givenStreamDataUploaded_StreamDataIsDownloaded() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
@ -233,7 +240,7 @@ public class JetS3tLiveTest {
}
@Test
public void whenFileCopied_CopyIsSame() throws Exception {
void whenFileCopied_CopyIsSame() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
@ -260,7 +267,7 @@ public class JetS3tLiveTest {
// Get hashes and compare
String origMD5 = getFileMD5("src/test/resources/test.jpg");
String newMD5 = getFileMD5("src/test/resources/testcopy.jpg");
assertTrue(origMD5.equals(newMD5));
assertEquals(origMD5, newMD5);
// Clean up
deleteObject("test.jpg");
@ -271,7 +278,7 @@ public class JetS3tLiveTest {
@Test
public void whenFileRenamed_NewNameIsSame() throws Exception {
void whenFileRenamed_NewNameIsSame() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
@ -297,7 +304,7 @@ public class JetS3tLiveTest {
// Get hashes and compare
String origMD5 = getFileMD5("src/test/resources/test.jpg");
String newMD5 = getFileMD5("src/test/resources/spidey.jpg");
assertTrue(origMD5.equals(newMD5));
assertEquals(origMD5, newMD5);
// Clean up
deleteObject("test.jpg");
@ -307,7 +314,7 @@ public class JetS3tLiveTest {
}
@Test
public void whenFileMoved_NewInstanceIsSame() throws Exception {
void whenFileMoved_NewInstanceIsSame() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
@ -338,7 +345,7 @@ public class JetS3tLiveTest {
// Get hashes and compare
String origMD5 = getFileMD5("src/test/resources/test.jpg");
String newMD5 = getFileMD5("src/test/resources/spidey.jpg");
assertTrue(origMD5.equals(newMD5));
assertEquals(origMD5, newMD5);
// Clean up
deleteBucket();

View File

@ -1,49 +0,0 @@
package com.baeldung.s3;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Before;
import org.junit.Test;
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
/**
* Required defined environment variables AWS_ACCESS_KEY_ID & AWS_ACCESS_KEY to access S3.
* Required S3 bucket and key that exist.
*/
public class AWSS3ObjectManualTest {
private static final String BUCKET = "your-bucket";
private static final String KEY_THAT_EXIST = "your-key-that-exist";
private AWSS3ObjectUtils s3ObjectUtils;
@Before
public void setUp() {
AmazonS3 client = AmazonS3ClientBuilder.standard()
.withRegion(Regions.DEFAULT_REGION)
.withCredentials(new EnvironmentVariableCredentialsProvider())
.build();
s3ObjectUtils = new AWSS3ObjectUtils(client);
}
@Test
public void whenVerifyIfObjectExistByDefaultMethod_thenCorrect() {
assertTrue(s3ObjectUtils.doesObjectExistByDefaultMethod(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
}
@Test
public void whenVerifyIfObjectExistByListObjects_thenCorrect() {
assertTrue(s3ObjectUtils.doesObjectExistByListObjects(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
}
@Test
public void whenVerifyIfObjectExistByMetaData_thenCorrect() {
assertTrue(s3ObjectUtils.doesObjectExistByMetaData(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
}
}

View File

@ -1,113 +0,0 @@
package com.baeldung.s3;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CopyObjectResult;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.model.DeleteObjectsResult;
import com.amazonaws.services.s3.model.PutObjectResult;
public class AWSS3ServiceIntegrationTest {
private static final String BUCKET_NAME = "bucket_name";
private static final String KEY_NAME = "key_name";
private static final String BUCKET_NAME2 = "bucket_name2";
private static final String KEY_NAME2 = "key_name2";
private AmazonS3 s3;
private AWSS3Service service;
@Before
public void setUp() {
s3 = mock(AmazonS3.class);
service = new AWSS3Service(s3);
}
@Test
public void whenInitializingAWSS3Service_thenNotNull() {
assertThat(new AWSS3Service()).isNotNull();
}
@Test
public void whenVerifyingIfS3BucketExist_thenCorrect() {
service.doesBucketExist(BUCKET_NAME);
verify(s3).doesBucketExist(BUCKET_NAME);
}
@Test
public void whenVerifyingCreationOfS3Bucket_thenCorrect() {
service.createBucket(BUCKET_NAME);
verify(s3).createBucket(BUCKET_NAME);
}
@Test
public void whenVerifyingListBuckets_thenCorrect() {
service.listBuckets();
verify(s3).listBuckets();
}
@Test
public void whenDeletingBucket_thenCorrect() {
service.deleteBucket(BUCKET_NAME);
verify(s3).deleteBucket(BUCKET_NAME);
}
@Test
public void whenVerifyingPutObject_thenCorrect() {
File file = mock(File.class);
PutObjectResult result = mock(PutObjectResult.class);
when(s3.putObject(anyString(), anyString(), (File) any())).thenReturn(result);
assertThat(service.putObject(BUCKET_NAME, KEY_NAME, file)).isEqualTo(result);
verify(s3).putObject(BUCKET_NAME, KEY_NAME, file);
}
@Test
public void whenVerifyingListObjects_thenCorrect() {
service.listObjects(BUCKET_NAME);
verify(s3).listObjects(BUCKET_NAME);
}
@Test
public void whenVerifyingGetObject_thenCorrect() {
service.getObject(BUCKET_NAME, KEY_NAME);
verify(s3).getObject(BUCKET_NAME, KEY_NAME);
}
@Test
public void whenVerifyingCopyObject_thenCorrect() {
CopyObjectResult result = mock(CopyObjectResult.class);
when(s3.copyObject(anyString(), anyString(), anyString(), anyString())).thenReturn(result);
assertThat(service.copyObject(BUCKET_NAME, KEY_NAME, BUCKET_NAME2, KEY_NAME2)).isEqualTo(result);
verify(s3).copyObject(BUCKET_NAME, KEY_NAME, BUCKET_NAME2, KEY_NAME2);
}
@Test
public void whenVerifyingDeleteObject_thenCorrect() {
service.deleteObject(BUCKET_NAME, KEY_NAME);
verify(s3).deleteObject(BUCKET_NAME, KEY_NAME);
}
@Test
public void whenVerifyingDeleteObjects_thenCorrect() {
DeleteObjectsRequest request = mock(DeleteObjectsRequest.class);
DeleteObjectsResult result = mock(DeleteObjectsResult.class);
when(s3.deleteObjects((DeleteObjectsRequest)any())).thenReturn(result);
assertThat(service.deleteObjects(request)).isEqualTo(result);
verify(s3).deleteObjects(request);
}
}

View File

@ -1,61 +0,0 @@
package com.baeldung.s3;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.Upload;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.concurrent.Executors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class MultipartUploadLiveTest {
private static final String BUCKET_NAME = "bucket_name";
private static final String KEY_NAME = "picture.jpg";
private AmazonS3 amazonS3;
private TransferManager tm;
private ProgressListener progressListener;
@Before
public void setup() {
amazonS3 = mock(AmazonS3.class);
tm = TransferManagerBuilder
.standard()
.withS3Client(amazonS3)
.withMultipartUploadThreshold((long) (5 * 1024 * 1025))
.withExecutorFactory(() -> Executors.newFixedThreadPool(5))
.build();
progressListener =
progressEvent -> System.out.println("Transferred bytes: " + progressEvent.getBytesTransferred());
}
@Test
public void whenUploadingFileWithTransferManager_thenVerifyUploadRequested() {
File file = mock(File.class);
PutObjectResult s3Result = mock(PutObjectResult.class);
when(amazonS3.putObject(anyString(), anyString(), (File) any())).thenReturn(s3Result);
when(file.getName()).thenReturn(KEY_NAME);
PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, KEY_NAME, file);
request.setGeneralProgressListener(progressListener);
Upload upload = tm.upload(request);
assertThat(upload).isNotNull();
verify(amazonS3).putObject(request);
}
}

View File

@ -0,0 +1,137 @@
package com.baeldung.s3;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.util.Collections;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
class S3ServiceIntegrationTest {
private static final String BUCKET_NAME = "bucket_name";
private static final String KEY_NAME = "key_name";
private static final String BUCKET_NAME2 = "bucket_name2";
private static final String KEY_NAME2 = "key_name2";
@Mock
private S3Client s3Client;
private S3Service s3Service;
private final String AWS_BUCKET = "baeldung-tutorial-s3";
@BeforeEach
public void setup() {
MockitoAnnotations.openMocks(this);
s3Service = new S3Service(s3Client);
}
@AfterEach
public void cleanup() {
s3Service.cleanup();
Mockito.verify(s3Client).close();
}
@Test
void whenInitializingAWSS3Service_thenNotNull() {
assertThat(new S3Service(s3Client)).isNotNull();
}
@Test
void whenVerifyingIfS3BucketExist_thenCorrect() {
HeadBucketRequest headBucketRequest = HeadBucketRequest.builder()
.bucket(BUCKET_NAME)
.build();
s3Service.doesBucketExist(BUCKET_NAME);
verify(s3Client).headBucket(headBucketRequest);
}
@Test
void whenVerifyingCreationOfS3Bucket_thenCorrect() {
CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
.bucket(BUCKET_NAME)
.build();
s3Service.createBucket(BUCKET_NAME);
verify(s3Client).createBucket(bucketRequest);
}
@Test
void whenVerifyingListBuckets_thenCorrect() {
when(s3Client.listBuckets()).thenReturn(ListBucketsResponse.builder().buckets(Collections.emptyList()).build());
s3Service.listBuckets();
Mockito.verify(s3Client).listBuckets();
}
@Test
void whenDeletingBucket_thenCorrect() {
DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder()
.bucket(BUCKET_NAME)
.build();
s3Service.deleteBucket(BUCKET_NAME);
verify(s3Client).deleteBucket(deleteBucketRequest);
}
@Test
void whenVerifyingListObjects_thenCorrect() {
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(Collections.emptyList()).build();
when(s3Client.listObjectsV2(request)).thenReturn(response);
s3Service.listObjects(AWS_BUCKET);
verify(s3Client).listObjectsV2(request);
}
@Test
void whenVerifyingCopyObject_thenCorrect() {
CopyObjectRequest request = CopyObjectRequest.builder()
.sourceBucket(BUCKET_NAME)
.sourceKey(KEY_NAME)
.destinationBucket(BUCKET_NAME2)
.destinationKey(KEY_NAME2)
.build();
CopyObjectResponse result = CopyObjectResponse.builder().build();
when(s3Client.copyObject(request)).thenReturn(result);
assertThat(s3Service.copyObject(BUCKET_NAME, KEY_NAME, BUCKET_NAME2, KEY_NAME2)).isEqualTo(result);
verify(s3Client).copyObject(request);
}
@Test
void whenVerifyingDeleteObject_thenCorrect() {
DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
.bucket(BUCKET_NAME)
.key(KEY_NAME)
.build();
s3Service.deleteObject(BUCKET_NAME, KEY_NAME);
verify(s3Client).deleteObject(deleteObjectRequest);
}
}

View File

@ -1,109 +1,109 @@
package com.baeldung.s3.listobjects;
import com.baeldung.s3.listobjects.S3Service;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
import java.util.Arrays;
import java.util.Collections;
import static org.mockito.Mockito.when;
class S3ServiceLiveTest {
@Mock
private S3Client s3Client;
private S3Service s3Service;
private String AWS_BUCKET = "baeldung-tutorial-s3";
@BeforeEach
public void setup() {
MockitoAnnotations.openMocks(this);
s3Service = new S3Service(s3Client);
}
@AfterEach
public void cleanup() {
s3Service.cleanup();
Mockito.verify(s3Client).close();
}
@Test
public void givenBucketName_whenListObjectsInBucket_thenReturnList() {
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(Collections.emptyList()).build();
when(s3Client.listObjectsV2(request)).thenReturn(response);
s3Service.listObjectsInBucket(AWS_BUCKET);
Mockito.verify(s3Client).listObjectsV2(request);
}
@Test
public void givenBucketName_whenListAllObjectsInBucket_thenReturnList() {
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(Collections.emptyList()).build();
when(s3Client.listObjectsV2(request)).thenReturn(response);
s3Service.listAllObjectsInBucket(AWS_BUCKET);
Mockito.verify(s3Client).listObjectsV2(request);
}
@Test
public void givenBucketNameAndPageSize_whenListAllObjectsInBucketPaginated_thenReturnPaginatedList() {
int pageSize = 10;
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).maxKeys(pageSize).build();
ListObjectsV2Iterable mockIterable = Mockito.mock(ListObjectsV2Iterable.class);
S3Object s3Object1 = S3Object.builder().key("object1").build();
S3Object s3Object2 = S3Object.builder().key("object2").build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(s3Object1, s3Object2).build();
when(s3Client.listObjectsV2Paginator(request)).thenReturn(mockIterable);
when(mockIterable.iterator()).thenReturn(Arrays.asList(response).iterator());
s3Service.listAllObjectsInBucketPaginated(AWS_BUCKET, pageSize);
Mockito.verify(s3Client).listObjectsV2Paginator(request);
}
@Test
public void givenBucketNamePageSizeAndPrefix_whenListAllObjectsInBucketPaginatedWithPrefix_thenReturnPaginatedList() {
int pageSize = 1;
String prefix = "folder/";
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).maxKeys(pageSize).prefix(prefix).build();
ListObjectsV2Iterable mockIterable = Mockito.mock(ListObjectsV2Iterable.class);
S3Object s3Object1 = S3Object.builder().key("folder/object1").build();
S3Object s3Object2 = S3Object.builder().key("folder/object2").build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(s3Object1, s3Object2).build();
when(s3Client.listObjectsV2Paginator(request)).thenReturn(mockIterable);
when(mockIterable.iterator()).thenReturn(Arrays.asList(response).iterator());
s3Service.listAllObjectsInBucketPaginatedWithPrefix(AWS_BUCKET, pageSize, prefix);
Mockito.verify(s3Client).listObjectsV2Paginator(request);
}
@Test
public void whenListBuckets_thenReturnBucketList() {
when(s3Client.listBuckets()).thenReturn(ListBucketsResponse.builder().buckets(Collections.emptyList()).build());
s3Service.listBuckets();
Mockito.verify(s3Client).listBuckets();
}
}
package com.baeldung.s3;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
import java.util.Arrays;
import java.util.Collections;
class S3ServiceLiveTest {
@Mock
private S3Client s3Client;
private S3Service s3Service;
private String AWS_BUCKET = "baeldung-tutorial-s3";
@BeforeEach
public void setup() {
MockitoAnnotations.openMocks(this);
s3Service = new S3Service(s3Client);
}
@AfterEach
public void cleanup() {
s3Service.cleanup();
Mockito.verify(s3Client).close();
}
@Test
void givenBucketName_whenListObjectsInBucket_thenReturnList() {
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(Collections.emptyList()).build();
when(s3Client.listObjectsV2(request)).thenReturn(response);
s3Service.listObjectsInBucket(AWS_BUCKET);
Mockito.verify(s3Client).listObjectsV2(request);
}
@Test
void givenBucketName_whenListAllObjectsInBucket_thenReturnList() {
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(Collections.emptyList()).build();
when(s3Client.listObjectsV2(request)).thenReturn(response);
s3Service.listAllObjectsInBucket(AWS_BUCKET);
Mockito.verify(s3Client).listObjectsV2(request);
}
@Test
void givenBucketNameAndPageSize_whenListAllObjectsInBucketPaginated_thenReturnPaginatedList() {
int pageSize = 10;
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).maxKeys(pageSize).build();
ListObjectsV2Iterable mockIterable = Mockito.mock(ListObjectsV2Iterable.class);
S3Object s3Object1 = S3Object.builder().key("object1").build();
S3Object s3Object2 = S3Object.builder().key("object2").build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(s3Object1, s3Object2).build();
when(s3Client.listObjectsV2Paginator(request)).thenReturn(mockIterable);
when(mockIterable.iterator()).thenReturn(Arrays.asList(response).iterator());
s3Service.listAllObjectsInBucketPaginated(AWS_BUCKET, pageSize);
Mockito.verify(s3Client).listObjectsV2Paginator(request);
}
@Test
void givenBucketNamePageSizeAndPrefix_whenListAllObjectsInBucketPaginatedWithPrefix_thenReturnPaginatedList() {
int pageSize = 1;
String prefix = "folder/";
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(AWS_BUCKET).maxKeys(pageSize).prefix(prefix).build();
ListObjectsV2Iterable mockIterable = Mockito.mock(ListObjectsV2Iterable.class);
S3Object s3Object1 = S3Object.builder().key("folder/object1").build();
S3Object s3Object2 = S3Object.builder().key("folder/object2").build();
ListObjectsV2Response response = ListObjectsV2Response.builder().contents(s3Object1, s3Object2).build();
when(s3Client.listObjectsV2Paginator(request)).thenReturn(mockIterable);
when(mockIterable.iterator()).thenReturn(Arrays.asList(response).iterator());
s3Service.listAllObjectsInBucketPaginatedWithPrefix(AWS_BUCKET, pageSize, prefix);
Mockito.verify(s3Client).listObjectsV2Paginator(request);
}
@Test
void whenListBuckets_thenReturnBucketList() {
when(s3Client.listBuckets()).thenReturn(ListBucketsResponse.builder().buckets(Collections.emptyList()).build());
s3Service.listBuckets();
Mockito.verify(s3Client).listBuckets();
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.s3;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import software.amazon.awssdk.services.s3.S3Client;
/**
* Required defined environment variables AWS_ACCESS_KEY_ID & AWS_ACCESS_KEY to access S3.
* Required S3 bucket and key that exist.
*/
class S3ServiceManualTest {
private static final String BUCKET_NAME = "bucket_name";
private static final String KEY_NAME = "key_name";
@Mock
private S3Client s3Client;
private S3Service s3Service;
@BeforeEach
public void setup() {
MockitoAnnotations.openMocks(this);
s3Service = new S3Service(s3Client);
}
@AfterEach
public void cleanup() {
s3Service.cleanup();
Mockito.verify(s3Client).close();
}
@Test
void whenVerifyIfObjectExistByDefaultMethod_thenCorrect() {
assertTrue(s3Service.doesObjectExistByDefaultMethod(BUCKET_NAME, KEY_NAME), "Key: " + KEY_NAME + " doesn't exist");
}
@Test
void whenVerifyIfObjectExistByListObjects_thenCorrect() {
assertTrue(s3Service.doesObjectExistByListObjects(BUCKET_NAME, KEY_NAME), "Key: " + KEY_NAME + " doesn't exist");
}
}

View File

@ -19,7 +19,7 @@
<module>aws-miscellaneous</module>
<module>aws-reactive</module>
<module>aws-s3</module>
<module>aws-s3-v2</module>
<module>aws-s3-update-object</module>
</modules>
<properties>

View File

@ -0,0 +1,15 @@
package reminderapplication;
import java.awt.GridBagConstraints;
import java.awt.Insets;
public class ConstraintsBuilder {
static GridBagConstraints constraint(int x, int y) {
final GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = x;
gridBagConstraints.gridy = y;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
return gridBagConstraints;
}
}

View File

@ -0,0 +1,194 @@
package reminderapplication;
import static reminderapplication.ConstraintsBuilder.*;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.lang.reflect.InvocationTargetException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class EditReminderFrame extends JFrame {
private static Timer TIMER = new Timer();
private final TimeReminderApplication reminderApplication;
private final JLabel reminderTextLabel;
private final JLabel repeatPeriodLabel;
private final JLabel setDelayLabel;
private final JComboBox<Integer> delay;
private final JComboBox<Integer> period;
private final JButton cancelButton;
private final JButton okButton;
private final JTextField textField;
private final JLabel delaysLabel;
private final JLabel periodLabel;
private final int reminderIndex;
public EditReminderFrame(TimeReminderApplication reminderApp, String reminderText, int delayInSeconds, int periodInSeconds, int index) throws HeadlessException {
this.reminderApplication = reminderApp;
reminderIndex = index;
textField = createTextField(reminderText);
delay = createDelayComboBox(delayInSeconds);
period = createPeriodComboBox(periodInSeconds);
cancelButton = createCancelButton();
okButton = createOkButton();
reminderTextLabel = createReminderTextLabel();
repeatPeriodLabel = createRepeatPeriodLabel();
setDelayLabel = createSetDelayLabel();
delaysLabel = createDelaysLabel();
periodLabel = createPeriodLabel();
configureVisualRepresentation();
configureActions();
}
private void configureActions() {
updateReminder();
}
private void configureVisualRepresentation() {
configureFrame();
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
add(reminderTextLabel, constraint(0,0));
add(repeatPeriodLabel, constraint(1,0));
add(setDelayLabel, constraint(2,0));
add(textField, constraint(0, 1));
add(delay, constraint(1, 1));
add(period, constraint(2, 1));
add(delaysLabel, constraint(1,3));
add(periodLabel, constraint(2,3));
add(okButton, constraint(1, 4));
add(cancelButton, constraint(2, 4));
pack();
setVisible(true);
}
private void configureFrame() {
setTitle("Set Reminder");
setName("Set Reminder");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
private static JLabel createSetDelayLabel() {
return createLabel("Set Delay", "Set Delay Label");
}
private static JLabel createRepeatPeriodLabel() {
return createLabel("Set Period", "Set Repeat Period Label");
}
private static JLabel createReminderTextLabel() {
return createLabel("Reminder Text", "Reminder Text Label");
}
private JLabel createPeriodLabel() {
return createLabel("0", "Period label");
}
private JLabel createDelaysLabel() {
return createLabel("30", "Delays Label");
}
private JComboBox<Integer> createPeriodComboBox(final int periodInSeconds) {
final JComboBox<Integer> comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{0, 5, 10, 20}));
comboBox.setSelectedItem(periodInSeconds);
comboBox.setName("set Period");
comboBox.addActionListener(e -> periodLabel.setText(comboBox.getSelectedItem().toString()));
return comboBox;
}
private JComboBox<Integer> createDelayComboBox(final int delayInSeconds) {
final JComboBox<Integer> comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{30, 25, 15, 5}));
comboBox.setSelectedItem(delayInSeconds);
comboBox.setName("set Delay");
comboBox.addActionListener(e -> delaysLabel.setText(comboBox.getSelectedItem().toString()));
return comboBox;
}
private JTextField createTextField(final String reminderText) {
final JTextField textField = new JTextField(20);
textField.setName("Field");
textField.setText(reminderText);
return textField;
}
private JButton createOkButton() {
final JButton button = new JButton("ok");
button.setName("OK");
return button;
}
private void updateReminder() {
okButton.addActionListener(e -> this.dispose());
okButton.addActionListener(e -> {
final int periodInSeconds = getTimeInSeconds(period);
final int delayInSeconds = getTimeInSeconds(delay);
final Reminder reminder = new Reminder(textField.getText(), delayInSeconds, periodInSeconds);
((DefaultListModel<Reminder>) reminderApplication.getReminders()).set(reminderIndex, reminder);
});
okButton.addActionListener(e -> scheduleReminder(textField, delay, period));
}
private void scheduleReminder(final JTextField textField, final JComboBox<Integer> delay, final JComboBox<Integer> period) {
final int periodInSeconds = getTimeInSeconds(period);
if (periodInSeconds == 0)
scheduleNonRepeatedReminder(textField, delay);
else
scheduleRepeatedReminder(textField, delay, period);
}
private void scheduleRepeatedReminder(final JTextField textField, final JComboBox<Integer> delay, final JComboBox<Integer> period) {
final int delayInSeconds = getTimeInSeconds(delay);
final int periodInSeconds = getTimeInSeconds(period);
final TimerTask timerTask = getTimerTask(textField.getText(), delayInSeconds, periodInSeconds);
TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(delayInSeconds), TimeUnit.SECONDS.toMillis(periodInSeconds));
}
private void scheduleNonRepeatedReminder(final JTextField textField, final JComboBox<Integer> delay) {
final int delayInSeconds = getTimeInSeconds(delay);
final int periodInSeconds = 0;
final TimerTask timerTask = getTimerTask(textField.getText(), delayInSeconds, periodInSeconds);
TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(delayInSeconds));
}
private int getTimeInSeconds(final JComboBox<Integer> comboBox) {
if (comboBox != null && comboBox.getSelectedItem() != null)
return ((Integer) comboBox.getSelectedItem());
else
return 0;
}
private TimerTask getTimerTask(final String reminderText, final Integer delayInSeconds, final Integer periodInSeconds) {
return new TimerTask() {
@Override
public void run() {
new ReminderPopupFrame(reminderApplication, reminderText, delayInSeconds, periodInSeconds);
}
};
}
private JButton createCancelButton() {
final JButton button = new JButton("cancel");
button.setName("Cancel");
button.addActionListener(e -> this.dispose());
return button;
}
private static JLabel createLabel(final String text, final String name) {
JLabel label = new JLabel(text);
label.setName(name);
return label;
}
}

View File

@ -0,0 +1,33 @@
package reminderapplication;
public class Reminder {
private static String REMINDER_FORMAT = "Reminder Text: %s; Delay: %d; Period: %d;";
private final String name;
private final int delay;
private final int period;
public Reminder(final String name, final int delay, final int period) {
this.name = name;
this.delay = delay;
this.period = period;
}
public String getName() {
return name;
}
public int getDelay() {
return delay;
}
public int getPeriod() {
return period;
}
@Override
public String toString() {
return REMINDER_FORMAT.formatted(name, delay, period);
}
}

View File

@ -0,0 +1,186 @@
package reminderapplication;
import static reminderapplication.ConstraintsBuilder.*;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class ReminderFrame extends JFrame {
private static Timer TIMER = new Timer();
private final TimeReminderApplication reminderApplication;
private final JLabel reminderTextLabel;
private final JLabel repeatPeriodLabel;
private final JLabel setDelayLabel;
private final JComboBox<Integer> delay;
private final JComboBox<Integer> period;
private final JButton cancelButton;
private final JButton okButton;
private final JTextField textField;
private final JLabel delaysLabel;
private final JLabel periodLabel;
public ReminderFrame(TimeReminderApplication reminderApp) throws HeadlessException {
this.reminderApplication = reminderApp;
textField = createTextField();
delay = createDelayComboBox();
period = createPeriodComboBox();
cancelButton = createCancelButton();
okButton = createOkButton();
reminderTextLabel = createReminderTextLabel();
repeatPeriodLabel = createRepeatPeriodLabel();
setDelayLabel = createSetDelayLabel();
delaysLabel = createDelaysLabel();
periodLabel = createPeriodLabel();
configureVisualRepresentation();
configureActions();
}
private void configureActions() {
createNewReminder();
}
private void configureVisualRepresentation() {
configureFrame();
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
add(reminderTextLabel, constraint(0,0));
add(repeatPeriodLabel, constraint(1,0));
add(setDelayLabel, constraint(2,0));
add(textField, constraint(0, 1));
add(delay, constraint(1, 1));
add(period, constraint(2, 1));
add(delaysLabel, constraint(1,3));
add(periodLabel, constraint(2,3));
add(okButton, constraint(1, 4));
add(cancelButton, constraint(2, 4));
pack();
setVisible(true);
}
private void configureFrame() {
setTitle("Set Reminder");
setName("Set Reminder");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
private static JLabel createSetDelayLabel() {
return createLabel("Set Delay", "Set Delay Label");
}
private static JLabel createRepeatPeriodLabel() {
return createLabel("Set Period", "Set Repeat Period Label");
}
private static JLabel createReminderTextLabel() {
return createLabel("Reminder Text", "Reminder Text Label");
}
private JLabel createPeriodLabel() {
return createLabel("0", "Period label");
}
private JLabel createDelaysLabel() {
return createLabel("30", "Delays Label");
}
private JComboBox<Integer> createPeriodComboBox() {
final JComboBox<Integer> comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{0, 5, 10, 20}));
comboBox.setName("set Period");
comboBox.addActionListener(e -> periodLabel.setText(comboBox.getSelectedItem().toString()));
return comboBox;
}
private JComboBox<Integer> createDelayComboBox() {
final JComboBox<Integer> comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{30, 25, 15, 5}));
comboBox.setName("set Delay");
comboBox.addActionListener(e -> delaysLabel.setText(comboBox.getSelectedItem().toString()));
return comboBox;
}
private JTextField createTextField() {
final JTextField textField = new JTextField(20);
textField.setName("Field");
return textField;
}
private JButton createOkButton() {
final JButton button = new JButton("ok");
button.setName("OK");
return button;
}
private void createNewReminder() {
okButton.addActionListener(e -> this.dispose());
okButton.addActionListener(e -> {
final int periodInSeconds = getTimeInSeconds(period);
final int delayInSeconds = getTimeInSeconds(delay);
final Reminder reminder = new Reminder(textField.getText(), delayInSeconds, periodInSeconds);
((DefaultListModel<Reminder>) reminderApplication.getReminders()).addElement(reminder);
});
okButton.addActionListener(e -> scheduleReminder(textField, delay, period));
}
private void scheduleReminder(final JTextField textField, final JComboBox<Integer> delay, final JComboBox<Integer> period) {
final int periodInSeconds = getTimeInSeconds(period);
if (periodInSeconds == 0)
scheduleNonRepeatedReminder(textField, delay);
else
scheduleRepeatedReminder(textField, delay, period);
}
private void scheduleRepeatedReminder(final JTextField textField, final JComboBox<Integer> delay, final JComboBox<Integer> period) {
final int delayInSeconds = getTimeInSeconds(delay) + 200;
final int periodInSeconds = getTimeInSeconds(period);
final TimerTask timerTask = getTimerTask(textField.getText(), delayInSeconds, periodInSeconds);
TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(delayInSeconds), TimeUnit.SECONDS.toMillis(periodInSeconds));
}
private void scheduleNonRepeatedReminder(final JTextField textField, final JComboBox<Integer> delay) {
final int delayInSeconds = getTimeInSeconds(delay);
final int periodInSeconds = 0;
final TimerTask timerTask = getTimerTask(textField.getText(), delayInSeconds, periodInSeconds);
TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(delayInSeconds));
}
private int getTimeInSeconds(final JComboBox<Integer> comboBox) {
if (comboBox != null && comboBox.getSelectedItem() != null)
return ((Integer) comboBox.getSelectedItem());
else
return 0;
}
private TimerTask getTimerTask(final String reminderText, final Integer delayInSeconds, final Integer periodInSeconds) {
return new TimerTask() {
@Override
public void run() {
new ReminderPopupFrame(reminderApplication, reminderText, delayInSeconds, periodInSeconds);
}
};
}
private JButton createCancelButton() {
final JButton button = new JButton("cancel");
button.setName("Cancel");
button.addActionListener(e -> this.dispose());
return button;
}
private static JLabel createLabel(final String text, final String name) {
JLabel label = new JLabel(text);
label.setName(name);
return label;
}
}

View File

@ -0,0 +1,151 @@
package reminderapplication;
import static reminderapplication.ConstraintsBuilder.*;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class ReminderPopupFrame extends JFrame {
private static final Timer TIMER = new Timer();
private final int AUTOMATIC_CLOSE_TIME_IN_SECONDS = 10;
private final TimeReminderApplication reminderApplication;
private final JLabel reminderTextLabel;
private final JLabel repeatPeriodLabel;
private final JLabel setDelayLabel;
private final JComboBox<Integer> delay;
private final JComboBox<Integer> period;
private final JButton cancelButton;
private final JButton okButton;
private final JTextField textField;
private final JLabel delaysLabel;
private final JLabel periodLabel;
public ReminderPopupFrame(TimeReminderApplication reminderApp, final String text, final Integer delayInSeconds, final Integer periodInSeconds) throws HeadlessException {
this.reminderApplication = reminderApp;
textField = createTextField(text);
delay = createDelayComboBox(delayInSeconds);
period = createPeriodComboBox(periodInSeconds);
cancelButton = createCancelButton();
okButton = createDisabledOkButton();
reminderTextLabel = createReminderTextLabel();
repeatPeriodLabel = createRepeatPeriodLabel();
setDelayLabel = createSetDelayLabel();
delaysLabel = createDelaysLabel();
periodLabel = createPeriodLabel();
configureVisualRepresentation();
configureActions();
}
private void configureActions() {
scheduleClosing();
}
private void scheduleClosing() {
final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
ReminderPopupFrame.this.dispose();
}
};
TIMER.schedule(timerTask, TimeUnit.SECONDS.toMillis(AUTOMATIC_CLOSE_TIME_IN_SECONDS));
}
private void configureVisualRepresentation() {
configureFrame();
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
add(reminderTextLabel, constraint(0,0));
add(repeatPeriodLabel, constraint(1,0));
add(setDelayLabel, constraint(2,0));
add(textField, constraint(0, 1));
add(delay, constraint(1, 1));
add(period, constraint(2, 1));
add(delaysLabel, constraint(1,3));
add(periodLabel, constraint(2,3));
add(okButton, constraint(1, 4));
add(cancelButton, constraint(2, 4));
pack();
setVisible(true);
}
private void configureFrame() {
setTitle("Set Reminder");
setName("Set Reminder");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
private static JLabel createSetDelayLabel() {
return createLabel("Set Delay", "Set Delay Label");
}
private static JLabel createRepeatPeriodLabel() {
return createLabel("Set Period", "Set Repeat Period Label");
}
private static JLabel createReminderTextLabel() {
return createLabel("Reminder Text", "Reminder Text Label");
}
private JLabel createPeriodLabel() {
return createLabel("0", "Period label");
}
private JLabel createDelaysLabel() {
return createLabel("30", "Delays Label");
}
private JComboBox<Integer> createPeriodComboBox(final Integer periodInSeconds) {
final JComboBox<Integer> comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{0, 5, 10, 20}));
comboBox.setName("set Period");
comboBox.setSelectedItem(periodInSeconds);
comboBox.addActionListener(e -> periodLabel.setText(comboBox.getSelectedItem().toString()));
return comboBox;
}
private JComboBox<Integer> createDelayComboBox(Integer delay) {
final JComboBox<Integer> comboBox = new JComboBox<>(new DefaultComboBoxModel<>(new Integer[]{30, 25, 15, 5}));
comboBox.setSelectedItem(delay);
comboBox.setName("set Delay");
comboBox.addActionListener(e -> delaysLabel.setText(comboBox.getSelectedItem().toString()));
return comboBox;
}
private JTextField createTextField(final String text) {
final JTextField textField = new JTextField(20);
textField.setName("Field");
textField.setText(text);
return textField;
}
private JButton createDisabledOkButton() {
final JButton button = new JButton("ok");
button.setName("OK");
button.setEnabled(false);
return button;
}
private JButton createCancelButton() {
final JButton button = new JButton("cancel");
button.setName("Cancel");
button.addActionListener(e -> this.dispose());
return button;
}
private static JLabel createLabel(final String text, final String name) {
JLabel label = new JLabel(text);
label.setName(name);
return label;
}
}

View File

@ -12,3 +12,4 @@ This module contains articles about Java 9 core features
- [Private Methods in Java Interfaces](https://www.baeldung.com/java-interface-private-methods)
- [Java Scanner useDelimiter with Examples](https://www.baeldung.com/java-scanner-usedelimiter)
- [Is There a Destructor in Java?](https://www.baeldung.com/java-destructor)
- [Java 9 Migration Issues and Resolutions](https://www.baeldung.com/java-9-migration-issue)

View File

@ -46,6 +46,11 @@
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${javax.xml.bind.version}</version>
</dependency>
</dependencies>
<build>
@ -58,6 +63,9 @@
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<compilerArgs>
<arg>--add-exports=java.base/com.sun.crypto.provider=ALL-UNNAMED</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
@ -74,6 +82,7 @@
<awaitility.version>1.7.0</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
<javax.xml.bind.version>2.4.0-b180725.0427</javax.xml.bind.version>
</properties>
</project>

View File

@ -1,15 +1,16 @@
package com.baeldung.prejpms;
package com.baeldung.java9.prejpms;
import java.io.StringWriter;
import java.lang.StackWalker.Option;
import java.lang.StackWalker.StackFrame;
import com.sun.crypto.provider.SunJCE;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicInteger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import com.sun.crypto.provider.SunJCE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -1,4 +1,4 @@
package com.baeldung.prejpms;
package com.baeldung.java9.prejpms;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;

View File

@ -8,3 +8,5 @@ This module contains articles about arrays conversion in Java
- [Convert a Byte Array to a Numeric Representation in Java](https://www.baeldung.com/java-byte-array-to-number)
- [Converting a String Array Into an int Array in Java](https://www.baeldung.com/java-convert-string-array-to-int-array)
- [Convert Java Array to Iterable](https://www.baeldung.com/java-array-convert-to-iterable)
- [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset)
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)

View File

@ -20,5 +20,4 @@
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,53 @@
package com.baeldung.array.conversions;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.util.Arrays;
import java.util.HashSet;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.Test;
import com.google.common.primitives.Ints;
public class PrimitiveIntArrayToHashSetUnitTest {
int[] arr = { 1, 2, 3, 4, 5 };
HashSet<Integer> expected = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
@Test
public void givenPrimitiveIntArray_whenConvertingByDirectConstructor_thenGiveWrongResult() {
HashSet<int[]> result = new HashSet<>(Arrays.asList(arr));
assertEquals(1, result.size());
assertNotEquals(expected, result);
}
@Test
public void givenPrimitiveIntArray_whenConvertingByLoop_thenSuccess() {
HashSet<Integer> result = new HashSet<>();
for (int num : arr) {
result.add(num);
}
assertEquals(expected, result);
}
@Test
public void givenPrimitiveIntArray_whenConvertingByStreams_thenSuccess() {
HashSet<Integer> result = Arrays.stream(arr).boxed().collect(Collectors.toCollection(HashSet::new));
assertEquals(expected, result);
}
@Test
public void givenPrimitiveIntArray_whenConvertingByArrayUtils_thenSuccess() {
HashSet<Integer> result = new HashSet<>(Arrays.asList(ArrayUtils.toObject(arr)));
assertEquals(expected, result);
}
@Test
public void givenPrimitiveIntArray_whenConvertingByGuava_thenSuccess() {
HashSet<Integer> result = new HashSet<>(Ints.asList(arr));
assertEquals(expected, result);
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.arraysums;
public class SumArraysUsingForEach {
public static int[] sumOfTwoArrays(int[] arr1, int[] arr2) {
int[] arr3 = new int[arr1.length];
int counter = 0;
for (int num1 : arr1) {
arr3[counter] = num1 + arr2[counter];
counter++;
}
return arr3;
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.arraysums;
public class SumArraysUsingForLoop {
public static int[] sumOfTwoArrays(int[] arr1, int[] arr2) {
int[] arr3 = new int[arr1.length];
for (int i = 0; i < arr1.length; i++) {
arr3[i] = arr1[i] + arr2[i];
}
return arr3;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.arraysums;
import java.util.Arrays;
import java.util.stream.IntStream;
public class SumArraysUsingStreams {
public static int[] sumOfTwoArrays(int[] arr1, int[] arr2) {
IntStream range = IntStream.range(0, Math.min(arr1.length, arr2.length));
IntStream stream3 = range.map(i -> arr1[i] + arr2[i]);
int[] arr3 = stream3.toArray();
return arr3;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.arraysums;
import com.baeldung.arraysums.SumArraysUsingForEach;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArraysUsingForEachUnitTest {
@Test
public void sumOfTwoArraysUsingForEach_GivenTwoEqualSizedIntArrays_ReturnsCorrectSumArray() {
int[] arr1 = { 4, 5, 1, 6, 4, 15 };
int[] arr2 = { 3, 5, 6, 1, 9, 6 };
int[] expected = { 7, 10, 7, 7, 13, 21 };
assertArrayEquals(expected, SumArraysUsingForEach.sumOfTwoArrays(arr1, arr2));
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.arraysums;
import com.baeldung.arraysums.SumArraysUsingForLoop;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArraysUsingForLoopUnitTest {
@Test
public void sumOfTwoArrays_GivenTwoEqualSizedIntArrays_ReturnsCorrectSumArray() {
int[] arr1 = {4, 5, 1, 6, 4, 15};
int[] arr2 = {3, 5, 6, 1, 9, 6};
int[] expected = {7, 10, 7, 7, 13, 21};
assertArrayEquals(expected, SumArraysUsingForLoop.sumOfTwoArrays(arr1, arr2));
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.arraysums;
import com.baeldung.arraysums.SumArraysUsingStreams;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArraysUsingStreamsUnitTest {
@Test
public void sumOfTwoArraysUsingStreams_GivenTwoEqualSizedIntArrays_ReturnsCorrectSumArray() {
int[] arr1 = {4, 5, 1, 6, 4, 15};
int[] arr2 = {3, 5, 6, 1, 9, 6};
int[] expected = {7, 10, 7, 7, 13, 21};
assertArrayEquals(expected, SumArraysUsingStreams.sumOfTwoArrays(arr1, arr2));
}
}

View File

@ -12,4 +12,5 @@ This module contains articles about conversions among Collection types and array
- [Convert a List of Integers to a List of Strings](https://www.baeldung.com/java-convert-list-integers-to-list-strings)
- [Combining Two Lists Into a Map in Java](https://www.baeldung.com/java-combine-two-lists-into-map)
- [Convert a List of Strings to a List of Integers](https://www.baeldung.com/java-convert-list-strings-to-integers)
- [Convert List to Long[] Array in Java](https://www.baeldung.com/java-convert-list-object-to-long-array)
- More articles: [[<-- prev]](../core-java-collections-conversions)

View File

@ -43,6 +43,7 @@
<properties>
<vavr.version>0.10.3</vavr.version>
<java.version>11</java.version>
<modelmapper.version>3.1.1</modelmapper.version>
</properties>
</project>

View File

@ -0,0 +1,46 @@
package com.baeldung.arrayconversion;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
public class ArrayListToArrayUnitTest {
private static final List<String> INPUT_LIST = Lists.newArrayList("Michael Bolton", "Michael Jackson", "Guns and Roses", "Bryan Adams", "Air Supply");
private static final String[] EXPECTED_ARRAY = new String[] { "Michael Bolton", "Michael Jackson", "Guns and Roses", "Bryan Adams", "Air Supply" };
@Test
void whenUsingForLoop_thenGetExpectedResult() {
String[] result = new String[INPUT_LIST.size()];
for (int i = 0; i < INPUT_LIST.size(); i++) {
result[i] = INPUT_LIST.get(i);
}
assertArrayEquals(EXPECTED_ARRAY, result);
}
@Test
void whenUsingListToArray_thenGetExpectedResult() {
String[] result = new String[INPUT_LIST.size()];
INPUT_LIST.toArray(result);
assertArrayEquals(EXPECTED_ARRAY, result);
String[] result2 = INPUT_LIST.toArray(new String[0]);
assertArrayEquals(EXPECTED_ARRAY, result2);
}
@Test
void whenUsingStreamApi_thenGetExpectedResult() {
String[] result = INPUT_LIST.stream()
.toArray(String[]::new);
assertArrayEquals(EXPECTED_ARRAY, result);
}
@Test
void whenUsingListToArrayInJava11_thenGetExpectedResult() {
String[] result = INPUT_LIST.toArray(String[]::new);
assertArrayEquals(EXPECTED_ARRAY, result);
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.arrayconversion;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.Iterator;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
public class ListToArrayFirstNElementsUnitTest {
private static final List<String> INPUT_LIST = Lists.newArrayList("one", "two", "three", "four", "five", "six", "seven");
private static final int n = 5;
@Test
void whenUsingForLoop_thenGetExpectedArray() {
String[] result = new String[n];
for (int i = 0; i < n; i++) {
result[i] = INPUT_LIST.get(i);
}
assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result);
String[] result2 = new String[n];
Iterator<String> iterator = INPUT_LIST.iterator();
for (int i = 0; i < n && iterator.hasNext(); i++) {
result2[i] = iterator.next();
}
assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result2);
}
@Test
void whenUsingSubList_thenGetExpectedArray() {
String[] result = new String[n];
INPUT_LIST.subList(0, n)
.toArray(result);
assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result);
String[] result2 = INPUT_LIST.subList(0, n)
.toArray(new String[0]);
assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result2);
// available only for java 11+
String[] result3 = INPUT_LIST.subList(0, n)
.toArray(String[]::new);
assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result3);
}
@Test
void whenUsingStream_thenGetExpectedArray() {
String[] result = INPUT_LIST.stream()
.limit(n)
.toArray(String[]::new);
assertArrayEquals(new String[] { "one", "two", "three", "four", "five" }, result);
}
}

View File

@ -11,3 +11,4 @@ This module contains articles about the Java List collection
- [Set Default Value for Elements in List](https://www.baeldung.com/java-list-set-default-values)
- [Get Unique Values From an ArrayList in Java](https://www.baeldung.com/java-unique-values-arraylist)
- [Converting a Java List to a Json Array](https://www.baeldung.com/java-converting-list-to-json-array)
- [Whats the Difference Between Iterator and ListIterator?](https://www.baeldung.com/java-iterator-vs-listiterator)

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-list-5</artifactId>
<name>core-java-collections-list-5</name>
@ -42,11 +42,33 @@
<version>1.18.26</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${org.json.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<jmh.version>1.21</jmh.version>
<commons-lang.version>2.2</commons-lang.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<gson.version>2.10.1</gson.version>
<jackson.version>2.15.2</jackson.version>
<org.json.version>20230618</org.json.version>
</properties>
</project>

View File

@ -0,0 +1,108 @@
package com.baeldung.java.iteratorandlistiterator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
public class IteratorVsListIteratorUnitTest {
@Test
void whenUsingIterator_thenWeCanTraverseForwardsAndRemoveElements() {
List<String> inputList = Lists.newArrayList("1", "2", "3", "4", "5");
Iterator<String> it = inputList.iterator();
while (it.hasNext()) {
String e = it.next();
if ("3".equals(e) || "5".equals(e)) {
it.remove();
}
}
assertEquals(Lists.newArrayList("1", "2", "4"), inputList);
}
@Test
void whenUsingListIteratorAlternatingNextAndPrevious_thenAlwaysGetTheSameElement() {
List<String> inputList = Lists.newArrayList("1", "2", "3", "4", "5");
ListIterator<String> lit = inputList.listIterator(); // ^ 1 2 3 4 5
lit.next(); // 1 ^ 2 3 4 5
lit.next(); // 1 2 ^ 3 4 5
for (int i = 1; i <= 100; i++) {
assertEquals("2", lit.previous());
assertEquals("2", lit.next());
}
}
@Test
void whenUsingListIterator_thenRetrieveElementInForwardAndBackwardDirection() {
List<String> inputList = Lists.newArrayList("1", "2", "3", "4", "5");
ListIterator<String> lit = inputList.listIterator(); // ^ 1 2 3 4 5
assertFalse(lit.hasPrevious()); // lit is at the beginning of the list
assertEquals(-1, lit.previousIndex());
assertEquals("1", lit.next()); // after next(): 1 ^ 2 3 4 5
assertEquals("2", lit.next()); // after next(): 1 2 ^ 3 4 5
assertEquals("3", lit.next()); // after next(): 1 2 3 ^ 4 5
assertTrue(lit.hasPrevious());
assertEquals(2, lit.previousIndex());
assertEquals("3", lit.previous()); // after previous(): 1 2 ^ 3 4 5
assertTrue(lit.hasPrevious());
assertEquals(1, lit.previousIndex());
assertEquals("2", lit.previous()); // after previous(): 1 ^ 2 3 4 5
assertTrue(lit.hasPrevious());
assertEquals(0, lit.previousIndex());
assertEquals("1", lit.previous()); // after previous(): ^ 1 2 3 4 5
}
@Test
void whenUsingSetElement_thenGetExpectedResult() {
List<String> inputList = Lists.newArrayList("1", "2", "3", "4", "5");
ListIterator<String> lit = inputList.listIterator(1); // ^ 1 2 3 4 5
lit.next(); // 1 ^ 2 3 4 5
assertEquals("3", lit.next()); // 1 2 ^ 3 4 5
lit.set("X");
assertEquals(Lists.newArrayList("1", "2", "X", "4", "5"), inputList);
assertEquals("X", lit.previous()); // 1 2 ^ X 4 5
assertEquals("2", lit.previous()); // 1 ^ 2 X 4 5
lit.set("Y");
assertEquals(Lists.newArrayList("1", "Y", "X", "4", "5"), inputList);
}
@Test
void whenUsingAddElement_thenGetExpectedResult() {
List<String> inputList = Lists.newArrayList("1", "2", "3", "4", "5");
ListIterator<String> lit = inputList.listIterator(); // ^ 1 2 3 4 5
lit.next(); // 1 ^ 2 3 4 5
lit.next(); // 1 2 ^ 3 4 5
lit.next(); // 1 2 3 ^ 4 5
lit.add("X"); // 1 2 3 X ^ 4 5
assertEquals("4", lit.next()); // 1 2 3 X 4 ^ 5
lit.previous(); // 1 2 3 X ^ 4 5
lit.previous(); // 1 2 3 ^ X 4 5
lit.previous(); // 1 2 ^ 3 X 4 5
lit.add("Y"); // 1 2 Y ^ 3 X 4 5
assertEquals("Y", lit.previous());
assertEquals(Lists.newArrayList("1", "2", "Y", "3", "X", "4", "5"), inputList);
}
}

View File

@ -13,7 +13,7 @@ import org.junit.Test;
import com.baeldung.list.Country;
public class ListContainsElementFromOtherListTest {
public class ListContainsElementFromOtherListUnitTest {
final private List<String> listOfLetters = Arrays.asList("a", "b", "c", "d");
final private List<String> listOfLettersWithOverlap = Arrays.asList("d", "e", "f", "g");
@ -65,4 +65,4 @@ public class ListContainsElementFromOtherListTest {
assertTrue(shouldBeTrue);
}
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.map.hashmap.kvtolist;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
public class MapKeysValuesToListUnitTest {
private static final HashMap<String, String> DEV_MAP;
static {
DEV_MAP = new HashMap<>();
DEV_MAP.put("Kent", "Linux");
DEV_MAP.put("Eric", "MacOS");
DEV_MAP.put("Kevin", "Windows");
DEV_MAP.put("Michal", "MacOS");
DEV_MAP.put("Saajan", "Linux");
}
@Test
void whenUsingKeySet_thenGetExpectedResult() {
List<String> keyList = new ArrayList<>(DEV_MAP.keySet());
// this assertion may fail, since hashMap doesn't preserve the insertion order
// assertEquals(Lists.newArrayList("Kent", "Eric", "Kevin", "Michal", "Saajan"), keyList);
assertThat(keyList).containsExactlyInAnyOrder("Kent", "Eric", "Kevin", "Michal", "Saajan");
}
@Test
void whenUsingValues_thenGetExpectedResult() {
List<String> valueList = new ArrayList<>(DEV_MAP.values());
assertThat(valueList).containsExactlyInAnyOrder("Linux", "MacOS", "Windows", "MacOS", "Linux");
}
@Test
void whenLoopingEntries_thenGetExpectedResult() {
List<String> keyList = new ArrayList<>();
List<String> valueList = new ArrayList<>();
for (Map.Entry<String, String> entry : DEV_MAP.entrySet()) {
keyList.add(entry.getKey());
valueList.add(entry.getValue());
}
assertKeyAndValueList(keyList, valueList);
}
@Test
void whenUsingForEach_thenGetExpectedResult() {
List<String> keyList = new ArrayList<>();
List<String> valueList = new ArrayList<>();
DEV_MAP.forEach((k, v) -> {
keyList.add(k);
valueList.add(v);
});
assertKeyAndValueList(keyList, valueList);
}
private void assertKeyAndValueList(List<String> keyList, List<String> valueList) {
assertThat(keyList).containsExactlyInAnyOrder("Kent", "Eric", "Kevin", "Michal", "Saajan");
assertThat(valueList).containsExactlyInAnyOrder("Linux", "MacOS", "Windows", "MacOS", "Linux");
for (int i = 0; i < keyList.size(); i++) {
assertThat(DEV_MAP).containsEntry(keyList.get(i), valueList.get(i));
}
}
}

View File

@ -5,3 +5,7 @@
- [Converting Object To Map in Java](https://www.baeldung.com/java-convert-object-to-map)
- [Difference Between Map.clear() and Instantiating a New Map](https://www.baeldung.com/java-map-clear-vs-new-map)
- [Converting JsonNode Object to Map](https://www.baeldung.com/jackson-jsonnode-map)
- [How to Modify a Key in a HashMap?](https://www.baeldung.com/java-hashmap-modify-key)
- [Converting String or String Array to Map in Java](https://www.baeldung.com/java-convert-string-to-map)
- [Remove Duplicate Values From HashMap in Java](https://www.baeldung.com/java-hashmap-delete-duplicates)
- [Sorting Java Map in Descending Order](https://www.baeldung.com/java-sort-map-descending)

View File

@ -0,0 +1,83 @@
package com.baeldung.map.removeuplicate;
import static java.util.stream.Collectors.toMap;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableMap;
public class RemoveDuplicateValuesUnitTest {
private Map<String, String> initDevMap() {
Map<String, String> devMap = new HashMap<>();
devMap.put("Tom", "Linux");
devMap.put("Kent", "Linux");
devMap.put("Bob", "MacOS");
devMap.put("Eric", "MacOS");
devMap.put("Peter", "Windows");
devMap.put("Saajan", "Windows");
devMap.put("Jan", "Windows");
devMap.put("Kevin", "FreeBSD");
return devMap;
}
@Test
void whenUsingReverseMap_thenDuplicateValuesAreRemoved() {
Map<String, String> devMap = initDevMap();
Map<String, String> tmpReverseMap = new HashMap<>();
Map<String, String> result = new HashMap<>();
for (String name : devMap.keySet()) {
tmpReverseMap.put(devMap.get(name), name);
}
for (String os : tmpReverseMap.keySet()) {
result.put(tmpReverseMap.get(os), os);
}
assertThat(result.values()).hasSize(4)
.containsExactlyInAnyOrder("Windows", "MacOS", "Linux", "FreeBSD");
}
@Test
void whenUsingStream_thenDuplicateValuesAreRemoved() {
Map<String, String> devMap = initDevMap();
Map<String, String> result = devMap.entrySet()
.stream()
.collect(toMap(Map.Entry::getValue, Map.Entry::getKey, (keyInMap, keyNew) -> keyInMap))
.entrySet()
.stream()
.collect(toMap(Map.Entry::getValue, Map.Entry::getKey));
assertThat(result.values()).hasSize(4)
.containsExactlyInAnyOrder("Windows", "MacOS", "Linux", "FreeBSD");
}
@Test
void whenUsingStream_thenDuplicateValuesAreRemovedAndOnlyLongestNamesExist() {
Map<String, String> devMap = initDevMap();
//@formatter:off
Map<String, String> expected = ImmutableMap.of(
"Eric", "MacOS",
"Kent", "Linux",
"Saajan", "Windows",
"Kevin", "FreeBSD");
//@formatter:on
Map<String, String> result = devMap.entrySet()
.stream()
.collect(toMap(Map.Entry::getValue, Map.Entry::getKey, (k1, k2) -> k1.length() > k2.length() ? k1 : k2))
.entrySet()
.stream()
.collect(toMap(Map.Entry::getValue, Map.Entry::getKey));
assertThat(result).hasSize(4)
.isEqualTo(expected);
}
}

View File

@ -0,0 +1,89 @@
package com.baeldung.stringtomap;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals;
public class StringToMapUnitTest {
public Map<String, String> convertStringToMap(String data) {
Map<String, String> map = new HashMap<>();
StringTokenizer tokenizer = new StringTokenizer(data, " ");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
String[] keyValue = token.split("=");
map.put(keyValue[0], keyValue[1]);
}
return map;
}
@Test
public void given_StringWithKeyValuePairs_whenUsing_convertStringToMap_thenMapCreated() {
String data = "name=John age=30 city=NewYork";
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("name", "John");
expectedMap.put("age", "30");
expectedMap.put("city", "NewYork");
Map<String, String> resultMap = convertStringToMap(data);
assertEquals(expectedMap, resultMap);
}
public Map<String, String> convertStringArrayToMap(String[] data) {
Map<String, String> map = new HashMap<>();
for (String keyValue : data) {
String[] parts = keyValue.split("=");
map.put(parts[0], parts[1]);
}
return map;
}
@Test
public void given_StringArrayWithKeyValuePairs_whenUsing_convertStringArrayToMap_thenMapCreated() {
String[] data = {"name=John", "age=30", "city=NewYork"};
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("name", "John");
expectedMap.put("age", "30");
expectedMap.put("city", "NewYork");
Map<String, String> resultMap = convertStringArrayToMap(data);
assertEquals(expectedMap, resultMap);
}
public Map<String, List<String>> convertStringArrayToMapWithDuplicates(String[] data) {
Map<String, List<String>> map = new HashMap<>();
for (String keyValue : data) {
String[] parts = keyValue.split("=");
String key = parts[0];
String value = parts[1];
if (map.containsKey(key)) {
List<String> valuesList = map.get(key);
valuesList.add(value);
} else {
List<String> valuesList = new ArrayList<>();
valuesList.add(value);
map.put(key, valuesList);
}
}
return map;
}
@Test
public void given_StringArrayWithKeyValuePairsWithDuplicates_whenUsing_convertStringArrayToMapWithDuplicates_thenMapCreatedWithLists() {
String[] data = {"name=John", "age=30", "city=NewYork", "age=31"};
Map<String, List<String>> expectedMap = new HashMap<>();
expectedMap.put("name", Collections.singletonList("John"));
expectedMap.put("age", Arrays.asList("30", "31"));
expectedMap.put("city", Collections.singletonList("NewYork"));
Map<String, List<String>> resultMap = convertStringArrayToMapWithDuplicates(data);
assertEquals(expectedMap, resultMap);
}
}

View File

@ -3,4 +3,5 @@
- [Using Streams to Collect Into a TreeSet](https://www.baeldung.com/java-stream-collect-into-treeset)
- [A Guide to LinkedHashSet in Java](https://www.baeldung.com/java-linkedhashset)
- [Sorting a HashSet in Java](https://www.baeldung.com/java-sort-hashset)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-set)
- [How to Get First Item From a Java Set](https://www.baeldung.com/first-item-set)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-set)

View File

@ -0,0 +1,35 @@
package com.baeldung.firstitemfromset;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
import org.junit.Test;
public class GetFirstItemFromSetUnitTest {
@Test
public void givenASet_whenUsingIterator_thenRetrieveAnItem(){
Set<Integer> set = new LinkedHashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Iterator iterator = set.iterator();
if(iterator.hasNext()){
int retrieved = (int) iterator.next();
assertEquals(retrieved, 1);
}
}
@Test
public void givenASet_whenUsingStreams_thenRetrieveAnItem(){
Set<Integer> set = new LinkedHashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Optional<Integer> optional = set.stream().findFirst();
if(optional.isPresent()){
int retrieved = optional.get();
assertEquals(retrieved, 1);
}
}
}

View File

@ -0,0 +1,6 @@
## Core Java Conditionals
This module contains articles about Java Conditionals.
### Relevant articles:
- [Guide to the yield Keyword in Java](https://www.baeldung.com/java-yield-switch)

View File

@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-conditionals</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-compiler</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<compilerArgs>--enable-preview</compilerArgs>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
<release>14</release>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>14</maven.compiler.source.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<maven.compiler.target.version>14</maven.compiler.target.version>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
</properties>
</project>

View File

@ -0,0 +1,83 @@
package com.baeldung.conditionals;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class YieldTest {
enum Number {
ONE, TWO, THREE, FOUR
}
@Test
void whenSwitchingOnNumberOne_thenWillReturnString() {
Number number = Number.ONE;
String message;
switch (number) {
case ONE:
message = "Got a 1";
break;
case TWO:
message = "Got a 2";
break;
default:
message = "More than 2";
}
assertEquals("Got a 1", message);
}
@Test
void whenSwitchingWithArrowOnNumberTwo_thenWillReturnString() {
Number number = Number.TWO;
String message = switch (number) {
case ONE -> {
yield "Got a 1";
}
case TWO -> {
yield "Got a 2";
}
default -> {
yield "More than 2";
}
};
assertEquals("Got a 2", message);
}
@Test
void whenSwitchingWithArrowNoDefaultOnNumberTwo_thenWillReturnString() {
Number number = Number.TWO;
String message = switch (number) {
case ONE -> {
yield "Got a 1";
}
case TWO -> {
yield "Got a 2";
}
case THREE, FOUR -> {
yield "More than 2";
}
};
assertEquals("Got a 2", message);
}
@Test
void whenSwitchingWithColonOnNumberTwo_thenWillReturnString() {
Number number = Number.TWO;
String message = switch (number) {
case ONE:
yield "Got a 1";
case TWO:
yield "Got a 2";
default:
yield "More than 2";
};
assertEquals("Got a 2", message);
}
}

View File

@ -9,4 +9,5 @@ This module contains articles about date operations in Java.
- [Adding One Month to Current Date in Java](https://www.baeldung.com/java-adding-one-month-to-current-date)
- [How to Get Last Day of a Month in Java](https://www.baeldung.com/java-last-day-month)
- [Getting Yesterdays Date in Java](https://www.baeldung.com/java-find-yesterdays-date)
- [How to Get the Start and End Dates of a Year Using Java](https://www.baeldung.com/java-date-year-start-end)
- [[<-- Prev]](/core-java-modules/core-java-date-operations-2)

View File

@ -8,3 +8,4 @@ This module contains articles about converting between Java date and time object
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
- [Convert Between java.time.Instant and java.sql.Timestamp](https://www.baeldung.com/java-time-instant-to-java-sql-timestamp)
- [Convert Between LocalDateTime and ZonedDateTime](https://www.baeldung.com/java-localdatetime-zoneddatetime)
- [Conversion From 12-Hour Time to 24-Hour Time in Java](https://www.baeldung.com/java-convert-time-format)

View File

@ -0,0 +1,29 @@
package com.baeldung.epochtolocaldate;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
/**
* Class which shows a way to convert Epoch time in milliseconds to java.time.LocalDate.
*
* @author quincy
*
*/
public class EpochTimeToLocalDateConverter {
public static String main(String[] args) {
long epochTimeinMillisToConvert = 1624962431000L;
Instant instant = Instant.ofEpochMilli(epochTimeinMillisToConvert);
ZoneId zoneId = ZoneId.systemDefault(); // Use the system default time zone
LocalDate localDate = instant.atZone(zoneId).toLocalDate();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = localDate.format(formatter);
return formattedDate;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.epochtolocaldate;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
/**
* Class which shows a way to convert Epoch time in milliseconds to java.time.LocalDateTime.
*
* @author quincy
*
*/
public class EpochTimeToLocalDateTimeConverter {
public static String main(String[] args) {
long epochTimeinMillisToConvert = 1624962431000L;
Instant instant = Instant.ofEpochMilli(epochTimeinMillisToConvert);
ZoneId zoneId = ZoneId.systemDefault(); // Use the system default time zone
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = localDateTime.format(formatter);
return formattedDate;
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.epochtolocaldate;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class EpochTimeToLocalDateConverterUnitTest {
@Test
public void testConvertEpochTimeToLocalDate() {
long epochTimeMillis = 1624962431000L; // Example epoch time in millisecond
LocalDate expectedDate = LocalDate.of(2021, 6, 29);
Instant instant = Instant.ofEpochMilli(epochTimeMillis);
ZoneId zoneId = ZoneId.systemDefault();
LocalDate actualDate = instant.atZone(zoneId).toLocalDate();
assertEquals(expectedDate, actualDate);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.epochtolocaldate;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class EpochTimeToLocalDateTimeConverterUnitTest {
@Test
public void testConvertEpochTimeToLocalDateTime() {
long epochTimeMillis = 1624962431000L; // Example epoch time in milliseconds
LocalDateTime expectedDateTime = LocalDateTime.of(2021, 6, 29, 12, 13, 51);
Instant instant = Instant.ofEpochMilli(epochTimeMillis);
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime actualDateTime = instant.atZone(zoneId).toLocalDateTime();
assertEquals(expectedDateTime, actualDateTime);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.twelvehourstotwentyhours;
import static org.junit.jupiter.api.Assertions.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
import org.junit.jupiter.api.Test;
public class TimeConversionUnitTest {
@Test
public void givenTimeInTwelveHours_whenConvertingToTwentyHours_thenConverted() throws ParseException {
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
Date date = parseFormat.parse("06:00 PM");
assertEquals("18:00", displayFormat.format(date));
}
@Test
public void givenTimeInTwelveHours_whenConvertingToTwentyHoursWithDateTimeFormatter_thenConverted() throws ParseException {
String time = LocalTime.parse("06:00 PM", DateTimeFormatter.ofPattern("hh:mm a", Locale.US))
.format(DateTimeFormatter.ofPattern("HH:mm"));
assertEquals("18:00", time);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.socketexception;
import java.io.IOException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
public class SslServer {
public static void createSSLSocketWithEnabledProtocols(SSLServerSocketFactory socketFactory, int port, String[] enabledProtocols) {
SSLServerSocket serverSocket = null;
try {
serverSocket = (SSLServerSocket) socketFactory.createServerSocket(port);
// Set the enabled protocols
serverSocket.setEnabledProtocols(enabledProtocols);
System.out.println("Server is running on port " + port);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

View File

@ -1,25 +1,33 @@
package com.baeldung.socketexception;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.net.SocketException;
import java.util.concurrent.Executors;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import org.junit.BeforeClass;
import org.junit.Test;
public class SocketExceptionHandlingUnitTest {
private static final int PORT = 6699;
@BeforeClass
public static void runServer() throws IOException, InterruptedException {
Executors.newSingleThreadExecutor()
.submit(() -> new SocketServer().start(6699));
.submit(() -> new SocketServer().start(PORT));
Thread.sleep(100);
}
@Test
public void givenRunningServer_whenConnectToClosedSocket_thenHandleException() throws IOException {
SocketClient client = new SocketClient();
client.startConnection("127.0.0.1", 6699);
client.startConnection("127.0.0.1", PORT);
try {
client.sendMessage("hi");
client.sendMessage("hi again");
@ -28,4 +36,22 @@ public class SocketExceptionHandlingUnitTest {
}
}
@Test
public void givenRunningServer_whenConnectToSocket_thenHandleConnectionResetException() throws IOException {
// Enable multiple SSL/TLS protocols
String[] enabledProtocols = { "TLSv1.2", "TLSv1.3", "TLSv1.1", "TLSv1", "SSLv3", "SSLv3" };
SSLServerSocketFactory mockFactory = mock(SSLServerSocketFactory.class);
SSLServerSocket mockServerSocket = mock(SSLServerSocket.class);
// Set up the mock factory to return the mock server socket
when(mockFactory.createServerSocket(PORT)).thenReturn(mockServerSocket);
// Call the method being tested
SslServer.createSSLSocketWithEnabledProtocols(mockFactory, PORT, enabledProtocols);
// Verify that setEnabledProtocols and close were called
verify(mockServerSocket).setEnabledProtocols(enabledProtocols);
verify(mockServerSocket).close();
}
}

View File

@ -5,4 +5,5 @@ This module contains articles about core Java input/output(IO) APIs.
### Relevant Articles:
- [Constructing a Relative Path From Two Absolute Paths in Java](https://www.baeldung.com/java-relative-path-absolute)
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
- [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty)
- [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty)
- [Converting Relative to Absolute Paths in Java](https://www.baeldung.com/java-from-relative-to-absolute-paths)

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