Merge branch 'eugenp:master' into master
This commit is contained in:
+4
-1
@@ -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
|
||||
|
||||
+32
-33
@@ -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")));
|
||||
}
|
||||
|
||||
+161
@@ -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")));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+39
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -0,0 +1,46 @@
|
||||
<?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>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<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>
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
</properties>
|
||||
<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>1.12.523</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
+13
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -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);
|
||||
}
|
||||
}
|
||||
+80
@@ -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 jakarta.annotation.PostConstruct;
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
aws.s3bucket=baeldung-documents;
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
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.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("multipartFile", "test.txt",
|
||||
"text/plain", "test data".getBytes());
|
||||
|
||||
when(fileService.uploadFile(any(MultipartFile.class))).thenReturn("/documents/test.txt");
|
||||
|
||||
mockMvc.perform(multipart("/file/upload").file(multipartFile))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("/documents/test.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidMultipartFileAndExistingPath_whenUpdatedViaEndpoint_thenSamePathIsReturned() throws Exception {
|
||||
MockMultipartFile multipartFile = new MockMultipartFile("multipartFile", "test.txt",
|
||||
"text/plain", "test update data".getBytes());
|
||||
String existingFilePath = "/documents/existingFile.txt";
|
||||
|
||||
when(fileService.updateFile(any(MultipartFile.class), eq(existingFilePath))).thenReturn(existingFilePath);
|
||||
|
||||
mockMvc.perform(multipart("/file/update")
|
||||
.file(multipartFile)
|
||||
.param("exitingFilePath", existingFilePath))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(existingFilePath));
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
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.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.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"));
|
||||
}
|
||||
}
|
||||
@@ -20,5 +20,4 @@
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
+14
@@ -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;
|
||||
}
|
||||
}
|
||||
+12
@@ -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;
|
||||
}
|
||||
}
|
||||
+14
@@ -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;
|
||||
}
|
||||
}
|
||||
+16
@@ -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));
|
||||
}
|
||||
}
|
||||
+16
@@ -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));
|
||||
}
|
||||
}
|
||||
+16
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
+46
@@ -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);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user