Merge branch 'eugenp:master' into master
This commit is contained in:
commit
4891b5c575
|
@ -125,3 +125,6 @@ devDb*.db
|
|||
|
||||
#neo4j
|
||||
persistence-modules/neo4j/data/**
|
||||
/deep-shallow-copy/.mvn/wrapper
|
||||
/deep-shallow-copy/mvnw
|
||||
/deep-shallow-copy/mvnw.cmd
|
||||
|
|
|
@ -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")));
|
||||
}
|
||||
|
|
|
@ -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")));
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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>
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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;
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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>
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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>
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -3,10 +3,14 @@ package com.baeldung.jar;
|
|||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class JarAppUnitTest {
|
||||
|
||||
@Test
|
||||
public void findClassTest(){
|
||||
Assert.assertTrue(JarApp.findObjectMapperClass().endsWith("jackson-databind-2.13.3.jar"));
|
||||
Pattern databindPattern = Pattern.compile(".*jackson-databind-(\\d)+\\.(\\d)+\\.(\\d)\\.jar$");
|
||||
|
||||
Assert.assertTrue(databindPattern.matcher(JarApp.findObjectMapperClass()).matches());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.leetcode.magicsquare;
|
||||
package com.baeldung.magicsquare;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.leetcode.magicsquare;
|
||||
package com.baeldung.magicsquare;
|
||||
|
||||
import org.junit.platform.commons.util.StringUtils;
|
||||
|
||||
|
@ -172,7 +172,9 @@ public class MagicSquare {
|
|||
int value = getCell(x, y);
|
||||
if (value == 0) {
|
||||
sb.append(" ");
|
||||
sb.append(".".repeat(largestNumberLength));
|
||||
for (int i = 0; i < largestNumberLength; ++i) {
|
||||
sb.append(".");
|
||||
}
|
||||
sb.append(" ");
|
||||
} else {
|
||||
sb.append(String.format(formatString, value));
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.leetcode.magicsquare;
|
||||
package com.baeldung.magicsquare;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.subclassinnerclass;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class EmailNotifier extends Notifier {
|
||||
@Override
|
||||
void notify(Message e) {
|
||||
// Provide email specific implementation here
|
||||
}
|
||||
|
||||
// Inner class for email connection
|
||||
static class EmailConnector {
|
||||
private String emailHost;
|
||||
private int emailPort;
|
||||
// Getter Setters
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package com.baeldung.subclassinnerclass;
|
||||
|
||||
public class Message {
|
||||
private int message;
|
||||
// getter setter and other atteibutes
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.subclassinnerclass;
|
||||
|
||||
public class NotificationService {
|
||||
void notifyMessages() {
|
||||
// Sending a Text Message
|
||||
Message textMessage = new Message();
|
||||
Notifier textNotifier = new TextMessageNotifier();
|
||||
|
||||
textNotifier.notify(textMessage);
|
||||
|
||||
// Sending an Email Message
|
||||
Message emailMessage = new Message();
|
||||
Notifier emailNotifier = new EmailNotifier();
|
||||
|
||||
emailNotifier.notify(emailMessage);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.subclassinnerclass;
|
||||
|
||||
public abstract class Notifier {
|
||||
abstract void notify(Message e);
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.subclassinnerclass;
|
||||
|
||||
public class TextMessageNotifier extends Notifier {
|
||||
@Override
|
||||
void notify(Message e) {
|
||||
// Provide text message specific implementation here
|
||||
}
|
||||
|
||||
// Inner class for text message connection
|
||||
private static class SMSConnector {
|
||||
private String smsHost;
|
||||
// Getter Setters
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.subclassinnerclass;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class InnerClassUnitTest {
|
||||
@Test
|
||||
public void givenInnerStaticClassWhenInstantiatedThenOuterClassIsInstantiated() {
|
||||
Notifier emailNotifier = new EmailNotifier();
|
||||
EmailNotifier.EmailConnector emailConnector = new EmailNotifier.EmailConnector();
|
||||
|
||||
assertThat(emailNotifier).hasSameClassAs(new EmailNotifier());
|
||||
assertThat(emailConnector).isInstanceOf(EmailNotifier.EmailConnector.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.subclassinnerclass;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class SubClassUnitTest {
|
||||
@Test
|
||||
public void givenSubclassWhenInstantiatedThenSubclassObjectIsPossible() {
|
||||
Notifier emailNotifier = new EmailNotifier();
|
||||
assertThat(emailNotifier).hasSameClassAs(new EmailNotifier());
|
||||
assertThat(emailNotifier).isExactlyInstanceOf(EmailNotifier.class);
|
||||
|
||||
Notifier textMessageNotifier = new TextMessageNotifier();
|
||||
assertThat(textMessageNotifier).isInstanceOf(Notifier.class);
|
||||
assertThat(textMessageNotifier).isExactlyInstanceOf(TextMessageNotifier.class);
|
||||
}
|
||||
}
|
|
@ -27,7 +27,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-codec.version>1.15</commons-codec.version>
|
||||
<commons-codec.version>1.16.0</commons-codec.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,39 +0,0 @@
|
|||
<?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-leetcode</artifactId>
|
||||
<name>core-java-leetcode</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -13,28 +13,4 @@
|
|||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>${bouncycastle.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<version>${jaxb-api.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<bouncycastle.version>1.60</bouncycastle.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
<jaxb-api.version>2.3.1</jaxb-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -108,7 +108,6 @@
|
|||
<module>core-java-lang-operators-2</module>
|
||||
<module>core-java-lang-syntax</module>
|
||||
<module>core-java-lang-syntax-2</module>
|
||||
<module>core-java-leetcode</module>
|
||||
<module>core-java-locale</module>
|
||||
<module>core-java-networking</module>
|
||||
<module>core-java-networking-2</module>
|
||||
|
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.javaxval.listvalidation;
|
||||
|
||||
public interface AllLevels {
|
||||
}
|
|
@ -1,12 +1,7 @@
|
|||
package com.baeldung.listvalidation.domain;
|
||||
package com.baeldung.javaxval.listvalidation;
|
||||
|
||||
import com.baeldung.listvalidation.groups.AllLevels;
|
||||
import com.baeldung.listvalidation.groups.Junior;
|
||||
import com.baeldung.listvalidation.groups.MidSenior;
|
||||
import com.baeldung.listvalidation.groups.Senior;
|
||||
import org.springframework.lang.Nullable;
|
||||
import jakarta.validation.constraints.*;
|
||||
|
||||
import javax.validation.constraints.*;
|
||||
import java.util.Date;
|
||||
|
||||
public class JobAspirant {
|
||||
|
@ -14,7 +9,6 @@ public class JobAspirant {
|
|||
@Size(min = 5, message = "Name should have at least 5 characters", groups = AllLevels.class),
|
||||
@Size(max = 20, message = "Name should have at most 20 characters", groups = AllLevels.class)
|
||||
})
|
||||
|
||||
@Pattern.List({
|
||||
@Pattern(regexp = "^[\\p{Alpha} ]*$", message = "Name should contain only alphabets and space", groups = AllLevels.class),
|
||||
@Pattern(regexp = "^[^\\s].*$", message = "Name should not start with space", groups = AllLevels.class),
|
||||
|
@ -22,18 +16,8 @@ public class JobAspirant {
|
|||
@Pattern(regexp = "^((?! ).)*$", message = "Name should not contain consecutive spaces", groups = AllLevels.class),
|
||||
@Pattern(regexp = "^[^a-z].*$", message = "Name should not start with a lower case character", groups = AllLevels.class)
|
||||
})
|
||||
|
||||
|
||||
private String name;
|
||||
|
||||
public Integer getExperience() {
|
||||
return experience;
|
||||
}
|
||||
|
||||
public void setExperience(Integer experience) {
|
||||
this.experience = experience;
|
||||
}
|
||||
|
||||
@Min.List({
|
||||
@Min(value = 15, message = "Years of experience cannot be less than 15 Years", groups = Senior.class),
|
||||
@Min(value = 10, message = "Years of experience cannot be less than 10 Years", groups = MidSenior.class),
|
||||
|
@ -47,18 +31,16 @@ public class JobAspirant {
|
|||
private Integer experience;
|
||||
|
||||
@AssertTrue.List({
|
||||
@AssertTrue(message = "Terms and Conditions consent missing for Senior Level Job Application", groups = Senior.class),
|
||||
@AssertTrue(message = "Terms and Conditions consent missing for Mid-Senior Level Job Application", groups = MidSenior.class),
|
||||
@AssertTrue(message = "Terms and Conditions consent missing for Junior Level Job Application", groups = Junior.class)
|
||||
@AssertTrue(message = "Terms and Conditions consent missing for Senior Level Job", groups = Senior.class),
|
||||
@AssertTrue(message = "Terms and Conditions consent missing for Mid-Senior Level Job", groups = MidSenior.class),
|
||||
@AssertTrue(message = "Terms and Conditions consent missing for Junior Level Job", groups = Junior.class)
|
||||
})
|
||||
@Nullable
|
||||
private Boolean agreement;
|
||||
|
||||
@Nullable
|
||||
@Future.List({
|
||||
@Future(message = "Active passport is mandatory for Senior Level Job Application", groups = Senior.class),
|
||||
@Future(message = "Active passport is mandatory for Mid-Senior Level Job Application", groups = MidSenior.class),
|
||||
@Future(message = "Active passport is mandatory for Junior Level Job Application", groups = Junior.class)
|
||||
@Future(message = "Active passport is mandatory for Senior Level Job", groups = Senior.class),
|
||||
@Future(message = "Active passport is mandatory for Mid-Senior Level Job", groups = MidSenior.class),
|
||||
@Future(message = "Active passport is mandatory for Junior Level Job", groups = Junior.class)
|
||||
})
|
||||
private Date passportExpiryDate;
|
||||
|
||||
|
@ -70,8 +52,6 @@ public class JobAspirant {
|
|||
@Pattern(regexp = "^(Junior)$", message = "Job level should be Junior"
|
||||
,flags = Pattern.Flag.CASE_INSENSITIVE, groups = Junior.class)
|
||||
})
|
||||
// @Pattern(regexp = "^(Senior|MidSenior|Junior)$", message = "Job level should be Senior, MidSenior or Junior"
|
||||
// ,flags = Pattern.Flag.CASE_INSENSITIVE, groups = AllLevels.class)
|
||||
private String jobLevel;
|
||||
|
||||
public String getJobLevel() {
|
||||
|
@ -104,4 +84,12 @@ public class JobAspirant {
|
|||
public void setPassportExpiryDate(Date passportExpiryDate) {
|
||||
this.passportExpiryDate = passportExpiryDate;
|
||||
}
|
||||
|
||||
public Integer getExperience() {
|
||||
return experience;
|
||||
}
|
||||
|
||||
public void setExperience(Integer experience) {
|
||||
this.experience = experience;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.javaxval.listvalidation;
|
||||
|
||||
public interface Junior {
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.javaxval.listvalidation;
|
||||
|
||||
public interface MidSenior {
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.baeldung.javaxval.listvalidation;
|
||||
|
||||
public interface Senior {
|
||||
}
|
|
@ -0,0 +1,209 @@
|
|||
package com.baeldung.javaxval.listvalidation;
|
||||
|
||||
import jakarta.validation.ConstraintViolation;
|
||||
import jakarta.validation.Validation;
|
||||
import jakarta.validation.Validator;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class JobAspirantUnitTest {
|
||||
private static Validator validator;
|
||||
@BeforeClass
|
||||
public static void setupValidatorInstance() {
|
||||
validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelJunior_whenInValidMinExperience_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("Junior", "John Adam", "2025-12-31", 3, true);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, Junior.class);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action -> {
|
||||
assertThat(action.getPropertyPath().toString()).isEqualTo("experience");
|
||||
assertThat(action.getMessage()).isEqualTo("Years of experience cannot be less than 5 Years");
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelMidSenior_whenInvalidMinExperience_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("MidSenior", "John Adam", "2025-12-31", 8, true);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, MidSenior.class);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action -> {
|
||||
assertThat(action.getPropertyPath().toString()).isEqualTo("experience");
|
||||
assertThat(action.getMessage()).isEqualTo("Years of experience cannot be less than 10 Years");
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelSenior_whenInvalidMinExperience_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam", "2025-12-31", 13, true);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, Senior.class);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action -> {
|
||||
assertThat(action.getPropertyPath().toString()).isEqualTo("experience");
|
||||
assertThat(action.getMessage()).isEqualTo("Years of experience cannot be less than 15 Years");
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelJunior_whenInValidMaxExperience_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("Junior", "John Adam", "2025-12-31", 11, true);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, Junior.class);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action -> {
|
||||
assertThat(action.getPropertyPath().toString()).isEqualTo("experience");
|
||||
assertThat(action.getMessage()).isEqualTo("Years of experience cannot be more than 10 Years");
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelMidSenior_whenInvalidMaxExperience_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("MidSenior", "John Adam", "2025-12-31", 16, true);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, MidSenior.class);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action -> {
|
||||
assertThat(action.getPropertyPath().toString()).isEqualTo("experience");
|
||||
assertThat(action.getMessage()).isEqualTo("Years of experience cannot be more than 15 Years");
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelSenior_whenInvalidMaxExperience_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam", "2025-12-31", 23, true);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, Senior.class);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action -> {
|
||||
assertThat(action.getPropertyPath().toString()).isEqualTo("experience");
|
||||
assertThat(action.getMessage()).isEqualTo("Years of experience cannot be more than 20 Years");
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void whenInvalidName_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam", "2025-12-31", 17, true);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, Senior.class, AllLevels.class);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action -> {
|
||||
assertThat(action.getPropertyPath().toString()).isEqualTo("name");
|
||||
assertThat(action.getMessage()).isEqualTo("Name should not contain consecutive spaces");
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void givenJuniorLevel_whenInvalidAgreement_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("Junior", "John Adam", "2025-12-31", 7, false);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, Junior.class);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action -> {
|
||||
assertThat(action.getPropertyPath().toString()).isEqualTo("agreement");
|
||||
assertThat(action.getMessage()).isEqualTo("Terms and Conditions consent missing for Junior Level Job");
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void givenSeniorLevel_whenInvalidAgreement_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam", "2025-12-31", 17, false);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, Senior.class);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action -> {
|
||||
assertThat(action.getPropertyPath().toString()).isEqualTo("agreement");
|
||||
assertThat(action.getMessage()).isEqualTo("Terms and Conditions consent missing for Senior Level Job");
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelMidSenior_whenInvalidPassport_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("MidSenior", "John Adam", "2021-12-31", 12, true);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, MidSenior.class);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action -> {
|
||||
assertThat(action.getPropertyPath().toString()).isEqualTo("passportExpiryDate");
|
||||
assertThat(action.getMessage()).isEqualTo("Active passport is mandatory for Mid-Senior Level Job");
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelSenior_whenInvalidPassport_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam", "2021-12-31", 18, true);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, Senior.class);
|
||||
assertThat(violations.size()).isEqualTo(1);
|
||||
violations.forEach(action -> {
|
||||
assertThat(action.getPropertyPath().toString()).isEqualTo("passportExpiryDate");
|
||||
assertThat(action.getMessage()).isEqualTo("Active passport is mandatory for Senior Level Job");
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelSenior_whenAllFieldsValid_thenNoErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam", "2025-12-31", 17, true);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, Senior.class, AllLevels.class);
|
||||
assertThat(violations.size()).isEqualTo(0);
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelMidSenior_whenAllFieldsValid_thenNoErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("MidSenior", "John Adam", "2025-12-31", 12, true);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, MidSenior.class, AllLevels.class);
|
||||
assertThat(violations.size()).isEqualTo(0);
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelJunior_whenAllFieldsValid_thenNoErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("Junior", "John Adam", "2025-12-31", 7, true);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, Junior.class, AllLevels.class);
|
||||
assertThat(violations.size()).isEqualTo(0);
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelJunior_whenAllFieldsInValid_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("Junior", " John Adam", "2022-12-31", 3, false);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, Junior.class, AllLevels.class);
|
||||
assertThat(violations.size()).isEqualTo(4);
|
||||
violations.forEach(action -> {
|
||||
String fieldName = action.getPropertyPath().toString();
|
||||
switch(fieldName) {
|
||||
case "name":
|
||||
assertThat(action.getMessage()).isEqualTo("Name should not start with space");
|
||||
break;
|
||||
case "passportExpiryDate":
|
||||
assertThat(action.getMessage()).isEqualTo("Active passport is mandatory for Junior Level Job");
|
||||
break;
|
||||
case "experience":
|
||||
assertThat(action.getMessage()).isEqualTo("Years of experience cannot be less than 5 Years");
|
||||
break;
|
||||
case "agreement":
|
||||
assertThat(action.getMessage()).isEqualTo("Terms and Conditions consent missing for Junior Level Job");
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
@Test
|
||||
public void givenJobLevelSenior_whenAllFieldsInValid_thenExpectErrors() throws ParseException {
|
||||
JobAspirant jobAspirant = getJobAspirant("Senior", "John Adam ", "2022-12-31", 12, false);
|
||||
Set<ConstraintViolation<JobAspirant>> violations = validator.validate(jobAspirant, Senior.class, AllLevels.class);
|
||||
assertThat(violations.size()).isEqualTo(4);
|
||||
violations.forEach(action -> {
|
||||
String fieldName = action.getPropertyPath().toString();
|
||||
switch(fieldName) {
|
||||
case "name":
|
||||
assertThat(action.getMessage()).isEqualTo("Name should not end with space");
|
||||
break;
|
||||
case "passportExpiryDate":
|
||||
assertThat(action.getMessage()).isEqualTo("Active passport is mandatory for Senior Level Job");
|
||||
break;
|
||||
case "experience":
|
||||
assertThat(action.getMessage()).isEqualTo("Years of experience cannot be less than 15 Years");
|
||||
break;
|
||||
case "agreement":
|
||||
assertThat(action.getMessage()).isEqualTo("Terms and Conditions consent missing for Senior Level Job");
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
private JobAspirant getJobAspirant(String jobLevel, String name, String passportExpDate, int exp, boolean agmt) throws ParseException {
|
||||
JobAspirant jobAspirant = new JobAspirant();
|
||||
jobAspirant.setName(name);
|
||||
jobAspirant.setPassportExpiryDate(convertStringToDate(passportExpDate));
|
||||
jobAspirant.setJobLevel(jobLevel);
|
||||
jobAspirant.setExperience(exp);
|
||||
jobAspirant.setAgreement(agmt);
|
||||
return jobAspirant;
|
||||
}
|
||||
private Date convertStringToDate(String date) throws ParseException {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
|
||||
return formatter.parse(date);
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
-XX:-TieredCompilation -XX:TieredStopAtLevel=1
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,62 @@
|
|||
<?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>maven-build-optimization</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>maven-build-optimization</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>maven-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-profiler-plugin</artifactId>
|
||||
<version>${profiler.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>${failsafe.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>skipITs</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<failsafe.version>3.1.2</failsafe.version>
|
||||
<profiler.version>1.7</profiler.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -20,6 +20,7 @@
|
|||
<module>dependency-exclusion</module>
|
||||
<module>host-maven-repo-example</module>
|
||||
<module>maven-archetype</module>
|
||||
<module>maven-build-optimization</module>
|
||||
<module>maven-builder-plugin</module>
|
||||
<module>maven-classifier</module>
|
||||
<module>maven-copy-files</module>
|
||||
|
|
|
@ -1,3 +1,3 @@
|
|||
## Parent Boot 2
|
||||
## Parent Boot 3
|
||||
|
||||
This is a parent module for all projects using Spring Boot 3.
|
||||
|
|
|
@ -18,7 +18,7 @@ public class Email {
|
|||
private String address;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "employee_id")
|
||||
@JoinColumn(name = "employee_id", referencedColumnName = "id")
|
||||
private OfficialEmployee employee;
|
||||
|
||||
public Long getId() {
|
||||
|
|
|
@ -1,178 +0,0 @@
|
|||
package com.baeldung.neo4j;
|
||||
|
||||
|
||||
import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.neo4j.configuration.GraphDatabaseSettings;
|
||||
import org.neo4j.dbms.api.DatabaseManagementService;
|
||||
import org.neo4j.dbms.api.DatabaseManagementServiceBuilder;
|
||||
import org.neo4j.graphdb.GraphDatabaseService;
|
||||
import org.neo4j.graphdb.Label;
|
||||
import org.neo4j.graphdb.Node;
|
||||
import org.neo4j.graphdb.NotFoundException;
|
||||
import org.neo4j.graphdb.RelationshipType;
|
||||
import org.neo4j.graphdb.Result;
|
||||
import org.neo4j.graphdb.Transaction;
|
||||
|
||||
/**
|
||||
* To run this test you will need to have an instance of the docker running on your machine (Docker desktop - for Windows and Docker instance for linux)
|
||||
* After your docker instance is up run this test
|
||||
*/
|
||||
public class Neo4jLiveTest {
|
||||
|
||||
private static GraphDatabaseService graphDb;
|
||||
private static Transaction transaction;
|
||||
private static DatabaseManagementService managementService;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
managementService = new DatabaseManagementServiceBuilder(new File("data/cars").toPath())
|
||||
.setConfig( GraphDatabaseSettings.transaction_timeout, Duration.ofSeconds( 60 ) )
|
||||
.setConfig( GraphDatabaseSettings.preallocate_logical_logs, false ).build();
|
||||
graphDb = managementService.database( DEFAULT_DATABASE_NAME );
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
managementService.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPersonCar() {
|
||||
transaction = graphDb.beginTx();
|
||||
Node car = transaction.createNode(Label.label("Car"));
|
||||
car.setProperty("make", "tesla");
|
||||
car.setProperty("model", "model3");
|
||||
|
||||
Node owner = transaction.createNode(Label.label("Person"));
|
||||
owner.setProperty("firstName", "baeldung");
|
||||
owner.setProperty("lastName", "baeldung");
|
||||
|
||||
owner.createRelationshipTo(car, RelationshipType.withName("owner"));
|
||||
|
||||
Result result = transaction.execute("MATCH (c:Car) <-[owner]- (p:Person) " +
|
||||
"WHERE c.make = 'tesla'" +
|
||||
"RETURN p.firstName, p.lastName");
|
||||
|
||||
Map<String, Object> firstResult = result.next();
|
||||
|
||||
Assert.assertEquals("baeldung", firstResult.get("p.firstName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateNode() {
|
||||
transaction = graphDb.beginTx();
|
||||
Result result = transaction.execute("CREATE (baeldung:Company {name:\"Baeldung\"})" +
|
||||
"RETURN baeldung");
|
||||
|
||||
Map<String, Object> firstResult = result.next();
|
||||
Node firstNode = (Node) firstResult.get("baeldung");
|
||||
|
||||
Assert.assertEquals(firstNode.getProperty("name"), "Baeldung");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateNodeAndLink() {
|
||||
transaction = graphDb.beginTx();
|
||||
Result result = transaction.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
|
||||
"-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
|
||||
"RETURN baeldung, tesla");
|
||||
|
||||
Map<String, Object> firstResult = result.next();
|
||||
|
||||
Assert.assertTrue(firstResult.containsKey("baeldung"));
|
||||
Assert.assertTrue(firstResult.containsKey("tesla"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFindAndReturn() {
|
||||
transaction = graphDb.beginTx();
|
||||
transaction.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
|
||||
"-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
|
||||
"RETURN baeldung, tesla");
|
||||
|
||||
Result result = transaction.execute("MATCH (company:Company)-[:owns]-> (car:Car)" +
|
||||
"WHERE car.make='tesla' and car.model='modelX'" +
|
||||
"RETURN company.name");
|
||||
|
||||
Map<String, Object> firstResult = result.next();
|
||||
|
||||
Assert.assertEquals(firstResult.get("company.name"), "Baeldung");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdate() {
|
||||
transaction = graphDb.beginTx();
|
||||
transaction.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
|
||||
"-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
|
||||
"RETURN baeldung, tesla");
|
||||
|
||||
Result result = transaction.execute("MATCH (car:Car)" +
|
||||
"WHERE car.make='tesla'" +
|
||||
" SET car.milage=120" +
|
||||
" SET car :Car:Electro" +
|
||||
" SET car.model=NULL" +
|
||||
" RETURN car");
|
||||
|
||||
Map<String, Object> firstResult = result.next();
|
||||
Node car = (Node) firstResult.get("car");
|
||||
|
||||
Assert.assertEquals(car.getProperty("milage"), 120L);
|
||||
Assert.assertEquals(car.getLabels(), Arrays.asList(Label.label("Car"), Label.label("Electro")));
|
||||
|
||||
try {
|
||||
car.getProperty("model");
|
||||
Assert.fail();
|
||||
} catch (NotFoundException e) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDelete() {
|
||||
transaction = graphDb.beginTx();
|
||||
transaction.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
|
||||
"-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
|
||||
"RETURN baeldung, tesla");
|
||||
|
||||
transaction.execute("MATCH (company:Company)" +
|
||||
" WHERE company.name='Baeldung'" +
|
||||
" DELETE company");
|
||||
|
||||
Result result = transaction.execute("MATCH (company:Company)" +
|
||||
" WHERE company.name='Baeldung'" +
|
||||
" RETURN company");
|
||||
|
||||
Assert.assertFalse(result.hasNext());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindings() {
|
||||
transaction = graphDb.beginTx();
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("name", "baeldung");
|
||||
params.put("make", "tesla");
|
||||
params.put("model", "modelS");
|
||||
|
||||
Result result = transaction.execute("CREATE (baeldung:Company {name:$name}) " +
|
||||
"-[:owns]-> (tesla:Car {make: $make, model: $model})" +
|
||||
"RETURN baeldung, tesla", params);
|
||||
|
||||
Map<String, Object> firstResult = result.next();
|
||||
Assert.assertTrue(firstResult.containsKey("baeldung"));
|
||||
Assert.assertTrue(firstResult.containsKey("tesla"));
|
||||
|
||||
Node car = (Node) firstResult.get("tesla");
|
||||
Assert.assertEquals(car.getProperty("model"), "modelS");
|
||||
}
|
||||
}
|
|
@ -15,53 +15,39 @@
|
|||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j-ogm-embedded-driver</artifactId>
|
||||
<version>${neo4j-ogm.version}</version>
|
||||
<groupId>org.neo4j.test</groupId>
|
||||
<artifactId>neo4j-harness</artifactId>
|
||||
<version>${neo4j-harness.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-neo4j</artifactId>
|
||||
<version>${spring-data-neo4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.voodoodyne.jackson.jsog</groupId>
|
||||
<artifactId>jackson-jsog</artifactId>
|
||||
<version>${jackson-jsog.version}</version>
|
||||
<scope>compile</scope>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-neo4j</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j-ogm-test</artifactId>
|
||||
<version>${neo4j-ogm.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.neo4j.test</groupId>
|
||||
<artifactId>neo4j-harness</artifactId>
|
||||
<version>${neo4j.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring-test.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<neo4j.version>3.4.6</neo4j.version>
|
||||
<spring-data-neo4j.version>5.0.1.RELEASE</spring-data-neo4j.version>
|
||||
<jackson-jsog.version>1.1</jackson-jsog.version>
|
||||
<spring-boot.version>2.0.1.RELEASE</spring-boot.version>
|
||||
<spring-test.version>5.0.1.RELEASE</spring-test.version>
|
||||
<neo4j-ogm.version>3.1.2</neo4j-ogm.version>
|
||||
<spring-boot.version>2.7.14</spring-boot.version>
|
||||
<neo4j-harness.version>5.10.0</neo4j-harness.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,12 +1,12 @@
|
|||
package com.baeldung.listvalidation;
|
||||
|
||||
package com.baeldung.spring.data.neo4j;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringJobApplicationDemoApp {
|
||||
public class Neo4JApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringJobApplicationDemoApp.class, args);
|
||||
SpringApplication.run(Neo4JApplication.class, args);
|
||||
}
|
||||
}
|
|
@ -1,26 +0,0 @@
|
|||
package com.baeldung.spring.data.neo4j.config;
|
||||
|
||||
import org.neo4j.ogm.config.Configuration.Builder;
|
||||
import org.neo4j.ogm.session.SessionFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
|
||||
|
||||
@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" })
|
||||
@Configuration
|
||||
@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repository")
|
||||
public class MovieDatabaseNeo4jConfiguration {
|
||||
|
||||
public static final String URL = System.getenv("NEO4J_URL") != null ? System.getenv("NEO4J_URL") : "http://neo4j:movies@localhost:7474";
|
||||
|
||||
@Bean
|
||||
public org.neo4j.ogm.config.Configuration getConfiguration() {
|
||||
return new Builder().uri(URL).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SessionFactory getSessionFactory() {
|
||||
return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain");
|
||||
}
|
||||
}
|
|
@ -1,36 +0,0 @@
|
|||
package com.baeldung.spring.data.neo4j.config;
|
||||
|
||||
import org.neo4j.ogm.config.Configuration.Builder;
|
||||
import org.neo4j.ogm.session.SessionFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
|
||||
import org.springframework.data.neo4j.transaction.Neo4jTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" })
|
||||
@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repository")
|
||||
@Profile({ "embedded", "test" })
|
||||
public class MovieDatabaseNeo4jTestConfiguration {
|
||||
|
||||
@Bean
|
||||
public org.neo4j.ogm.config.Configuration getConfiguration() {
|
||||
org.neo4j.ogm.config.Configuration config = new Builder().build();
|
||||
return config;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SessionFactory getSessionFactory() {
|
||||
return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Neo4jTransactionManager transactionManager() {
|
||||
return new Neo4jTransactionManager(getSessionFactory());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.spring.data.neo4j.config;
|
||||
|
||||
import org.neo4j.cypherdsl.core.renderer.Dialect;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class Neo4jConfig {
|
||||
@Bean
|
||||
org.neo4j.cypherdsl.core.renderer.Configuration cypherDslConfiguration() {
|
||||
return org.neo4j.cypherdsl.core.renderer.Configuration.newConfig()
|
||||
.withDialect(Dialect.NEO4J_5).build();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.spring.data.neo4j.domain;
|
||||
|
||||
|
||||
import org.springframework.data.neo4j.core.schema.Id;
|
||||
import org.springframework.data.neo4j.core.schema.Node;
|
||||
import org.springframework.data.neo4j.core.schema.Relationship;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Node("Author")
|
||||
public class Author {
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@Relationship(type = "WRITTEN_BY", direction = Relationship.Direction.INCOMING)
|
||||
private List<Book> books;
|
||||
|
||||
public Author(Long id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<Book> getBooks() {
|
||||
return books;
|
||||
}
|
||||
|
||||
public void setBooks(List<Book> books) {
|
||||
this.books = books;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.spring.data.neo4j.domain;
|
||||
|
||||
import org.springframework.data.neo4j.core.schema.Id;
|
||||
import org.springframework.data.neo4j.core.schema.Node;
|
||||
import org.springframework.data.neo4j.core.schema.Property;
|
||||
import org.springframework.data.neo4j.core.schema.Relationship;
|
||||
|
||||
@Node("Book")
|
||||
public class Book {
|
||||
@Id
|
||||
private String isbn;
|
||||
|
||||
@Property("name")
|
||||
private String title;
|
||||
|
||||
private Integer year;
|
||||
|
||||
@Relationship(type = "WRITTEN_BY", direction = Relationship.Direction.OUTGOING)
|
||||
private Author author;
|
||||
|
||||
public Book(String isbn, String title, Integer year) {
|
||||
this.isbn = isbn;
|
||||
this.title = title;
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public String getIsbn() {
|
||||
return isbn;
|
||||
}
|
||||
|
||||
public void setIsbn(String isbn) {
|
||||
this.isbn = isbn;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Integer getYear() {
|
||||
return year;
|
||||
}
|
||||
|
||||
public void setYear(Integer year) {
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public Author getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(Author author) {
|
||||
this.author = author;
|
||||
}
|
||||
}
|
|
@ -1,48 +0,0 @@
|
|||
package com.baeldung.spring.data.neo4j.domain;
|
||||
|
||||
import org.neo4j.ogm.annotation.GeneratedValue;
|
||||
import org.neo4j.ogm.annotation.Id;
|
||||
import org.neo4j.ogm.annotation.NodeEntity;
|
||||
import org.neo4j.ogm.annotation.Relationship;
|
||||
|
||||
@NodeEntity
|
||||
public class Car {
|
||||
@Id @GeneratedValue
|
||||
private Long id;
|
||||
|
||||
private String make;
|
||||
|
||||
@Relationship(direction = "INCOMING")
|
||||
private Company company;
|
||||
|
||||
public Car(String make, String model) {
|
||||
this.make = make;
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getMake() {
|
||||
return make;
|
||||
}
|
||||
|
||||
public void setMake(String make) {
|
||||
this.make = make;
|
||||
}
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public void setModel(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
private String model;
|
||||
}
|
|
@ -1,42 +0,0 @@
|
|||
package com.baeldung.spring.data.neo4j.domain;
|
||||
|
||||
import org.neo4j.ogm.annotation.NodeEntity;
|
||||
import org.neo4j.ogm.annotation.Relationship;
|
||||
|
||||
@NodeEntity
|
||||
public class Company {
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@Relationship(type="owns")
|
||||
private Car car;
|
||||
|
||||
public Company(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Car getCar() {
|
||||
return car;
|
||||
}
|
||||
|
||||
public void setCar(Car car) {
|
||||
this.car = car;
|
||||
}
|
||||
}
|
|
@ -1,64 +0,0 @@
|
|||
package com.baeldung.spring.data.neo4j.domain;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
||||
import com.voodoodyne.jackson.jsog.JSOGGenerator;
|
||||
|
||||
import org.neo4j.ogm.annotation.GeneratedValue;
|
||||
import org.neo4j.ogm.annotation.Id;
|
||||
import org.neo4j.ogm.annotation.NodeEntity;
|
||||
import org.neo4j.ogm.annotation.Relationship;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
@JsonIdentityInfo(generator = JSOGGenerator.class)
|
||||
|
||||
@NodeEntity
|
||||
public class Movie {
|
||||
@Id @GeneratedValue
|
||||
Long id;
|
||||
|
||||
private String title;
|
||||
|
||||
private int released;
|
||||
private String tagline;
|
||||
|
||||
@Relationship(type = "ACTED_IN", direction = Relationship.INCOMING)
|
||||
private List<Role> roles;
|
||||
|
||||
public Movie() {
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public int getReleased() {
|
||||
return released;
|
||||
}
|
||||
|
||||
public String getTagline() {
|
||||
return tagline;
|
||||
}
|
||||
|
||||
public Collection<Role> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public void setReleased(int released) {
|
||||
this.released = released;
|
||||
}
|
||||
|
||||
public void setTagline(String tagline) {
|
||||
this.tagline = tagline;
|
||||
}
|
||||
|
||||
public void setRoles(List<Role> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,52 +0,0 @@
|
|||
package com.baeldung.spring.data.neo4j.domain;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
||||
import com.voodoodyne.jackson.jsog.JSOGGenerator;
|
||||
|
||||
import org.neo4j.ogm.annotation.GeneratedValue;
|
||||
import org.neo4j.ogm.annotation.Id;
|
||||
import org.neo4j.ogm.annotation.NodeEntity;
|
||||
import org.neo4j.ogm.annotation.Relationship;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@JsonIdentityInfo(generator = JSOGGenerator.class)
|
||||
@NodeEntity
|
||||
public class Person {
|
||||
@Id @GeneratedValue
|
||||
Long id;
|
||||
|
||||
private String name;
|
||||
private int born;
|
||||
|
||||
@Relationship(type = "ACTED_IN")
|
||||
private List<Movie> movies;
|
||||
|
||||
public Person() {
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getBorn() {
|
||||
return born;
|
||||
}
|
||||
|
||||
public List<Movie> getMovies() {
|
||||
return movies;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setBorn(int born) {
|
||||
this.born = born;
|
||||
}
|
||||
|
||||
public void setMovies(List<Movie> movies) {
|
||||
this.movies = movies;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,50 +0,0 @@
|
|||
package com.baeldung.spring.data.neo4j.domain;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
||||
import com.voodoodyne.jackson.jsog.JSOGGenerator;
|
||||
import org.neo4j.ogm.annotation.EndNode;
|
||||
import org.neo4j.ogm.annotation.GeneratedValue;
|
||||
import org.neo4j.ogm.annotation.Id;
|
||||
import org.neo4j.ogm.annotation.RelationshipEntity;
|
||||
import org.neo4j.ogm.annotation.StartNode;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
@JsonIdentityInfo(generator = JSOGGenerator.class)
|
||||
@RelationshipEntity(type = "ACTED_IN")
|
||||
public class Role {
|
||||
@Id @GeneratedValue
|
||||
Long id;
|
||||
private Collection<String> roles;
|
||||
@StartNode
|
||||
private Person person;
|
||||
@EndNode
|
||||
private Movie movie;
|
||||
|
||||
public Role() {
|
||||
}
|
||||
|
||||
public Collection<String> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public Person getPerson() {
|
||||
return person;
|
||||
}
|
||||
|
||||
public Movie getMovie() {
|
||||
return movie;
|
||||
}
|
||||
|
||||
public void setRoles(Collection<String> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public void setPerson(Person person) {
|
||||
this.person = person;
|
||||
}
|
||||
|
||||
public void setMovie(Movie movie) {
|
||||
this.movie = movie;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.spring.data.neo4j.repository;
|
||||
|
||||
import com.baeldung.spring.data.neo4j.domain.Author;
|
||||
import com.baeldung.spring.data.neo4j.domain.Book;
|
||||
import org.springframework.data.neo4j.repository.Neo4jRepository;
|
||||
import org.springframework.data.neo4j.repository.query.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface AuthorRepository extends Neo4jRepository<Author, Long> {
|
||||
@Query("MATCH (b:Book)-[:WRITTEN_BY]->(a:Author) WHERE a.name = $name AND b.year > $year RETURN b")
|
||||
List<Book> findBooksAfterYear(@Param("name") String name, @Param("year") Integer year);
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.spring.data.neo4j.repository;
|
||||
|
||||
|
||||
import com.baeldung.spring.data.neo4j.domain.Book;
|
||||
import org.springframework.data.neo4j.repository.Neo4jRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface BookRepository extends Neo4jRepository<Book, String> {
|
||||
Book findOneByTitle(String title);
|
||||
List<Book> findAllByYear(Integer year);
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
package com.baeldung.spring.data.neo4j.repository;
|
||||
|
||||
import com.baeldung.spring.data.neo4j.domain.Movie;
|
||||
import org.springframework.data.neo4j.annotation.Query;
|
||||
import org.springframework.data.neo4j.repository.Neo4jRepository;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Repository
|
||||
public interface MovieRepository extends Neo4jRepository<Movie, Long> {
|
||||
|
||||
Movie findByTitle(@Param("title") String title);
|
||||
|
||||
@Query("MATCH (m:Movie) WHERE m.title =~ ('(?i).*'+{title}+'.*') RETURN m")
|
||||
Collection<Movie> findByTitleContaining(@Param("title") String title);
|
||||
|
||||
@Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}")
|
||||
List<Map<String, Object>> graph(@Param("limit") int limit);
|
||||
}
|
|
@ -1,9 +0,0 @@
|
|||
package com.baeldung.spring.data.neo4j.repository;
|
||||
|
||||
import com.baeldung.spring.data.neo4j.domain.Person;
|
||||
import org.springframework.data.neo4j.repository.Neo4jRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface PersonRepository extends Neo4jRepository<Person, Long> {
|
||||
}
|
|
@ -1,51 +0,0 @@
|
|||
package com.baeldung.spring.data.neo4j.services;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.baeldung.spring.data.neo4j.repository.MovieRepository;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class MovieService {
|
||||
|
||||
@Autowired
|
||||
private MovieRepository movieRepository;
|
||||
|
||||
private Map<String, Object> toD3Format(Iterator<Map<String, Object>> result) {
|
||||
List<Map<String, Object>> nodes = new ArrayList<>();
|
||||
List<Map<String, Object>> rels = new ArrayList<>();
|
||||
int i = 0;
|
||||
while (result.hasNext()) {
|
||||
Map<String, Object> row = result.next();
|
||||
nodes.add(map("title", row.get("movie"), "label", "movie"));
|
||||
int target = i;
|
||||
i++;
|
||||
for (Object name : (Collection) row.get("cast")) {
|
||||
Map<String, Object> actor = map("title", name, "label", "actor");
|
||||
int source = nodes.indexOf(actor);
|
||||
if (source == -1) {
|
||||
nodes.add(actor);
|
||||
source = i++;
|
||||
}
|
||||
rels.add(map("source", source, "target", target));
|
||||
}
|
||||
}
|
||||
return map("nodes", nodes, "links", rels);
|
||||
}
|
||||
|
||||
private Map<String, Object> map(String key1, Object value1, String key2, Object value2) {
|
||||
Map<String, Object> result = new HashMap<>(2);
|
||||
result.put(key1, value1);
|
||||
result.put(key2, value2);
|
||||
return result;
|
||||
}
|
||||
|
||||
public Map<String, Object> graph(int limit) {
|
||||
Iterator<Map<String, Object>> result = movieRepository.graph(limit).iterator();
|
||||
return toD3Format(result);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
spring.neo4j.uri=bolt://localhost:7687
|
||||
spring.neo4j.authentication.username=neo4j
|
||||
spring.neo4j.authentication.password=password
|
Binary file not shown.
Before Width: | Height: | Size: 855 B |
|
@ -1,19 +0,0 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class)
|
||||
@ActiveProfiles(profiles = "test")
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package com.baeldung.spring.data.neo4j;
|
||||
|
||||
import com.baeldung.spring.data.neo4j.domain.Book;
|
||||
import com.baeldung.spring.data.neo4j.repository.AuthorRepository;
|
||||
import com.baeldung.spring.data.neo4j.repository.BookRepository;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.neo4j.harness.Neo4j;
|
||||
import org.neo4j.harness.Neo4jBuilders;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@DataNeo4jTest
|
||||
public class BookAndAuthorRepositoryIntegrationTest {
|
||||
|
||||
private static Neo4j newServer;
|
||||
|
||||
@BeforeAll
|
||||
static void initializeNeo4j() {
|
||||
newServer = Neo4jBuilders.newInProcessBuilder()
|
||||
.withDisabledServer()
|
||||
.withFixture("CREATE (b:Book {isbn: '978-0547928210', name: 'The Fellowship of the Ring', year: 1954})" +
|
||||
"-[:WRITTEN_BY]->(a:Author {id: 1, name: 'J. R. R. Tolkien'})" +
|
||||
"CREATE (b2:Book {isbn: '978-0547928203', name: 'The Two Towers', year: 1956})-[:WRITTEN_BY]->(a)")
|
||||
.build();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopNeo4j() {
|
||||
newServer.close();
|
||||
}
|
||||
|
||||
@DynamicPropertySource
|
||||
static void neo4jProperties(DynamicPropertyRegistry registry) {
|
||||
registry.add("spring.neo4j.uri", newServer::boltURI);
|
||||
registry.add("spring.neo4j.authentication.username", () -> "neo4j");
|
||||
registry.add("spring.neo4j.authentication.password", () -> "null");
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private BookRepository bookRepository;
|
||||
|
||||
@Autowired
|
||||
private AuthorRepository authorRepository;
|
||||
|
||||
@Test
|
||||
void givenBookExists_whenFindOneByTitle_thenBookIsReturned() {
|
||||
Book book = bookRepository.findOneByTitle("The Two Towers");
|
||||
Assertions.assertEquals("978-0547928203", book.getIsbn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOneBookExistsForYear_whenFindAllByYear_thenOneBookIsReturned() {
|
||||
List<Book> books = bookRepository.findAllByYear(1954);
|
||||
Assertions.assertEquals(1, books.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOneBookExistsAfterYear_whenFindBooksAfterYear_thenOneBookIsReturned() {
|
||||
List<Book> books = authorRepository.findBooksAfterYear("J. R. R. Tolkien", 1955);
|
||||
Assertions.assertEquals(1, books.size());
|
||||
}
|
||||
}
|
|
@ -1,131 +0,0 @@
|
|||
package com.baeldung.spring.data.neo4j;
|
||||
|
||||
import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration;
|
||||
import com.baeldung.spring.data.neo4j.domain.Movie;
|
||||
import com.baeldung.spring.data.neo4j.domain.Person;
|
||||
import com.baeldung.spring.data.neo4j.domain.Role;
|
||||
import com.baeldung.spring.data.neo4j.repository.MovieRepository;
|
||||
import com.baeldung.spring.data.neo4j.repository.PersonRepository;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static junit.framework.TestCase.assertNull;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class)
|
||||
@ActiveProfiles(profiles = "test")
|
||||
public class MovieRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private MovieRepository movieRepository;
|
||||
|
||||
@Autowired
|
||||
private PersonRepository personRepository;
|
||||
|
||||
public MovieRepositoryIntegrationTest() {
|
||||
}
|
||||
|
||||
@Before
|
||||
public void initializeDatabase() {
|
||||
System.out.println("seeding embedded database");
|
||||
Movie italianJob = new Movie();
|
||||
italianJob.setTitle("The Italian Job");
|
||||
italianJob.setReleased(1999);
|
||||
movieRepository.save(italianJob);
|
||||
|
||||
Person mark = new Person();
|
||||
mark.setName("Mark Wahlberg");
|
||||
personRepository.save(mark);
|
||||
|
||||
Role charlie = new Role();
|
||||
charlie.setMovie(italianJob);
|
||||
charlie.setPerson(mark);
|
||||
Collection<String> roleNames = new HashSet<>();
|
||||
roleNames.add("Charlie Croker");
|
||||
charlie.setRoles(roleNames);
|
||||
List<Role> roles = new ArrayList<>();
|
||||
roles.add(charlie);
|
||||
italianJob.setRoles(roles);
|
||||
movieRepository.save(italianJob);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
public void testFindByTitle() {
|
||||
System.out.println("findByTitle");
|
||||
String title = "The Italian Job";
|
||||
Movie result = movieRepository.findByTitle(title);
|
||||
assertNotNull(result);
|
||||
assertEquals(1999, result.getReleased());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
public void testCount() {
|
||||
System.out.println("count");
|
||||
long movieCount = movieRepository.count();
|
||||
assertNotNull(movieCount);
|
||||
assertEquals(1, movieCount);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
public void testFindAll() {
|
||||
System.out.println("findAll");
|
||||
Collection<Movie> result = (Collection<Movie>) movieRepository.findAll();
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
public void testFindByTitleContaining() {
|
||||
System.out.println("findByTitleContaining");
|
||||
String title = "Italian";
|
||||
Collection<Movie> result = movieRepository.findByTitleContaining(title);
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
public void testGraph() {
|
||||
System.out.println("graph");
|
||||
List<Map<String, Object>> graph = movieRepository.graph(5);
|
||||
assertEquals(1, graph.size());
|
||||
Map<String, Object> map = graph.get(0);
|
||||
assertEquals(2, map.size());
|
||||
String[] cast = (String[]) map.get("cast");
|
||||
String movie = (String) map.get("movie");
|
||||
assertEquals("The Italian Job", movie);
|
||||
assertEquals("Mark Wahlberg", cast[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
public void testDeleteMovie() {
|
||||
System.out.println("deleteMovie");
|
||||
movieRepository.delete(movieRepository.findByTitle("The Italian Job"));
|
||||
assertNull(movieRepository.findByTitle("The Italian Job"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
public void testDeleteAll() {
|
||||
System.out.println("deleteAll");
|
||||
movieRepository.deleteAll();
|
||||
Collection<Movie> result = (Collection<Movie>) movieRepository.findAll();
|
||||
assertEquals(0, result.size());
|
||||
}
|
||||
}
|
|
@ -21,7 +21,7 @@ import java.util.List;
|
|||
|
||||
@Testcontainers
|
||||
@SpringBootTest
|
||||
class OrderServiceIntegrationTest {
|
||||
class OrderServiceLiveTest {
|
||||
|
||||
@Container
|
||||
static MySQLContainer<?> mySQLContainer1 = new MySQLContainer<>("mysql:8.0.23")
|
18
pom.xml
18
pom.xml
|
@ -346,7 +346,7 @@
|
|||
<module>core-java-modules/core-java-serialization</module>
|
||||
<module>core-java-modules/core-java-lang</module>
|
||||
<module>core-java-modules/core-java-lang-math-3</module>
|
||||
<module>core-java-modules/core-java-collections-conversions-2</module>
|
||||
|
||||
<module>core-java-modules/core-java-streams-2</module>
|
||||
|
||||
<!-- <module>ethereum</module> --> <!-- JAVA-6001 -->
|
||||
|
@ -368,7 +368,6 @@
|
|||
<module>persistence-modules/hibernate-ogm</module> <!-- hibernate-ogm wasn't updated because it doesn't support jakarta API -->
|
||||
<module>persistence-modules/java-cassandra</module> <!-- JAVA-21464 cassandra-unit library doesn't support to run with jdk9 and above -->
|
||||
<module>persistence-modules/spring-data-cassandra-reactive</module> <!--JAVA-21844-->
|
||||
<module>persistence-modules/spring-data-neo4j</module>
|
||||
<module>java-nashorn</module>
|
||||
<module>jeromq</module>
|
||||
</modules>
|
||||
|
@ -525,7 +524,7 @@
|
|||
<module>core-java-modules/core-java-serialization</module>
|
||||
<module>core-java-modules/core-java-lang</module>
|
||||
<module>core-java-modules/core-java-lang-math-3</module>
|
||||
<module>core-java-modules/core-java-collections-conversions-2</module>
|
||||
|
||||
<module>core-java-modules/core-java-streams-2</module>
|
||||
|
||||
<!-- <module>ethereum</module> --> <!-- JAVA-6001 -->
|
||||
|
@ -545,7 +544,6 @@
|
|||
<module>persistence-modules/hibernate-ogm</module> <!-- hibernate-ogm wasn't updated because it doesn't support jakarta API -->
|
||||
<module>persistence-modules/java-cassandra</module> <!-- JAVA-21464 cassandra-unit library doesn't support to run with jdk9 and above -->
|
||||
<module>persistence-modules/spring-data-cassandra-reactive</module> <!--JAVA-21844-->
|
||||
<module>persistence-modules/spring-data-neo4j</module>
|
||||
<module>java-nashorn</module>
|
||||
</modules>
|
||||
|
||||
|
@ -705,7 +703,6 @@
|
|||
<module>osgi</module>
|
||||
<module>spring-katharsis</module>
|
||||
<module>logging-modules</module>
|
||||
<module>spring-boot-documentation</module>
|
||||
<module>spring-boot-modules</module>
|
||||
<module>apache-httpclient</module>
|
||||
<module>apache-httpclient4</module>
|
||||
|
@ -760,6 +757,7 @@
|
|||
|
||||
<module>algorithms-modules</module>
|
||||
<module>apache-libraries</module>
|
||||
<module>apache-libraries-2</module>
|
||||
<module>apache-poi</module>
|
||||
<module>apache-velocity</module>
|
||||
<module>di-modules</module>
|
||||
|
@ -909,7 +907,7 @@
|
|||
|
||||
<module>spring-kafka</module>
|
||||
|
||||
<!--<module>spring-native</module>--> <!-- Fixing in JAVA-24009 -->
|
||||
<module>spring-native</module>
|
||||
<module>spring-security-modules</module>
|
||||
<module>spring-protobuf</module>
|
||||
<module>spring-quartz</module>
|
||||
|
@ -940,6 +938,7 @@
|
|||
<module>image-processing</module>
|
||||
<module>language-interop</module>
|
||||
<module>gradle-modules/gradle/maven-to-gradle</module>
|
||||
<module>persistence-modules/spring-data-neo4j</module>
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
|
@ -977,7 +976,6 @@
|
|||
<module>osgi</module>
|
||||
<module>spring-katharsis</module>
|
||||
<module>logging-modules</module>
|
||||
<module>spring-boot-documentation</module>
|
||||
<module>spring-boot-modules</module>
|
||||
<module>apache-httpclient</module>
|
||||
<module>apache-httpclient4</module>
|
||||
|
@ -1026,6 +1024,7 @@
|
|||
|
||||
<module>algorithms-modules</module>
|
||||
<module>apache-libraries</module>
|
||||
<module>apache-libraries-2</module>
|
||||
<module>apache-poi</module>
|
||||
<module>apache-velocity</module>
|
||||
<module>di-modules</module>
|
||||
|
@ -1180,7 +1179,7 @@
|
|||
|
||||
<module>spring-kafka</module>
|
||||
|
||||
<!--<module>spring-native</module>--> <!-- Fixing in JAVA-24009 -->
|
||||
<module>spring-native</module>
|
||||
<module>spring-security-modules</module>
|
||||
<module>spring-protobuf</module>
|
||||
<module>spring-quartz</module>
|
||||
|
@ -1211,6 +1210,7 @@
|
|||
<module>image-processing</module>
|
||||
<module>language-interop</module>
|
||||
<module>gradle-modules/gradle/maven-to-gradle</module>
|
||||
<module>persistence-modules/spring-data-neo4j</module>
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
|
@ -1280,7 +1280,7 @@
|
|||
<commons-collections4.version>4.4</commons-collections4.version>
|
||||
<commons-io.version>2.11.0</commons-io.version>
|
||||
<commons-lang.version>2.6</commons-lang.version>
|
||||
<commons-lang3.version>3.12.0</commons-lang3.version>
|
||||
<commons-lang3.version>3.13.0</commons-lang3.version>
|
||||
<commons-cli.version>1.5.0</commons-cli.version>
|
||||
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
|
||||
<javax.servlet-api.version>4.0.1</javax.servlet-api.version>
|
||||
|
|
|
@ -1,46 +0,0 @@
|
|||
<?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>
|
||||
<groupId>com.baeldung.spring-boot-documentation</groupId>
|
||||
<artifactId>spring-boot-documentation</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<name>spring-boot-documentation</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>springwolf</module>
|
||||
</modules>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>junit-bom</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<properties>
|
||||
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,82 +0,0 @@
|
|||
<?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>springwolf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>springwolf</name>
|
||||
<description>Documentation Spring Event Driven API Using AsyncAPI and Springwolf</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring-boot-documentation</groupId>
|
||||
<artifactId>spring-boot-documentation</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.kafka</groupId>
|
||||
<artifactId>spring-kafka</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.swagger.core.v3</groupId>
|
||||
<artifactId>swagger-core-jakarta</artifactId>
|
||||
<version>${swagger-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.springwolf</groupId>
|
||||
<artifactId>springwolf-kafka</artifactId>
|
||||
<version>${springwolf-kafka.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.springwolf</groupId>
|
||||
<artifactId>springwolf-ui</artifactId>
|
||||
<version>${springwolf-ui.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.kafka</groupId>
|
||||
<artifactId>spring-kafka-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${testcontainers-kafka.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.boot.documentation.springwolf.SpringwolfApplication</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<swagger-core.version>2.2.11</swagger-core.version>
|
||||
<springwolf-kafka.version>0.12.1</springwolf-kafka.version>
|
||||
<springwolf-ui.version>0.8.0</springwolf-ui.version>
|
||||
<testcontainers-kafka.version>1.18.3</testcontainers-kafka.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -97,6 +97,7 @@
|
|||
<module>spring-boot-properties-3</module>
|
||||
<module>spring-boot-properties-4</module>
|
||||
<module>spring-boot-properties-migrator-demo</module>
|
||||
<module>spring-boot-documentation</module>
|
||||
</modules>
|
||||
|
||||
<dependencyManagement>
|
||||
|
|
|
@ -0,0 +1,102 @@
|
|||
<?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>
|
||||
<groupId>com.baeldung.spring-boot-documentation</groupId>
|
||||
<artifactId>spring-boot-documentation</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<name>spring-boot-documentation</name>
|
||||
<description>Documentation Spring Event Driven API Using AsyncAPI and Springwolf</description>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-3/pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>junit-bom</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.kafka</groupId>
|
||||
<artifactId>spring-kafka</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.swagger.core.v3</groupId>
|
||||
<artifactId>swagger-core-jakarta</artifactId>
|
||||
<version>${swagger-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.springwolf</groupId>
|
||||
<artifactId>springwolf-kafka</artifactId>
|
||||
<version>${springwolf-kafka.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.springwolf</groupId>
|
||||
<artifactId>springwolf-ui</artifactId>
|
||||
<version>${springwolf-ui.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.kafka</groupId>
|
||||
<artifactId>spring-kafka-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${testcontainers-kafka.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.boot.documentation.springwolf.SpringwolfApplication</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
|
||||
<swagger-core.version>2.2.11</swagger-core.version>
|
||||
<springwolf-kafka.version>0.12.1</springwolf-kafka.version>
|
||||
<springwolf-ui.version>0.8.0</springwolf-ui.version>
|
||||
<testcontainers-kafka.version>1.18.3</testcontainers-kafka.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue