From 2bb03452c25202826b30ab9890b070d140a2fc04 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Fri, 24 May 2019 00:46:42 +0530 Subject: [PATCH 001/352] [BAEL-14776] - Upgraded to spring boot 2 --- spring-security-mvc-session/pom.xml | 27 +++---------------- .../java/org/baeldung/spring/MvcConfig.java | 5 ++-- .../baeldung/spring/SecSecurityConfig.java | 11 ++++++-- 3 files changed, 15 insertions(+), 28 deletions(-) diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index c0e1527a24..c1fbda0f98 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -8,10 +8,10 @@ war - com.baeldung - parent-spring-4 - 0.0.1-SNAPSHOT - ../parent-spring-4 + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -21,17 +21,14 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} org.springframework.security spring-security-config - ${org.springframework.security.version} org.springframework.security spring-security-taglibs - ${org.springframework.security.version} @@ -39,7 +36,6 @@ org.springframework spring-core - ${spring.version} commons-logging @@ -50,43 +46,34 @@ org.springframework spring-context - ${spring.version} org.springframework spring-jdbc - ${spring.version} org.springframework spring-beans - ${spring.version} org.springframework spring-aop - ${spring.version} org.springframework spring-tx - ${spring.version} org.springframework spring-expression - ${spring.version} - org.springframework spring-web - ${spring.version} org.springframework spring-webmvc - ${spring.version} @@ -94,14 +81,12 @@ javax.servlet javax.servlet-api - ${javax.servlet-api.version} provided javax.servlet jstl - ${jstl.version} runtime @@ -117,7 +102,6 @@ org.springframework.boot spring-boot-starter-test - 1.5.10.RELEASE test @@ -166,9 +150,6 @@ - - 4.2.6.RELEASE - 3.0.2 diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java index 9e9c240181..b9f50ded73 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java @@ -5,13 +5,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); @@ -21,7 +21,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); registry.addViewController("/anonymous.html"); diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java index deeea78e4e..b7996ebf18 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -8,6 +8,8 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.session.HttpSessionEventPublisher; @@ -24,9 +26,9 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(final AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.inMemoryAuthentication() - .withUser("user1").password("user1Pass").roles("USER") + .withUser("user1").password(passwordEncoder().encode("user1Pass")).roles("USER") .and() - .withUser("admin1").password("admin1Pass").roles("ADMIN"); + .withUser("admin1").password(passwordEncoder().encode("admin1Pass")).roles("ADMIN"); // @formatter:on } @@ -68,5 +70,10 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public HttpSessionEventPublisher httpSessionEventPublisher() { return new HttpSessionEventPublisher(); } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } From 1de5fc5a0dab70e91a41788824251b2036aec827 Mon Sep 17 00:00:00 2001 From: isaolmez Date: Sun, 9 Jun 2019 18:10:18 +0300 Subject: [PATCH 002/352] BAEL-2981: Added code samples for Handlebars.java --- libraries-2/pom.xml | 18 +-- .../handlebars/BasicUsageUnitTest.java | 104 ++++++++++++++++++ .../handlebars/BuiltinHelperUnitTest.java | 101 +++++++++++++++++ .../handlebars/CustomHelperUnitTest.java | 54 +++++++++ .../com/baeldung/handlebars/HelperSource.java | 9 ++ .../java/com/baeldung/handlebars/Person.java | 58 ++++++++++ .../handlebars/ReusingTemplatesUnitTest.java | 44 ++++++++ libraries-2/src/test/resources/greeting.hbs | 1 + .../src/test/resources/handlebars/each.html | 3 + .../resources/handlebars/each_mustache.html | 3 + .../test/resources/handlebars/greeting.html | 1 + .../src/test/resources/handlebars/header.html | 1 + .../src/test/resources/handlebars/if.html | 5 + .../resources/handlebars/if_mustache.html | 5 + .../resources/handlebars/messagebase.html | 9 ++ .../src/test/resources/handlebars/page.html | 2 + .../src/test/resources/handlebars/person.html | 1 + .../resources/handlebars/simplemessage.html | 4 + .../src/test/resources/handlebars/with.html | 3 + .../resources/handlebars/with_mustache.html | 3 + 20 files changed, 422 insertions(+), 7 deletions(-) create mode 100644 libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java create mode 100644 libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java create mode 100644 libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java create mode 100644 libraries-2/src/test/java/com/baeldung/handlebars/HelperSource.java create mode 100644 libraries-2/src/test/java/com/baeldung/handlebars/Person.java create mode 100644 libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java create mode 100644 libraries-2/src/test/resources/greeting.hbs create mode 100644 libraries-2/src/test/resources/handlebars/each.html create mode 100644 libraries-2/src/test/resources/handlebars/each_mustache.html create mode 100644 libraries-2/src/test/resources/handlebars/greeting.html create mode 100644 libraries-2/src/test/resources/handlebars/header.html create mode 100644 libraries-2/src/test/resources/handlebars/if.html create mode 100644 libraries-2/src/test/resources/handlebars/if_mustache.html create mode 100644 libraries-2/src/test/resources/handlebars/messagebase.html create mode 100644 libraries-2/src/test/resources/handlebars/page.html create mode 100644 libraries-2/src/test/resources/handlebars/person.html create mode 100644 libraries-2/src/test/resources/handlebars/simplemessage.html create mode 100644 libraries-2/src/test/resources/handlebars/with.html create mode 100644 libraries-2/src/test/resources/handlebars/with_mustache.html diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 8e493e2d05..686996686f 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -81,13 +81,17 @@ 3.14.2 test - - - edu.uci.ics - crawler4j - ${crawler4j.version} - - + + edu.uci.ics + crawler4j + ${crawler4j.version} + + + + com.github.jknack + handlebars + 4.1.2 + diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java new file mode 100644 index 0000000000..a2b535f4dd --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java @@ -0,0 +1,104 @@ +package com.baeldung.handlebars; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.github.jknack.handlebars.Handlebars; +import com.github.jknack.handlebars.Template; +import com.github.jknack.handlebars.io.ClassPathTemplateLoader; +import com.github.jknack.handlebars.io.TemplateLoader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; + +public class BasicUsageUnitTest { + + @Test + public void whenThereIsNoTemplateFile_ThenCompilesInline() throws IOException { + Handlebars handlebars = new Handlebars(); + Template template = handlebars.compileInline("Hi {{this}}!"); + + String templateString = template.apply("Baeldung"); + + assertThat(templateString).isEqualTo("Hi Baeldung!"); + } + + @Test + public void whenParameterMapIsSupplied_thenDisplays() throws IOException { + Handlebars handlebars = new Handlebars(); + Template template = handlebars.compileInline("Hi {{name}}!"); + + Map parameterMap = new HashMap<>(); + parameterMap.put("name", "Baeldung"); + String templateString = template.apply(parameterMap); + + assertThat(templateString).isEqualTo("Hi Baeldung!"); + } + + @Test + public void whenParameterObjectIsSupplied_ThenDisplays() throws IOException { + Handlebars handlebars = new Handlebars(); + Template template = handlebars.compileInline("Hi {{name}}!"); + + Person person = new Person(); + person.setName("Baeldung"); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("Hi Baeldung!"); + } + + @Test + public void whenMultipleParametersAreSupplied_ThenDisplays() throws IOException { + Handlebars handlebars = new Handlebars(); + Template template = handlebars.compileInline("Hi {{name}}! This is {{topic}}."); + + Map parameterMap = new HashMap<>(); + parameterMap.put("name", "Baeldung"); + parameterMap.put("topic", "Handlebars"); + String templateString = template.apply(parameterMap); + + assertThat(templateString).isEqualTo("Hi Baeldung! This is Handlebars."); + } + + @Test + public void whenNoLoaderIsGiven_ThenSearchesClasspath() throws IOException { + Handlebars handlebars = new Handlebars(); + Template template = handlebars.compile("greeting"); + + Person person = getPerson("Baeldung"); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("Hi Baeldung!"); + } + + @Test + public void whenClasspathTemplateLoaderIsGiven_ThenSearchesClasspathWithPrefixSuffix() throws IOException { + TemplateLoader loader = new ClassPathTemplateLoader("/handlebars", ".html"); + Handlebars handlebars = new Handlebars(loader); + Template template = handlebars.compile("greeting"); + + Person person = getPerson("Baeldung"); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("Hi Baeldung!"); + } + + @Test + public void whenMultipleLoadersAreGiven_ThenSearchesSequentially() throws IOException { + TemplateLoader firstLoader = new ClassPathTemplateLoader("/handlebars", ".html"); + TemplateLoader secondLoader = new ClassPathTemplateLoader("/templates", ".html"); + Handlebars handlebars = new Handlebars().with(firstLoader, secondLoader); + Template template = handlebars.compile("greeting"); + + Person person = getPerson("Baeldung"); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("Hi Baeldung!"); + } + + private Person getPerson(String name) { + Person person = new Person(); + person.setName(name); + return person; + } +} diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java new file mode 100644 index 0000000000..b44ac63b5a --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java @@ -0,0 +1,101 @@ +package com.baeldung.handlebars; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.github.jknack.handlebars.Handlebars; +import com.github.jknack.handlebars.Template; +import com.github.jknack.handlebars.io.ClassPathTemplateLoader; +import com.github.jknack.handlebars.io.TemplateLoader; +import java.io.IOException; +import org.junit.Test; + +public class BuiltinHelperUnitTest { + + private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html"); + + @Test + public void whenUsedWith_ThenContextChanges() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("with"); + + Person person = getPerson("Baeldung"); + person.getAddress().setStreet("World"); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\n

I live in World

\n"); + } + + @Test + public void whenUsedWithMustacheStyle_ThenContextChanges() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("with_mustache"); + + Person person = getPerson("Baeldung"); + person.getAddress().setStreet("World"); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\n

I live in World

\n"); + } + + @Test + public void whenUsedEach_ThenIterates() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("each"); + + Person person = getPerson("Baeldung"); + Person friend1 = getPerson("Java"); + Person friend2 = getPerson("Spring"); + person.getFriends().add(friend1); + person.getFriends().add(friend2); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\nJava is my friend.\n" + + "\nSpring is my friend.\n"); + } + + @Test + public void whenUsedEachMustacheStyle_ThenIterates() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("each_mustache"); + + Person person = getPerson("Baeldung"); + Person friend1 = getPerson("Java"); + Person friend2 = getPerson("Spring"); + person.getFriends().add(friend1); + person.getFriends().add(friend2); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\nJava is my friend.\n" + + "\nSpring is my friend.\n"); + } + + @Test + public void whenUsedIf_ThenPutsCondition() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("if"); + + Person person = getPerson("Baeldung"); + person.setBusy(true); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\n

Baeldung is busy.

\n"); + } + + @Test + public void whenUsedIfMustacheStyle_ThenPutsCondition() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("if_mustache"); + + Person person = getPerson("Baeldung"); + person.setBusy(true); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\n

Baeldung is busy.

\n"); + } + + private Person getPerson(String name) { + Person person = new Person(); + person.setName(name); + return person; + } +} diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java new file mode 100644 index 0000000000..ce74d55e70 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.handlebars; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.github.jknack.handlebars.Handlebars; +import com.github.jknack.handlebars.Helper; +import com.github.jknack.handlebars.Options; +import com.github.jknack.handlebars.Template; +import com.github.jknack.handlebars.io.ClassPathTemplateLoader; +import com.github.jknack.handlebars.io.TemplateLoader; +import java.io.IOException; +import org.junit.Test; + +public class CustomHelperUnitTest { + + private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html"); + + @Test + public void whenHelperIsCreated_ThenCanRegister() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + handlebars.registerHelper("person", new Helper() { + @Override + public Object apply(Person context, Options options) throws IOException { + String busyString = context.isBusy() ? "busy" : "available"; + return context.getName() + " - " + busyString; + } + }); + Template template = handlebars.compile("person"); + + Person person = getPerson("Baeldung"); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("Baeldung - busy"); + } + + @Test + public void whenHelperSourceIsCreated_ThenCanRegister() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + handlebars.registerHelpers(new HelperSource()); + Template template = handlebars.compile("person"); + + Person person = getPerson("Baeldung"); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("Baeldung - busy"); + } + + private Person getPerson(String name) { + Person person = new Person(); + person.setName(name); + person.setBusy(true); + return person; + } +} diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/HelperSource.java b/libraries-2/src/test/java/com/baeldung/handlebars/HelperSource.java new file mode 100644 index 0000000000..2b7d705af9 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/handlebars/HelperSource.java @@ -0,0 +1,9 @@ +package com.baeldung.handlebars; + +public class HelperSource { + + public String person(Person context) { + String busyString = context.isBusy() ? "busy" : "available"; + return context.getName() + " - " + busyString; + } +} diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/Person.java b/libraries-2/src/test/java/com/baeldung/handlebars/Person.java new file mode 100644 index 0000000000..9ddc0fdffb --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/handlebars/Person.java @@ -0,0 +1,58 @@ +package com.baeldung.handlebars; + +import java.util.ArrayList; +import java.util.List; + +public class Person { + + private String name; + private boolean busy; + private Address address = new Address(); + private List friends = new ArrayList<>(); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isBusy() { + return busy; + } + + public void setBusy(boolean busy) { + this.busy = busy; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public List getFriends() { + return friends; + } + + public void setFriends(List friends) { + this.friends = friends; + } + + public static class Address { + + private String street; + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java new file mode 100644 index 0000000000..1e2844ab1e --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.handlebars; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.github.jknack.handlebars.Handlebars; +import com.github.jknack.handlebars.Template; +import com.github.jknack.handlebars.io.ClassPathTemplateLoader; +import com.github.jknack.handlebars.io.TemplateLoader; +import java.io.IOException; +import org.junit.Test; + +public class ReusingTemplatesUnitTest { + + private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html"); + + @Test + public void whenOtherTemplateIsReferenced_ThenCanReuse() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("page"); + + Person person = new Person(); + person.setName("Baeldung"); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("

Hi Baeldung!

\n

This is the page Baeldung

"); + } + + @Test + public void whenBlockIsDefined_ThenCanOverrideWithPartial() throws IOException { + Handlebars handlebars = new Handlebars(templateLoader); + Template template = handlebars.compile("simplemessage"); + + Person person = new Person(); + person.setName("Baeldung"); + String templateString = template.apply(person); + + assertThat(templateString).isEqualTo("\n\n" + + "\n" + + "\n This is the intro\n\n" + + "\n Hi there!\n\n" + + "\n" + + ""); + } +} diff --git a/libraries-2/src/test/resources/greeting.hbs b/libraries-2/src/test/resources/greeting.hbs new file mode 100644 index 0000000000..71a8266bce --- /dev/null +++ b/libraries-2/src/test/resources/greeting.hbs @@ -0,0 +1 @@ +Hi {{name}}! \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/each.html b/libraries-2/src/test/resources/handlebars/each.html new file mode 100644 index 0000000000..1570311bfc --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/each.html @@ -0,0 +1,3 @@ +{{#each friends}} +{{name}} is my friend. +{{/each}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/each_mustache.html b/libraries-2/src/test/resources/handlebars/each_mustache.html new file mode 100644 index 0000000000..1570311bfc --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/each_mustache.html @@ -0,0 +1,3 @@ +{{#each friends}} +{{name}} is my friend. +{{/each}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/greeting.html b/libraries-2/src/test/resources/handlebars/greeting.html new file mode 100644 index 0000000000..71a8266bce --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/greeting.html @@ -0,0 +1 @@ +Hi {{name}}! \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/header.html b/libraries-2/src/test/resources/handlebars/header.html new file mode 100644 index 0000000000..80cca699e4 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/header.html @@ -0,0 +1 @@ +

Hi {{name}}!

\ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/if.html b/libraries-2/src/test/resources/handlebars/if.html new file mode 100644 index 0000000000..ebdc724f66 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/if.html @@ -0,0 +1,5 @@ +{{#if busy}} +

{{name}} is busy.

+{{else}} +

{{name}} is not busy.

+{{/if}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/if_mustache.html b/libraries-2/src/test/resources/handlebars/if_mustache.html new file mode 100644 index 0000000000..d75f5fa8f9 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/if_mustache.html @@ -0,0 +1,5 @@ +{{#if busy}} +

{{name}} is busy.

+{{^}} +

{{name}} is not busy.

+{{/if}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/messagebase.html b/libraries-2/src/test/resources/handlebars/messagebase.html new file mode 100644 index 0000000000..7ee3257e06 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/messagebase.html @@ -0,0 +1,9 @@ + + +{{#block "intro"}} + This is the intro +{{/block}} +{{#block "message"}} +{{/block}} + + \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/page.html b/libraries-2/src/test/resources/handlebars/page.html new file mode 100644 index 0000000000..27b20737f3 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/page.html @@ -0,0 +1,2 @@ +{{>header}} +

This is the page {{name}}

\ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/person.html b/libraries-2/src/test/resources/handlebars/person.html new file mode 100644 index 0000000000..5207d49266 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/person.html @@ -0,0 +1 @@ +{{#person this}}{{/person}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/simplemessage.html b/libraries-2/src/test/resources/handlebars/simplemessage.html new file mode 100644 index 0000000000..3b3a01980a --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/simplemessage.html @@ -0,0 +1,4 @@ +{{#partial "message" }} + Hi there! +{{/partial}} +{{> messagebase}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/with.html b/libraries-2/src/test/resources/handlebars/with.html new file mode 100644 index 0000000000..90077b4835 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/with.html @@ -0,0 +1,3 @@ +{{#with address}} +

I live in {{street}}

+{{/with}} \ No newline at end of file diff --git a/libraries-2/src/test/resources/handlebars/with_mustache.html b/libraries-2/src/test/resources/handlebars/with_mustache.html new file mode 100644 index 0000000000..3adf6a7556 --- /dev/null +++ b/libraries-2/src/test/resources/handlebars/with_mustache.html @@ -0,0 +1,3 @@ +{{#address}} +

I live in {{street}}

+{{/address}} \ No newline at end of file From ad818f174e019f0f87b16cc3cc3414ed60ab65a2 Mon Sep 17 00:00:00 2001 From: Chirag Dewan Date: Sun, 16 Jun 2019 00:03:53 +0530 Subject: [PATCH 003/352] BAEL-2953 A guide to Apache Mesos --- libraries-2/pom.xml | 7 ++ .../com/baeldung/mesos/HelloWorldMain.java | 42 ++++++++ .../mesos/executors/HelloWorldExecutor.java | 59 +++++++++++ .../mesos/schedulers/HelloWorldScheduler.java | 100 ++++++++++++++++++ 4 files changed, 208 insertions(+) create mode 100644 libraries-2/src/main/java/com/baeldung/mesos/HelloWorldMain.java create mode 100644 libraries-2/src/main/java/com/baeldung/mesos/executors/HelloWorldExecutor.java create mode 100644 libraries-2/src/main/java/com/baeldung/mesos/schedulers/HelloWorldScheduler.java diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 32f3f23812..e8c667c9c7 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -99,6 +99,12 @@ ${crawler4j.version} + + org.apache.mesos + mesos + ${mesos.library.version} + + @@ -109,5 +115,6 @@ 3.17.2 4.4.0 2.1.4.RELEASE + 0.28.3 diff --git a/libraries-2/src/main/java/com/baeldung/mesos/HelloWorldMain.java b/libraries-2/src/main/java/com/baeldung/mesos/HelloWorldMain.java new file mode 100644 index 0000000000..e4bf593e7e --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/mesos/HelloWorldMain.java @@ -0,0 +1,42 @@ +package com.baeldung.mesos; + +import com.baeldung.mesos.schedulers.HelloWorldScheduler; +import org.apache.mesos.MesosSchedulerDriver; +import org.apache.mesos.Protos; +import org.apache.mesos.Protos.CommandInfo; +import org.apache.mesos.Protos.ExecutorInfo; +import org.apache.mesos.Protos.FrameworkInfo; + +public class HelloWorldMain { + + public static void main(String[] args) { + + String path = System.getProperty("user.dir") + + "/target/libraries2-1.0.0-SNAPSHOT.jar"; + + CommandInfo.URI uri = CommandInfo.URI.newBuilder().setValue(path).setExtract(false).build(); + + String helloWorldCommand = "java -cp libraries2-1.0.0-SNAPSHOT.jar com.baeldung.mesos.executors.HelloWorldExecutor"; + CommandInfo commandInfoHelloWorld = CommandInfo.newBuilder().setValue(helloWorldCommand).addUris(uri) + .build(); + + ExecutorInfo executorHelloWorld = ExecutorInfo.newBuilder() + .setExecutorId(Protos.ExecutorID.newBuilder().setValue("HelloWorldExecutor")) + .setCommand(commandInfoHelloWorld).setName("Hello World (Java)").setSource("java").build(); + + FrameworkInfo.Builder frameworkBuilder = FrameworkInfo.newBuilder().setFailoverTimeout(120000) + .setUser("") + .setName("Hello World Framework (Java)"); + + frameworkBuilder.setPrincipal("test-framework-java"); + + MesosSchedulerDriver driver = new MesosSchedulerDriver(new HelloWorldScheduler(executorHelloWorld), frameworkBuilder.build(), args[0]); + + int status = driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1; + + // Ensure that the driver process terminates. + driver.stop(); + + System.exit(status); + } +} diff --git a/libraries-2/src/main/java/com/baeldung/mesos/executors/HelloWorldExecutor.java b/libraries-2/src/main/java/com/baeldung/mesos/executors/HelloWorldExecutor.java new file mode 100644 index 0000000000..a8620bbce3 --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/mesos/executors/HelloWorldExecutor.java @@ -0,0 +1,59 @@ +package com.baeldung.mesos.executors; + +import org.apache.mesos.Executor; +import org.apache.mesos.ExecutorDriver; +import org.apache.mesos.MesosExecutorDriver; +import org.apache.mesos.Protos; +import org.apache.mesos.Protos.TaskInfo; + +public class HelloWorldExecutor implements Executor { + @Override + public void registered(ExecutorDriver driver, Protos.ExecutorInfo executorInfo, Protos.FrameworkInfo frameworkInfo, Protos.SlaveInfo slaveInfo) { + } + + @Override + public void reregistered(ExecutorDriver driver, Protos.SlaveInfo slaveInfo) { + } + + @Override + public void disconnected(ExecutorDriver driver) { + } + + @Override + public void launchTask(ExecutorDriver driver, TaskInfo task) { + + Protos.TaskStatus status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId()) + .setState(Protos.TaskState.TASK_RUNNING).build(); + driver.sendStatusUpdate(status); + + String myStatus = "Hello Framework"; + driver.sendFrameworkMessage(myStatus.getBytes()); + + System.out.println("Hello World!!!"); + + status = Protos.TaskStatus.newBuilder().setTaskId(task.getTaskId()) + .setState(Protos.TaskState.TASK_FINISHED).build(); + driver.sendStatusUpdate(status); + } + + @Override + public void killTask(ExecutorDriver driver, Protos.TaskID taskId) { + } + + @Override + public void frameworkMessage(ExecutorDriver driver, byte[] data) { + } + + @Override + public void shutdown(ExecutorDriver driver) { + } + + @Override + public void error(ExecutorDriver driver, String message) { + } + + public static void main(String[] args) { + MesosExecutorDriver driver = new MesosExecutorDriver(new HelloWorldExecutor()); + System.exit(driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1); + } +} diff --git a/libraries-2/src/main/java/com/baeldung/mesos/schedulers/HelloWorldScheduler.java b/libraries-2/src/main/java/com/baeldung/mesos/schedulers/HelloWorldScheduler.java new file mode 100644 index 0000000000..68808b4dd0 --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/mesos/schedulers/HelloWorldScheduler.java @@ -0,0 +1,100 @@ +package com.baeldung.mesos.schedulers; + +import com.google.protobuf.ByteString; +import org.apache.mesos.Protos; +import org.apache.mesos.Protos.ExecutorInfo; +import org.apache.mesos.Protos.Offer; +import org.apache.mesos.Protos.OfferID; +import org.apache.mesos.Protos.TaskInfo; +import org.apache.mesos.Scheduler; +import org.apache.mesos.SchedulerDriver; + +import java.util.ArrayList; +import java.util.List; + +public class HelloWorldScheduler implements Scheduler { + + private int launchedTasks = 0; + private final ExecutorInfo helloWorldExecutor; + + public HelloWorldScheduler(ExecutorInfo helloWorldExecutor) { + this.helloWorldExecutor = helloWorldExecutor; + } + + @Override + public void registered(SchedulerDriver schedulerDriver, Protos.FrameworkID frameworkID, Protos.MasterInfo masterInfo) { + + } + + @Override + public void reregistered(SchedulerDriver schedulerDriver, Protos.MasterInfo masterInfo) { + + } + + @Override + public void resourceOffers(SchedulerDriver schedulerDriver, List list) { + + for (Offer offer : list) { + List tasks = new ArrayList(); + Protos.TaskID taskId = Protos.TaskID.newBuilder().setValue(Integer.toString(launchedTasks++)).build(); + + System.out.println("Launching printHelloWorld " + taskId.getValue() + " Hello World Java"); + TaskInfo printHelloWorld = TaskInfo + .newBuilder() + .setName("printHelloWorld " + taskId.getValue()) + .setTaskId(taskId) + .setSlaveId(offer.getSlaveId()) + .addResources( + Protos.Resource.newBuilder().setName("cpus").setType(Protos.Value.Type.SCALAR) + .setScalar(Protos.Value.Scalar.newBuilder().setValue(1))) + .addResources( + Protos.Resource.newBuilder().setName("mem").setType(Protos.Value.Type.SCALAR) + .setScalar(Protos.Value.Scalar.newBuilder().setValue(128))) + .setExecutor(ExecutorInfo.newBuilder(helloWorldExecutor)).build(); + + List offerIDS = new ArrayList<>(); + offerIDS.add(offer.getId()); + + tasks.add(printHelloWorld); + + schedulerDriver.declineOffer(offer.getId()); + schedulerDriver.launchTasks(offerIDS, tasks); + } + + } + + @Override + public void offerRescinded(SchedulerDriver schedulerDriver, OfferID offerID) { + + } + + @Override + public void statusUpdate(SchedulerDriver schedulerDriver, Protos.TaskStatus taskStatus) { + + } + + @Override + public void frameworkMessage(SchedulerDriver schedulerDriver, Protos.ExecutorID executorID, Protos.SlaveID slaveID, byte[] bytes) { + + } + + @Override + public void disconnected(SchedulerDriver schedulerDriver) { + + } + + @Override + public void slaveLost(SchedulerDriver schedulerDriver, Protos.SlaveID slaveID) { + + } + + @Override + public void executorLost(SchedulerDriver schedulerDriver, Protos.ExecutorID executorID, Protos.SlaveID slaveID, int i) { + + } + + @Override + public void error(SchedulerDriver schedulerDriver, String s) { + + } +} From 2d0eeabcd88f83a8e56ae3eb6d02e9275e1085f4 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 16 Jun 2019 00:28:58 +0530 Subject: [PATCH 004/352] [BAEL-14776] - Converted to boot project and added starters inn pom.xml --- core-java-modules/core-java-lambdas/README.MD | 2 +- spring-security-mvc-session/pom.xml | 51 +++---------------- .../baeldung/SpringSessionApplication.java | 12 +++++ 3 files changed, 21 insertions(+), 44 deletions(-) create mode 100644 spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java diff --git a/core-java-modules/core-java-lambdas/README.MD b/core-java-modules/core-java-lambdas/README.MD index 31790ffbb1..10b876735e 100644 --- a/core-java-modules/core-java-lambdas/README.MD +++ b/core-java-modules/core-java-lambdas/README.MD @@ -1,3 +1,3 @@ -### Relevant Articles +## Relevant articles: - [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables) diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index c1fbda0f98..276f651436 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -19,12 +19,8 @@ - org.springframework.security - spring-security-web - - - org.springframework.security - spring-security-config + org.springframework.boot + spring-boot-starter-security org.springframework.security @@ -32,48 +28,17 @@ - - org.springframework - spring-core - - - commons-logging - commons-logging - - + org.springframework.boot + spring-boot-starter-web - org.springframework - spring-context + org.apache.tomcat.embed + tomcat-embed-jasper - org.springframework - spring-jdbc - - - org.springframework - spring-beans - - - org.springframework - spring-aop - - - org.springframework - spring-tx - - - org.springframework - spring-expression - - - org.springframework - spring-web - - - org.springframework - spring-webmvc + org.springframework.boot + spring-boot-starter-tomcat diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java b/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java new file mode 100644 index 0000000000..9e52f0430a --- /dev/null +++ b/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringSessionApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringSessionApplication.class, args); + } +} From 40c2e9541fd9193efdc1cbf5a53cb013200e0834 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 16 Jun 2019 11:43:26 +0530 Subject: [PATCH 005/352] [BAEL-15412] - Moved article to libraries-http module --- libraries-http/README.md | 7 ++ libraries-http/pom.xml | 81 +++++++++++++++++++ .../googlehttpclientguide/GitHubExample.java | 0 .../googlehttpclientguide/GitHubUrl.java | 0 .../baeldung/googlehttpclientguide/User.java | 0 .../googlehttpclientguide/logging.properties | 0 libraries-http/src/main/resources/logback.xml | 13 +++ .../AsyncHttpClientLiveTest.java | 0 .../test/java/com/baeldung/client/Consts.java | 0 .../okhttp/DefaultContentTypeInterceptor.java | 0 .../okhttp/OkHttpFileUploadingLiveTest.java | 3 + .../baeldung/okhttp/OkHttpGetLiveTest.java | 3 + .../baeldung/okhttp/OkHttpHeaderLiveTest.java | 0 .../baeldung/okhttp/OkHttpMiscLiveTest.java | 3 + .../okhttp/OkHttpPostingLiveTest.java | 3 + .../okhttp/OkHttpRedirectLiveTest.java | 0 .../okhttp/ProgressRequestWrapper.java | 0 libraries/README.md | 3 - libraries/pom.xml | 9 +-- pom.xml | 2 + spring-rest/README.md | 1 - spring-rest/pom.xml | 9 --- 22 files changed, 116 insertions(+), 21 deletions(-) create mode 100644 libraries-http/README.md create mode 100644 libraries-http/pom.xml rename {libraries => libraries-http}/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java (100%) rename {libraries => libraries-http}/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java (100%) rename {libraries => libraries-http}/src/main/java/com/baeldung/googlehttpclientguide/User.java (100%) rename {libraries => libraries-http}/src/main/java/com/baeldung/googlehttpclientguide/logging.properties (100%) create mode 100644 libraries-http/src/main/resources/logback.xml rename {libraries => libraries-http}/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java (100%) rename {spring-rest => libraries-http}/src/test/java/com/baeldung/client/Consts.java (100%) rename {spring-rest => libraries-http}/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java (100%) rename {spring-rest => libraries-http}/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java (93%) rename {spring-rest => libraries-http}/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java (93%) rename {spring-rest => libraries-http}/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java (100%) rename {spring-rest => libraries-http}/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java (95%) rename {spring-rest => libraries-http}/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java (94%) rename {spring-rest => libraries-http}/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java (100%) rename {spring-rest => libraries-http}/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java (100%) diff --git a/libraries-http/README.md b/libraries-http/README.md new file mode 100644 index 0000000000..dd8c6a5f67 --- /dev/null +++ b/libraries-http/README.md @@ -0,0 +1,7 @@ + +### Relevant Articles: + +- [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp) +- [A Guide to Google-Http-Client](http://www.baeldung.com/google-http-client) +- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client) +- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets) diff --git a/libraries-http/pom.xml b/libraries-http/pom.xml new file mode 100644 index 0000000000..6006a93aef --- /dev/null +++ b/libraries-http/pom.xml @@ -0,0 +1,81 @@ + + + + 4.0.0 + libraries-http + libraries-http + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + + + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + + + + + com.google.http-client + google-http-client + ${googleclient.version} + + + com.google.http-client + google-http-client-jackson2 + ${googleclient.version} + + + com.google.http-client + google-http-client-gson + ${googleclient.version} + + + + + org.asynchttpclient + async-http-client + ${async.http.client.version} + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + com.google.code.gson + gson + 2.8.5 + + + + com.squareup.okhttp3 + mockwebserver + ${com.squareup.okhttp3.version} + test + + + + + + 3.6.2 + 3.14.2 + 1.23.0 + 2.2.0 + + diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java b/libraries-http/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java similarity index 100% rename from libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java rename to libraries-http/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java b/libraries-http/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java similarity index 100% rename from libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java rename to libraries-http/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java b/libraries-http/src/main/java/com/baeldung/googlehttpclientguide/User.java similarity index 100% rename from libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java rename to libraries-http/src/main/java/com/baeldung/googlehttpclientguide/User.java diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/logging.properties b/libraries-http/src/main/java/com/baeldung/googlehttpclientguide/logging.properties similarity index 100% rename from libraries/src/main/java/com/baeldung/googlehttpclientguide/logging.properties rename to libraries-http/src/main/java/com/baeldung/googlehttpclientguide/logging.properties diff --git a/libraries-http/src/main/resources/logback.xml b/libraries-http/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/libraries-http/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java b/libraries-http/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java rename to libraries-http/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientLiveTest.java diff --git a/spring-rest/src/test/java/com/baeldung/client/Consts.java b/libraries-http/src/test/java/com/baeldung/client/Consts.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/client/Consts.java rename to libraries-http/src/test/java/com/baeldung/client/Consts.java diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java b/libraries-http/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java rename to libraries-http/src/test/java/com/baeldung/okhttp/DefaultContentTypeInterceptor.java diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java similarity index 93% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java index 75980a5360..7b28c17607 100644 --- a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java +++ b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpFileUploadingLiveTest.java @@ -19,6 +19,9 @@ import okhttp3.Response; import org.junit.Before; import org.junit.Test; +/** + * Execute spring-rest module before running this live test + */ public class OkHttpFileUploadingLiveTest { private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java similarity index 93% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java index 3edd2eab06..5efc4aa998 100644 --- a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java +++ b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpGetLiveTest.java @@ -17,6 +17,9 @@ import okhttp3.Response; import org.junit.Before; import org.junit.Test; +/** + * Execute spring-rest module before running this live test + */ public class OkHttpGetLiveTest { private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpHeaderLiveTest.java diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java similarity index 95% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java index 207ad14e71..24617794d1 100644 --- a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java +++ b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpMiscLiveTest.java @@ -20,6 +20,9 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * Execute spring-rest module before running this live test + */ public class OkHttpMiscLiveTest { private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java similarity index 94% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java index 66fee0b626..19e689c093 100644 --- a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java +++ b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpPostingLiveTest.java @@ -20,6 +20,9 @@ import okhttp3.Response; import org.junit.Before; import org.junit.Test; +/** + * Execute spring-rest module before running this live test + */ public class OkHttpPostingLiveTest { private static final String BASE_URL = "http://localhost:" + APPLICATION_PORT + "/spring-rest"; diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java b/libraries-http/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java rename to libraries-http/src/test/java/com/baeldung/okhttp/OkHttpRedirectLiveTest.java diff --git a/spring-rest/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java b/libraries-http/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java similarity index 100% rename from spring-rest/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java rename to libraries-http/src/test/java/com/baeldung/okhttp/ProgressRequestWrapper.java diff --git a/libraries/README.md b/libraries/README.md index f6a39daef1..f6f2cf4e07 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -36,14 +36,11 @@ - [Introduction To Docx4J](http://www.baeldung.com/docx4j) - [Introduction to StreamEx](http://www.baeldung.com/streamex) - [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle) -- [A Guide to Google-Http-Client](http://www.baeldung.com/google-http-client) - [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client) - [A Docker Guide for Java](http://www.baeldung.com/docker-java-api) - [Introduction To OpenCSV](http://www.baeldung.com/opencsv) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) -- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client) - [Introduction to Smooks](http://www.baeldung.com/smooks) -- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets) - [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan) - [Introduction to OpenCSV](http://www.baeldung.com/opencsv) - [A Guide to Unirest](http://www.baeldung.com/unirest) diff --git a/libraries/pom.xml b/libraries/pom.xml index 7823732224..f6c88197bd 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -25,13 +25,7 @@ ${typesafe-akka.version} test - - - - org.asynchttpclient - async-http-client - ${async.http.client.version} - + org.beykery @@ -871,7 +865,6 @@ 2.0.0 1.7.0 3.0.14 - 2.2.0 9.1.5.Final 4.1 1.4.9 diff --git a/pom.xml b/pom.xml index 9760e06bc1..a099dd7d68 100644 --- a/pom.xml +++ b/pom.xml @@ -505,6 +505,7 @@ libraries-primitive libraries-security libraries-server + libraries-http linkrest logging-modules lombok @@ -1183,6 +1184,7 @@ libraries-apache-commons libraries-security libraries-server + libraries-http linkrest logging-modules lombok diff --git a/spring-rest/README.md b/spring-rest/README.md index 5d7894cdf8..54b47604d4 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -6,7 +6,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping) - [Returning Custom Status Codes from Spring Controllers](http://www.baeldung.com/spring-mvc-controller-custom-http-status-code) -- [A Guide to OkHttp](http://www.baeldung.com/guide-to-okhttp) - [Binary Data Formats in a Spring REST API](http://www.baeldung.com/spring-rest-api-with-binary-data-formats) - [Guide to UriComponentsBuilder in Spring](http://www.baeldung.com/spring-uricomponentsbuilder) - [Introduction to FindBugs](http://www.baeldung.com/intro-to-findbugs) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 36934af101..99bdd7646d 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -93,13 +93,6 @@ commons-lang3 - - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - - org.hamcrest @@ -280,8 +273,6 @@ 3.0.4 3.0.0 false - - 3.4.1 2.2.0 3.5.11 From 112fed951642dcdade2e0c617c4dba285a8afa4c Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 16 Jun 2019 21:32:47 +0530 Subject: [PATCH 006/352] [BAEL-14776] - Removed explicit version mention from xml config file --- .../src/main/resources/webSecurityConfig.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml index e8aa2f76bc..42ff4c2186 100644 --- a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml @@ -2,9 +2,9 @@ From 416c103cdae797b9314cccb9ea1f43b36b4d6b17 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Fri, 24 May 2019 15:01:37 -0300 Subject: [PATCH 007/352] Created new empty module spring-mvc-basics --- .gitignore | 4 + spring-mvc-basics/README.md | 8 + spring-mvc-basics/pom.xml | 299 ++++++++++++++++++ .../com/baeldung/config/AppInitializer.java | 27 ++ .../src/main/resources/annotations.properties | 0 .../SpringContextIntegrationTest.java | 21 ++ 6 files changed, 359 insertions(+) create mode 100644 spring-mvc-basics/README.md create mode 100644 spring-mvc-basics/pom.xml create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java create mode 100644 spring-mvc-basics/src/main/resources/annotations.properties create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java diff --git a/.gitignore b/.gitignore index 50cb889e5b..e84b19c168 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ */bin/* +bin/ *.class @@ -21,6 +22,9 @@ *.iws out/ +# VSCode +.vscode/ + # Mac .DS_Store diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md new file mode 100644 index 0000000000..46681afb48 --- /dev/null +++ b/spring-mvc-basics/README.md @@ -0,0 +1,8 @@ +========= + +## Spring MVC Basics with Java Configuration Example Project + +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml new file mode 100644 index 0000000000..777537b0b9 --- /dev/null +++ b/spring-mvc-basics/pom.xml @@ -0,0 +1,299 @@ + + 4.0.0 + com.baeldung + spring-mvc-basics + 0.1-SNAPSHOT + spring-mvc-basics + war + + + parent-spring-5 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + org.springframework + spring-webmvc + ${spring.version} + + + javax.servlet + javax.servlet-api + 4.0.1 + + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.3 + + + javax.servlet + jstl + ${jstl.version} + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + + org.aspectj + aspectjrt + 1.9.1 + + + org.aspectj + aspectjweaver + 1.9.1 + + + + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + + commons-io + commons-io + + + + + net.sourceforge.htmlunit + htmlunit + 2.32 + + + commons-logging + commons-logging + + + commons-io + commons-io + + + + + commons-io + commons-io + ${commons-io.version} + + + + + org.thymeleaf + thymeleaf-spring4 + ${thymeleaf.version} + + + org.thymeleaf + thymeleaf + ${thymeleaf.version} + + + + com.jayway.jsonpath + json-path + test + 2.4.0 + + + org.springframework + spring-test + ${spring.version} + test + + + + + org.apache.poi + poi-ooxml + ${poi.version} + + + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator.version} + + + + + + com.google.code.gson + gson + 2.8.5 + + + org.springframework + spring-websocket + ${spring.version} + + + + org.springframework + spring-messaging + ${spring.version} + + + + + spring-mvc-basics + + + src/main/resources + true + + + + + + + maven-resources-plugin + ${maven-resources-plugin.version} + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + + + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + **/*IntTest.java + + + **/*LiveTest.java + + + + + + + json + + + + + org.codehaus.cargo + cargo-maven2-plugin + + false + + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + + + + + + + 3.0.9.RELEASE + + + 6.0.10.Final + 5.1.40 + + + 6.0.10.Final + + + 19.0 + 3.5 + 1.3.2 + 2.5 + 2.2.0 + + + 4.4.5 + 4.5.2 + 3.0.7 + 2.23 + + + 3.2.2 + 2.7 + 1.6.1 + 3.1.0 + + + 1.9.1 + + + 3.16-beta1 + + 3.0.1-b06 + + + + + diff --git a/spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java b/spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java new file mode 100644 index 0000000000..a76d955e4f --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/config/AppInitializer.java @@ -0,0 +1,27 @@ +package com.baeldung.config; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class AppInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) throws ServletException { + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); + + context.scan("com.baeldung"); + + container.addListener(new ContextLoaderListener(context)); + + ServletRegistration.Dynamic dispatcher = container.addServlet("mvc", new DispatcherServlet(context)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/"); + } + +} diff --git a/spring-mvc-basics/src/main/resources/annotations.properties b/spring-mvc-basics/src/main/resources/annotations.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..d8cf4cfc0d --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.config.AppInitializer; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppInitializer.class }, loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + + } +} From 20c2c2dd7634c37d15ac405287bd8e9b52756f00 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sat, 25 May 2019 12:03:17 -0300 Subject: [PATCH 008/352] * moved 'Spring MVC Tutorial' code from spring-mvc-java to new module spring-mvc-basics * cleaned spring-mvc-basics pom --- spring-mvc-basics/.gitignore | 13 + spring-mvc-basics/README.md | 1 + spring-mvc-basics/pom.xml | 253 +----------------- .../baeldung/spring/web/config/WebConfig.java | 33 +++ .../web/controller/SampleController.java | 13 + .../src/main/resources/annotations.properties | 0 .../src/main/resources/mvc-configuration.xml | 20 ++ .../src/main/webapp/WEB-INF/view/index.jsp | 7 + .../src/main/webapp/WEB-INF/view/sample.jsp | 7 + spring-mvc-java/README.md | 1 - spring-mvc-java/pom.xml | 1 - 11 files changed, 103 insertions(+), 246 deletions(-) create mode 100644 spring-mvc-basics/.gitignore create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java delete mode 100644 spring-mvc-basics/src/main/resources/annotations.properties create mode 100644 spring-mvc-basics/src/main/resources/mvc-configuration.xml create mode 100644 spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp create mode 100644 spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp diff --git a/spring-mvc-basics/.gitignore b/spring-mvc-basics/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-mvc-basics/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 46681afb48..63d046de2d 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -6,3 +6,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: +- [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml index 777537b0b9..8217421948 100644 --- a/spring-mvc-basics/pom.xml +++ b/spring-mvc-basics/pom.xml @@ -1,4 +1,5 @@ - 4.0.0 com.baeldung @@ -15,136 +16,33 @@ - - org.springframework + + org.springframework spring-webmvc ${spring.version} javax.servlet javax.servlet-api - 4.0.1 + ${javax.servlet-api.version} javax.servlet.jsp javax.servlet.jsp-api - 2.3.3 + ${javax.jsp-api.version} javax.servlet jstl ${jstl.version} - - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - org.aspectj - aspectjrt - 1.9.1 - - - org.aspectj - aspectjweaver - 1.9.1 - - - - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - - - commons-io - commons-io - - - - - net.sourceforge.htmlunit - htmlunit - 2.32 - - - commons-logging - commons-logging - - - commons-io - commons-io - - - - - commons-io - commons-io - ${commons-io.version} - - - - - org.thymeleaf - thymeleaf-spring4 - ${thymeleaf.version} - - - org.thymeleaf - thymeleaf - ${thymeleaf.version} - - - - com.jayway.jsonpath - json-path - test - 2.4.0 - org.springframework spring-test - ${spring.version} + ${spring.version} test - - - - org.apache.poi - poi-ooxml - ${poi.version} - - - - - org.hibernate.validator - hibernate-validator - ${hibernate-validator.version} - - - - - - com.google.code.gson - gson - 2.8.5 - - - org.springframework - spring-websocket - ${spring.version} - - - - org.springframework - spring-messaging - ${spring.version} - @@ -155,144 +53,11 @@ true - - - - - maven-resources-plugin - ${maven-resources-plugin.version} - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - - - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*IntegrationTest.java - **/*IntTest.java - - - **/*LiveTest.java - - - - - - - json - - - - - org.codehaus.cargo - cargo-maven2-plugin - - false - - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - - - - - - - - 3.0.9.RELEASE - - - 6.0.10.Final - 5.1.40 - - - 6.0.10.Final - - - 19.0 - 3.5 - 1.3.2 - 2.5 - 2.2.0 - - - 4.4.5 - 4.5.2 - 3.0.7 - 2.23 - - - 3.2.2 - 2.7 - 1.6.1 - 3.1.0 - - - 1.9.1 - - - 3.16-beta1 - - 3.0.1-b06 - + 4.0.1 + 2.3.3 diff --git a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java new file mode 100644 index 0000000000..6ee20d7a6b --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.spring.web.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = { "com.baeldung.web.controller" }) +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/") + .setViewName("index"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + bean.setOrder(0); + return bean; + } +} \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java new file mode 100644 index 0000000000..c13986e005 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java @@ -0,0 +1,13 @@ +package com.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class SampleController { + @GetMapping("/sample") + public String showForm() { + return "sample"; + } + +} diff --git a/spring-mvc-basics/src/main/resources/annotations.properties b/spring-mvc-basics/src/main/resources/annotations.properties deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-mvc-basics/src/main/resources/mvc-configuration.xml b/spring-mvc-basics/src/main/resources/mvc-configuration.xml new file mode 100644 index 0000000000..7505614c99 --- /dev/null +++ b/spring-mvc-basics/src/main/resources/mvc-configuration.xml @@ -0,0 +1,20 @@ + + + + + + + + + /WEB-INF/view/ + + + .jsp + + + + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp new file mode 100644 index 0000000000..4f4eb0068d --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/index.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the index view

+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp new file mode 100644 index 0000000000..7cc14b5dcd --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/sample.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample view

+ + \ No newline at end of file diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 3deeb21afc..2c0f594bd2 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -29,6 +29,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) -- [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 853d8db64c..ffa76d405d 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -34,7 +34,6 @@ javax.servlet jstl ${jstl.version} -
From 33d0ac573830369ee113b3689d16b1d775448594 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sun, 26 May 2019 15:30:12 -0300 Subject: [PATCH 009/352] * Moved Controller vs RestController article code from spring-mvc-java to spring-mvc-basics * now using jupiter tests for the tests involved * fixed error in involved test --- spring-mvc-basics/README.md | 1 + spring-mvc-basics/pom.xml | 14 +++++++ .../main/java/com/baeldung/model/Book.java | 42 +++++++++++++++++++ .../web/controller/SimpleBookController.java | 0 .../controller/SimpleBookRestController.java | 0 .../SpringContextIntegrationTest.java | 2 +- .../SimpleBookControllerIntegrationTest.java | 8 ++-- ...mpleBookRestControllerIntegrationTest.java | 12 +++--- spring-mvc-java/README.md | 1 - 9 files changed, 66 insertions(+), 14 deletions(-) create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/model/Book.java rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/SimpleBookController.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java (90%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java (85%) diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 63d046de2d..aa1fffdf42 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -7,3 +7,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) +- [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml index 8217421948..cb9f1be9eb 100644 --- a/spring-mvc-basics/pom.xml +++ b/spring-mvc-basics/pom.xml @@ -36,6 +36,13 @@ jstl ${jstl.version} + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + org.springframework @@ -43,6 +50,12 @@ ${spring.version} test + + com.jayway.jsonpath + json-path + test + ${jayway.json-path.version} + @@ -58,6 +71,7 @@ 4.0.1 2.3.3 + 2.4.0 diff --git a/spring-mvc-basics/src/main/java/com/baeldung/model/Book.java b/spring-mvc-basics/src/main/java/com/baeldung/model/Book.java new file mode 100644 index 0000000000..bdfa1d835a --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/Book.java @@ -0,0 +1,42 @@ +package com.baeldung.model; + +public class Book { + + private int id; + private String author; + private String title; + + public Book() { + } + + public Book(int id, String author, String title) { + this.id = id; + this.author = author; + this.title = title; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/SimpleBookRestController.java diff --git a/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java index d8cf4cfc0d..511e56aeab 100644 --- a/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java similarity index 90% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java index 23be3a1655..87d70c2d29 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java @@ -5,19 +5,17 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import com.baeldung.web.controller.SimpleBookController; - public class SimpleBookControllerIntegrationTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; - @Before + @BeforeEach public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java similarity index 85% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java index c5bd53f1a7..294943f2e2 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java @@ -5,27 +5,25 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import com.baeldung.web.controller.SimpleBookController; - public class SimpleBookRestControllerIntegrationTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; - @Before + @BeforeEach public void setup() { - this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookController()).build(); + this.mockMvc = MockMvcBuilders.standaloneSetup(new SimpleBookRestController()).build(); } @Test public void givenBookId_whenMockMVC_thenVerifyResponse() throws Exception { this.mockMvc - .perform(get("/books/42")) + .perform(get("/books-rest/42")) .andExpect(status().isOk()) .andExpect(content().contentType(CONTENT_TYPE)) .andExpect(jsonPath("$.id").value(42)); diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 2c0f594bd2..e39ddd8af7 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -24,7 +24,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) - [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) - [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) -- [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) From ee4953b7ef831d4205e505225497adb4073f5793 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sun, 26 May 2019 17:42:54 -0300 Subject: [PATCH 010/352] * Added example and test for "using @ResponseStatus" article in the spring-mvc-basics module --- spring-mvc-basics/README.md | 1 + .../ResponseStatusRestController.java | 48 +++++++++++++++++ ...seStatusRestControllerIntegrationTest.java | 52 +++++++++++++++++++ spring-mvc-java/README.md | 1 - 4 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index aa1fffdf42..c8a0ac6508 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -8,3 +8,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) +- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java new file mode 100644 index 0000000000..4cc7589bc8 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ResponseStatusRestController.java @@ -0,0 +1,48 @@ +package com.baeldung.web.controller; + +import java.util.concurrent.ThreadLocalRandom; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.model.Book; + +@RestController +public class ResponseStatusRestController { + + @GetMapping("/teapot") + @ResponseStatus(HttpStatus.I_AM_A_TEAPOT) + public void teaPot() { + } + + @GetMapping("empty") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void emptyResponse() { + } + + @GetMapping("empty-no-responsestatus") + public void emptyResponseWithoutResponseStatus() { + } + + @PostMapping("create") + @ResponseStatus(HttpStatus.CREATED) + public Book createEntity() { + // here we would create and persist an entity + int randomInt = ThreadLocalRandom.current() + .nextInt(1, 100); + Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt); + return entity; + } + + @PostMapping("create-no-responsestatus") + public Book createEntityWithoutResponseStatus() { + // here we would create and persist an entity + int randomInt = ThreadLocalRandom.current() + .nextInt(1, 100); + Book entity = new Book(randomInt, "author" + randomInt, "title" + randomInt); + return entity; + } +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java new file mode 100644 index 0000000000..1f37a3750c --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ResponseStatusRestControllerIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class ResponseStatusRestControllerIntegrationTest { + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new ResponseStatusRestController()) + .build(); + } + + @Test + public void whenTeapotEndpointCalled_thenTeapotResponseObtained() throws Exception { + this.mockMvc.perform(get("/teapot")) + .andExpect(status().isIAmATeapot()); + } + + @Test + public void whenEmptyNoContentEndpointCalled_thenNoContentResponseObtained() throws Exception { + this.mockMvc.perform(get("/empty")) + .andExpect(status().isNoContent()); + } + + @Test + public void whenEmptyWithoutResponseStatusEndpointCalled_then200ResponseObtained() throws Exception { + this.mockMvc.perform(get("/empty-no-responsestatus")) + .andExpect(status().isOk()); + } + + @Test + public void whenCreateWithCreatedEndpointCalled_thenCreatedResponseObtained() throws Exception { + this.mockMvc.perform(post("/create")) + .andExpect(status().isCreated()); + } + + @Test + public void whenCreateWithoutResponseStatusEndpointCalled_thenCreatedResponseObtained() throws Exception { + this.mockMvc.perform(post("/create-no-responsestatus")) + .andExpect(status().isOk()); + } + +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index e39ddd8af7..4d1a7c172c 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -26,7 +26,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) -- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) From ed7630c2d092cc527dd5274bfb954de7910c10c5 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sun, 26 May 2019 19:08:28 -0300 Subject: [PATCH 011/352] Moved ViewResolver article related code from spring-mvc-java to spring-mvc-basics --- spring-mvc-basics/README.md | 3 +- spring-mvc-basics/pom.xml | 18 ++++++++-- .../baeldung/spring/web/config/WebConfig.java | 19 +++++++++++ .../web/controller/SampleController.java | 13 +++++++- .../src/main/resources/views.properties | 3 ++ .../src/main/resources/views.xml | 18 +++++----- .../src/main/webapp/WEB-INF/view2/sample2.jsp | 7 ++++ .../src/main/webapp/WEB-INF/view3/sample3.jsp | 7 ++++ .../controller/SampleControllerLiveTest.java | 33 +++++++++++++++++++ spring-mvc-java/README.md | 1 - .../baeldung/spring/web/config/WebConfig.java | 19 ----------- .../src/main/resources/views.properties | 3 -- 12 files changed, 108 insertions(+), 36 deletions(-) create mode 100644 spring-mvc-basics/src/main/resources/views.properties rename {spring-mvc-java => spring-mvc-basics}/src/main/resources/views.xml (65%) create mode 100644 spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp create mode 100644 spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java delete mode 100644 spring-mvc-java/src/main/resources/views.properties diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index c8a0ac6508..15b19cc1d0 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -8,4 +8,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) -- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) \ No newline at end of file +- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) +- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) \ No newline at end of file diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml index cb9f1be9eb..3bcf5bc4ca 100644 --- a/spring-mvc-basics/pom.xml +++ b/spring-mvc-basics/pom.xml @@ -36,12 +36,12 @@ jstl ${jstl.version} - + com.fasterxml.jackson.core jackson-databind - ${jackson.version} + ${jackson.version} @@ -56,6 +56,18 @@ test ${jayway.json-path.version} + + io.rest-assured + rest-assured + ${rest-assured.version} + test + + + org.hamcrest + hamcrest-all + ${hamcrest.version} + test + @@ -72,6 +84,8 @@ 4.0.1 2.3.3 2.4.0 + 4.0.0 + 1.3
diff --git a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 6ee20d7a6b..9fa9bd58db 100644 --- a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -3,12 +3,15 @@ package com.baeldung.spring.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; +import org.springframework.web.servlet.view.ResourceBundleViewResolver; +import org.springframework.web.servlet.view.XmlViewResolver; @EnableWebMvc @Configuration @@ -27,7 +30,23 @@ public class WebConfig implements WebMvcConfigurer { bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); + bean.setOrder(2); + return bean; + } + + @Bean + public ViewResolver resourceBundleViewResolver() { + final ResourceBundleViewResolver bean = new ResourceBundleViewResolver(); + bean.setBasename("views"); bean.setOrder(0); return bean; } + + @Bean + public ViewResolver xmlViewResolver() { + final XmlViewResolver bean = new XmlViewResolver(); + bean.setLocation(new ClassPathResource("views.xml")); + bean.setOrder(1); + return bean; + } } \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java index c13986e005..ce89669fde 100644 --- a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/SampleController.java @@ -5,9 +5,20 @@ import org.springframework.web.bind.annotation.GetMapping; @Controller public class SampleController { - @GetMapping("/sample") + + @GetMapping("/sample") public String showForm() { return "sample"; } + + @GetMapping("/sample2") + public String showForm2() { + return "sample2"; + } + + @GetMapping("/sample3") + public String showForm3() { + return "sample3"; + } } diff --git a/spring-mvc-basics/src/main/resources/views.properties b/spring-mvc-basics/src/main/resources/views.properties new file mode 100644 index 0000000000..06d042b446 --- /dev/null +++ b/spring-mvc-basics/src/main/resources/views.properties @@ -0,0 +1,3 @@ +sample2.(class)=org.springframework.web.servlet.view.JstlView +sample2.url=/WEB-INF/view2/sample2.jsp + diff --git a/spring-mvc-java/src/main/resources/views.xml b/spring-mvc-basics/src/main/resources/views.xml similarity index 65% rename from spring-mvc-java/src/main/resources/views.xml rename to spring-mvc-basics/src/main/resources/views.xml index 83bca5293d..a44d3deae4 100644 --- a/spring-mvc-java/src/main/resources/views.xml +++ b/spring-mvc-basics/src/main/resources/views.xml @@ -1,10 +1,10 @@ - - - - - - + + + + + + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp new file mode 100644 index 0000000000..c826700a75 --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view2/sample2.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample2 view

+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp new file mode 100644 index 0000000000..b58a0973da --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view3/sample3.jsp @@ -0,0 +1,7 @@ + + + + +

This is the body of the sample3 view

+ + \ No newline at end of file diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java new file mode 100644 index 0000000000..bd24bb6ff9 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java @@ -0,0 +1,33 @@ +package com.baeldung.web.controller; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +import io.restassured.RestAssured; + +public class SampleControllerLiveTest { + + private static final String SERVICE_BASE_URL = "/spring-mvc-basics"; + + @Test + public void whenSampleEndpointCalled_thenOkResponseObtained() throws Exception { + RestAssured.get(SERVICE_BASE_URL + "/sample") + .then() + .statusCode(HttpStatus.OK.value()); + } + + @Test + public void whenSample2EndpointCalled_thenOkResponseObtained() throws Exception { + RestAssured.get(SERVICE_BASE_URL + "/sample2") + .then() + .statusCode(HttpStatus.OK.value()); + } + + @Test + public void whenSample3EndpointCalled_thenOkResponseObtained() throws Exception { + RestAssured.get(SERVICE_BASE_URL + "/sample3") + .then() + .statusCode(HttpStatus.OK.value()); + } + +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 4d1a7c172c..c670b153cf 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -9,7 +9,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) - [Introduction to Pointcut Expressions in Spring](http://www.baeldung.com/spring-aop-pointcut-tutorial) - [Introduction to Advice Types in Spring](http://www.baeldung.com/spring-aop-advice-tutorial) -- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) - [Integration Testing in Spring](http://www.baeldung.com/integration-testing-in-spring) - [A Quick Guide to Spring MVC Matrix Variables](http://www.baeldung.com/spring-mvc-matrix-variables) - [Intro to WebSockets with Spring](http://www.baeldung.com/websockets-spring) diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 191d721dfb..96b50f2c37 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -12,7 +12,6 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import org.springframework.context.support.ResourceBundleMessageSource; -import org.springframework.core.io.ClassPathResource; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; @@ -26,8 +25,6 @@ import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; -import org.springframework.web.servlet.view.ResourceBundleViewResolver; -import org.springframework.web.servlet.view.XmlViewResolver; import org.springframework.web.util.UrlPathHelper; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; @@ -110,22 +107,6 @@ public class WebConfig implements WebMvcConfigurer { return multipartResolver; } - - @Bean - public ViewResolver xmlViewResolver() { - final XmlViewResolver bean = new XmlViewResolver(); - bean.setLocation(new ClassPathResource("views.xml")); - bean.setOrder(1); - return bean; - } - - @Bean - public ViewResolver resourceBundleViewResolver() { - final ResourceBundleViewResolver bean = new ResourceBundleViewResolver(); - bean.setBasename("views"); - bean.setOrder(0); - return bean; - } @Override public void extendMessageConverters(final List> converters) { diff --git a/spring-mvc-java/src/main/resources/views.properties b/spring-mvc-java/src/main/resources/views.properties deleted file mode 100644 index 95687cb62a..0000000000 --- a/spring-mvc-java/src/main/resources/views.properties +++ /dev/null @@ -1,3 +0,0 @@ -sample.(class)=org.springframework.web.servlet.view.JstlView -sample.url=/WEB-INF/view/sample.jsp - From 802000d5453fb9000736959849fcbf043eb39629 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Fri, 14 Jun 2019 12:40:42 -0300 Subject: [PATCH 012/352] Migrated spring-mvc-basics to a Spring Boot project --- spring-mvc-basics/pom.xml | 81 +++++-------------- .../main/java/com/baeldung/Application.java | 11 +++ .../baeldung/spring/web/config/WebConfig.java | 10 +-- .../src/main/resources/application.properties | 1 + .../SpringContextIntegrationTest.java | 12 +-- .../controller/SampleControllerLiveTest.java | 2 +- 6 files changed, 41 insertions(+), 76 deletions(-) create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/Application.java create mode 100644 spring-mvc-basics/src/main/resources/application.properties diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml index 3bcf5bc4ca..d04bdda8f6 100644 --- a/spring-mvc-basics/pom.xml +++ b/spring-mvc-basics/pom.xml @@ -1,3 +1,4 @@ + @@ -6,87 +7,49 @@ spring-mvc-basics 0.1-SNAPSHOT spring-mvc-basics - war + jar - parent-spring-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-spring-5 + ../parent-boot-2 - org.springframework - spring-webmvc - ${spring.version} + org.springframework.boot + spring-boot-starter-web + - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - javax.servlet.jsp - javax.servlet.jsp-api - ${javax.jsp-api.version} + org.apache.tomcat.embed + tomcat-embed-jasper + provided javax.servlet jstl ${jstl.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - org.springframework - spring-test - ${spring.version} - test - - - com.jayway.jsonpath - json-path - test - ${jayway.json-path.version} - - - io.rest-assured - rest-assured - ${rest-assured.version} - test - - - org.hamcrest - hamcrest-all - ${hamcrest.version} + org.springframework.boot + spring-boot-starter-test test - spring-mvc-basics - - - src/main/resources - true - - + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.Application + JAR + + + - - - 4.0.1 - 2.3.3 - 2.4.0 - 4.0.0 - 1.3 - - diff --git a/spring-mvc-basics/src/main/java/com/baeldung/Application.java b/spring-mvc-basics/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..d58049fb35 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/Application.java @@ -0,0 +1,11 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 9fa9bd58db..a56dfe550f 100644 --- a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -1,11 +1,9 @@ package com.baeldung.spring.web.config; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @@ -13,9 +11,9 @@ import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.ResourceBundleViewResolver; import org.springframework.web.servlet.view.XmlViewResolver; -@EnableWebMvc +//@EnableWebMvc +//@ComponentScan(basePackages = { "com.baeldung.web.controller" }) @Configuration -@ComponentScan(basePackages = { "com.baeldung.web.controller" }) public class WebConfig implements WebMvcConfigurer { @Override @@ -33,7 +31,7 @@ public class WebConfig implements WebMvcConfigurer { bean.setOrder(2); return bean; } - + @Bean public ViewResolver resourceBundleViewResolver() { final ResourceBundleViewResolver bean = new ResourceBundleViewResolver(); @@ -41,7 +39,7 @@ public class WebConfig implements WebMvcConfigurer { bean.setOrder(0); return bean; } - + @Bean public ViewResolver xmlViewResolver() { final XmlViewResolver bean = new XmlViewResolver(); diff --git a/spring-mvc-basics/src/main/resources/application.properties b/spring-mvc-basics/src/main/resources/application.properties new file mode 100644 index 0000000000..4de974142e --- /dev/null +++ b/spring-mvc-basics/src/main/resources/application.properties @@ -0,0 +1 @@ +server.servlet.context-path=/spring-mvc-basics \ No newline at end of file diff --git a/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java index 511e56aeab..2feb9efce1 100644 --- a/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -1,17 +1,9 @@ package com.baeldung; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; -import com.baeldung.config.AppInitializer; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { AppInitializer.class }, loader = AnnotationConfigContextLoader.class) -@WebAppConfiguration +@SpringBootTest public class SpringContextIntegrationTest { @Test diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java index bd24bb6ff9..0b958996c9 100644 --- a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/SampleControllerLiveTest.java @@ -6,7 +6,7 @@ import org.springframework.http.HttpStatus; import io.restassured.RestAssured; public class SampleControllerLiveTest { - + private static final String SERVICE_BASE_URL = "/spring-mvc-basics"; @Test From 1e9364a7dc6663336c2616b3f0f3c12e3ab2ed70 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Fri, 14 Jun 2019 14:36:15 -0300 Subject: [PATCH 013/352] Moved code of article spring-handler-mappings from spring-mvc-java to spring-mvc-basics Renamed beans to avoid collisions --- spring-mvc-basics/README.md | 3 ++- .../handlermapping/BeanNameHandlerMappingController.java | 0 .../handlermapping/SimpleUrlMappingController.java | 0 .../web/controller/handlermapping/WelcomeController.java | 0 .../baeldung/config/BeanNameUrlHandlerMappingConfig.java | 7 +++---- .../com/baeldung/config/HandlerMappingDefaultConfig.java | 2 +- .../baeldung/config/HandlerMappingPrioritiesConfig.java | 6 +++--- .../com/baeldung/config/SimpleUrlHandlerMappingConfig.java | 6 +++--- .../BeanNameMappingConfigIntegrationTest.java | 0 .../HandlerMappingDefaultConfigIntegrationTest.java | 0 .../HandlerMappingPriorityConfigIntegrationTest.java | 0 .../SimpleUrlMappingConfigIntegrationTest.java | 0 .../src/test/resources/BeanNameUrlHandlerMappingConfig.xml | 0 .../resources/ControllerClassNameHandlerMappingConfig.xml | 0 .../test/resources/HandlerMappingConfiguringPriorities.xml | 0 .../src/test/resources/SimpleUrlHandlerMappingConfig.xml | 0 spring-mvc-java/README.md | 1 - 17 files changed, 12 insertions(+), 13 deletions(-) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java (76%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java (90%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java (89%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java (85%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/resources/BeanNameUrlHandlerMappingConfig.xml (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/resources/ControllerClassNameHandlerMappingConfig.xml (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/resources/HandlerMappingConfiguringPriorities.xml (100%) rename {spring-mvc-java => spring-mvc-basics}/src/test/resources/SimpleUrlHandlerMappingConfig.xml (100%) diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 15b19cc1d0..997e6a88df 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -9,4 +9,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) -- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) \ No newline at end of file +- [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) +- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/BeanNameHandlerMappingController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/SimpleUrlMappingController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/handlermapping/WelcomeController.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java similarity index 76% rename from spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java index e3dcb15de8..577825d8c5 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/BeanNameUrlHandlerMappingConfig.java @@ -1,11 +1,10 @@ package com.baeldung.config; -import com.baeldung.web.controller.handlermapping.WelcomeController; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; -import org.springframework.web.servlet.view.InternalResourceViewResolver; + +import com.baeldung.web.controller.handlermapping.WelcomeController; @Configuration public class BeanNameUrlHandlerMappingConfig { @@ -16,7 +15,7 @@ public class BeanNameUrlHandlerMappingConfig { } @Bean("/beanNameUrl") - public WelcomeController welcome() { + public WelcomeController welcomeBeanNameMappingConfig() { return new WelcomeController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java similarity index 90% rename from spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java index d3a329a387..4072278fee 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingDefaultConfig.java @@ -16,7 +16,7 @@ public class HandlerMappingDefaultConfig { } @Bean - public WelcomeController welcome() { + public WelcomeController welcomeDefaultMappingConfig() { return new WelcomeController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java similarity index 89% rename from spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java index 2d80dbfeaf..c5fec171a7 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/HandlerMappingPrioritiesConfig.java @@ -16,14 +16,14 @@ import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; public class HandlerMappingPrioritiesConfig { @Bean - BeanNameUrlHandlerMapping beanNameUrlHandlerMapping() { + BeanNameUrlHandlerMapping beanNameUrlHandlerMappingOrder1() { BeanNameUrlHandlerMapping beanNameUrlHandlerMapping = new BeanNameUrlHandlerMapping(); beanNameUrlHandlerMapping.setOrder(1); return beanNameUrlHandlerMapping; } @Bean - public SimpleUrlHandlerMapping simpleUrlHandlerMapping() { + public SimpleUrlHandlerMapping simpleUrlHandlerMappingOrder0() { SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping(); simpleUrlHandlerMapping.setOrder(0); Map urlMap = new HashMap<>(); @@ -37,7 +37,7 @@ public class HandlerMappingPrioritiesConfig { return new SimpleUrlMappingController(); } - @Bean("/welcome") + @Bean("/welcome-priorities") public BeanNameHandlerMappingController beanNameHandlerMapping() { return new BeanNameHandlerMappingController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java b/spring-mvc-basics/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java similarity index 85% rename from spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java rename to spring-mvc-basics/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java index c7921c2706..7a366ecbd7 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/config/SimpleUrlHandlerMappingConfig.java @@ -18,7 +18,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; public class SimpleUrlHandlerMappingConfig { @Bean - public ViewResolver viewResolver() { + public ViewResolver viewResolverSimpleMappingConfig() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/"); viewResolver.setSuffix(".jsp"); @@ -29,13 +29,13 @@ public class SimpleUrlHandlerMappingConfig { public SimpleUrlHandlerMapping simpleUrlHandlerMapping() { SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping(); Map urlMap = new HashMap<>(); - urlMap.put("/simpleUrlWelcome", welcome()); + urlMap.put("/simpleUrlWelcome", welcomeSimpleMappingConfig()); simpleUrlHandlerMapping.setUrlMap(urlMap); return simpleUrlHandlerMapping; } @Bean - public WelcomeController welcome() { + public WelcomeController welcomeSimpleMappingConfig() { return new WelcomeController(); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java diff --git a/spring-mvc-java/src/test/resources/BeanNameUrlHandlerMappingConfig.xml b/spring-mvc-basics/src/test/resources/BeanNameUrlHandlerMappingConfig.xml similarity index 100% rename from spring-mvc-java/src/test/resources/BeanNameUrlHandlerMappingConfig.xml rename to spring-mvc-basics/src/test/resources/BeanNameUrlHandlerMappingConfig.xml diff --git a/spring-mvc-java/src/test/resources/ControllerClassNameHandlerMappingConfig.xml b/spring-mvc-basics/src/test/resources/ControllerClassNameHandlerMappingConfig.xml similarity index 100% rename from spring-mvc-java/src/test/resources/ControllerClassNameHandlerMappingConfig.xml rename to spring-mvc-basics/src/test/resources/ControllerClassNameHandlerMappingConfig.xml diff --git a/spring-mvc-java/src/test/resources/HandlerMappingConfiguringPriorities.xml b/spring-mvc-basics/src/test/resources/HandlerMappingConfiguringPriorities.xml similarity index 100% rename from spring-mvc-java/src/test/resources/HandlerMappingConfiguringPriorities.xml rename to spring-mvc-basics/src/test/resources/HandlerMappingConfiguringPriorities.xml diff --git a/spring-mvc-java/src/test/resources/SimpleUrlHandlerMappingConfig.xml b/spring-mvc-basics/src/test/resources/SimpleUrlHandlerMappingConfig.xml similarity index 100% rename from spring-mvc-java/src/test/resources/SimpleUrlHandlerMappingConfig.xml rename to spring-mvc-basics/src/test/resources/SimpleUrlHandlerMappingConfig.xml diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index c670b153cf..8ba9b5fd1e 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -17,7 +17,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) - [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) -- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) - [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) From 684bc16314051832cb5f4e14efbf2c6afc50fe23 Mon Sep 17 00:00:00 2001 From: isaolmez Date: Mon, 17 Jun 2019 22:41:32 +0300 Subject: [PATCH 014/352] BAEL-2981: Added header for tests and formatted pom.xml --- libraries-2/pom.xml | 162 +++++++++--------- .../handlebars/BasicUsageUnitTest.java | 5 + .../handlebars/BuiltinHelperUnitTest.java | 5 + .../handlebars/CustomHelperUnitTest.java | 5 + .../handlebars/ReusingTemplatesUnitTest.java | 5 + 5 files changed, 101 insertions(+), 81 deletions(-) diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 686996686f..a7aa3dc544 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -1,86 +1,86 @@ + 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"> - 4.0.0 - libraries2 - libraries2 + 4.0.0 + libraries2 + libraries2 - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - jboss-public-repository-group - JBoss Public Repository Group - http://repository.jboss.org/nexus/content/groups/public/ - - true - never - - - true - daily - - - + + + jboss-public-repository-group + JBoss Public Repository Group + http://repository.jboss.org/nexus/content/groups/public/ + + true + never + + + true + daily + + + - - - org.assertj - assertj-core - ${assertj.version} - - - io.github.classgraph - classgraph - ${classgraph.version} - - - org.jbpm - jbpm-test - ${jbpm.version} - - - info.picocli - picocli - ${picocli.version} - - - org.springframework.boot - spring-boot-starter - ${spring-boot-starter.version} - + + + org.assertj + assertj-core + ${assertj.version} + + + io.github.classgraph + classgraph + ${classgraph.version} + + + org.jbpm + jbpm-test + ${jbpm.version} + + + info.picocli + picocli + ${picocli.version} + + + org.springframework.boot + spring-boot-starter + ${spring-boot-starter.version} + - - - com.squareup.okhttp3 - okhttp - 3.14.2 - + + + com.squareup.okhttp3 + okhttp + 3.14.2 + - - com.fasterxml.jackson.core - jackson-databind - 2.9.9 - + + com.fasterxml.jackson.core + jackson-databind + 2.9.9 + - - com.google.code.gson - gson - 2.8.5 - + + com.google.code.gson + gson + 2.8.5 + - - com.squareup.okhttp3 - mockwebserver - 3.14.2 - test - + + com.squareup.okhttp3 + mockwebserver + 3.14.2 + test + edu.uci.ics crawler4j @@ -92,14 +92,14 @@ handlebars 4.1.2 - + - - 3.6.2 - 4.8.28 - 6.0.0.Final - 3.9.6 + + 3.6.2 + 4.8.28 + 6.0.0.Final + 3.9.6 4.4.0 - 2.1.4.RELEASE - + 2.1.4.RELEASE + diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java index a2b535f4dd..bf7afa0fc9 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java @@ -11,6 +11,11 @@ import java.util.HashMap; import java.util.Map; import org.junit.Test; +/** + * Showcases the tag usage and different template loading mechanisms. + * + * @author isaolmez + */ public class BasicUsageUnitTest { @Test diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java index b44ac63b5a..84529a74ce 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java @@ -9,6 +9,11 @@ import com.github.jknack.handlebars.io.TemplateLoader; import java.io.IOException; import org.junit.Test; +/** + * Showcases the built-in template helpers. + * + * @author isaolmez + */ public class BuiltinHelperUnitTest { private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html"); diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java index ce74d55e70..18f02fe013 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java @@ -11,6 +11,11 @@ import com.github.jknack.handlebars.io.TemplateLoader; import java.io.IOException; import org.junit.Test; +/** + * Showcases implementing a custom template helper. + * + * @author isaolmez + */ public class CustomHelperUnitTest { private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html"); diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java index 1e2844ab1e..8741294703 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java @@ -9,6 +9,11 @@ import com.github.jknack.handlebars.io.TemplateLoader; import java.io.IOException; import org.junit.Test; +/** + * Showcases reusing the existing templates. + * + * @author isaolmez + */ public class ReusingTemplatesUnitTest { private TemplateLoader templateLoader = new ClassPathTemplateLoader("/handlebars", ".html"); From 3862de2519b684c4a397f190daac7362711b3463 Mon Sep 17 00:00:00 2001 From: Chandra Prakash Date: Thu, 20 Jun 2019 00:41:47 -0400 Subject: [PATCH 015/352] BAEL-3045 Validate Date Check if a string contains valid date --- java-dates-2/DaveValidatorUsingLocalDate.java | 24 ++++++++++++++ java-dates-2/pom.xml | 7 ++++ .../date/validation/DateValidator.java | 5 +++ .../DateValidatorUsingApacheValidator.java | 11 +++++++ .../DateValidatorUsingDateFormat.java | 25 +++++++++++++++ .../DateValidatorUsingDateTimeFormatter.java | 22 +++++++++++++ .../DateValidatorUsingLocalDate.java | 23 +++++++++++++ ...ValidatorUsingApacheValidatorUnitTest.java | 20 ++++++++++++ .../DateValidatorUsingDateFormatUnitTest.java | 23 +++++++++++++ ...lidatorUsingDateTimeFormatterUnitTest.java | 32 +++++++++++++++++++ .../DateValidatorUsingLocalDateUnitTest.java | 27 ++++++++++++++++ 11 files changed, 219 insertions(+) create mode 100644 java-dates-2/DaveValidatorUsingLocalDate.java create mode 100644 java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java create mode 100644 java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingApacheValidator.java create mode 100644 java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateFormat.java create mode 100644 java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatter.java create mode 100644 java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingLocalDate.java create mode 100644 java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingApacheValidatorUnitTest.java create mode 100644 java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateFormatUnitTest.java create mode 100644 java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatterUnitTest.java create mode 100644 java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingLocalDateUnitTest.java diff --git a/java-dates-2/DaveValidatorUsingLocalDate.java b/java-dates-2/DaveValidatorUsingLocalDate.java new file mode 100644 index 0000000000..251757df97 --- /dev/null +++ b/java-dates-2/DaveValidatorUsingLocalDate.java @@ -0,0 +1,24 @@ +package com.baeldung.date.validation; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +public class DaveValidatorUsingLocalDate implements DateValidator { + private DateTimeFormatter dateFormatter; + + public DaveValidatorUsingLocalDate(DateTimeFormatter dateFormatter) { + super(); + this.dateFormatter = dateFormatter; + } + + @Override + public boolean validate(String dateStr) { + try { + LocalDate.parse(dateStr, this.dateFormatter); + } catch (DateTimeParseException e) { + return false; + } + return true; + } +} diff --git a/java-dates-2/pom.xml b/java-dates-2/pom.xml index 9307a794b9..2f861ff5f4 100644 --- a/java-dates-2/pom.xml +++ b/java-dates-2/pom.xml @@ -20,6 +20,13 @@ joda-time ${joda-time.version} + + + + commons-validator + commons-validator + 1.6 + diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java new file mode 100644 index 0000000000..74c1bf7445 --- /dev/null +++ b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java @@ -0,0 +1,5 @@ +package com.baeldung.date.validation; + +public interface DateValidator { + public boolean isValid(String dateStr); +} diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingApacheValidator.java b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingApacheValidator.java new file mode 100644 index 0000000000..f7b2f48d2d --- /dev/null +++ b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingApacheValidator.java @@ -0,0 +1,11 @@ +package com.baeldung.date.validation; + +import org.apache.commons.validator.GenericValidator; + +public class DateValidatorUsingApacheValidator implements DateValidator { + + @Override + public boolean isValid(String dateStr) { + return GenericValidator.isDate(dateStr, "yyyy-MM-dd", true); + } +} diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateFormat.java b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateFormat.java new file mode 100644 index 0000000000..eb0fbdb086 --- /dev/null +++ b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateFormat.java @@ -0,0 +1,25 @@ +package com.baeldung.date.validation; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +public class DateValidatorUsingDateFormat implements DateValidator { + private String dateFormat; + + public DateValidatorUsingDateFormat(String dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public boolean isValid(String dateStr) { + DateFormat sdf = new SimpleDateFormat(this.dateFormat); + sdf.setLenient(false); + try { + sdf.parse(dateStr); + } catch (ParseException e) { + return false; + } + return true; + } +} diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatter.java b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatter.java new file mode 100644 index 0000000000..0f68baf06e --- /dev/null +++ b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatter.java @@ -0,0 +1,22 @@ +package com.baeldung.date.validation; + +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +public class DateValidatorUsingDateTimeFormatter implements DateValidator { + private DateTimeFormatter dateFormatter; + + public DateValidatorUsingDateTimeFormatter(DateTimeFormatter dateFormatter) { + this.dateFormatter = dateFormatter; + } + + @Override + public boolean isValid(String dateStr) { + try { + this.dateFormatter.parse(dateStr); + } catch (DateTimeParseException e) { + return false; + } + return true; + } +} diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingLocalDate.java b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingLocalDate.java new file mode 100644 index 0000000000..f04c2e4185 --- /dev/null +++ b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidatorUsingLocalDate.java @@ -0,0 +1,23 @@ +package com.baeldung.date.validation; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +public class DateValidatorUsingLocalDate implements DateValidator { + private DateTimeFormatter dateFormatter; + + public DateValidatorUsingLocalDate(DateTimeFormatter dateFormatter) { + this.dateFormatter = dateFormatter; + } + + @Override + public boolean isValid(String dateStr) { + try { + LocalDate.parse(dateStr, this.dateFormatter); + } catch (DateTimeParseException e) { + return false; + } + return true; + } +} diff --git a/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingApacheValidatorUnitTest.java b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingApacheValidatorUnitTest.java new file mode 100644 index 0000000000..daa464722a --- /dev/null +++ b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingApacheValidatorUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.date.validation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.apache.commons.validator.GenericValidator; +import org.junit.Test; + +public class DateValidatorUsingApacheValidatorUnitTest { + + @Test + public void whenValidDatePassed_ThenTrue() { + assertTrue(GenericValidator.isDate("2019-02-28", "yyyy-MM-dd", true)); + } + + @Test + public void whenInvalidDatePassed_ThenFalse() { + assertFalse(GenericValidator.isDate("2019-02-29", "yyyy-MM-dd", true)); + } +} diff --git a/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateFormatUnitTest.java b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateFormatUnitTest.java new file mode 100644 index 0000000000..9b86b3381c --- /dev/null +++ b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateFormatUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.date.validation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class DateValidatorUsingDateFormatUnitTest { + + @Test + public void givenValidator_whenValidDatePassed_ThenTrue() { + DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); + + assertTrue(validator.isValid("02/28/2019")); + } + + @Test + public void givenValidator_whenInvalidDatePassed_ThenFalse() { + DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); + + assertFalse(validator.isValid("02/30/2019")); + } +} diff --git a/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatterUnitTest.java b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatterUnitTest.java new file mode 100644 index 0000000000..368b04f8e3 --- /dev/null +++ b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingDateTimeFormatterUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.date.validation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.time.format.DateTimeFormatter; +import java.time.format.ResolverStyle; +import java.util.Locale; + +import org.junit.Test; + +public class DateValidatorUsingDateTimeFormatterUnitTest { + + @Test + public void givenValidator_whenValidDatePassed_ThenTrue() { + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.US) + .withResolverStyle(ResolverStyle.STRICT); + DateValidator validator = new DateValidatorUsingDateTimeFormatter(dateFormatter); + + assertTrue(validator.isValid("2019-02-28")); + } + + @Test + public void givenValidator_whenInValidDatePassed_ThenFalse() { + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.US) + .withResolverStyle(ResolverStyle.STRICT); + DateValidator validator = new DateValidatorUsingDateTimeFormatter(dateFormatter); + + assertFalse(validator.isValid("2019-02-30")); + } + +} diff --git a/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingLocalDateUnitTest.java b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingLocalDateUnitTest.java new file mode 100644 index 0000000000..63296359db --- /dev/null +++ b/java-dates-2/src/test/java/com/baeldung/date/validation/DateValidatorUsingLocalDateUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.date.validation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.time.format.DateTimeFormatter; + +import org.junit.Test; + +public class DateValidatorUsingLocalDateUnitTest { + + @Test + public void givenValidator_whenValidDatePassed_ThenTrue() { + DateTimeFormatter dateFormatter = DateTimeFormatter.BASIC_ISO_DATE; + DateValidator validator = new DateValidatorUsingLocalDate(dateFormatter); + + assertTrue(validator.isValid("20190228")); + } + + @Test + public void givenValidator_whenInValidDatePassed_ThenFalse() { + DateTimeFormatter dateFormatter = DateTimeFormatter.BASIC_ISO_DATE; + DateValidator validator = new DateValidatorUsingLocalDate(dateFormatter); + + assertFalse(validator.isValid("20190230")); + } +} From c2823762a7113e257cf4cf7eb297f8da87f3d242 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Thu, 20 Jun 2019 14:27:03 +0200 Subject: [PATCH 016/352] BAEL-3001 --- .../com/baeldung/random/SecureRandomDemo.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 java-numbers/src/main/java/com/baeldung/random/SecureRandomDemo.java diff --git a/java-numbers/src/main/java/com/baeldung/random/SecureRandomDemo.java b/java-numbers/src/main/java/com/baeldung/random/SecureRandomDemo.java new file mode 100644 index 0000000000..ee65f920e9 --- /dev/null +++ b/java-numbers/src/main/java/com/baeldung/random/SecureRandomDemo.java @@ -0,0 +1,36 @@ +package com.baeldung.random; + +import java.security.SecureRandom; +import java.security.NoSuchAlgorithmException; +import java.util.stream.IntStream; +import java.util.stream.LongStream; +import java.util.stream.DoubleStream; + +public interface SecureRandomDemo { + + public static void generateSecureRandomValues() { + SecureRandom sr = new SecureRandom(); + + int randomInt = sr.nextInt(); + long randomLong = sr.nextLong(); + float randomFloat = sr.nextFloat(); + double randomDouble = sr.nextDouble(); + boolean randomBoolean = sr.nextBoolean(); + + IntStream randomIntStream = sr.ints(); + LongStream randomLongStream = sr.longs(); + DoubleStream randomDoubleStream = sr.doubles(); + + byte[] values = new byte[124]; + sr.nextBytes(values); + } + + public static SecureRandom getSecureRandomForAlgorithm(String algorithm) throws NoSuchAlgorithmException { + if(algorithm == null || algorithm.isEmpty()) { + return new SecureRandom(); + } + + return SecureRandom.getInstance(algorithm); + } + +} From 6e1910a8146f3c140837b6c5a43c8ab4178a8cd9 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 20 Jun 2019 21:45:00 +0300 Subject: [PATCH 017/352] Delete DaveValidatorUsingLocalDate.java --- java-dates-2/DaveValidatorUsingLocalDate.java | 24 ------------------- 1 file changed, 24 deletions(-) delete mode 100644 java-dates-2/DaveValidatorUsingLocalDate.java diff --git a/java-dates-2/DaveValidatorUsingLocalDate.java b/java-dates-2/DaveValidatorUsingLocalDate.java deleted file mode 100644 index 251757df97..0000000000 --- a/java-dates-2/DaveValidatorUsingLocalDate.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.date.validation; - -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; - -public class DaveValidatorUsingLocalDate implements DateValidator { - private DateTimeFormatter dateFormatter; - - public DaveValidatorUsingLocalDate(DateTimeFormatter dateFormatter) { - super(); - this.dateFormatter = dateFormatter; - } - - @Override - public boolean validate(String dateStr) { - try { - LocalDate.parse(dateStr, this.dateFormatter); - } catch (DateTimeParseException e) { - return false; - } - return true; - } -} From fcc4fa4afae5caffedf336ee61f91bd51fdbeae4 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Fri, 21 Jun 2019 16:07:02 +0200 Subject: [PATCH 018/352] format --- .../src/main/java/com/baeldung/random/SecureRandomDemo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java-numbers/src/main/java/com/baeldung/random/SecureRandomDemo.java b/java-numbers/src/main/java/com/baeldung/random/SecureRandomDemo.java index ee65f920e9..02f815f5a7 100644 --- a/java-numbers/src/main/java/com/baeldung/random/SecureRandomDemo.java +++ b/java-numbers/src/main/java/com/baeldung/random/SecureRandomDemo.java @@ -26,7 +26,7 @@ public interface SecureRandomDemo { } public static SecureRandom getSecureRandomForAlgorithm(String algorithm) throws NoSuchAlgorithmException { - if(algorithm == null || algorithm.isEmpty()) { + if (algorithm == null || algorithm.isEmpty()) { return new SecureRandom(); } From ca3ef57f043643bab9d1b8713d609d568e0e2e90 Mon Sep 17 00:00:00 2001 From: isaolmez Date: Sat, 22 Jun 2019 11:18:41 +0300 Subject: [PATCH 019/352] BAEL-2981: Changed helper name --- .../test/java/com/baeldung/handlebars/CustomHelperUnitTest.java | 2 +- .../src/test/java/com/baeldung/handlebars/HelperSource.java | 2 +- libraries-2/src/test/resources/handlebars/person.html | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java index 18f02fe013..6966d69cef 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java @@ -23,7 +23,7 @@ public class CustomHelperUnitTest { @Test public void whenHelperIsCreated_ThenCanRegister() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); - handlebars.registerHelper("person", new Helper() { + handlebars.registerHelper("isBusy", new Helper() { @Override public Object apply(Person context, Options options) throws IOException { String busyString = context.isBusy() ? "busy" : "available"; diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/HelperSource.java b/libraries-2/src/test/java/com/baeldung/handlebars/HelperSource.java index 2b7d705af9..b98786c029 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/HelperSource.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/HelperSource.java @@ -2,7 +2,7 @@ package com.baeldung.handlebars; public class HelperSource { - public String person(Person context) { + public String isBusy(Person context) { String busyString = context.isBusy() ? "busy" : "available"; return context.getName() + " - " + busyString; } diff --git a/libraries-2/src/test/resources/handlebars/person.html b/libraries-2/src/test/resources/handlebars/person.html index 5207d49266..9df7850f60 100644 --- a/libraries-2/src/test/resources/handlebars/person.html +++ b/libraries-2/src/test/resources/handlebars/person.html @@ -1 +1 @@ -{{#person this}}{{/person}} \ No newline at end of file +{{#isBusy this}}{{/isBusy}} \ No newline at end of file From 29912c960e3f8ceba3a3dbd2ef8393abe53b63d1 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 22 Jun 2019 18:43:22 +0300 Subject: [PATCH 020/352] upload files mongodb and spring boot --- .../spring-boot-persistence-mongodb/pom.xml | 4 ++ .../mongodb/daos/PhotoRepository.java | 9 +++ .../com/baeldung/mongodb/models/Photo.java | 51 ++++++++++++++ .../com/baeldung/mongodb/models/Video.java | 39 +++++++++++ .../mongodb/services/PhotoService.java | 38 +++++++++++ .../mongodb/services/VideoService.java | 56 ++++++++++++++++ .../baeldung/mongodb/web/PhotoController.java | 50 ++++++++++++++ .../baeldung/mongodb/web/VideoController.java | 67 +++++++++++++++++++ .../src/main/resources/application.properties | 7 +- .../src/main/resources/templates/index.html | 14 ++++ .../src/main/resources/templates/photos.html | 10 +++ .../main/resources/templates/uploadPhoto.html | 15 +++++ .../main/resources/templates/uploadVideo.html | 15 +++++ .../src/main/resources/templates/videos.html | 15 +++++ 14 files changed, 389 insertions(+), 1 deletion(-) create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/index.html create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/photos.html create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadPhoto.html create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadVideo.html create mode 100644 persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/videos.html diff --git a/persistence-modules/spring-boot-persistence-mongodb/pom.xml b/persistence-modules/spring-boot-persistence-mongodb/pom.xml index 585e54bf57..dae5efa6d0 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/pom.xml +++ b/persistence-modules/spring-boot-persistence-mongodb/pom.xml @@ -20,6 +20,10 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-thymeleaf + org.springframework.boot diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java new file mode 100644 index 0000000000..d38e11c055 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.mongodb.daos; + +import org.springframework.data.mongodb.repository.MongoRepository; + +import com.baeldung.mongodb.models.Photo; + +public interface PhotoRepository extends MongoRepository { + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java new file mode 100644 index 0000000000..13f1a3cd19 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java @@ -0,0 +1,51 @@ +package com.baeldung.mongodb.models; + +import org.bson.types.Binary; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document(collection = "photos") +public class Photo { + + @Id + private String id; + + private String title; + + private Binary image; + + public Photo(String title) { + super(); + this.title = title; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Binary getImage() { + return image; + } + + public void setImage(Binary image) { + this.image = image; + } + + @Override + public String toString() { + return "Photo [id=" + id + ", title=" + title + ", image=" + image + "]"; + } + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java new file mode 100644 index 0000000000..617f0cdbfd --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java @@ -0,0 +1,39 @@ +package com.baeldung.mongodb.models; + +import java.io.InputStream; + +public class Video { + private String title; + private InputStream stream; + + public Video() { + super(); + } + + public Video(String title) { + super(); + this.title = title; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public InputStream getStream() { + return stream; + } + + public void setStream(InputStream stream) { + this.stream = stream; + } + + @Override + public String toString() { + return "Video [title=" + title + "]"; + } + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java new file mode 100644 index 0000000000..685d67c40f --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java @@ -0,0 +1,38 @@ +package com.baeldung.mongodb.services; + +import java.io.IOException; +import java.util.Optional; + +import org.bson.BsonBinarySubType; +import org.bson.types.Binary; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.mongodb.daos.PhotoRepository; +import com.baeldung.mongodb.models.Photo; + +@Service +public class PhotoService { + + @Autowired + private PhotoRepository photoRepo; + + public Photo getPhoto(String id) { + Optional result = photoRepo.findById(id); + return result.isPresent() ? result.get() : null; + } + + public String addPhoto(String title, MultipartFile file) { + String id = null; + try { + Photo photo = new Photo(title); + photo.setImage(new Binary(BsonBinarySubType.BINARY, file.getBytes())); + photo = photoRepo.insert(photo); + id = photo.getId(); + } catch (IOException e) { + return null; + } + return id; + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java new file mode 100644 index 0000000000..dea6540973 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java @@ -0,0 +1,56 @@ +package com.baeldung.mongodb.services; + +import java.io.IOException; + +import org.bson.types.ObjectId; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.gridfs.GridFsOperations; +import org.springframework.data.mongodb.gridfs.GridFsTemplate; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.mongodb.models.Video; +import com.mongodb.BasicDBObject; +import com.mongodb.DBObject; +import com.mongodb.client.gridfs.model.GridFSFile; + +@Service +public class VideoService { + + @Autowired + private GridFsTemplate gridFsTemplate; + + @Autowired + private GridFsOperations operations; + + public Video getVideo(String id) { + Video video = null; + GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id))); + if (file != null) { + video = new Video(); + video.setTitle(file.getMetadata().get("title").toString()); + try { + video.setStream(operations.getResource(file).getInputStream()); + } catch (IOException e) { + return null; + } + } + return video; + } + + public String addVideo(String title, MultipartFile file) { + DBObject metaData = new BasicDBObject(); + metaData.put("type", "video"); + metaData.put("title", title); + ObjectId id; + try { + id = gridFsTemplate.store(file.getInputStream(), file.getName(), file.getContentType(), metaData); + } catch (IOException e) { + return null; + } + return id.toString(); + } + +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java new file mode 100644 index 0000000000..fffb6ec320 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java @@ -0,0 +1,50 @@ +package com.baeldung.mongodb.web; + +import java.util.Base64; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.mongodb.models.Photo; +import com.baeldung.mongodb.services.PhotoService; + +@Controller +public class PhotoController { + + @Autowired + private PhotoService photoService; + + @GetMapping("/photos/{id}") + public String getPhoto(@PathVariable String id, Model model) { + Photo photo = photoService.getPhoto(id); + if (photo != null) { + model.addAttribute("title", photo.getTitle()); + model.addAttribute("image", Base64.getEncoder().encodeToString(photo.getImage().getData())); + return "photos"; + } + model.addAttribute("message", "Photo not found"); + return "index"; + } + + @GetMapping("/photos/upload") + public String uploadPhoto(Model model) { + model.addAttribute("message", "hello"); + return "uploadPhoto"; + } + + @PostMapping("/photos/add") + public String addPhoto(@RequestParam("title") String title, @RequestParam("image") MultipartFile image, Model model) { + String id = photoService.addPhoto(title, image); + if (id == null) { + model.addAttribute("message", "Error Occurred"); + return "index"; + } + return "redirect:/photos/" + id; + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java new file mode 100644 index 0000000000..e5fda0cc64 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java @@ -0,0 +1,67 @@ +package com.baeldung.mongodb.web; + +import java.io.IOException; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.util.FileCopyUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +import com.baeldung.mongodb.models.Video; +import com.baeldung.mongodb.services.VideoService; + +@Controller +public class VideoController { + + @Autowired + private VideoService videoService; + + @GetMapping("/videos/{id}") + public String getVideo(@PathVariable String id, Model model) { + Video video = videoService.getVideo(id); + if (video != null) { + model.addAttribute("title", video.getTitle()); + model.addAttribute("url", "/videos/stream/" + id); + return "videos"; + } + model.addAttribute("message", "Video not found"); + return "index"; + } + + @GetMapping("/videos/stream/{id}") + public void streamVideo(@PathVariable String id, HttpServletResponse response) { + Video video = videoService.getVideo(id); + if (video != null) { + try { + FileCopyUtils.copy(video.getStream(), response.getOutputStream()); + } catch (IOException e) { + response.setStatus(500); + } + } else { + response.setStatus(404); + } + } + + @GetMapping("/videos/upload") + public String uploadVideo(Model model) { + model.addAttribute("message", "hello"); + return "uploadVideo"; + } + + @PostMapping("/videos/add") + public String addVideo(@RequestParam("title") String title, @RequestParam("file") MultipartFile file, Model model) { + String id = videoService.addVideo(title, file); + if (id == null) { + model.addAttribute("message", "Error Occurred"); + return "index"; + } + return "redirect:/videos/" + id; + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties index 5b1b8000d0..6548f2b28a 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties @@ -1,8 +1,13 @@ spring.application.name=spring-boot-persistence -server.port=${PORT:0} +server.port=8082 #spring boot mongodb spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=springboot-mongo +spring.thymeleaf.cache=false + +spring.servlet.multipart.max-file-size=256MB +spring.servlet.multipart.max-request-size=256MB +spring.servlet.multipart.enabled=true \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/index.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/index.html new file mode 100644 index 0000000000..f99e9caa8b --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/index.html @@ -0,0 +1,14 @@ + + + +Upload Files MongoDB + + +

Home Page

+
Message
+
+ Upload new Photo +

+ Upload new Video + + diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/photos.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/photos.html new file mode 100644 index 0000000000..b5d56d020a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/photos.html @@ -0,0 +1,10 @@ + + +

View Photo

+ Title: name +
+ sample +

+ Back to home page + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadPhoto.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadPhoto.html new file mode 100644 index 0000000000..6d51c06d8f --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadPhoto.html @@ -0,0 +1,15 @@ + + + +

Upload new Photo

+
+ Title: +
+ Image: +
+
+ +
+ + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadVideo.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadVideo.html new file mode 100644 index 0000000000..ebc29d98e2 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/uploadVideo.html @@ -0,0 +1,15 @@ + + + +

Upload new Video

+
+ Title: +
+ Video: +
+
+ +
+ + + \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/videos.html b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/videos.html new file mode 100644 index 0000000000..b0ee0fc577 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/templates/videos.html @@ -0,0 +1,15 @@ + + +

View Video

+ Title: title +
+
+ + + +

+ Back to home page + + \ No newline at end of file From f13b1e78ef0528eabf0b0903b284070122600324 Mon Sep 17 00:00:00 2001 From: gpq5 Date: Sat, 22 Jun 2019 22:17:12 +0530 Subject: [PATCH 021/352] [BAEL-3002] Comparing 2 JSON objects with Jackson --- .../json/compare/JsonCompareUnitTest.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java diff --git a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java new file mode 100644 index 0000000000..02f6726901 --- /dev/null +++ b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.jackson.json.compare; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.Comparator; + +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.NumericNode; + +public class JsonCompareUnitTest { + + @Test + public void givenTwoSameJsonDataObjects_whenCompared_thenAreEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String jsonString1 = "{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\",\"k4\":\"v4\"}"; + String jsonString2 = "{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\",\"k4\":\"v4\"}"; + JsonNode actualObj1 = mapper.readTree(jsonString1); + JsonNode actualObj2 = mapper.readTree(jsonString2); + + assertTrue(actualObj1.equals(actualObj2)); + + } + + @Test + public void givenTwoJsonDataObjects_whenComparedUsingCustomComparator_thenEqual() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + + String jsonString1 = "{\"k1\": 5,\"k2\":9191}"; + String jsonString2 = "{\"k1\": 5.0,\"k2\":9191}"; + JsonNode actualObj1 = mapper.readTree(jsonString1); + JsonNode actualObj2 = mapper.readTree(jsonString2); + + assertFalse(actualObj1.equals(actualObj2)); + + Comparator cmp = new Comparator() { + @Override + public int compare(JsonNode o1, JsonNode o2) { + if (o1.equals(o2)) { + return 0; + } + if ((o1 instanceof NumericNode) && (o2 instanceof NumericNode)) { + double d1 = ((NumericNode) o1).asDouble(); + double d2 = ((NumericNode) o2).asDouble(); + if (d1 == d2) { + return 0; + } + } + return 1; + } + }; + + assertTrue(actualObj1.equals(cmp, actualObj2)); + + } + +} From 07b49e32c2ef1a65328482e1a251d1349485e219 Mon Sep 17 00:00:00 2001 From: Ariel Papuga Date: Fri, 21 Jun 2019 22:01:00 +0200 Subject: [PATCH 022/352] BAEL-2921 Understanding getBean --- .../baeldung/getbean/AnnotationConfig.java | 22 ++++++++++ .../main/java/com/baeldung/getbean/Lion.java | 13 ++++++ .../main/java/com/baeldung/getbean/Tiger.java | 13 ++++++ .../getbean/GetBeanByNameAndTypeUnitTest.java | 33 +++++++++++++++ .../getbean/GetBeanByNameUnitTest.java | 40 +++++++++++++++++++ ...NameWithConstructorParametersUnitTest.java | 38 ++++++++++++++++++ .../getbean/GetBeanByTypeUnitTest.java | 33 +++++++++++++++ ...TypeWithConstructorParametersUnitTest.java | 26 ++++++++++++ 8 files changed, 218 insertions(+) create mode 100644 spring-core/src/main/java/com/baeldung/getbean/AnnotationConfig.java create mode 100644 spring-core/src/main/java/com/baeldung/getbean/Lion.java create mode 100644 spring-core/src/main/java/com/baeldung/getbean/Tiger.java create mode 100644 spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java create mode 100644 spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java create mode 100644 spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java create mode 100644 spring-core/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java create mode 100644 spring-core/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java diff --git a/spring-core/src/main/java/com/baeldung/getbean/AnnotationConfig.java b/spring-core/src/main/java/com/baeldung/getbean/AnnotationConfig.java new file mode 100644 index 0000000000..12e3ab55e3 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/getbean/AnnotationConfig.java @@ -0,0 +1,22 @@ +package com.baeldung.getbean; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; + +@Configuration +class AnnotationConfig { + + @Bean(name = {"tiger", "kitty"}) + @Scope(value = "prototype") + Tiger getTiger(String name) { + return new Tiger(name); + } + + @Bean(name = "lion") + Lion getLion() { + return new Lion("Hardcoded lion name"); + } + + interface Animal {} +} diff --git a/spring-core/src/main/java/com/baeldung/getbean/Lion.java b/spring-core/src/main/java/com/baeldung/getbean/Lion.java new file mode 100644 index 0000000000..96c569aeb9 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/getbean/Lion.java @@ -0,0 +1,13 @@ +package com.baeldung.getbean; + +class Lion implements AnnotationConfig.Animal { + private String name; + + Lion(String name) { + this.name = name; + } + + String getName() { + return name; + } +} diff --git a/spring-core/src/main/java/com/baeldung/getbean/Tiger.java b/spring-core/src/main/java/com/baeldung/getbean/Tiger.java new file mode 100644 index 0000000000..85b9626c79 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/getbean/Tiger.java @@ -0,0 +1,13 @@ +package com.baeldung.getbean; + +class Tiger implements AnnotationConfig.Animal { + private String name; + + Tiger(String name) { + this.name = name; + } + + String getName() { + return name; + } +} diff --git a/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java b/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java new file mode 100644 index 0000000000..e06804c28e --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.getbean; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.BeanNotOfRequiredTypeException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class GetBeanByNameAndTypeUnitTest { + private ApplicationContext context; + + @BeforeAll + void setup() { + context = new AnnotationConfigApplicationContext(AnnotationConfig.class); + } + + @Test + void whenSpecifiedMatchingNameAndType_thenShouldReturnRelatedBean() { + Lion lion = context.getBean("lion", Lion.class); + + assertEquals("Hardcoded lion name", lion.getName()); + } + + @Test + void whenSpecifiedNotMatchingNameAndType_thenShouldThrowException() { + assertThrows(BeanNotOfRequiredTypeException.class, () -> context.getBean("lion", Tiger.class)); + } +} diff --git a/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java b/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java new file mode 100644 index 0000000000..70a135b314 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.getbean; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class GetBeanByNameUnitTest { + private ApplicationContext context; + + @BeforeAll + void setup() { + context = new AnnotationConfigApplicationContext(AnnotationConfig.class); + } + + @Test + void whenGivenExistingBeanName_shouldReturnThatBean() { + Object requestedBean = context.getBean("lion"); + + assertEquals(requestedBean.getClass(), Lion.class); + } + + @Test + void whenGivenNonExistingBeanName_shouldThrowException() { + assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean("non-existing")); + } + + @Test + void whenCastingToWrongType_thenShouldThrowException() { + assertThrows(ClassCastException.class, () -> { + Tiger tiger = (Tiger) context.getBean("lion"); + }); + } +} diff --git a/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java b/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java new file mode 100644 index 0000000000..4ac8c1ac13 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.getbean; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.UnsatisfiedDependencyException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class GetBeanByNameWithConstructorParametersUnitTest { + private ApplicationContext context; + + @BeforeAll + void setup() { + context = new AnnotationConfigApplicationContext(AnnotationConfig.class); + } + + @Test + void whenGivenCorrectNameOrAlias_shouldReturnBeanWithSpecifiedName() { + Tiger tiger = (Tiger) context.getBean("tiger", "Cutie"); + Tiger tigerSecond = (Tiger) context.getBean("tiger", "Striped"); + Tiger tigerViaAlias = (Tiger) context.getBean("kitty", "Siberian"); + assertEquals("Cutie", tiger.getName()); + assertEquals("Striped", tigerSecond.getName()); + assertEquals("Siberian", tigerViaAlias.getName()); + } + + @Test + void whenNoArgumentSpecifiedForPrototypeBean_thenShouldThrowException() { + assertThrows(UnsatisfiedDependencyException.class, () -> { + Tiger tiger = (Tiger) context.getBean("tiger"); + }); + } +} diff --git a/spring-core/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java b/spring-core/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java new file mode 100644 index 0000000000..a4d4ab732b --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.getbean; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.NoUniqueBeanDefinitionException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class GetBeanByTypeUnitTest { + private ApplicationContext context; + + @BeforeAll + void setup() { + context = new AnnotationConfigApplicationContext(AnnotationConfig.class); + } + + @Test + void whenGivenExistingUniqueType_thenShouldReturnRelatedBean() { + Lion lion = context.getBean(Lion.class); + + assertNotNull(lion); + } + + @Test + void whenGivenAmbiguousType_thenShouldThrowException() { + assertThrows(NoUniqueBeanDefinitionException.class, () -> context.getBean(AnnotationConfig.Animal.class)); + } +} diff --git a/spring-core/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java b/spring-core/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java new file mode 100644 index 0000000000..08bcb92145 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.getbean; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class GetBeanByTypeWithConstructorParametersUnitTest { + private ApplicationContext context; + + @BeforeAll + void setup() { + context = new AnnotationConfigApplicationContext(AnnotationConfig.class); + } + + @Test + void whenGivenExistingTypeAndValidParameters_thenShouldReturnRelatedBean() { + Tiger tiger = context.getBean(Tiger.class, "Shere Khan"); + + assertEquals("Shere Khan", tiger.getName()); + } +} From 0eeb8a37f5d6fa5870f583e4e66b879895102927 Mon Sep 17 00:00:00 2001 From: gpq5 Date: Sun, 23 Jun 2019 08:58:20 +0530 Subject: [PATCH 023/352] added additional examples --- .../json/compare/JsonCompareUnitTest.java | 47 +++++++++++++++---- 1 file changed, 38 insertions(+), 9 deletions(-) diff --git a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java index 02f6726901..100f999d10 100644 --- a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java +++ b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java @@ -18,10 +18,39 @@ public class JsonCompareUnitTest { public void givenTwoSameJsonDataObjects_whenCompared_thenAreEqual() throws IOException { ObjectMapper mapper = new ObjectMapper(); - String jsonString1 = "{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\",\"k4\":\"v4\"}"; - String jsonString2 = "{\"k1\":\"v1\",\"k2\":\"v2\",\"k3\":\"v3\",\"k4\":\"v4\"}"; - JsonNode actualObj1 = mapper.readTree(jsonString1); - JsonNode actualObj2 = mapper.readTree(jsonString2); + String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34 }}"; + String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34 }}"; + + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + assertTrue(actualObj1.equals(actualObj2)); + + } + + @Test + public void givenTwoSameNestedJsonDataObjects_whenCompared_thenAreEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34,\n" + "\"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}"; + String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34,\n" + "\"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}"; + + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + assertTrue(actualObj1.equals(actualObj2)); + + } + + @Test + public void givenTwoSameListJsonDataObjects_whenCompared_thenAreEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"skills\":[\"Java\", \"C++\", \"Python\"] }}"; + String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"skills\":[\"Java\", \"C++\", \"Python\"] }}"; + + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); assertTrue(actualObj1.equals(actualObj2)); @@ -31,12 +60,11 @@ public class JsonCompareUnitTest { public void givenTwoJsonDataObjects_whenComparedUsingCustomComparator_thenEqual() throws Exception { ObjectMapper mapper = new ObjectMapper(); - String jsonString1 = "{\"k1\": 5,\"k2\":9191}"; - String jsonString2 = "{\"k1\": 5.0,\"k2\":9191}"; - JsonNode actualObj1 = mapper.readTree(jsonString1); - JsonNode actualObj2 = mapper.readTree(jsonString2); + String s1 = "{\"name\": \"John\",\"score\":5.0}"; + String s2 = "{\"name\": \"John\",\"score\":5}"; + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); - assertFalse(actualObj1.equals(actualObj2)); Comparator cmp = new Comparator() { @Override @@ -55,6 +83,7 @@ public class JsonCompareUnitTest { } }; + assertFalse(actualObj1.equals(actualObj2)); assertTrue(actualObj1.equals(cmp, actualObj2)); } From 212326a754c4f9849bb6ed114b5d70c1df84fe4d Mon Sep 17 00:00:00 2001 From: Denis Zhdanov Date: Sun, 23 Jun 2019 13:50:50 +0800 Subject: [PATCH 024/352] BAEL-2910 MockMvc Kotlin DSL * configured spring repo in the 'parent-kotlin' model to allow using spring's milestone artifacts * configured jackson kotlin module in the 'parent-kotlin' to allow easy use of kotlin data classes with jackson * switched spring-mvc-kotlin from explicit spring dependencies to spring-boot * mockmvc dsl article's source and tests --- parent-kotlin/pom.xml | 11 +++- spring-mvc-kotlin/pom.xml | 12 ++-- .../kotlin/mockmvc/MockMvcController.kt | 26 ++++++++ .../baeldung/kotlin/mockmvc/MockMvcModel.kt | 10 +++ .../kotlin/mockmvc/MockMvcControllerTest.kt | 61 +++++++++++++++++++ 5 files changed, 113 insertions(+), 7 deletions(-) create mode 100644 spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt create mode 100644 spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt create mode 100644 spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index 6f7fe6c102..d993fad3c6 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -26,6 +26,11 @@ kotlin-eap http://dl.bintray.com/kotlin/kotlin-eap + + spring-milestone + Spring Milestone Repository + http://repo.spring.io/milestone + @@ -40,7 +45,7 @@ org.springframework.boot spring-boot-dependencies - 2.0.1.RELEASE + 2.2.0.M4 pom import @@ -80,6 +85,10 @@ ktor-gson ${ktor.io.version}
+ + com.fasterxml.jackson.module + jackson-module-kotlin + org.jetbrains.kotlin diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml index fc76f58727..fb1f242644 100644 --- a/spring-mvc-kotlin/pom.xml +++ b/spring-mvc-kotlin/pom.xml @@ -15,12 +15,12 @@ - org.springframework - spring-web + org.springframework.boot + spring-boot-starter-web - org.springframework - spring-webmvc + org.springframework.boot + spring-boot-starter-json org.thymeleaf @@ -46,8 +46,8 @@ test - org.springframework - spring-test + org.springframework.boot + spring-boot-starter-test test diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt new file mode 100644 index 0000000000..68ab5f31a6 --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt @@ -0,0 +1,26 @@ +package com.baeldung.kotlin.mockmvc + +import org.springframework.http.MediaType +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestMethod +import org.springframework.web.bind.annotation.RestController + +@RestController +@RequestMapping("/mockmvc") +class MockMvcController { + + @RequestMapping(value = ["/validate"], method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE]) + fun validate(@RequestBody request: Request): Response { + val error = if (request.name.first == "admin") { + null + } else { + ERROR + } + return Response(error) + } + + companion object { + const val ERROR = "invalid user" + } +} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt new file mode 100644 index 0000000000..3231b6f186 --- /dev/null +++ b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt @@ -0,0 +1,10 @@ +package com.baeldung.kotlin.mockmvc + +import com.fasterxml.jackson.annotation.JsonInclude + +data class Name(val first: String, val last: String) + +data class Request(val name: Name) + +@JsonInclude(JsonInclude.Include.NON_NULL) +data class Response(val error: String?) \ No newline at end of file diff --git a/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt new file mode 100644 index 0000000000..802cd4c1e7 --- /dev/null +++ b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt @@ -0,0 +1,61 @@ +package com.baeldung.kotlin.mockmvc + +import com.fasterxml.jackson.databind.ObjectMapper +import org.junit.Test +import org.junit.runner.RunWith +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity.status +import org.springframework.test.context.junit4.SpringRunner +import org.springframework.test.web.servlet.MockMvc +import org.springframework.test.web.servlet.post +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders +import org.springframework.test.web.servlet.result.MockMvcResultHandlers +import org.springframework.test.web.servlet.result.MockMvcResultMatchers + +@RunWith(SpringRunner::class) +@WebMvcTest +class MockMvcControllerTest { + + @Autowired lateinit var mockMvc: MockMvc + @Autowired lateinit var mapper: ObjectMapper + + @Test + fun `when supported user is given then raw MockMvc-based validation is successful`() { + mockMvc.perform(MockMvcRequestBuilders + .post("/mockmvc/validate") + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(mapper.writeValueAsString(Request(Name("admin", ""))))) + .andExpect(MockMvcResultMatchers.status().isOk) + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.content().string("{}")) + } + + @Test + fun `when supported user is given then kotlin DSL-based validation is successful`() { + doTest(Request(Name("admin", "")), Response(null)) + } + + @Test + fun `when unsupported user is given then validation is failed`() { + doTest(Request(Name("some-name", "some-surname")), Response(MockMvcController.ERROR)) + } + + private fun doTest(input: Request, expectation: Response) { + mockMvc.post("/mockmvc/validate") { + contentType = MediaType.APPLICATION_JSON + content = mapper.writeValueAsString(input) + accept = MediaType.APPLICATION_JSON + }.andExpect { + status { isOk } + content { contentType(MediaType.APPLICATION_JSON) } + content { json(mapper.writeValueAsString(expectation)) } + } + } +} + +@SpringBootApplication +class MockMvcApplication \ No newline at end of file From 706035468b8992f58fd79ecc3d47311f92dd8104 Mon Sep 17 00:00:00 2001 From: gpq5 Date: Sun, 23 Jun 2019 12:35:44 +0530 Subject: [PATCH 025/352] Minor fixes --- .../jackson/json/compare/JsonCompareUnitTest.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java index 100f999d10..05b89abc09 100644 --- a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java +++ b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java @@ -18,8 +18,8 @@ public class JsonCompareUnitTest { public void givenTwoSameJsonDataObjects_whenCompared_thenAreEqual() throws IOException { ObjectMapper mapper = new ObjectMapper(); - String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34 }}"; - String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34 }}"; + String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\", \"age\": 34 }}"; + String s2 = "{\"employee\": {\"id\": \"1212\",\"age\": 34, \"fullName\": \"John Miles\" }}"; JsonNode actualObj1 = mapper.readTree(s1); JsonNode actualObj2 = mapper.readTree(s2); @@ -29,11 +29,11 @@ public class JsonCompareUnitTest { } @Test - public void givenTwoSameNestedJsonDataObjects_whenCompared_thenAreEqual() throws IOException { + public void givenTwoSameNestedJsonDataObjects_whenCompared_thenEqual() throws IOException { ObjectMapper mapper = new ObjectMapper(); - String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34,\n" + "\"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}"; - String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34,\n" + "\"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}"; + String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}"; + String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}"; JsonNode actualObj1 = mapper.readTree(s1); JsonNode actualObj2 = mapper.readTree(s2); @@ -43,7 +43,7 @@ public class JsonCompareUnitTest { } @Test - public void givenTwoSameListJsonDataObjects_whenCompared_thenAreEqual() throws IOException { + public void givenTwoSameListJsonDataObjects_whenCompared_thenEqual() throws IOException { ObjectMapper mapper = new ObjectMapper(); String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"skills\":[\"Java\", \"C++\", \"Python\"] }}"; @@ -57,7 +57,7 @@ public class JsonCompareUnitTest { } @Test - public void givenTwoJsonDataObjects_whenComparedUsingCustomComparator_thenEqual() throws Exception { + public void givenTwoJsonDataObjects_whenComparedUsingCustomComparator_thenEqual() throws IOException { ObjectMapper mapper = new ObjectMapper(); String s1 = "{\"name\": \"John\",\"score\":5.0}"; @@ -65,7 +65,6 @@ public class JsonCompareUnitTest { JsonNode actualObj1 = mapper.readTree(s1); JsonNode actualObj2 = mapper.readTree(s2); - Comparator cmp = new Comparator() { @Override public int compare(JsonNode o1, JsonNode o2) { From 7b244aabda6c96de0a7c6ff992790136e424209a Mon Sep 17 00:00:00 2001 From: Arho Huttunen Date: Sun, 23 Jun 2019 10:07:06 +0300 Subject: [PATCH 026/352] BAEL-2911 - JUnit Custom Display Name Generator API --- .../ReplaceUnderscoresGeneratorUnitTest.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/ReplaceUnderscoresGeneratorUnitTest.java diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/ReplaceUnderscoresGeneratorUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/ReplaceUnderscoresGeneratorUnitTest.java new file mode 100644 index 0000000000..d6e023cfe8 --- /dev/null +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/ReplaceUnderscoresGeneratorUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.displayname; + +import org.junit.jupiter.api.*; + +@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) +class ReplaceUnderscoresGeneratorUnitTest { + + @Nested + class when_doing_something { + + @Test + void then_should_happen_something() { + } + + @Test + @DisplayName("@DisplayName takes precedence over generation") + void override_generator() { + } + } +} From aa80328881546ff41c9ea43f30c179b93394f340 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 23 Jun 2019 17:22:18 +0530 Subject: [PATCH 027/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/rest-template --- .../java/org/baeldung/client/RestTemplateBasicLiveTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java index a54c124d5f..ff3034a50d 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java @@ -188,7 +188,7 @@ public class RestTemplateBasicLiveTest { final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody() .getId(); final HttpEntity requestUpdate = new HttpEntity<>(updatedResource, headers); - final ClientHttpRequestFactory requestFactory = getSimpleClientHttpRequestFactory(); + final ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory(); final RestTemplate template = new RestTemplate(requestFactory); template.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter())); template.patchForObject(resourceUrl, requestUpdate, Void.class); @@ -262,7 +262,7 @@ public class RestTemplateBasicLiveTest { // Simply setting restTemplate timeout using ClientHttpRequestFactory - ClientHttpRequestFactory getSimpleClientHttpRequestFactory() { + ClientHttpRequestFactory getClientHttpRequestFactory() { final int timeout = 5; final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); clientHttpRequestFactory.setConnectTimeout(timeout * 1000); From 559de5cfd6373f81804f31324d676694597e1235 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 23 Jun 2019 17:55:03 +0530 Subject: [PATCH 028/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api --- .../baeldung/web/controller/CustomController.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java diff --git a/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java b/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java new file mode 100644 index 0000000000..7d40b9bb8d --- /dev/null +++ b/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomController.java @@ -0,0 +1,14 @@ +package org.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class CustomController { + + @RequestMapping(value = "/custom", method = RequestMethod.POST) + public String custom() { + return "custom"; + } +} \ No newline at end of file From 57fa2baf7215b417c58bc67235e71cb25d6e188a Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 23 Jun 2019 20:30:38 +0530 Subject: [PATCH 029/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/spring-requestmapping --- .../org/baeldung/config/{WebConfig.java => MvcConfig.java} | 4 ++-- .../controller/status/ExampleControllerIntegrationTest.java | 4 ++-- .../web/test/BazzNewMappingsExampleIntegrationTest.java | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) rename spring-rest-simple/src/main/java/org/baeldung/config/{WebConfig.java => MvcConfig.java} (97%) diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest-simple/src/main/java/org/baeldung/config/MvcConfig.java similarity index 97% rename from spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java rename to spring-rest-simple/src/main/java/org/baeldung/config/MvcConfig.java index 191b87a8f2..66bb3eabce 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest-simple/src/main/java/org/baeldung/config/MvcConfig.java @@ -25,9 +25,9 @@ import java.util.List; @Configuration @EnableWebMvc @ComponentScan({ "org.baeldung.web" }) -public class WebConfig implements WebMvcConfigurer { +public class MvcConfig implements WebMvcConfigurer { - public WebConfig() { + public MvcConfig() { super(); } diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java b/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java index 7f78146b84..12fa00eed3 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java +++ b/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java @@ -3,7 +3,7 @@ package org.baeldung.web.controller.status; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.config.WebConfig; +import org.baeldung.config.MvcConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -17,7 +17,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = WebConfig.class) +@ContextConfiguration(classes = MvcConfig.class) @WebAppConfiguration @AutoConfigureWebClient public class ExampleControllerIntegrationTest { diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java b/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java index dfb3ff7a38..25429bcc7a 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java +++ b/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java @@ -10,7 +10,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.config.WebConfig; +import org.baeldung.config.MvcConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -25,7 +25,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = WebConfig.class) +@ContextConfiguration(classes = MvcConfig.class) @WebAppConfiguration @AutoConfigureWebClient public class BazzNewMappingsExampleIntegrationTest { From badc9eb5626d00a0a2fb996f44780b2e3debd9ef Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 23 Jun 2019 20:55:07 +0530 Subject: [PATCH 030/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/spring-boot-actuators --- ...althIndicator.java => DownstreamServiceHealthIndicator.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/{DownstreamServiceReactiveHealthIndicator.java => DownstreamServiceHealthIndicator.java} (87%) diff --git a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java similarity index 87% rename from spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java index 7360def71e..81e77d9c61 100644 --- a/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceReactiveHealthIndicator.java +++ b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/actuator/DownstreamServiceHealthIndicator.java @@ -6,7 +6,7 @@ import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @Component -public class DownstreamServiceReactiveHealthIndicator implements ReactiveHealthIndicator { +public class DownstreamServiceHealthIndicator implements ReactiveHealthIndicator { @Override public Mono health() { From 74f46ef95a78c64c0ba53237f9048f68544d3d2e Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 23 Jun 2019 21:05:41 +0530 Subject: [PATCH 031/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/java-optional --- .../com/baeldung/java8/optional/OptionalUnitTest.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java index bd7943c77b..bf594610bb 100644 --- a/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java +++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java @@ -259,4 +259,15 @@ public class OptionalUnitTest { LOG.debug("Getting default value..."); return "Default Value"; } + +// Uncomment code when code base is compatiable with Java 11 +// @Test +// public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() { +// Optional opt = Optional.of("Baeldung"); +// assertFalse(opt.isEmpty()); +// +// opt = Optional.ofNullable(null); +// assertTrue(opt.isEmpty()); +// } + } \ No newline at end of file From b1ff8e6289108e6af544026e853fc0a0e7281877 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 23 Jun 2019 23:06:32 +0530 Subject: [PATCH 032/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/spring-profiles --- .../org/baeldung/startup/ProfileManager.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 spring-all/src/main/java/org/baeldung/startup/ProfileManager.java diff --git a/spring-all/src/main/java/org/baeldung/startup/ProfileManager.java b/spring-all/src/main/java/org/baeldung/startup/ProfileManager.java new file mode 100644 index 0000000000..41db539265 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/startup/ProfileManager.java @@ -0,0 +1,18 @@ +package org.baeldung.startup; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public class ProfileManager { + + @Autowired + private Environment environment; + + public void getActiveProfiles() { + for (final String profileName : environment.getActiveProfiles()) { + System.out.println("Currently active profile - " + profileName); + } + } +} From 69d6c80a49921bcee01a220e80a7ed32dc6c424a Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 23 Jun 2019 23:32:05 +0530 Subject: [PATCH 033/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/transaction-configuration-with-jpa-and-spring --- .../src/main/java/com/baeldung/config/PersistenceJPAConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java index 9fae34d99e..e202e45b32 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java @@ -39,7 +39,7 @@ public class PersistenceJPAConfig { // beans @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); From 0dc22fbc7af524f051316a158d345332bfc35492 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Mon, 24 Jun 2019 00:16:24 +0530 Subject: [PATCH 034/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/spring-jdbc-jdbctemplate --- .../java/com/baeldung/jdbc/EmployeeDAO.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java index 9ba4ebdb6d..eef085f386 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java @@ -16,6 +16,7 @@ import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils; +import org.springframework.jdbc.core.simple.SimpleJdbcCall; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; @@ -27,6 +28,8 @@ public class EmployeeDAO { private NamedParameterJdbcTemplate namedParameterJdbcTemplate; private SimpleJdbcInsert simpleJdbcInsert; + + private SimpleJdbcCall simpleJdbcCall; @Autowired public void setDataSource(final DataSource dataSource) { @@ -36,7 +39,9 @@ public class EmployeeDAO { namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("EMPLOYEE"); - + + // Commented as the database is H2, change the database and create procedure READ_EMPLOYEE before calling getEmployeeUsingSimpleJdbcCall + //simpleJdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("READ_EMPLOYEE"); } public int getCountOfEmployees() { @@ -110,4 +115,15 @@ public class EmployeeDAO { final int[] updateCounts = namedParameterJdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (:id, :firstName, :lastName, :address)", batch); return updateCounts; } + + public Employee getEmployeeUsingSimpleJdbcCall(int id) { + SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id); + Map out = simpleJdbcCall.execute(in); + + Employee emp = new Employee(); + emp.setFirstName((String) out.get("FIRST_NAME")); + emp.setLastName((String) out.get("LAST_NAME")); + + return emp; + } } From 2e2af71a58fff5ad98068e4c332d72438420e732 Mon Sep 17 00:00:00 2001 From: isaolmez Date: Mon, 24 Jun 2019 23:13:05 +0300 Subject: [PATCH 035/352] BAEL-2981: Updated tests --- .../com/baeldung/handlebars/BasicUsageUnitTest.java | 12 ++++++------ .../baeldung/handlebars/BuiltinHelperUnitTest.java | 12 ++++++------ .../baeldung/handlebars/CustomHelperUnitTest.java | 4 ++-- .../handlebars/ReusingTemplatesUnitTest.java | 4 ++-- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java index bf7afa0fc9..3eb325dbb6 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/BasicUsageUnitTest.java @@ -32,9 +32,9 @@ public class BasicUsageUnitTest { public void whenParameterMapIsSupplied_thenDisplays() throws IOException { Handlebars handlebars = new Handlebars(); Template template = handlebars.compileInline("Hi {{name}}!"); - Map parameterMap = new HashMap<>(); parameterMap.put("name", "Baeldung"); + String templateString = template.apply(parameterMap); assertThat(templateString).isEqualTo("Hi Baeldung!"); @@ -44,9 +44,9 @@ public class BasicUsageUnitTest { public void whenParameterObjectIsSupplied_ThenDisplays() throws IOException { Handlebars handlebars = new Handlebars(); Template template = handlebars.compileInline("Hi {{name}}!"); - Person person = new Person(); person.setName("Baeldung"); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("Hi Baeldung!"); @@ -56,10 +56,10 @@ public class BasicUsageUnitTest { public void whenMultipleParametersAreSupplied_ThenDisplays() throws IOException { Handlebars handlebars = new Handlebars(); Template template = handlebars.compileInline("Hi {{name}}! This is {{topic}}."); - Map parameterMap = new HashMap<>(); parameterMap.put("name", "Baeldung"); parameterMap.put("topic", "Handlebars"); + String templateString = template.apply(parameterMap); assertThat(templateString).isEqualTo("Hi Baeldung! This is Handlebars."); @@ -69,8 +69,8 @@ public class BasicUsageUnitTest { public void whenNoLoaderIsGiven_ThenSearchesClasspath() throws IOException { Handlebars handlebars = new Handlebars(); Template template = handlebars.compile("greeting"); - Person person = getPerson("Baeldung"); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("Hi Baeldung!"); @@ -81,8 +81,8 @@ public class BasicUsageUnitTest { TemplateLoader loader = new ClassPathTemplateLoader("/handlebars", ".html"); Handlebars handlebars = new Handlebars(loader); Template template = handlebars.compile("greeting"); - Person person = getPerson("Baeldung"); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("Hi Baeldung!"); @@ -94,8 +94,8 @@ public class BasicUsageUnitTest { TemplateLoader secondLoader = new ClassPathTemplateLoader("/templates", ".html"); Handlebars handlebars = new Handlebars().with(firstLoader, secondLoader); Template template = handlebars.compile("greeting"); - Person person = getPerson("Baeldung"); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("Hi Baeldung!"); diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java index 84529a74ce..6749f7fe0a 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/BuiltinHelperUnitTest.java @@ -22,9 +22,9 @@ public class BuiltinHelperUnitTest { public void whenUsedWith_ThenContextChanges() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("with"); - Person person = getPerson("Baeldung"); person.getAddress().setStreet("World"); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("\n

I live in World

\n"); @@ -34,9 +34,9 @@ public class BuiltinHelperUnitTest { public void whenUsedWithMustacheStyle_ThenContextChanges() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("with_mustache"); - Person person = getPerson("Baeldung"); person.getAddress().setStreet("World"); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("\n

I live in World

\n"); @@ -46,12 +46,12 @@ public class BuiltinHelperUnitTest { public void whenUsedEach_ThenIterates() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("each"); - Person person = getPerson("Baeldung"); Person friend1 = getPerson("Java"); Person friend2 = getPerson("Spring"); person.getFriends().add(friend1); person.getFriends().add(friend2); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("\nJava is my friend.\n" @@ -62,12 +62,12 @@ public class BuiltinHelperUnitTest { public void whenUsedEachMustacheStyle_ThenIterates() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("each_mustache"); - Person person = getPerson("Baeldung"); Person friend1 = getPerson("Java"); Person friend2 = getPerson("Spring"); person.getFriends().add(friend1); person.getFriends().add(friend2); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("\nJava is my friend.\n" @@ -78,9 +78,9 @@ public class BuiltinHelperUnitTest { public void whenUsedIf_ThenPutsCondition() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("if"); - Person person = getPerson("Baeldung"); person.setBusy(true); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("\n

Baeldung is busy.

\n"); @@ -90,9 +90,9 @@ public class BuiltinHelperUnitTest { public void whenUsedIfMustacheStyle_ThenPutsCondition() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("if_mustache"); - Person person = getPerson("Baeldung"); person.setBusy(true); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("\n

Baeldung is busy.

\n"); diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java index 6966d69cef..a3c6667654 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/CustomHelperUnitTest.java @@ -31,8 +31,8 @@ public class CustomHelperUnitTest { } }); Template template = handlebars.compile("person"); - Person person = getPerson("Baeldung"); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("Baeldung - busy"); @@ -43,8 +43,8 @@ public class CustomHelperUnitTest { Handlebars handlebars = new Handlebars(templateLoader); handlebars.registerHelpers(new HelperSource()); Template template = handlebars.compile("person"); - Person person = getPerson("Baeldung"); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("Baeldung - busy"); diff --git a/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java b/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java index 8741294703..36f78f486e 100644 --- a/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/handlebars/ReusingTemplatesUnitTest.java @@ -22,9 +22,9 @@ public class ReusingTemplatesUnitTest { public void whenOtherTemplateIsReferenced_ThenCanReuse() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("page"); - Person person = new Person(); person.setName("Baeldung"); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("

Hi Baeldung!

\n

This is the page Baeldung

"); @@ -34,9 +34,9 @@ public class ReusingTemplatesUnitTest { public void whenBlockIsDefined_ThenCanOverrideWithPartial() throws IOException { Handlebars handlebars = new Handlebars(templateLoader); Template template = handlebars.compile("simplemessage"); - Person person = new Person(); person.setName("Baeldung"); + String templateString = template.apply(person); assertThat(templateString).isEqualTo("\n\n" From 9ee237c69c7208cdc27b62628a891a92827bee89 Mon Sep 17 00:00:00 2001 From: Johan Janssen Date: Wed, 26 Jun 2019 20:33:48 +0200 Subject: [PATCH 036/352] Breaking out of nested loops (#7196) * Added Maven profiles example. * Added break examples. --- .../com/baeldung/breakloop/LoopBreaking.java | 47 +++++++++++++++++++ .../breakloop/LoopBreakingUnitTest.java | 25 ++++++++++ 2 files changed, 72 insertions(+) create mode 100644 core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/breakloop/LoopBreaking.java create mode 100644 core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/breakloop/LoopBreakingUnitTest.java diff --git a/core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/breakloop/LoopBreaking.java b/core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/breakloop/LoopBreaking.java new file mode 100644 index 0000000000..90b99f57cb --- /dev/null +++ b/core-java-modules/core-java-lang-syntax/src/main/java/com/baeldung/breakloop/LoopBreaking.java @@ -0,0 +1,47 @@ +package com.baeldung.breakloop; + +public class LoopBreaking { + + public String simpleBreak() { + String result = ""; + for (int outerCounter = 0; outerCounter < 2; outerCounter++) { + result += "outer" + outerCounter; + for (int innerCounter = 0; innerCounter < 2; innerCounter++) { + result += "inner" + innerCounter; + if (innerCounter == 0) { + break; + } + } + } + return result; + } + + public String labelBreak() { + String result = ""; + myBreakLabel: + for (int outerCounter = 0; outerCounter < 2; outerCounter++) { + result += "outer" + outerCounter; + for (int innerCounter = 0; innerCounter < 2; innerCounter++) { + result += "inner" + innerCounter; + if (innerCounter == 0) { + break myBreakLabel; + } + } + } + return result; + } + + public String usingReturn() { + String result = ""; + for (int outerCounter = 0; outerCounter < 2; outerCounter++) { + result += "outer" + outerCounter; + for (int innerCounter = 0; innerCounter < 2; innerCounter++) { + result += "inner" + innerCounter; + if (innerCounter == 0) { + return result; + } + } + } + return "failed"; + } +} diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/breakloop/LoopBreakingUnitTest.java b/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/breakloop/LoopBreakingUnitTest.java new file mode 100644 index 0000000000..c4b6573c86 --- /dev/null +++ b/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/breakloop/LoopBreakingUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.breakloop; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class LoopBreakingUnitTest { + + private LoopBreaking loopBreaking = new LoopBreaking(); + + @Test + void whenUsingBreak_shouldBreakInnerLoop() { + assertEquals("outer0inner0outer1inner0", loopBreaking.simpleBreak()); + } + + @Test + void whenUsingLabeledBreak_shouldBreakInnerLoopAndOuterLoop() { + assertEquals("outer0inner0", loopBreaking.labelBreak()); + } + + @Test + void whenUsingReturn_shouldBreakInnerLoopAndOuterLoop() { + assertEquals("outer0inner0", loopBreaking.usingReturn()); + } +} \ No newline at end of file From 21cb183c1a80fbd79d80e0d0c68c58469cff692f Mon Sep 17 00:00:00 2001 From: Drazen Nikolic Date: Wed, 26 Jun 2019 20:58:08 +0200 Subject: [PATCH 037/352] BAEL-2486: Changes after the editor's review. (#7199) (cherry picked from commit 00cd1360e417a4f9be00ae6648294cc38a06c1c8) --- .../baeldung/tailablecursor/service/InfoLogsCounter.java | 4 ++-- .../baeldung/tailablecursor/service/WarnLogsCounter.java | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/InfoLogsCounter.java b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/InfoLogsCounter.java index b30eba0b25..29301bffec 100644 --- a/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/InfoLogsCounter.java +++ b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/InfoLogsCounter.java @@ -18,8 +18,8 @@ public class InfoLogsCounter implements LogsCounter { public InfoLogsCounter(LogsRepository repository) { Flux stream = repository.findByLevel(LogLevel.INFO); - this.subscription = stream.subscribe(l -> { - log.info("INFO log received: " + l); + this.subscription = stream.subscribe(logEntity -> { + log.info("INFO log received: " + logEntity); counter.incrementAndGet(); }); } diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/WarnLogsCounter.java b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/WarnLogsCounter.java index b21f61fa88..2dff8e8e40 100644 --- a/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/WarnLogsCounter.java +++ b/spring-5-data-reactive/src/main/java/com/baeldung/tailablecursor/service/WarnLogsCounter.java @@ -3,7 +3,7 @@ package com.baeldung.tailablecursor.service; import com.baeldung.tailablecursor.domain.Log; import com.baeldung.tailablecursor.domain.LogLevel; import lombok.extern.slf4j.Slf4j; -import org.springframework.data.mongodb.core.ReactiveMongoTemplate; +import org.springframework.data.mongodb.core.ReactiveMongoOperations; import reactor.core.Disposable; import reactor.core.publisher.Flux; @@ -21,10 +21,10 @@ public class WarnLogsCounter implements LogsCounter { private final AtomicInteger counter = new AtomicInteger(); private final Disposable subscription; - public WarnLogsCounter(ReactiveMongoTemplate template) { + public WarnLogsCounter(ReactiveMongoOperations template) { Flux stream = template.tail(query(where(LEVEL_FIELD_NAME).is(LogLevel.WARN)), Log.class); - subscription = stream.subscribe(l -> { - log.warn("WARN log received: " + l); + subscription = stream.subscribe(logEntity -> { + log.warn("WARN log received: " + logEntity); counter.incrementAndGet(); }); } From 0c7c689d3b619c448fda1731ac9e2c1f367314df Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 26 Jun 2019 22:07:16 +0200 Subject: [PATCH 038/352] Add parallel-collectors samples (#7187) * Add ParallelCollectorsTest * Add dependency * Fix naming --- libraries-2/pom.xml | 5 + .../ParallelCollectorsUnitTest.java | 168 ++++++++++++++++++ 2 files changed, 173 insertions(+) create mode 100644 libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index c18b4aae64..f7be463f1a 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -30,6 +30,11 @@ + + com.pivovarit + parallel-collectors + 1.1.0 + org.assertj assertj-core diff --git a/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java b/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java new file mode 100644 index 0000000000..adc753a8ad --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java @@ -0,0 +1,168 @@ +package com.baeldung.parallel_collectors; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +import static com.pivovarit.collectors.ParallelCollectors.parallel; +import static com.pivovarit.collectors.ParallelCollectors.parallelOrdered; +import static com.pivovarit.collectors.ParallelCollectors.parallelToCollection; +import static com.pivovarit.collectors.ParallelCollectors.parallelToList; +import static com.pivovarit.collectors.ParallelCollectors.parallelToMap; +import static com.pivovarit.collectors.ParallelCollectors.parallelToStream; + +public class ParallelCollectorsUnitTest { + + @Test + public void shouldProcessInParallelWithStreams() { + List ids = Arrays.asList(1, 2, 3); + + List results = ids.parallelStream() + .map(i -> fetchById(i)) + .collect(Collectors.toList()); + + System.out.println(results); + } + + @Test + public void shouldProcessInParallelWithParallelCollectors() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + CompletableFuture> results = ids.stream() + .collect(parallelToList(i -> fetchById(i), executor, 4)); + + System.out.println(results.join()); + } + + @Test + public void shouldCollectToList() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + List results = ids.stream() + .collect(parallelToList(i -> fetchById(i), executor, 4)) + .join(); + + System.out.println(results); // [user-1, user-2, user-3] + } + + @Test + public void shouldCollectToCollection() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + List results = ids.stream() + .collect(parallelToCollection(i -> fetchById(i), LinkedList::new, executor, 4)) + .join(); + + System.out.println(results); // [user-1, user-2, user-3] + } + + @Test + public void shouldCollectToStream() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + Map> results = ids.stream() + .collect(parallelToStream(i -> fetchById(i), executor, 4)) + .thenApply(stream -> stream.collect(Collectors.groupingBy(i -> i.length()))) + .join(); + + System.out.println(results); // [user-1, user-2, user-3] + } + + @Test + public void shouldStreamInCompletionOrder() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + ids.stream() + .collect(parallel(i -> fetchByIdWithRandomDelay(i), executor, 4)) + .forEach(System.out::println); + } + + @Test + public void shouldStreamInOriginalOrder() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + ids.stream() + .collect(parallelOrdered(i -> fetchByIdWithRandomDelay(i), executor, 4)) + .forEach(System.out::println); + } + + @Test + public void shouldCollectToMap() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + Map results = ids.stream() + .collect(parallelToMap(i -> i, i -> fetchById(i), executor, 4)) + .join(); + + System.out.println(results); // {1=user-1, 2=user-2, 3=user-3} + } + + @Test + public void shouldCollectToTreeMap() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + Map results = ids.stream() + .collect(parallelToMap(i -> i, i -> fetchById(i), TreeMap::new, executor, 4)) + .join(); + + System.out.println(results); // {1=user-1, 2=user-2, 3=user-3} + } + + @Test + public void shouldCollectToTreeMapAndResolveClashes() { + ExecutorService executor = Executors.newFixedThreadPool(10); + + List ids = Arrays.asList(1, 2, 3); + + Map results = ids.stream() + .collect(parallelToMap(i -> i, i -> fetchById(i), TreeMap::new, (s1, s2) -> s1, executor, 4)) + .join(); + + System.out.println(results); // {1=user-1, 2=user-2, 3=user-3} + } + + private static String fetchById(int id) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // ignore shamelessly + } + + return "user-" + id; + } + + private static String fetchByIdWithRandomDelay(int id) { + try { + Thread.sleep(ThreadLocalRandom.current().nextInt(1000)); + } catch (InterruptedException e) { + // ignore shamelessly + } + + return "user-" + id; + } +} From e6e2510a5675fb380b0fd981c7928e0e7de7721c Mon Sep 17 00:00:00 2001 From: antmordel Date: Thu, 27 Jun 2019 10:01:46 +0100 Subject: [PATCH 039/352] Fixed problem with the package --- .../intstreams}/IntStreamsConversionsUnitTest.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename java-streams-2/src/test/java/com/baeldung/{convert.instreams => convert/intstreams}/IntStreamsConversionsUnitTest.java (100%) diff --git a/java-streams-2/src/test/java/com/baeldung/convert.instreams/IntStreamsConversionsUnitTest.java b/java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java similarity index 100% rename from java-streams-2/src/test/java/com/baeldung/convert.instreams/IntStreamsConversionsUnitTest.java rename to java-streams-2/src/test/java/com/baeldung/convert/intstreams/IntStreamsConversionsUnitTest.java From 2e783b0f22e6f3e300ab337cbdb45cca3f86d8bb Mon Sep 17 00:00:00 2001 From: Amy DeGregorio Date: Thu, 27 Jun 2019 06:33:46 -0400 Subject: [PATCH 040/352] BAEL 3015 (#7200) * BAEL-3015 * BAEL-3015 remove tabs --- .../main/resources/templates/enums/view.html | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/spring-thymeleaf-2/src/main/resources/templates/enums/view.html b/spring-thymeleaf-2/src/main/resources/templates/enums/view.html index 5f473886d6..f766f66277 100644 --- a/spring-thymeleaf-2/src/main/resources/templates/enums/view.html +++ b/spring-thymeleaf-2/src/main/resources/templates/enums/view.html @@ -5,26 +5,26 @@ Enums in Thymeleaf -

View Widget

-
- - -
-
- - -
-
- This color screams danger. -
-
- Green is for go. -
-
- Alert - Warning - Caution - All Good -
+

View Widget

+
+ + +
+
+ + +
+
+ This color screams danger. +
+
+ Green is for go. +
+
+ Alert + Warning + Caution + All Good +
\ No newline at end of file From 649c65199ff9082bb92ac349bd226e60fecdf250 Mon Sep 17 00:00:00 2001 From: Juan Vaccari Date: Thu, 27 Jun 2019 17:39:11 +0100 Subject: [PATCH 041/352] BAEL-2928 - change methods name to follow Java conventions --- spring-all/src/main/java/org/baeldung/primary/Config.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-all/src/main/java/org/baeldung/primary/Config.java b/spring-all/src/main/java/org/baeldung/primary/Config.java index b39f2b9db3..bdcfe019e6 100644 --- a/spring-all/src/main/java/org/baeldung/primary/Config.java +++ b/spring-all/src/main/java/org/baeldung/primary/Config.java @@ -10,13 +10,13 @@ import org.springframework.context.annotation.Primary; public class Config { @Bean - public Employee JohnEmployee(){ + public Employee johnEmployee(){ return new Employee("John"); } @Bean @Primary - public Employee TonyEmployee(){ + public Employee tonyEmployee(){ return new Employee("Tony"); } } From 67a99828f15ba718866618f2b6ede56da474ef10 Mon Sep 17 00:00:00 2001 From: Lukasz Rys Date: Thu, 27 Jun 2019 22:50:12 +0200 Subject: [PATCH 042/352] Feature/bael 2515 override properties (#7165) * [ BAEL-2515] : Add override properties article * [ BAEL-2515] : Rename tests * [ BAEL-2515 ]: Remove hyperlink from README --- spring-boot-testing/README.MD | 1 + .../overrideproperties/Application.java | 11 +++++++ .../resolver/PropertySourceResolver.java | 24 +++++++++++++++ ...PropertySourceResolverIntegrationTest.java | 27 +++++++++++++++++ ...PropertySourceResolverIntegrationTest.java | 29 +++++++++++++++++++ .../PropertyOverrideContextInitializer.java | 17 +++++++++++ ...PropertySourceResolverIntegrationTest.java | 26 +++++++++++++++++ ...PropertySourceResolverIntegrationTest.java | 27 +++++++++++++++++ .../resources/application-test.properties | 5 ++++ .../src/test/resources/application.properties | 7 +++++ .../context-override-application.properties | 1 + 11 files changed, 175 insertions(+) create mode 100644 spring-boot-testing/src/main/java/com/baeldung/overrideproperties/Application.java create mode 100644 spring-boot-testing/src/main/java/com/baeldung/overrideproperties/resolver/PropertySourceResolver.java create mode 100644 spring-boot-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java create mode 100644 spring-boot-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java create mode 100644 spring-boot-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java create mode 100644 spring-boot-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java create mode 100644 spring-boot-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java create mode 100644 spring-boot-testing/src/test/resources/application-test.properties create mode 100644 spring-boot-testing/src/test/resources/application.properties create mode 100644 spring-boot-testing/src/test/resources/context-override-application.properties diff --git a/spring-boot-testing/README.MD b/spring-boot-testing/README.MD index 99d7db5743..d303179ef6 100644 --- a/spring-boot-testing/README.MD +++ b/spring-boot-testing/README.MD @@ -6,3 +6,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Testing with Spring and Spock](https://www.baeldung.com/spring-spock-testing) - [Exclude Auto-Configuration Classes in Spring Boot Tests](https://www.baeldung.com/spring-boot-exclude-auto-configuration-test) - [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level) +- [Override properties in Spring] diff --git a/spring-boot-testing/src/main/java/com/baeldung/overrideproperties/Application.java b/spring-boot-testing/src/main/java/com/baeldung/overrideproperties/Application.java new file mode 100644 index 0000000000..ac215bf78e --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/overrideproperties/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.overrideproperties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-testing/src/main/java/com/baeldung/overrideproperties/resolver/PropertySourceResolver.java b/spring-boot-testing/src/main/java/com/baeldung/overrideproperties/resolver/PropertySourceResolver.java new file mode 100644 index 0000000000..074092b7df --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/overrideproperties/resolver/PropertySourceResolver.java @@ -0,0 +1,24 @@ +package com.baeldung.overrideproperties.resolver; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class PropertySourceResolver { + + private final String firstProperty; + private final String secondProperty; + + public PropertySourceResolver(@Value("${example.firstProperty}") String firstProperty, @Value("${example.secondProperty}") String secondProperty) { + this.firstProperty = firstProperty; + this.secondProperty = secondProperty; + } + + public String getFirstProperty() { + return firstProperty; + } + + public String getSecondProperty() { + return secondProperty; + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java new file mode 100644 index 0000000000..9b692edd7b --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.overrideproperties; + +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@ContextConfiguration(initializers = PropertyOverrideContextInitializer.class, classes = Application.class) +public class ContextPropertySourceResolverIntegrationTest { + + @Autowired private PropertySourceResolver propertySourceResolver; + + @Test + public void shouldContext_overridePropertyValues() { + final String firstProperty = propertySourceResolver.getFirstProperty(); + final String secondProperty = propertySourceResolver.getSecondProperty(); + + assertEquals(PropertyOverrideContextInitializer.PROPERTY_FIRST_VALUE, firstProperty); + assertEquals("contextFile", secondProperty); + } + +} \ No newline at end of file diff --git a/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java new file mode 100644 index 0000000000..95d83420b7 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java @@ -0,0 +1,29 @@ +package com.baeldung.overrideproperties; + +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest +@ActiveProfiles("test") +public class ProfilePropertySourceResolverIntegrationTest { + + @Autowired private PropertySourceResolver propertySourceResolver; + + @Test + public void shouldProfiledProperty_overridePropertyValues() { + final String firstProperty = propertySourceResolver.getFirstProperty(); + final String secondProperty = propertySourceResolver.getSecondProperty(); + + assertEquals("profile", firstProperty); + assertEquals("file", secondProperty); + } + +} \ No newline at end of file diff --git a/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java b/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java new file mode 100644 index 0000000000..a8c4267c5c --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java @@ -0,0 +1,17 @@ +package com.baeldung.overrideproperties; + +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.test.context.support.TestPropertySourceUtils; + +public class PropertyOverrideContextInitializer implements ApplicationContextInitializer { + + static final String PROPERTY_FIRST_VALUE = "contextClass"; + + @Override + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + TestPropertySourceUtils.addInlinedPropertiesToEnvironment(configurableApplicationContext, "example.firstProperty=" + PROPERTY_FIRST_VALUE); + + TestPropertySourceUtils.addPropertiesFilesToEnvironment(configurableApplicationContext, "context-override-application.properties"); + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java new file mode 100644 index 0000000000..573a46dd5f --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.overrideproperties; + +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(properties = { "example.firstProperty=annotation" }) +public class SpringBootPropertySourceResolverIntegrationTest { + + @Autowired private PropertySourceResolver propertySourceResolver; + + @Test + public void shouldSpringBootTestAnnotation_overridePropertyValues() { + final String firstProperty = propertySourceResolver.getFirstProperty(); + final String secondProperty = propertySourceResolver.getSecondProperty(); + + Assert.assertEquals("annotation", firstProperty); + Assert.assertEquals("file", secondProperty); + } + +} \ No newline at end of file diff --git a/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java new file mode 100644 index 0000000000..c724713854 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.overrideproperties; + +import com.baeldung.overrideproperties.resolver.PropertySourceResolver; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class TestResourcePropertySourceResolverIntegrationTest { + + @Autowired private PropertySourceResolver propertySourceResolver; + + @Test + public void shouldTestResourceFile_overridePropertyValues() { + final String firstProperty = propertySourceResolver.getFirstProperty(); + final String secondProperty = propertySourceResolver.getSecondProperty(); + + assertEquals("file", firstProperty); + assertEquals("file", secondProperty); + } + +} \ No newline at end of file diff --git a/spring-boot-testing/src/test/resources/application-test.properties b/spring-boot-testing/src/test/resources/application-test.properties new file mode 100644 index 0000000000..da187d8086 --- /dev/null +++ b/spring-boot-testing/src/test/resources/application-test.properties @@ -0,0 +1,5 @@ +# test properties +spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration + +# override properties +example.firstProperty=profile \ No newline at end of file diff --git a/spring-boot-testing/src/test/resources/application.properties b/spring-boot-testing/src/test/resources/application.properties new file mode 100644 index 0000000000..e71b24a4e1 --- /dev/null +++ b/spring-boot-testing/src/test/resources/application.properties @@ -0,0 +1,7 @@ +# security +spring.security.user.name=john +spring.security.user.password=123 + +# override properties +example.firstProperty=file +example.secondProperty=file \ No newline at end of file diff --git a/spring-boot-testing/src/test/resources/context-override-application.properties b/spring-boot-testing/src/test/resources/context-override-application.properties new file mode 100644 index 0000000000..c39e5d3966 --- /dev/null +++ b/spring-boot-testing/src/test/resources/context-override-application.properties @@ -0,0 +1 @@ +example.secondProperty=contextFile \ No newline at end of file From ad0ff16de9800ecec01a13b370a3b756f130af32 Mon Sep 17 00:00:00 2001 From: Chandra Prakash Date: Thu, 27 Jun 2019 18:03:17 -0400 Subject: [PATCH 043/352] Update java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java Co-Authored-By: KevinGilmore --- .../main/java/com/baeldung/date/validation/DateValidator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java index 74c1bf7445..b774edab43 100644 --- a/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java +++ b/java-dates-2/src/main/java/com/baeldung/date/validation/DateValidator.java @@ -1,5 +1,5 @@ package com.baeldung.date.validation; public interface DateValidator { - public boolean isValid(String dateStr); + boolean isValid(String dateStr); } From 3d50c203a630fb42652ad1898e50b0d50eaa2e70 Mon Sep 17 00:00:00 2001 From: gpq5 Date: Fri, 28 Jun 2019 10:15:05 +0530 Subject: [PATCH 044/352] made changes as per review comments --- .../json/compare/JsonCompareUnitTest.java | 46 ++++++++++--------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java index 05b89abc09..2f2c18e248 100644 --- a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java +++ b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.jackson.json.compare; -import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; @@ -24,7 +25,7 @@ public class JsonCompareUnitTest { JsonNode actualObj1 = mapper.readTree(s1); JsonNode actualObj2 = mapper.readTree(s2); - assertTrue(actualObj1.equals(actualObj2)); + assertEquals(actualObj1, actualObj2); } @@ -38,7 +39,7 @@ public class JsonCompareUnitTest { JsonNode actualObj1 = mapper.readTree(s1); JsonNode actualObj2 = mapper.readTree(s2); - assertTrue(actualObj1.equals(actualObj2)); + assertEquals(actualObj1, actualObj2); } @@ -52,7 +53,7 @@ public class JsonCompareUnitTest { JsonNode actualObj1 = mapper.readTree(s1); JsonNode actualObj2 = mapper.readTree(s2); - assertTrue(actualObj1.equals(actualObj2)); + assertEquals(actualObj1, actualObj2); } @@ -65,26 +66,27 @@ public class JsonCompareUnitTest { JsonNode actualObj1 = mapper.readTree(s1); JsonNode actualObj2 = mapper.readTree(s2); - Comparator cmp = new Comparator() { - @Override - public int compare(JsonNode o1, JsonNode o2) { - if (o1.equals(o2)) { - return 0; - } - if ((o1 instanceof NumericNode) && (o2 instanceof NumericNode)) { - double d1 = ((NumericNode) o1).asDouble(); - double d2 = ((NumericNode) o2).asDouble(); - if (d1 == d2) { - return 0; - } - } - return 1; - } - }; + NumericNodeComparator cmp = new NumericNodeComparator(); - assertFalse(actualObj1.equals(actualObj2)); + assertNotEquals(actualObj1, actualObj2); assertTrue(actualObj1.equals(cmp, actualObj2)); } - + + public class NumericNodeComparator implements Comparator { + @Override + public int compare(JsonNode o1, JsonNode o2) { + if (o1.equals(o2)) { + return 0; + } + if ((o1 instanceof NumericNode) && (o2 instanceof NumericNode)) { + Double d1 = ((NumericNode) o1).asDouble(); + Double d2 = ((NumericNode) o2).asDouble(); + if (d1.equals(d2)) { + return 0; + } + } + return 1; + } + } } From 72c39bab4c63f01da9703b079d0f099f67ef0d17 Mon Sep 17 00:00:00 2001 From: Ariel Papuga Date: Mon, 24 Jun 2019 23:09:44 +0200 Subject: [PATCH 045/352] BAEL-2921 Review: creation of spring-core-2 module --- pom.xml | 1 + spring-core-2/pom.xml | 60 +++++++++++++++++++ .../baeldung/getbean/AnnotationConfig.java | 0 .../main/java/com/baeldung/getbean/Lion.java | 0 .../main/java/com/baeldung/getbean/Tiger.java | 0 .../getbean/GetBeanByNameAndTypeUnitTest.java | 0 .../getbean/GetBeanByNameUnitTest.java | 4 +- ...NameWithConstructorParametersUnitTest.java | 18 ++++-- .../getbean/GetBeanByTypeUnitTest.java | 0 ...TypeWithConstructorParametersUnitTest.java | 0 10 files changed, 75 insertions(+), 8 deletions(-) create mode 100644 spring-core-2/pom.xml rename {spring-core => spring-core-2}/src/main/java/com/baeldung/getbean/AnnotationConfig.java (100%) rename {spring-core => spring-core-2}/src/main/java/com/baeldung/getbean/Lion.java (100%) rename {spring-core => spring-core-2}/src/main/java/com/baeldung/getbean/Tiger.java (100%) rename {spring-core => spring-core-2}/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java (100%) rename {spring-core => spring-core-2}/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java (91%) rename {spring-core => spring-core-2}/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java (70%) rename {spring-core => spring-core-2}/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java (100%) rename {spring-core => spring-core-2}/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java (100%) diff --git a/pom.xml b/pom.xml index 9760e06bc1..aae8f500bb 100644 --- a/pom.xml +++ b/pom.xml @@ -659,6 +659,7 @@ spring-cloud-data-flow spring-core + spring-core-2 spring-cucumber spring-data-rest diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml new file mode 100644 index 0000000000..8e4c539e3b --- /dev/null +++ b/spring-core-2/pom.xml @@ -0,0 +1,60 @@ + + + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + + 4.0.0 + + spring-core-2 + + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-api + ${junit.jupiter.version} + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.1 + + + + + + 5.1.4.RELEASE + 5.0.2 + + + \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/getbean/AnnotationConfig.java b/spring-core-2/src/main/java/com/baeldung/getbean/AnnotationConfig.java similarity index 100% rename from spring-core/src/main/java/com/baeldung/getbean/AnnotationConfig.java rename to spring-core-2/src/main/java/com/baeldung/getbean/AnnotationConfig.java diff --git a/spring-core/src/main/java/com/baeldung/getbean/Lion.java b/spring-core-2/src/main/java/com/baeldung/getbean/Lion.java similarity index 100% rename from spring-core/src/main/java/com/baeldung/getbean/Lion.java rename to spring-core-2/src/main/java/com/baeldung/getbean/Lion.java diff --git a/spring-core/src/main/java/com/baeldung/getbean/Tiger.java b/spring-core-2/src/main/java/com/baeldung/getbean/Tiger.java similarity index 100% rename from spring-core/src/main/java/com/baeldung/getbean/Tiger.java rename to spring-core-2/src/main/java/com/baeldung/getbean/Tiger.java diff --git a/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java similarity index 100% rename from spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java rename to spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameAndTypeUnitTest.java diff --git a/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java similarity index 91% rename from spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java rename to spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java index 70a135b314..4d6d77e39d 100644 --- a/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java +++ b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameUnitTest.java @@ -21,9 +21,9 @@ class GetBeanByNameUnitTest { @Test void whenGivenExistingBeanName_shouldReturnThatBean() { - Object requestedBean = context.getBean("lion"); + Object lion = context.getBean("lion"); - assertEquals(requestedBean.getClass(), Lion.class); + assertEquals(lion.getClass(), Lion.class); } @Test diff --git a/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java similarity index 70% rename from spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java rename to spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java index 4ac8c1ac13..32d37e4ff2 100644 --- a/spring-core/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java +++ b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByNameWithConstructorParametersUnitTest.java @@ -19,14 +19,20 @@ class GetBeanByNameWithConstructorParametersUnitTest { context = new AnnotationConfigApplicationContext(AnnotationConfig.class); } + @Test + void whenGivenCorrectName_thenShouldReturnBeanWithSpecifiedName() { + Tiger tiger = (Tiger) context.getBean("tiger", "Siberian"); + + assertEquals("Siberian", tiger.getName()); + } + @Test void whenGivenCorrectNameOrAlias_shouldReturnBeanWithSpecifiedName() { - Tiger tiger = (Tiger) context.getBean("tiger", "Cutie"); - Tiger tigerSecond = (Tiger) context.getBean("tiger", "Striped"); - Tiger tigerViaAlias = (Tiger) context.getBean("kitty", "Siberian"); - assertEquals("Cutie", tiger.getName()); - assertEquals("Striped", tigerSecond.getName()); - assertEquals("Siberian", tigerViaAlias.getName()); + Tiger tiger = (Tiger) context.getBean("tiger", "Siberian"); + Tiger secondTiger = (Tiger) context.getBean("tiger", "Striped"); + + assertEquals("Siberian", tiger.getName()); + assertEquals("Striped", secondTiger.getName()); } @Test diff --git a/spring-core/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java similarity index 100% rename from spring-core/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java rename to spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByTypeUnitTest.java diff --git a/spring-core/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java b/spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java similarity index 100% rename from spring-core/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java rename to spring-core-2/src/test/java/com/baeldung/getbean/GetBeanByTypeWithConstructorParametersUnitTest.java From 1c5e02d4d1a4ece73519533d55179e07330e9a50 Mon Sep 17 00:00:00 2001 From: Eric Martin Date: Fri, 28 Jun 2019 19:48:04 -0500 Subject: [PATCH 046/352] Update pom.xml Tabs/spaces. Added to integration profile. --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index aae8f500bb..d535ca87a5 100644 --- a/pom.xml +++ b/pom.xml @@ -659,7 +659,7 @@ spring-cloud-data-flow spring-core - spring-core-2 + spring-core-2 spring-cucumber spring-data-rest @@ -1324,6 +1324,7 @@ spring-cloud-data-flow spring-core + spring-core-2 spring-cucumber spring-data-rest From 2235c2e7800661bba9b9e15fc00395811abf1b5c Mon Sep 17 00:00:00 2001 From: Laurentiu Delcea Date: Sat, 29 Jun 2019 14:51:36 +0300 Subject: [PATCH 047/352] Convert tab to spaces (#7206) --- libraries-server/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml index 873cca9b9b..72794729a5 100644 --- a/libraries-server/pom.xml +++ b/libraries-server/pom.xml @@ -65,7 +65,7 @@ ${junit.version} test
- + org.apache.tomcat @@ -120,8 +120,8 @@ 4.1 8.5.24 4.3.1 - 1.2.0 - 2.3.1 + 1.2.0 + 2.3.1 \ No newline at end of file From cf4b0e2129f1db7859fd4c25af542cdced0aa366 Mon Sep 17 00:00:00 2001 From: Pavan Shankar Koli Date: Sat, 29 Jun 2019 18:53:11 +0530 Subject: [PATCH 048/352] BAEL-2578 Disabling auto configuration --- .../spring-data-jpa/README.md | 3 ++ .../spring-data-jpa/pom.xml | 50 +++++++++++++++++++ .../java/com/baeldung/jpa/SpringDataJPA.java | 15 ++++++ .../src/main/resources/application.properties | 1 + .../src/main/resources/logback.xml | 13 +++++ .../jpa/SpringDataJPAIntegrationTest.java | 26 ++++++++++ .../spring-data-mongodb/README.md | 4 ++ .../spring-data-mongodb/pom.xml | 43 ++++++++++++++++ .../baeldung/mongodb/SpringDataMongoDB.java | 15 ++++++ .../src/main/resources/application.properties | 1 + .../src/main/resources/logback.xml | 13 +++++ .../SpringDataMongoDBIntegrationTest.java | 25 ++++++++++ .../spring-data-redis/README.md | 4 ++ .../spring-data-redis/pom.xml | 43 ++++++++++++++++ .../com/baeldung/redis/SpringDataRedis.java | 14 ++++++ .../src/main/resources/application.properties | 1 + .../src/main/resources/logback.xml | 13 +++++ .../redis/SpringDataRedisIntegrationTest.java | 25 ++++++++++ 18 files changed, 309 insertions(+) create mode 100644 spring-data-disable-auto-configuration/spring-data-jpa/README.md create mode 100644 spring-data-disable-auto-configuration/spring-data-jpa/pom.xml create mode 100644 spring-data-disable-auto-configuration/spring-data-jpa/src/main/java/com/baeldung/jpa/SpringDataJPA.java create mode 100644 spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/application.properties create mode 100644 spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/logback.xml create mode 100644 spring-data-disable-auto-configuration/spring-data-jpa/src/test/java/com/baeldung/jpa/SpringDataJPAIntegrationTest.java create mode 100644 spring-data-disable-auto-configuration/spring-data-mongodb/README.md create mode 100644 spring-data-disable-auto-configuration/spring-data-mongodb/pom.xml create mode 100644 spring-data-disable-auto-configuration/spring-data-mongodb/src/main/java/com/baeldung/mongodb/SpringDataMongoDB.java create mode 100644 spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/application.properties create mode 100644 spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/logback.xml create mode 100644 spring-data-disable-auto-configuration/spring-data-mongodb/src/test/java/com/baeldung/mongodb/SpringDataMongoDBIntegrationTest.java create mode 100644 spring-data-disable-auto-configuration/spring-data-redis/README.md create mode 100644 spring-data-disable-auto-configuration/spring-data-redis/pom.xml create mode 100644 spring-data-disable-auto-configuration/spring-data-redis/src/main/java/com/baeldung/redis/SpringDataRedis.java create mode 100644 spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/application.properties create mode 100644 spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/logback.xml create mode 100644 spring-data-disable-auto-configuration/spring-data-redis/src/test/java/com/baeldung/redis/SpringDataRedisIntegrationTest.java diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/README.md b/spring-data-disable-auto-configuration/spring-data-jpa/README.md new file mode 100644 index 0000000000..23117c9903 --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-jpa/README.md @@ -0,0 +1,3 @@ +This module is for Jira BAEL-2578 + +### Relevant Articles: diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/pom.xml b/spring-data-disable-auto-configuration/spring-data-jpa/pom.xml new file mode 100644 index 0000000000..db431fb7fa --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-jpa/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + com.baeldung + spring-data-jpa + 0.0.1-SNAPSHOT + spring-data-jpa + jar + Spring Data with JPA + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + 2.1.6.RELEASE + + + + com.h2database + h2 + 1.4.197 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/src/main/java/com/baeldung/jpa/SpringDataJPA.java b/spring-data-disable-auto-configuration/spring-data-jpa/src/main/java/com/baeldung/jpa/SpringDataJPA.java new file mode 100644 index 0000000000..bec1b18010 --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-jpa/src/main/java/com/baeldung/jpa/SpringDataJPA.java @@ -0,0 +1,15 @@ +package com.baeldung.jpa; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; + +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +public class SpringDataJPA { + + public static void main(String[] args) { + SpringApplication.run(SpringDataJPA.class, args); + } +} diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/application.properties b/spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/application.properties new file mode 100644 index 0000000000..fc33388896 --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/logback.xml b/spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/src/test/java/com/baeldung/jpa/SpringDataJPAIntegrationTest.java b/spring-data-disable-auto-configuration/spring-data-jpa/src/test/java/com/baeldung/jpa/SpringDataJPAIntegrationTest.java new file mode 100644 index 0000000000..170f60f861 --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-jpa/src/test/java/com/baeldung/jpa/SpringDataJPAIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.jpa; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.sql.DataSource; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataJPA.class) +public class SpringDataJPAIntegrationTest { + + @Autowired + private ApplicationContext context; + + @Test(expected = NoSuchBeanDefinitionException.class) + public void givenAutoconfigurationIsDisable_whenApplicationStarts_thenContextWillNotHaveTheAutoconfiguredClasses() { + context.getBean(DataSource.class); + } + +} diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/README.md b/spring-data-disable-auto-configuration/spring-data-mongodb/README.md new file mode 100644 index 0000000000..b91f5eda5a --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-mongodb/README.md @@ -0,0 +1,4 @@ +This module is for Jira BAEL-2578 + + +### Relevant Articles: diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/pom.xml b/spring-data-disable-auto-configuration/spring-data-mongodb/pom.xml new file mode 100644 index 0000000000..95bf32545b --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-mongodb/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + com.baeldung + spring-data-mongodb + 0.0.1-SNAPSHOT + spring-data-mongodb + jar + Spring Data with MongoDB + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-mongodb + 2.1.6.RELEASE + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/java/com/baeldung/mongodb/SpringDataMongoDB.java b/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/java/com/baeldung/mongodb/SpringDataMongoDB.java new file mode 100644 index 0000000000..a38eddb0e8 --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/java/com/baeldung/mongodb/SpringDataMongoDB.java @@ -0,0 +1,15 @@ +package com.baeldung.mongodb; + + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; +import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; + +@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class}) +public class SpringDataMongoDB { + + public static void main(String[] args) { + SpringApplication.run(SpringMongoDB.class, args); + } +} diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/application.properties b/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/application.properties new file mode 100644 index 0000000000..9f190ed8ae --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/logback.xml b/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/src/test/java/com/baeldung/mongodb/SpringDataMongoDBIntegrationTest.java b/spring-data-disable-auto-configuration/spring-data-mongodb/src/test/java/com/baeldung/mongodb/SpringDataMongoDBIntegrationTest.java new file mode 100644 index 0000000000..33f5620c32 --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-mongodb/src/test/java/com/baeldung/mongodb/SpringDataMongoDBIntegrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.mongodb; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.test.context.junit4.SpringRunner; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringMongoDB.class) +public class SpringDataMongoDBIntegrationTest { + + @Autowired + private ApplicationContext context; + + @Test(expected = NoSuchBeanDefinitionException.class) + public void givenAutoconfigurationIsDisable_whenApplicationStarts_thenContextWillNotHaveTheAutoconfiguredClasses() { + context.getBean(MongoTemplate.class); + } + +} diff --git a/spring-data-disable-auto-configuration/spring-data-redis/README.md b/spring-data-disable-auto-configuration/spring-data-redis/README.md new file mode 100644 index 0000000000..b91f5eda5a --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-redis/README.md @@ -0,0 +1,4 @@ +This module is for Jira BAEL-2578 + + +### Relevant Articles: diff --git a/spring-data-disable-auto-configuration/spring-data-redis/pom.xml b/spring-data-disable-auto-configuration/spring-data-redis/pom.xml new file mode 100644 index 0000000000..7c997033ed --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-redis/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + com.baeldung + spring-data-redis + 0.0.1-SNAPSHOT + spring-data-redis + jar + Spring Data with Redis + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-redis + 2.1.6.RELEASE + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-redis/src/main/java/com/baeldung/redis/SpringDataRedis.java b/spring-data-disable-auto-configuration/spring-data-redis/src/main/java/com/baeldung/redis/SpringDataRedis.java new file mode 100644 index 0000000000..d5a682834b --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-redis/src/main/java/com/baeldung/redis/SpringDataRedis.java @@ -0,0 +1,14 @@ +package com.baeldung.redis; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; +import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration; + +@SpringBootApplication(exclude = {RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class}) +public class SpringDataRedis { + + public static void main(String[] args) { + SpringApplication.run(SpringRedis.class, args); + } +} diff --git a/spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/application.properties b/spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/application.properties new file mode 100644 index 0000000000..8c5a8dbbfd --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration, org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/logback.xml b/spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-redis/src/test/java/com/baeldung/redis/SpringDataRedisIntegrationTest.java b/spring-data-disable-auto-configuration/spring-data-redis/src/test/java/com/baeldung/redis/SpringDataRedisIntegrationTest.java new file mode 100644 index 0000000000..e142713417 --- /dev/null +++ b/spring-data-disable-auto-configuration/spring-data-redis/src/test/java/com/baeldung/redis/SpringDataRedisIntegrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.redis; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.test.context.junit4.SpringRunner; + + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringRedis.class) +public class SpringDataRedisIntegrationTest { + + @Autowired + private ApplicationContext context; + + @Test(expected = NoSuchBeanDefinitionException.class) + public void givenAutoconfigurationIsDisable_whenApplicationStarts_thenContextWillNotHaveTheAutoconfiguredClasses() { + context.getBean(RedisTemplate.class); + } + +} From a14dc0d889f4eda9132734cf455dd7df2606f79f Mon Sep 17 00:00:00 2001 From: Kamlesh Kumar Date: Sat, 29 Jun 2019 18:54:06 +0530 Subject: [PATCH 049/352] Updated the previous variable in loop (#7205) --- .../baeldung/algorithms/checksortedlist/SortedListChecker.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/SortedListChecker.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/SortedListChecker.java index d2aa159e6d..ab6eb6bc14 100644 --- a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/SortedListChecker.java +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checksortedlist/SortedListChecker.java @@ -27,6 +27,7 @@ public class SortedListChecker { if (previous.compareTo(current) > 0) { return false; } + previous = current; } return true; } @@ -43,6 +44,7 @@ public class SortedListChecker { if (employeeComparator.compare(previous, current) > 0) { return false; } + previous = current; } return true; } From f2c6eb9c1033b8599570b0153b56a58591cc80bf Mon Sep 17 00:00:00 2001 From: Devender Kumar <47500074+kumar-devender@users.noreply.github.com> Date: Sat, 29 Jun 2019 15:49:06 +0200 Subject: [PATCH 050/352] cascade type module (#7021) * Added cascading type mudule * fix compile error * updated dependency version in pom --- .../jpa-hibernate-cascade-type/pom.xml | 71 ++++++++ .../com/baeldung/cascading/HibernateUtil.java | 45 +++++ .../baeldung/cascading/domain/Address.java | 64 +++++++ .../com/baeldung/cascading/domain/Person.java | 38 ++++ .../cascading/CasCadeTypeUnitTest.java | 169 ++++++++++++++++++ .../src/test/resources/hibernate.properties | 10 ++ persistence-modules/pom.xml | 1 + 7 files changed, 398 insertions(+) create mode 100644 persistence-modules/jpa-hibernate-cascade-type/pom.xml create mode 100644 persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/HibernateUtil.java create mode 100644 persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Address.java create mode 100644 persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Person.java create mode 100644 persistence-modules/jpa-hibernate-cascade-type/src/test/java/com/baeldung/cascading/CasCadeTypeUnitTest.java create mode 100644 persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties diff --git a/persistence-modules/jpa-hibernate-cascade-type/pom.xml b/persistence-modules/jpa-hibernate-cascade-type/pom.xml new file mode 100644 index 0000000000..8cfc2a5fa2 --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/pom.xml @@ -0,0 +1,71 @@ + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + jpa-hibernate-cascade-type + 4.0.0 + 1.0.0-SNAPSHOT + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + com.h2database + h2 + ${h2.version} + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + javax.el + javax.el-api + ${javax.el-api.version} + + + org.glassfish + javax.el + ${org.glassfish.javax.el.version} + + + + + jpa-hibernate-cascade-type + + + src/test/resources + true + + + + + + 5.4.3.Final + 3.12.2 + 6.0.17.Final + 3.0.0 + 3.0.1-b11 + 1.8 + 1.8 + + + \ No newline at end of file diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/HibernateUtil.java b/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/HibernateUtil.java new file mode 100644 index 0000000000..700c289e38 --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/HibernateUtil.java @@ -0,0 +1,45 @@ +package com.baeldung.cascading; + +import com.baeldung.cascading.domain.Address; +import com.baeldung.cascading.domain.Person; +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +public class HibernateUtil { + private static SessionFactory sessionFactory; + + public static SessionFactory getSessionFactory() { + try { + Properties properties = getProperties(); + Configuration configuration = new Configuration(); + configuration.setProperties(properties); + configuration.addAnnotatedClass(Person.class); + configuration.addAnnotatedClass(Address.class); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(configuration.getProperties()).build(); + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + return sessionFactory; + } catch (IOException e) { + e.printStackTrace(); + } + return sessionFactory; + } + + private static Properties getProperties() throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource("hibernate.properties"); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } +} diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Address.java b/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Address.java new file mode 100644 index 0000000000..a16b0f81b6 --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Address.java @@ -0,0 +1,64 @@ +package com.baeldung.cascading.domain; + +import javax.persistence.*; + +@Entity +public class Address { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + private String street; + private int houseNumber; + private String city; + private int zipCode; + @ManyToOne(fetch = FetchType.LAZY) + private Person person; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Person getPerson() { + return person; + } + + public void setPerson(Person person) { + this.person = person; + } + + public String getStreet() { + return street; + } + + public int getHouseNumber() { + return houseNumber; + } + + public void setHouseNumber(int houseNumber) { + this.houseNumber = houseNumber; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public int getZipCode() { + return zipCode; + } + + public void setZipCode(int zipCode) { + this.zipCode = zipCode; + } + + public void setStreet(String street) { + this.street = street; + } +} diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Person.java b/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Person.java new file mode 100644 index 0000000000..9ca61323b3 --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/main/java/com/baeldung/cascading/domain/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.cascading.domain; + +import javax.persistence.*; +import java.util.List; + +@Entity +public class Person { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + private String name; + @OneToMany(mappedBy = "person", cascade = CascadeType.ALL) + private List
addresses; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public List
getAddresses() { + return addresses; + } + + public void setAddresses(List
addresses) { + this.addresses = addresses; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/test/java/com/baeldung/cascading/CasCadeTypeUnitTest.java b/persistence-modules/jpa-hibernate-cascade-type/src/test/java/com/baeldung/cascading/CasCadeTypeUnitTest.java new file mode 100644 index 0000000000..a196bdac12 --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/test/java/com/baeldung/cascading/CasCadeTypeUnitTest.java @@ -0,0 +1,169 @@ +package com.baeldung.cascading; + +import com.baeldung.cascading.domain.Address; +import com.baeldung.cascading.domain.Person; +import org.assertj.core.api.Assertions; +import org.hibernate.*; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.Arrays; + +public class CasCadeTypeUnitTest { + private static SessionFactory sessionFactory; + private Session session; + private Transaction transaction; + + @BeforeClass + public static void beforeTests() { + sessionFactory = HibernateUtil.getSessionFactory(); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void testPersist() { + Person person = new Person(); + Address address = new Address(); + address.setPerson(person); + person.setAddresses(Arrays.asList(address)); + session.persist(person); + session.flush(); + session.clear(); + } + + @Test + public void testMerge() { + int addressId; + Person person = buildPerson("devender"); + Address address = buildAddress(person); + person.setAddresses(Arrays.asList(address)); + session.persist(person); + session.flush(); + addressId = address.getId(); + session.clear(); + + Address savedAddressEntity = session.find(Address.class, addressId); + Person savedPersonEntity = savedAddressEntity.getPerson(); + savedPersonEntity.setName("devender kumar"); + savedAddressEntity.setHouseNumber(24); + session.merge(savedPersonEntity); + session.flush(); + } + + @Test + public void testRemove() { + int personId; + Person person = buildPerson("devender"); + Address address = buildAddress(person); + person.setAddresses(Arrays.asList(address)); + session.persist(person); + session.flush(); + personId = person.getId(); + session.clear(); + + Person savedPersonEntity = session.find(Person.class, personId); + session.remove(savedPersonEntity); + session.flush(); + } + + @Test + public void testDetach() { + Person person = buildPerson("devender"); + Address address = buildAddress(person); + person.setAddresses(Arrays.asList(address)); + session.persist(person); + session.flush(); + Assertions.assertThat(session.contains(person)).isTrue(); + Assertions.assertThat(session.contains(address)).isTrue(); + + session.detach(person); + Assertions.assertThat(session.contains(person)).isFalse(); + Assertions.assertThat(session.contains(address)).isFalse(); + } + + @Test + public void testLock() { + Person person = buildPerson("devender"); + Address address = buildAddress(person); + person.setAddresses(Arrays.asList(address)); + session.persist(person); + session.flush(); + Assertions.assertThat(session.contains(person)).isTrue(); + Assertions.assertThat(session.contains(address)).isTrue(); + + session.detach(person); + Assertions.assertThat(session.contains(person)).isFalse(); + Assertions.assertThat(session.contains(address)).isFalse(); + session.unwrap(Session.class) + .buildLockRequest(new LockOptions(LockMode.NONE)) + .lock(person); + + Assertions.assertThat(session.contains(person)).isTrue(); + Assertions.assertThat(session.contains(address)).isTrue(); + } + + @Test + public void testRefresh() { + Person person = buildPerson("devender"); + Address address = buildAddress(person); + person.setAddresses(Arrays.asList(address)); + session.persist(person); + session.flush(); + person.setName("Devender Kumar"); + address.setHouseNumber(24); + session.refresh(person); + Assertions.assertThat(person.getName()).isEqualTo("devender"); + Assertions.assertThat(address.getHouseNumber()).isEqualTo(23); + } + + @Test + public void testReplicate() { + Person person = buildPerson("devender"); + person.setId(2); + Address address = buildAddress(person); + address.setId(2); + person.setAddresses(Arrays.asList(address)); + session.unwrap(Session.class).replicate(person, ReplicationMode.OVERWRITE); + session.flush(); + Assertions.assertThat(person.getId()).isEqualTo(2); + Assertions.assertThat(address.getId()).isEqualTo(2); + } + + @Test + public void testSaveOrUpdate() { + Person person = buildPerson("devender"); + Address address = buildAddress(person); + person.setAddresses(Arrays.asList(address)); + session.saveOrUpdate(person); + session.flush(); + } + + private Address buildAddress(Person person) { + Address address = new Address(); + address.setCity("Berlin"); + address.setHouseNumber(23); + address.setStreet("Zeughofstraße"); + address.setZipCode(123001); + address.setPerson(person); + return address; + } + + private Person buildPerson(String name) { + Person person = new Person(); + person.setName(name); + return person; + } +} diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..c22da2496b --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties @@ -0,0 +1,10 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index e6d883334f..390bcc9d51 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -57,5 +57,6 @@ spring-hibernate4 spring-jpa spring-persistence-simple + jpa-hibernate-cascade-type From 783a93fb47407e5ffd655230d18c98fa15736eda Mon Sep 17 00:00:00 2001 From: Maiklins Date: Sat, 29 Jun 2019 16:03:56 +0200 Subject: [PATCH 051/352] BAEL-2933 The Difference Between Collection.stream().forEach() and Collection.forEach() (#7191) --- .../src/main/java/com/baeldung/forEach/ReverseList.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename core-java-modules/{core-java-8 => core-java-8-2}/src/main/java/com/baeldung/forEach/ReverseList.java (100%) diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/forEach/ReverseList.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/forEach/ReverseList.java similarity index 100% rename from core-java-modules/core-java-8/src/main/java/com/baeldung/forEach/ReverseList.java rename to core-java-modules/core-java-8-2/src/main/java/com/baeldung/forEach/ReverseList.java From 11b02b5ba64093a0a8ca7c9722f251f3c9c3a356 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 29 Jun 2019 20:56:30 +0530 Subject: [PATCH 052/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/mockito-annotations --- .../java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java index 4f5ceb04e7..568492ca10 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java @@ -30,7 +30,7 @@ public class MockitoInjectIntoSpyUnitTest { private MyDictionary spyDic; @Test - public void whenUseInjectMocksAnnotation_thenCorrect2() { + public void whenUseInjectMocksAnnotation_thenCorrect() { Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning"); assertEquals("aMeaning", spyDic.getMeaning("aWord")); From 00a32f4f4d392adfa25d7332752d81ce09dfc88c Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 29 Jun 2019 21:08:34 +0530 Subject: [PATCH 053/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/spring-boot-security-autoconfiguration --- ...iguration.java => BasicConfiguration.java} | 2 +- ...=> BasicConfigurationIntegrationTest.java} | 33 +++++++++---------- 2 files changed, 17 insertions(+), 18 deletions(-) rename spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/{BasicAuthConfiguration.java => BasicConfiguration.java} (94%) rename spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/{BasicAuthConfigurationIntegrationTest.java => BasicConfigurationIntegrationTest.java} (90%) diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicConfiguration.java similarity index 94% rename from spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java rename to spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicConfiguration.java index 592ef5354d..3cfa45421c 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicAuthConfiguration.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicConfiguration.java @@ -10,7 +10,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity -public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter { +public class BasicConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicConfigurationIntegrationTest.java similarity index 90% rename from spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java rename to spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicConfigurationIntegrationTest.java index c091aa6d75..f221712513 100644 --- a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicAuthConfigurationIntegrationTest.java +++ b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicConfigurationIntegrationTest.java @@ -1,27 +1,26 @@ package com.baeldung.springbootsecurity.basic_auth; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootSecurityApplication.class) -public class BasicAuthConfigurationIntegrationTest { +public class BasicConfigurationIntegrationTest { TestRestTemplate restTemplate; URL base; @@ -45,7 +44,7 @@ public class BasicAuthConfigurationIntegrationTest { } @Test - public void whenUserWithWrongCredentialsRequestsHomePage_ThenUnauthorizedPage() throws IllegalStateException, IOException { + public void whenUserWithWrongCredentials_thenUnauthorizedPage() throws IllegalStateException, IOException { restTemplate = new TestRestTemplate("user", "wrongpassword"); ResponseEntity response = restTemplate.getForEntity(base.toString(), String.class); From fc0fa0d31d351acf7c6656c3990e0fec4468a6d7 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 29 Jun 2019 21:19:52 +0530 Subject: [PATCH 054/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/java-groupingby-collector --- .../java_8_features/groupingby/Tuple.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java new file mode 100644 index 0000000000..7a9f62341e --- /dev/null +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/Tuple.java @@ -0,0 +1,34 @@ +package com.baeldung.java_8_features.groupingby; + +public class Tuple { + + private BlogPostType type; + private String author; + + public Tuple(BlogPostType type, String author) { + super(); + this.type = type; + this.author = author; + } + + public BlogPostType getType() { + return type; + } + + public void setType(BlogPostType type) { + this.type = type; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + @Override + public String toString() { + return "Tuple [type=" + type + ", author=" + author + ", getType()=" + getType() + ", getAuthor()=" + getAuthor() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; + } +} From ce8f3f54c54b3f953085a1b56ab2cb94b37baddf Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 29 Jun 2019 21:34:55 +0530 Subject: [PATCH 055/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/spring-classpath-file-access --- .../baeldung/resource/SpringResourceIntegrationTest.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java index a7a2a9032a..c7a2984045 100644 --- a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.File; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -77,7 +78,7 @@ public class SpringResourceIntegrationTest { @Test public void whenResourceUtils_thenReadSuccessful() throws IOException { - final File employeeFile = ResourceUtils.getFile("classpath:data/employees.dat"); + final File employeeFile = loadEmployeesWithSpringInternalClass(); final String employees = new String(Files.readAllBytes(employeeFile.toPath())); assertEquals(EMPLOYEES_EXPECTED, employees); } @@ -112,4 +113,8 @@ public class SpringResourceIntegrationTest { final String employees = new String(Files.readAllBytes(resource.toPath())); assertEquals(EMPLOYEES_EXPECTED, employees); } + + public File loadEmployeesWithSpringInternalClass() throws FileNotFoundException { + return ResourceUtils.getFile("classpath:data/employees.dat"); + } } From 6af16b82fb95397aac602ccd08ec3bcd5e7ed541 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Sat, 29 Jun 2019 21:37:40 +0300 Subject: [PATCH 056/352] BAEL-2995 - possible lossy conversion --- .../ConversionTechniquesUnitTest.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 java-numbers/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java diff --git a/java-numbers/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java b/java-numbers/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java new file mode 100644 index 0000000000..9ed714e853 --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.lossyconversion; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.jupiter.api.Test; + +public class ConversionTechniquesUnitTest { + + @Test + public void testPrimitiveConversion() { + + double doubleNum = 15.6; + int integerNum = (int) doubleNum; + + assertEquals(integerNum, 15); + } + + @Test + public void testWrapperConversion() { + + Double doubleNum = 10.3; + double dbl = doubleNum.doubleValue(); + int intgr = (int) dbl; + Integer intNum = Integer.valueOf(intgr); + + assertTrue(intNum == 10); + } + + @Test + public void testWrapperToPrimitiveConversion() { + + Float floatNum = 17.564f; + long longNum = floatNum.longValue(); + + assertEquals(longNum, 17l); + + Double doubleNum = 15.9999; + int intNum = doubleNum.intValue(); + + assertEquals(intNum, 15); + + longNum = Math.round(doubleNum); + + assertEquals(longNum, 16); + } + + @Test + public void testWrapperToPrimitiveConversionUsingMathRound() { + + Double doubleNum = 15.9999; + long longNum = Math.round(doubleNum); + + assertEquals(longNum, 16); + } +} From 181f7fe8d4e7bd697a2335d80dad60b28fec133f Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 30 Jun 2019 00:28:15 +0530 Subject: [PATCH 057/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/jackson-ignore-null-fields --- .../jackson/test/JacksonSerializationIgnoreUnitTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java b/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java index 4230420132..146f274380 100644 --- a/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java +++ b/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java @@ -165,7 +165,7 @@ public class JacksonSerializationIgnoreUnitTest { } @Test - public final void givenIgnoringNullFieldsOnClass_whenWritingObjectWithNullField_thenFieldIsIgnored() throws JsonProcessingException { + public final void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull(); @@ -178,7 +178,7 @@ public class JacksonSerializationIgnoreUnitTest { } @Test - public final void givenIgnoringNullFieldsGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { + public final void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); final MyDto dtoObject = new MyDto(); From 57adf2dcfe37dcf3eba50348fc0b864d8400777b Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 30 Jun 2019 01:05:30 +0530 Subject: [PATCH 058/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/spring-kafka --- .../spring/kafka/KafkaConsumerConfig.java | 25 ++++++++----------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java index 9353e63ff6..933d2353aa 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaConsumerConfig.java @@ -29,39 +29,36 @@ public class KafkaConsumerConfig { props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); return new DefaultKafkaConsumerFactory<>(props); } + + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory(String groupId) { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory(groupId)); + return factory; + } @Bean public ConcurrentKafkaListenerContainerFactory fooKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("foo")); - return factory; + return kafkaListenerContainerFactory("foo"); } @Bean public ConcurrentKafkaListenerContainerFactory barKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("bar")); - return factory; + return kafkaListenerContainerFactory("bar"); } @Bean public ConcurrentKafkaListenerContainerFactory headersKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("headers")); - return factory; + return kafkaListenerContainerFactory("headers"); } @Bean public ConcurrentKafkaListenerContainerFactory partitionsKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("partitions")); - return factory; + return kafkaListenerContainerFactory("partitions"); } @Bean public ConcurrentKafkaListenerContainerFactory filterKafkaListenerContainerFactory() { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - factory.setConsumerFactory(consumerFactory("filter")); + ConcurrentKafkaListenerContainerFactory factory = kafkaListenerContainerFactory("filter"); factory.setRecordFilterStrategy(record -> record.value() .contains("World")); return factory; From 447c8c35991abbd8b325cc730e4622c224ddaae4 Mon Sep 17 00:00:00 2001 From: Denis Date: Sun, 30 Jun 2019 06:51:05 +0200 Subject: [PATCH 059/352] BAEL-2983 java objects generation with EasyRandom (#7209) --- easy-random/pom.xml | 23 ++++++ .../easy/random/model/Department.java | 17 +++++ .../baeldung/easy/random/model/Employee.java | 70 +++++++++++++++++++ .../org/baeldung/easy/random/model/Grade.java | 22 ++++++ .../baeldung/easy/random/model/Person.java | 30 ++++++++ .../easy/random/model/YearQuarter.java | 50 +++++++++++++ .../randomizer/YearQuarterRandomizer.java | 18 +++++ .../easy/random/EasyRandomUnitTest.java | 63 +++++++++++++++++ pom.xml | 1 + 9 files changed, 294 insertions(+) create mode 100644 easy-random/pom.xml create mode 100644 easy-random/src/main/java/org/baeldung/easy/random/model/Department.java create mode 100644 easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java create mode 100644 easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java create mode 100644 easy-random/src/main/java/org/baeldung/easy/random/model/Person.java create mode 100644 easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java create mode 100644 easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java create mode 100644 easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java diff --git a/easy-random/pom.xml b/easy-random/pom.xml new file mode 100644 index 0000000000..61f0ed2cd4 --- /dev/null +++ b/easy-random/pom.xml @@ -0,0 +1,23 @@ + + + 4.0.0 + easy-random + easy-random + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + org.jeasy + easy-random-core + 4.0.0 + + + + \ No newline at end of file diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/Department.java b/easy-random/src/main/java/org/baeldung/easy/random/model/Department.java new file mode 100644 index 0000000000..ee4dc82771 --- /dev/null +++ b/easy-random/src/main/java/org/baeldung/easy/random/model/Department.java @@ -0,0 +1,17 @@ +package org.baeldung.easy.random.model; + +import java.util.StringJoiner; + +public class Department { + private String depName; + + public Department(String depName) { + this.depName = depName; + } + + @Override + public String toString() { + return new StringJoiner(", ", Department.class.getSimpleName() + "[", "]").add("depName='" + depName + "'") + .toString(); + } +} diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java b/easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java new file mode 100644 index 0000000000..ef63642ca2 --- /dev/null +++ b/easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java @@ -0,0 +1,70 @@ +package org.baeldung.easy.random.model; + +import java.util.*; + +public class Employee { + + private long id; + private String firstName; + private String lastName; + private Department department; + private Collection coworkers; + private Map quarterGrades; + + public Employee(long id, String firstName, String lastName, Department department) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.department = department; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Employee employee = (Employee) o; + return id == employee.id; + } + + @Override + public int hashCode() { + return Objects.hash(id); + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public long getId() { + return id; + } + + public Department getDepartment() { + return department; + } + + public Collection getCoworkers() { + return Collections.unmodifiableCollection(coworkers); + } + + public Map getQuarterGrades() { + return Collections.unmodifiableMap(quarterGrades); + } + + @Override + public String toString() { + return new StringJoiner(", ", Employee.class.getSimpleName() + "[", "]").add("id=" + id) + .add("firstName='" + firstName + "'") + .add("lastName='" + lastName + "'") + .add("department=" + department) + .add("coworkers size=" + ((coworkers == null) ? 0 : coworkers.size())) + .add("quarterGrades=" + quarterGrades) + .toString(); + } +} diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java b/easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java new file mode 100644 index 0000000000..cb979be3b8 --- /dev/null +++ b/easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java @@ -0,0 +1,22 @@ +package org.baeldung.easy.random.model; + +import java.util.StringJoiner; + +public class Grade { + + private int grade; + + public Grade(int grade) { + this.grade = grade; + } + + public int getGrade() { + return grade; + } + + @Override + public String toString() { + return new StringJoiner(", ", Grade.class.getSimpleName() + "[", "]").add("grade=" + grade) + .toString(); + } +} diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/Person.java b/easy-random/src/main/java/org/baeldung/easy/random/model/Person.java new file mode 100644 index 0000000000..c941499993 --- /dev/null +++ b/easy-random/src/main/java/org/baeldung/easy/random/model/Person.java @@ -0,0 +1,30 @@ +package org.baeldung.easy.random.model; + +import java.util.StringJoiner; + +public class Person { + + private String firstName; + private String lastName; + private Integer age; + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public Integer getAge() { + return age; + } + + @Override + public String toString() { + return new StringJoiner(", ", Person.class.getSimpleName() + "[", "]").add("firstName='" + firstName + "'") + .add("lastName='" + lastName + "'") + .add("age=" + age) + .toString(); + } +} diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java b/easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java new file mode 100644 index 0000000000..c2868f09b8 --- /dev/null +++ b/easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java @@ -0,0 +1,50 @@ +package org.baeldung.easy.random.model; + +import java.time.LocalDate; +import java.util.Objects; +import java.util.StringJoiner; + +public class YearQuarter { + + private LocalDate startDate; + private LocalDate endDate; + + public YearQuarter(LocalDate startDate) { + this.startDate = startDate; + autoAdjustEndDate(); + } + + private void autoAdjustEndDate() { + endDate = startDate.plusMonths(3L); + } + + public LocalDate getStartDate() { + return startDate; + } + + public LocalDate getEndDate() { + return endDate; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + YearQuarter quarter = (YearQuarter) o; + return Objects.equals(startDate, quarter.startDate) && Objects.equals(endDate, quarter.endDate); + } + + @Override + public int hashCode() { + return Objects.hash(startDate, endDate); + } + + @Override + public String toString() { + return new StringJoiner(", ", YearQuarter.class.getSimpleName() + "[", "]").add("startDate=" + startDate) + .add("endDate=" + endDate) + .toString(); + } +} diff --git a/easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java b/easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java new file mode 100644 index 0000000000..05232ffcbc --- /dev/null +++ b/easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java @@ -0,0 +1,18 @@ +package org.baeldung.easy.random.randomizer; + +import org.baeldung.easy.random.model.YearQuarter; +import org.jeasy.random.api.Randomizer; + +import java.time.LocalDate; +import java.time.Month; + +public class YearQuarterRandomizer implements Randomizer { + + private LocalDate date = LocalDate.of(1990, Month.SEPTEMBER, 25); + + @Override + public YearQuarter getRandomValue() { + date = date.plusMonths(3); + return new YearQuarter(date); + } +} diff --git a/easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java b/easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java new file mode 100644 index 0000000000..9f7a23db66 --- /dev/null +++ b/easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java @@ -0,0 +1,63 @@ +package org.baeldung.easy.random; + +import org.baeldung.easy.random.model.Employee; +import org.baeldung.easy.random.model.Person; +import org.baeldung.easy.random.model.YearQuarter; +import org.baeldung.easy.random.randomizer.YearQuarterRandomizer; +import org.jeasy.random.EasyRandom; +import org.jeasy.random.EasyRandomParameters; +import org.jeasy.random.FieldPredicates; +import org.jeasy.random.TypePredicates; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.*; + +class EasyRandomUnitTest { + + @Test + void givenDefaultConfiguration_thenGenerateSingleObject() { + EasyRandom generator = new EasyRandom(); + Person person = generator.nextObject(Person.class); + + assertNotNull(person.getAge()); + assertNotNull(person.getFirstName()); + assertNotNull(person.getLastName()); + } + + @Test + void givenDefaultConfiguration_thenGenerateObjectsList() { + EasyRandom generator = new EasyRandom(); + List persons = generator.objects(Person.class, 5) + .collect(Collectors.toList()); + + assertEquals(5, persons.size()); + } + + @Test + void givenCustomConfiguration_thenGenerateSingleEmployee() { + EasyRandomParameters parameters = new EasyRandomParameters(); + parameters.stringLengthRange(3, 3); + parameters.collectionSizeRange(5, 5); + parameters.excludeField(FieldPredicates.named("lastName").and(FieldPredicates.inClass(Employee.class))); + parameters.excludeType(TypePredicates.inPackage("not.existing.pkg")); + parameters.randomize(YearQuarter.class, new YearQuarterRandomizer()); + + EasyRandom generator = new EasyRandom(parameters); + Employee employee = generator.nextObject(Employee.class); + + assertEquals(3, employee.getFirstName().length()); + assertEquals(5, employee.getCoworkers().size()); + assertEquals(5, employee.getQuarterGrades().size()); + assertNotNull(employee.getDepartment()); + + assertNull(employee.getLastName()); + + for (YearQuarter key : employee.getQuarterGrades().keySet()) { + assertEquals(key.getStartDate(), key.getEndDate().minusMonths(3L)); + } + } + +} diff --git a/pom.xml b/pom.xml index 982c52c54e..6365e407f5 100644 --- a/pom.xml +++ b/pom.xml @@ -422,6 +422,7 @@ drools dubbo + easy-random ethereum feign From 26c28f981568ce8fd28df4a636f7b5b7173f86df Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 30 Jun 2019 15:59:22 +0530 Subject: [PATCH 060/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/spring-bean-scopes --- .../test/java/org/baeldung/scopes/ScopesIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-all/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java b/spring-all/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java index aa88a3775e..0ae99610f6 100644 --- a/spring-all/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/scopes/ScopesIntegrationTest.java @@ -12,7 +12,7 @@ public class ScopesIntegrationTest { private static final String NAME_OTHER = "Anna Jones"; @Test - public void testScopeSingleton() { + public void givenSingletonScope_whenSetName_thenEqualNames() { final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); final Person personSingletonA = (Person) applicationContext.getBean("personSingleton"); @@ -25,7 +25,7 @@ public class ScopesIntegrationTest { } @Test - public void testScopePrototype() { + public void givenPrototypeScope_whenSetNames_thenDifferentNames() { final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml"); final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype"); From 81eeba2e3264cb2151f20301bc898b814344b77f Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 30 Jun 2019 16:16:25 +0530 Subject: [PATCH 061/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration --- .../com/baeldung/web/exception/BadRequestException.java | 8 ++++++++ .../baeldung/web/exception/ResourceNotFoundException.java | 8 ++++++++ 2 files changed, 16 insertions(+) create mode 100644 spring-boot-rest/src/main/java/com/baeldung/web/exception/BadRequestException.java create mode 100644 spring-boot-rest/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/exception/BadRequestException.java b/spring-boot-rest/src/main/java/com/baeldung/web/exception/BadRequestException.java new file mode 100644 index 0000000000..9ebf885d4b --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/exception/BadRequestException.java @@ -0,0 +1,8 @@ +package com.baeldung.web.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.BAD_REQUEST) +public class BadRequestException extends RuntimeException { +} diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java b/spring-boot-rest/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java new file mode 100644 index 0000000000..a80802eadf --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/exception/ResourceNotFoundException.java @@ -0,0 +1,8 @@ +package com.baeldung.web.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException { +} From 082493402763533a059fdf36ae4109588414bd13 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 30 Jun 2019 16:37:31 +0530 Subject: [PATCH 062/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/intro-to-project-lombok --- .../baeldung/lombok/getter/GetterLazy.java | 4 +-- .../com/baeldung/lombok/intro/Utility.java | 26 +++++++++++++++++++ lombok/src/main/resources/sure_in_my_jar.txt | 1 + 3 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 lombok/src/main/java/com/baeldung/lombok/intro/Utility.java create mode 100644 lombok/src/main/resources/sure_in_my_jar.txt diff --git a/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java b/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java index 5ac82a74d8..604c45be3b 100644 --- a/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java +++ b/lombok/src/main/java/com/baeldung/lombok/getter/GetterLazy.java @@ -13,9 +13,9 @@ public class GetterLazy { private static final String DELIMETER = ","; @Getter(lazy = true) - private final Map transactions = readTxnsFromFile(); + private final Map transactions = getTransactions(); - private Map readTxnsFromFile() { + private Map getTransactions() { final Map cache = new HashMap<>(); List txnRows = readTxnListFromFile(); diff --git a/lombok/src/main/java/com/baeldung/lombok/intro/Utility.java b/lombok/src/main/java/com/baeldung/lombok/intro/Utility.java new file mode 100644 index 0000000000..07198d2ffc --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/intro/Utility.java @@ -0,0 +1,26 @@ +package com.baeldung.lombok.intro; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.stream.Collectors; + +import lombok.SneakyThrows; +import lombok.Synchronized; + +public class Utility { + + @SneakyThrows + public String resourceAsString() throws IOException { + try (InputStream is = this.getClass().getResourceAsStream("sure_in_my_jar.txt")) { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); + return br.lines().collect(Collectors.joining("\n")); + } + } + + @Synchronized + public void putValueInCache(String key, String value) { + System.out.println("Thread safe here with key : [" + key + "] and value[" + value + "]"); + } +} diff --git a/lombok/src/main/resources/sure_in_my_jar.txt b/lombok/src/main/resources/sure_in_my_jar.txt new file mode 100644 index 0000000000..5ab2f8a432 --- /dev/null +++ b/lombok/src/main/resources/sure_in_my_jar.txt @@ -0,0 +1 @@ +Hello \ No newline at end of file From bc39e680a2d978b11fedaf27021ec860b7c8d126 Mon Sep 17 00:00:00 2001 From: eelhazati Date: Sun, 30 Jun 2019 16:45:00 +0100 Subject: [PATCH 063/352] OAuth2 framework implementation. --- .../oauth2-authorization-server/pom.xml | 72 ++++++ .../server/OAuth2ServerApplication.java | 8 + .../authorization/server/PEMKeyUtils.java | 17 ++ .../server/api/AuthorizationEndpoint.java | 185 ++++++++++++++++ .../authorization/server/api/JWKEndpoint.java | 38 ++++ .../server/api/TokenEndpoint.java | 86 +++++++ .../AuthorizationCodeGrantTypeHandler.java | 99 +++++++++ .../AuthorizationGrantTypeHandler.java | 8 + .../server/model/AppDataRepository.java | 27 +++ .../server/model/AuthorizationCode.java | 73 ++++++ .../authorization/server/model/Client.java | 62 ++++++ .../authorization/server/model/User.java | 58 +++++ .../server/security/UserIdentityStore.java | 37 ++++ .../server/web/AuthorizationEndpoint.java | 209 ++++++++++++++++++ .../server/web/TokenEndpoint.java | 70 ++++++ .../src/main/liberty/config/server.xml | 32 +++ .../META-INF/microprofile-config.properties | 2 + .../main/resources/META-INF/persistence.xml | 14 ++ .../main/resources/META-INF/private-key.pem | 28 +++ .../main/resources/META-INF/public-key.pem | 9 + .../src/main/resources/data.sql | 3 + .../src/main/webapp/WEB-INF/beans.xml | 6 + .../src/main/webapp/authorize.jsp | 54 +++++ .../src/main/webapp/error.jsp | 25 +++ .../src/main/webapp/login-error.jsp | 0 .../src/main/webapp/login.jsp | 49 ++++ oauth2-framework-impl/oauth2-client/pom.xml | 28 +++ .../client/AuthorizationCodeServlet.java | 39 ++++ .../oauth2/client/CallbackServlet.java | 76 +++++++ .../oauth2/client/DownstreamCallServlet.java | 49 ++++ .../src/main/liberty/config/server.xml | 19 ++ .../META-INF/microprofile-config.properties | 12 + .../src/main/webapp/WEB-INF/beans.xml | 6 + .../src/main/webapp/WEB-INF/web.xml | 5 + .../oauth2-client/src/main/webapp/index.jsp | 97 ++++++++ .../oauth2-resource-server/pom.xml | 40 ++++ .../OAuth2ResourceServerApplication.java | 13 ++ .../server/secure/ProtectedResource.java | 38 ++++ .../src/main/liberty/config/server.xml | 20 ++ .../META-INF/microprofile-config.properties | 2 + .../main/resources/META-INF/public-key.pem | 9 + .../src/main/webapp/WEB-INF/beans.xml | 6 + .../src/main/webapp/index.html | 37 ++++ oauth2-framework-impl/pom.xml | 93 ++++++++ 44 files changed, 1860 insertions(+) create mode 100644 oauth2-framework-impl/oauth2-authorization-server/pom.xml create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/OAuth2ServerApplication.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/PEMKeyUtils.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/JWKEndpoint.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationGrantTypeHandler.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AppDataRepository.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AuthorizationCode.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/Client.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/User.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/security/UserIdentityStore.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/liberty/config/server.xml create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/microprofile-config.properties create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/persistence.xml create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/private-key.pem create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/public-key.pem create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/resources/data.sql create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/WEB-INF/beans.xml create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/error.jsp create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login-error.jsp create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login.jsp create mode 100644 oauth2-framework-impl/oauth2-client/pom.xml create mode 100644 oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AuthorizationCodeServlet.java create mode 100644 oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java create mode 100644 oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/DownstreamCallServlet.java create mode 100644 oauth2-framework-impl/oauth2-client/src/main/liberty/config/server.xml create mode 100644 oauth2-framework-impl/oauth2-client/src/main/resources/META-INF/microprofile-config.properties create mode 100644 oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/beans.xml create mode 100644 oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/web.xml create mode 100644 oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp create mode 100644 oauth2-framework-impl/oauth2-resource-server/pom.xml create mode 100644 oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/OAuth2ResourceServerApplication.java create mode 100644 oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/secure/ProtectedResource.java create mode 100644 oauth2-framework-impl/oauth2-resource-server/src/main/liberty/config/server.xml create mode 100644 oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/microprofile-config.properties create mode 100644 oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/public-key.pem create mode 100644 oauth2-framework-impl/oauth2-resource-server/src/main/webapp/WEB-INF/beans.xml create mode 100644 oauth2-framework-impl/oauth2-resource-server/src/main/webapp/index.html create mode 100644 oauth2-framework-impl/pom.xml diff --git a/oauth2-framework-impl/oauth2-authorization-server/pom.xml b/oauth2-framework-impl/oauth2-authorization-server/pom.xml new file mode 100644 index 0000000000..8db2150558 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + oauth2-authorization-server + war + + + com.baeldung.oauth2 + oauth2-framework-impl + 1.0-SNAPSHOT + + + + 1.4.199 + 9080 + 9443 + + + + + com.nimbusds + nimbus-jose-jwt + 7.3 + + + org.bouncycastle + bcprov-jdk15on + 1.62 + + + org.bouncycastle + bcpkix-jdk15on + 1.62 + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-h2-dependency + package + + copy + + + + + + + com.h2database + h2 + ${h2.version} + jar + ${project.build.directory}/liberty/wlp/usr/shared/resources/ + + + + + + + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/OAuth2ServerApplication.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/OAuth2ServerApplication.java new file mode 100644 index 0000000000..62d6b04464 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/OAuth2ServerApplication.java @@ -0,0 +1,8 @@ +package com.baeldung.oauth2.authorization.server; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/") +public class OAuth2ServerApplication extends Application { +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/PEMKeyUtils.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/PEMKeyUtils.java new file mode 100644 index 0000000000..dab57b91a7 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/PEMKeyUtils.java @@ -0,0 +1,17 @@ +package com.baeldung.oauth2.authorization.server; + +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; + +import static java.lang.Thread.currentThread; + + +public class PEMKeyUtils { + + public static String readKeyAsString(String keyLocation) throws Exception { + URI uri = currentThread().getContextClassLoader().getResource(keyLocation).toURI(); + byte[] byteArray = Files.readAllBytes(Paths.get(uri)); + return new String(byteArray); + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java new file mode 100644 index 0000000000..10e78a2dfd --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java @@ -0,0 +1,185 @@ +package com.baeldung.oauth2.authorization.server.api; + +import com.baeldung.oauth2.authorization.server.handler.AuthorizationGrantTypeHandler; +import com.baeldung.oauth2.authorization.server.model.AppDataRepository; +import com.baeldung.oauth2.authorization.server.model.AuthorizationCode; +import com.baeldung.oauth2.authorization.server.model.Client; +import com.baeldung.oauth2.authorization.server.model.User; + +import javax.annotation.security.RolesAllowed; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Instance; +import javax.enterprise.inject.literal.NamedLiteral; +import javax.inject.Inject; +import javax.json.JsonObject; +import javax.security.enterprise.SecurityContext; +import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.*; +import java.io.IOException; +import java.net.URI; +import java.security.Principal; +import java.time.LocalDateTime; +import java.util.*; + +@FormAuthenticationMechanismDefinition( + loginToContinue = @LoginToContinue(loginPage = "/login.jsp", errorPage = "/login.jsp") +) +@RolesAllowed("USER") +@RequestScoped +@Path("authorize") +public class AuthorizationEndpoint { + + @Inject + private SecurityContext securityContext; + + @Inject + private AppDataRepository appDataRepository; + + @Inject + Instance authorizationGrantTypeHandlers; + + @GET + @Produces(MediaType.TEXT_HTML) + public Response doGet(@Context HttpServletRequest request, + @Context HttpServletResponse response, + @Context UriInfo uriInfo) throws ServletException, IOException { + MultivaluedMap params = uriInfo.getQueryParameters(); + Principal principal = securityContext.getCallerPrincipal(); + + //error about redirect_uri && client_id ==> forward user, thus to error.jsp. + //otherwise ==> sendRedirect redirect_uri?error=error&error_description=error_description + //1. client_id + String clientId = params.getFirst("client_id"); + if (clientId == null || clientId.isEmpty()) { + return informUserAboutError(request, response, "Invalid client_id :" + clientId); + } + Client client = appDataRepository.getClient(clientId); + if (client == null) { + return informUserAboutError(request, response, "Invalid client_id :" + clientId); + } + //2. Client Authorized Grant Type + String clientError = ""; + if (client.getAuthorizedGrantTypes() != null && !client.getAuthorizedGrantTypes().contains("authorization_code")) { + return informUserAboutError(request, response, "Authorization Grant type, authorization_code, is not allowed for this client :" + clientId); + } + + //3. redirectUri + String redirectUri = params.getFirst("redirect_uri"); + if (client.getRedirectUri() != null && !client.getRedirectUri().isEmpty()) { + if (redirectUri != null && !redirectUri.isEmpty() && !client.getRedirectUri().equals(redirectUri)) { + //sould be in the client.redirectUri + return informUserAboutError(request, response, "redirect_uri is pre-registred and should match"); + } + redirectUri = client.getRedirectUri(); + params.putSingle("resolved_redirect_uri", redirectUri); + } else { + if (redirectUri == null || redirectUri.isEmpty()) { + return informUserAboutError(request, response, "redirect_uri is not pre-registred and should be provided"); + } + params.putSingle("resolved_redirect_uri", redirectUri); + } + request.setAttribute("client", client); + + //4. response_type + String responseType = params.getFirst("response_type"); + if (!"code".equals(responseType) && !"token".equals(responseType)) { + //error = "invalid_grant :" + responseType + ", response_type params should be code or token:"; + //return informUserAboutError(error); + } + + //Save params in session + request.getSession().setAttribute("ORIGINAL_PARAMS", params); + + //4.scope: Optional + String requestedScope = request.getParameter("scope"); + if (requestedScope == null || requestedScope.isEmpty()) { + requestedScope = client.getScope(); + } + User user = appDataRepository.getUser(principal.getName()); + String allowedScopes = checkUserScopes(user.getScopes(), requestedScope); + request.setAttribute("scopes", allowedScopes); + + request.getRequestDispatcher("/authorize.jsp").forward(request, response); + return null; + } + + @POST + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + @Produces(MediaType.TEXT_HTML) + public Response doPost(@Context HttpServletRequest request, + @Context HttpServletResponse response, + MultivaluedMap params) throws Exception { + MultivaluedMap originalParams = (MultivaluedMap) request.getSession().getAttribute("ORIGINAL_PARAMS"); + if (originalParams == null) { + return informUserAboutError(request, response, "No pending authorization request."); + } + String redirectUri = originalParams.getFirst("resolved_redirect_uri"); + StringBuilder sb = new StringBuilder(redirectUri); + + String approbationStatus = params.getFirst("approbation_status"); + if ("NO".equals(approbationStatus)) { + URI location = UriBuilder.fromUri(sb.toString()) + .queryParam("error", "User doesn't approved the request.") + .queryParam("error_description", "User doesn't approved the request.") + .build(); + return Response.seeOther(location).build(); + } + //==> YES + List approvedScopes = params.get("scope"); + if (approvedScopes == null || approvedScopes.isEmpty()) { + URI location = UriBuilder.fromUri(sb.toString()) + .queryParam("error", "User doesn't approved the request.") + .queryParam("error_description", "User doesn't approved the request.") + .build(); + return Response.seeOther(location).build(); + } + + String responseType = originalParams.getFirst("response_type"); + String clientId = originalParams.getFirst("client_id"); + if ("code".equals(responseType)) { + String userId = securityContext.getCallerPrincipal().getName(); + AuthorizationCode authorizationCode = new AuthorizationCode(); + authorizationCode.setClientId(clientId); + authorizationCode.setUserId(userId); + authorizationCode.setApprovedScopes(String.join(" ", approvedScopes)); + authorizationCode.setExpirationDate(LocalDateTime.now().plusMinutes(10)); + authorizationCode.setRedirectUri(redirectUri); + appDataRepository.save(authorizationCode); + String code = authorizationCode.getCode(); + sb.append("?code=").append(code); + } else { + //Implicit: responseType=token + AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of("implicit")).get(); + JsonObject tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params); + sb.append("#access_token=").append(tokenResponse.getString("access_token")) + .append("&token_type=").append(tokenResponse.getString("token_type")) + .append("&scope=").append(tokenResponse.getString("scope")); + } + String state = originalParams.getFirst("state"); + if (state != null) { + sb.append("&state=").append(state); + } + return Response.seeOther(UriBuilder.fromUri(sb.toString()).build()).build(); + } + + private String checkUserScopes(String userScopes, String requestedScope) { + Set allowedScopes = new LinkedHashSet<>(); + Set rScopes = new HashSet(Arrays.asList(requestedScope.split(" "))); + Set uScopes = new HashSet(Arrays.asList(userScopes.split(" "))); + for (String scope : uScopes) { + if (rScopes.contains(scope)) allowedScopes.add(scope); + } + return String.join(" ", allowedScopes); + } + + private Response informUserAboutError(HttpServletRequest request, HttpServletResponse response, String error) throws ServletException, IOException { + request.setAttribute("error", error); + request.getRequestDispatcher("/error.jsp").forward(request, response); + return null; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/JWKEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/JWKEndpoint.java new file mode 100644 index 0000000000..9d38c823b9 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/JWKEndpoint.java @@ -0,0 +1,38 @@ +package com.baeldung.oauth2.authorization.server.api; + +import com.baeldung.oauth2.authorization.server.PEMKeyUtils; +import com.nimbusds.jose.jwk.JWK; +import org.eclipse.microprofile.config.Config; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.Arrays; + +@Path("jwk") +@ApplicationScoped +public class JWKEndpoint { + + @Inject + private Config config; + + @GET + public Response getKey(@QueryParam("format") String format) throws Exception { + if (format != null && !Arrays.asList("jwk", "pem").contains(format)) { + return Response.status(Response.Status.BAD_REQUEST).entity("Public Key Format should be : jwk or pem").build(); + } + String verificationkey = config.getValue("verificationkey", String.class); + String pemEncodedRSAPublicKey = PEMKeyUtils.readKeyAsString(verificationkey); + if (format == null || format.equals("jwk")) { + JWK jwk = JWK.parseFromPEMEncodedObjects(pemEncodedRSAPublicKey); + return Response.ok(jwk.toJSONString()).type(MediaType.APPLICATION_JSON).build(); + } else if (format.equals("pem")) { + return Response.ok(pemEncodedRSAPublicKey).build(); + } + return null; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java new file mode 100644 index 0000000000..f39bb2ea2d --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java @@ -0,0 +1,86 @@ +package com.baeldung.oauth2.authorization.server.api; + +import com.baeldung.oauth2.authorization.server.handler.AuthorizationGrantTypeHandler; +import com.baeldung.oauth2.authorization.server.model.AppDataRepository; +import com.baeldung.oauth2.authorization.server.model.Client; +import com.nimbusds.jose.JOSEException; + +import javax.enterprise.inject.Instance; +import javax.enterprise.inject.literal.NamedLiteral; +import javax.inject.Inject; +import javax.json.Json; +import javax.json.JsonObject; +import javax.ws.rs.*; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +@Path("token") +public class TokenEndpoint { + + List supportedGrantTypes = Collections.singletonList("authorization_code"); + + @Inject + private AppDataRepository appDataRepository; + + @Inject + Instance authorizationGrantTypeHandlers; + + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + public Response token(MultivaluedMap params, + @HeaderParam(HttpHeaders.AUTHORIZATION) String authHeader) throws JOSEException { + + //Check grant_type params + String grantType = params.getFirst("grant_type"); + Objects.requireNonNull(grantType, "grant_type params is required"); + if (!supportedGrantTypes.contains(grantType)) { + JsonObject error = Json.createObjectBuilder() + .add("error", "unsupported_grant_type") + .add("error_description", "grant type should be one of :" + supportedGrantTypes) + .build(); + return Response.status(Response.Status.BAD_REQUEST) + .entity(error).build(); + + } + + //Client Authentication + String[] clientCredentials = extract(authHeader); + String clientId = clientCredentials[0]; + String clientSecret = clientCredentials[1]; + Client client = appDataRepository.getClient(clientId); + if (client == null || clientSecret == null || !clientSecret.equals(client.getClientSecret())) { + JsonObject error = Json.createObjectBuilder() + .add("error", "invalid_client") + .build(); + return Response.status(Response.Status.UNAUTHORIZED) + .entity(error).build(); + } + + AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get(); + JsonObject tokenResponse = null; + try { + tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params); + } catch (Exception e) { + e.printStackTrace(); + } + + return Response.ok(tokenResponse) + .header("Cache-Control", "no-store") + .header("Pragma", "no-cache") + .build(); + } + + private String[] extract(String authHeader) { + if (authHeader != null && authHeader.startsWith("Basic ")) { + return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":"); + } + return null; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java new file mode 100644 index 0000000000..889c7fcea2 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java @@ -0,0 +1,99 @@ +package com.baeldung.oauth2.authorization.server.handler; + +import com.baeldung.oauth2.authorization.server.PEMKeyUtils; +import com.baeldung.oauth2.authorization.server.model.AuthorizationCode; +import com.nimbusds.jose.JOSEObjectType; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jose.jwk.JWK; +import com.nimbusds.jose.jwk.RSAKey; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.json.Json; +import javax.json.JsonObject; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MultivaluedMap; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Date; +import java.util.UUID; + +@Named("authorization_code") +public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantTypeHandler { + + @PersistenceContext + private EntityManager entityManager; + + @Inject + private Config config; + + @Override + public JsonObject createAccessToken(String clientId, MultivaluedMap params) throws Exception { + //1. code is required + String code = params.getFirst("code"); + if (code == null || "".equals(code)) { + throw new WebApplicationException("invalid_grant"); + } + AuthorizationCode authorizationCode = entityManager.find(AuthorizationCode.class, code); + if (!authorizationCode.getExpirationDate().isAfter(LocalDateTime.now())) { + throw new WebApplicationException("code Expired !"); + } + String redirectUri = params.getFirst("redirect_uri"); + //redirecturi match + if (authorizationCode.getRedirectUri() != null && !authorizationCode.getRedirectUri().equals(redirectUri)) { + //redirectUri params should be the same as the requested redirectUri. + throw new WebApplicationException("invalid_grant"); + } + //client match + if (!clientId.equals(authorizationCode.getClientId())) { + throw new WebApplicationException("invalid_grant"); + } + + //JWT Header + JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); + + Instant now = Instant.now(); + Long expiresInMin = 30L; + Date expiresIn = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES)); + + //3. JWT Payload or claims + JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder() + .issuer("http://localhost:9080") + .subject(authorizationCode.getUserId()) + .claim("upn", authorizationCode.getUserId()) + .audience("http://localhost:9280") + .claim("scope", authorizationCode.getApprovedScopes()) + .claim("groups", Arrays.asList(authorizationCode.getApprovedScopes().split(" "))) + .expirationTime(expiresIn) // expires in 30 minutes + .notBeforeTime(Date.from(now)) + .issueTime(Date.from(now)) + .jwtID(UUID.randomUUID().toString()) + .build(); + SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims); + + //4. Signing + String signingkey = config.getValue("signingkey", String.class); + String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey); + RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey); + signedJWT.sign(new RSASSASigner(rsaKey.toRSAPrivateKey())); + + //5. Finally the JWT access token + String accessToken = signedJWT.serialize(); + + return Json.createObjectBuilder() + .add("token_type", "Bearer") + .add("access_token", accessToken) + .add("expires_in", expiresInMin * 60) + .add("scope", authorizationCode.getApprovedScopes()) + .build(); + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationGrantTypeHandler.java new file mode 100644 index 0000000000..a5afe293ef --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationGrantTypeHandler.java @@ -0,0 +1,8 @@ +package com.baeldung.oauth2.authorization.server.handler; + +import javax.json.JsonObject; +import javax.ws.rs.core.MultivaluedMap; + +public interface AuthorizationGrantTypeHandler { + JsonObject createAccessToken(String clientId, MultivaluedMap params) throws Exception; +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AppDataRepository.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AppDataRepository.java new file mode 100644 index 0000000000..6b827d6a3d --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AppDataRepository.java @@ -0,0 +1,27 @@ +package com.baeldung.oauth2.authorization.server.model; + +import javax.enterprise.context.ApplicationScoped; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.transaction.Transactional; + +@ApplicationScoped +public class AppDataRepository { + + @PersistenceContext + private EntityManager entityManager; + + public Client getClient(String clientId) { + return entityManager.find(Client.class, clientId); + } + + public User getUser(String userId) { + return entityManager.find(User.class, userId); + } + + @Transactional + public AuthorizationCode save(AuthorizationCode authorizationCode) { + entityManager.persist(authorizationCode); + return authorizationCode; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AuthorizationCode.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AuthorizationCode.java new file mode 100644 index 0000000000..a2ec088eb9 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/AuthorizationCode.java @@ -0,0 +1,73 @@ +package com.baeldung.oauth2.authorization.server.model; + +import javax.persistence.*; +import java.time.LocalDateTime; + +@Entity +@Table(name = "authorization_code") +public class AuthorizationCode { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "code") + private String code; + @Column(name = "client_id") + private String clientId; + @Column(name = "user_id") + private String userId; + @Column(name = "approved_scopes") + private String approvedScopes; + + @Column(name = "redirect_uri") + private String redirectUri; + + @Column(name = "expiration_date") + private LocalDateTime expirationDate; + + public String getUserId() { + return userId; + } + + public void setUserId(String username) { + this.userId = username; + } + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getApprovedScopes() { + return approvedScopes; + } + + public void setApprovedScopes(String approvedScopes) { + this.approvedScopes = approvedScopes; + } + + public String getRedirectUri() { + return redirectUri; + } + + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } + + public LocalDateTime getExpirationDate() { + return expirationDate; + } + + public void setExpirationDate(LocalDateTime expirationDate) { + this.expirationDate = expirationDate; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/Client.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/Client.java new file mode 100644 index 0000000000..9b5ad2f904 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/Client.java @@ -0,0 +1,62 @@ +package com.baeldung.oauth2.authorization.server.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "clients") +public class Client { + @Id + @Column(name = "client_id") + private String clientId; + @Column(name = "client_secret") + private String clientSecret; + @Column(name = "redirect_uri") + private String redirectUri; + @Column(name = "scope") + private String scope; + @Column(name = "authorized_grant_types") + private String authorizedGrantTypes; + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + public String getRedirectUri() { + return redirectUri; + } + + public void setRedirectUri(String redirectUri) { + this.redirectUri = redirectUri; + } + + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + + public String getAuthorizedGrantTypes() { + return authorizedGrantTypes; + } + + public void setAuthorizedGrantTypes(String authorizedGrantTypes) { + this.authorizedGrantTypes = authorizedGrantTypes; + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/User.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/User.java new file mode 100644 index 0000000000..b3821715f4 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/model/User.java @@ -0,0 +1,58 @@ +package com.baeldung.oauth2.authorization.server.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.security.Principal; + +@Entity +@Table(name = "users") +public class User implements Principal { + @Id + @Column(name = "user_id") + private String userId; + @Column(name = "password") + private String password; + @Column(name = "roles") + private String roles; + @Column(name = "scopes") + private String scopes; + + public String getUserId() { + return userId; + } + + public void setUserId(String username) { + this.userId = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getRoles() { + return roles; + } + + public void setRoles(String roles) { + this.roles = roles; + } + + public String getScopes() { + return scopes; + } + + public void setScopes(String scopes) { + this.scopes = scopes; + } + + @Override + public String getName() { + return getUserId(); + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/security/UserIdentityStore.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/security/UserIdentityStore.java new file mode 100644 index 0000000000..a32ab32cd4 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/security/UserIdentityStore.java @@ -0,0 +1,37 @@ +package com.baeldung.oauth2.authorization.server.security; + +import com.baeldung.oauth2.authorization.server.model.AppDataRepository; +import com.baeldung.oauth2.authorization.server.model.User; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.security.enterprise.credential.Credential; +import javax.security.enterprise.credential.UsernamePasswordCredential; +import javax.security.enterprise.identitystore.CredentialValidationResult; +import javax.security.enterprise.identitystore.IdentityStore; +import javax.transaction.Transactional; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Objects; + +import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT; + +@ApplicationScoped +@Transactional +public class UserIdentityStore implements IdentityStore { + + @Inject + private AppDataRepository appDataRepository; + + @Override + public CredentialValidationResult validate(Credential credential) { + UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential; + String userId = usernamePasswordCredential.getCaller(); + User user = appDataRepository.getUser(userId); + Objects.requireNonNull(user, "User should be not null"); + if (usernamePasswordCredential.getPasswordAsString().equals(user.getPassword())) { + return new CredentialValidationResult(userId, new HashSet<>(Arrays.asList(user.getRoles().split(",")))); + } + return INVALID_RESULT; + } +} \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java new file mode 100644 index 0000000000..84b9a89c54 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java @@ -0,0 +1,209 @@ +//package com.baeldung.security.oauth2.server.web; +// +//import AuthorizationCode; +//import Client; +//import User; +//import com.baeldung.security.oauth2.server.service.AuthCodeService; +// +//import javax.ejb.EJB; +//import javax.enterprise.context.RequestScoped; +//import javax.inject.Inject; +//import javax.persistence.EntityManager; +//import javax.persistence.PersistenceContext; +//import javax.security.enterprise.SecurityContext; +//import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition; +//import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; +//import javax.servlet.ServletException; +//import javax.servlet.annotation.HttpConstraint; +//import javax.servlet.annotation.ServletSecurity; +//import javax.servlet.annotation.WebServlet; +//import javax.servlet.http.HttpServlet; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import java.io.IOException; +//import java.security.Principal; +//import java.util.*; +// +///** +// * 1. GET http://localhost:8080/app/ (302) +// * 2. GET http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (302) +// * 3. GET http://localhost:8080/uaa/login (200) with initial request as hidden input +// * 4. POST http://localhost:8080/uaa/login (username, password, initial client request) (302) +// * 5. GET http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (200) +// * 7. POST http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (302) +// * 8. GET http://localhost:8080/app/?code=rkWijq06mL&state=A123 (200) +// */ +///* +// +//Query Params: +// client_id: app +// redirect_uri: http://localhost:8080/app/ +// response_type: code +// state: A123 +// +// ==> GET user login WITH client request as hidden input: +// +// +// ==> After user login ==> Initial client request +// ==> gen code +// == redirect to redirect uri + params code & state : 302, location : http://localhost:8080/app/?code=w6A0YQFzzg&state=A123 +//*/ +// +////authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 +////http://localhost:9080/authorize?response_type=code&client_id=client_id_1&redirect_uri=http://localhost:9080/app&state=A123 +// +////@RequestScoped +//@FormAuthenticationMechanismDefinition( +// loginToContinue = @LoginToContinue( +// loginPage = "/login-servlet", +// errorPage = "/login-error-servlet" +// ) +//) +//@WebServlet({"/authorize"}) +//@ServletSecurity(@HttpConstraint(rolesAllowed = "user")) +////@Stateless +//@RequestScoped +//public class AuthorizationEndpoint extends HttpServlet { +// +// private static final List authorizedResponseTypes = Arrays.asList("code", "token"); +// +// @Inject +// private SecurityContext securityContext; +// +// @PersistenceContext(name = "jpa-oauth2-pu") +// private EntityManager entityManager; +// +// @EJB +// private AuthCodeService authCodeService; +// +// //HTTP GET IS A MUST, POST IS OPTIONAL +// @Override +// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { +// +// String error = ""; +// +// //1. User Authentication +// Principal principal = securityContext.getCallerPrincipal(); +// +// //2. Check for a valid client_id +// String clientId = request.getParameter("client_id"); +// if (clientId == null) { +// request.setAttribute("error", "The client " + clientId + " doesn't exist."); +// } +// request.setAttribute("clientId", clientId); +// Client client = entityManager.find(Client.class, clientId); +// if (client == null) { +// request.setAttribute("error", "The client " + clientId + " doesn't exist."); +// } +// +// //3. check for a valid response_type +// String responseType = request.getParameter("response_type"); +// if (!authorizedResponseTypes.contains(responseType)) { +// error = "invalid_grant :" + responseType + ", response_type params should be one of :" + authorizedResponseTypes; +// request.setAttribute("error", error); +// request.getRequestDispatcher("/error.jsp") +// .forward(request, response); +// } +// +// //4. Optional redirect_uri, if provided should match +// String redirectUri = request.getParameter("redirect_uri"); +// checkRedirectUri(client, redirectUri); +// +// //save params +// String currentUri = request.getRequestURI(); +// request.setAttribute("post_redirect_uri", currentUri); +// +// String state = request.getParameter("state"); +// Map requestMap = new HashMap<>(); +// requestMap.put("response_type", responseType); +// requestMap.put("client_id", clientId); +// requestMap.put("redirect_uri", redirectUri); +// requestMap.put("state", state); +// request.setAttribute("requestMap", requestMap); +// +// //5.scope: Optional +// String requestedScope = request.getParameter("scope"); +// if (requestedScope.isEmpty()) { +// requestedScope = client.getScope(); +// } +// //requestedScope should be a subset of the client scope: clientScopes.containsAll(requestedScopes) +// //checkRequestedScope(requestedScope, client.getScope()); +// +// //sub set of user scope +// //allowed scope by the user +// +// User user = entityManager.find(User.class, principal.getName()); +// request.setAttribute("scopes", requestedScope); +// +// +// forward("/authorize.jsp", request, response); +// } +// +// @Override +// protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { +// String clientId = request.getParameter("client_id"); +// +// String responseType = request.getParameter("response_type"); +// if (!authorizedResponseTypes.contains(responseType)) { +// String error = "invalid_grant :" + responseType + ", response_type params should be one of :" + authorizedResponseTypes; +// request.setAttribute("error", error); +// forward("/error.jsp", request, response); +// } +// +// Client client = entityManager.find(Client.class, clientId); +// Objects.requireNonNull(client); +// +// String userId = securityContext.getCallerPrincipal().getName(); +// AuthorizationCode authorizationCode = new AuthorizationCode(); +// authorizationCode.setClientId(clientId); +// authorizationCode.setUserId(userId); +// String redirectUri = request.getParameter("redirect_uri"); +// authorizationCode.setRedirectUri(redirectUri); +// +// redirectUri = checkRedirectUri(client, redirectUri); +// +// String[] scope = request.getParameterValues("scope"); +// if (scope == null) { +// request.setAttribute("error", "User doesn't approved any scope"); +// forward("/error.jsp", request, response); +// } +// +// String approvedScopes = String.join(" ", scope); +// authorizationCode.setApprovedScopes(approvedScopes); +// +// //entityManager.persist(authorizationCode); +// authCodeService.save(authorizationCode); +// String code = authorizationCode.getCode(); +// +// StringBuilder sb = new StringBuilder(redirectUri); +// sb.append("?code=").append(code); +// +// //If the client send a state, Send it back +// String state = request.getParameter("state"); +// if (state != null) { +// sb.append("&state=").append(state); +// } +// response.sendRedirect(sb.toString()); +// } +// +// private String checkRedirectUri(Client client, String redirectUri) { +// //redirect uri +// if (redirectUri == null) { +// //erreur: param redirect_uri && client redirect_uri don't match. +// redirectUri = client.getRedirectUri(); +// if (redirectUri == null) { +// throw new IllegalStateException("redirectUri shloud be not null, unless a registred client have a redirect_uri."); +// } +// } else if (!redirectUri.equals(client.getRedirectUri())) { +// throw new IllegalStateException("request redirectUri and client registred redirect_uri should match."); +// } +// return redirectUri; +// } +// +// private void forward(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { +// request.getRequestDispatcher(path) +// .forward(request, response); +// } +//} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java new file mode 100644 index 0000000000..73085a68d1 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java @@ -0,0 +1,70 @@ +//package com.baeldung.security.oauth2.server.web; +// +//import AuthorizationGrantTypeHandler; +//import TokenResponse; +//import com.baeldung.security.oauth2.server.security.Authenticated; +//import com.nimbusds.jose.JOSEException; +// +//import javax.enterprise.inject.Instance; +//import javax.enterprise.inject.literal.NamedLiteral; +//import javax.inject.Inject; +//import javax.security.enterprise.SecurityContext; +//import javax.ws.rs.Consumes; +//import javax.ws.rs.POST; +//import javax.ws.rs.Path; +//import javax.ws.rs.Produces; +//import javax.ws.rs.core.MediaType; +//import javax.ws.rs.core.MultivaluedMap; +//import javax.ws.rs.core.Response; +//import java.security.Principal; +//import java.util.Arrays; +//import java.util.List; +//import java.util.Objects; +// +///** +// * { +// * "access_token" : "acb6803a48114d9fb4761e403c17f812", +// * "token_type" : "bearer", +// * "id_token" : "eyJhbGciOiJIUzI1NiIsImprdSI6Imh0dHBzOi8vbG9jYWxob3N0OjgwODAvdWFhL3Rva2VuX2tleXMiLCJraWQiOiJsZWdhY3ktdG9rZW4ta2V5IiwidHlwIjoiSldUIn0.eyJzdWIiOiIwNzYzZTM2MS02ODUwLTQ3N2ItYjk1Ny1iMmExZjU3MjczMTQiLCJhdWQiOlsibG9naW4iXSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3VhYS9vYXV0aC90b2tlbiIsImV4cCI6MTU1NzgzMDM4NSwiaWF0IjoxNTU3Nzg3MTg1LCJhenAiOiJsb2dpbiIsInNjb3BlIjpbIm9wZW5pZCJdLCJlbWFpbCI6IndyaHBONUB0ZXN0Lm9yZyIsInppZCI6InVhYSIsIm9yaWdpbiI6InVhYSIsImp0aSI6ImFjYjY4MDNhNDgxMTRkOWZiNDc2MWU0MDNjMTdmODEyIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImNsaWVudF9pZCI6ImxvZ2luIiwiY2lkIjoibG9naW4iLCJncmFudF90eXBlIjoiYXV0aG9yaXphdGlvbl9jb2RlIiwidXNlcl9uYW1lIjoid3JocE41QHRlc3Qub3JnIiwicmV2X3NpZyI6ImI3MjE5ZGYxIiwidXNlcl9pZCI6IjA3NjNlMzYxLTY4NTAtNDc3Yi1iOTU3LWIyYTFmNTcyNzMxNCIsImF1dGhfdGltZSI6MTU1Nzc4NzE4NX0.Fo8wZ_Zq9mwFks3LfXQ1PfJ4ugppjWvioZM6jSqAAQQ", +// * "refresh_token" : "f59dcb5dcbca45f981f16ce519d61486-r", +// * "expires_in" : 43199, +// * "scope" : "openid oauth.approvals", +// * "jti" : "acb6803a48114d9fb4761e403c17f812" +// * } +// */ +//@Path("token") +//public class TokenEndpoint { +// +// List supportedGrantTypes = Arrays.asList("authorization_code", "password", "refresh_token", "client_credentials"); +// +// @Inject +// private SecurityContext securityContext; +// +// @Inject +// Instance authorizationGrantTypeHandlers; +// +// @POST +// @Produces(MediaType.APPLICATION_JSON) +// @Consumes(MediaType.APPLICATION_FORM_URLENCODED) +// @Authenticated +// public Response token(MultivaluedMap params) throws JOSEException { +// //Authenticate client with [basic] http authentication mechanism +// Principal principal = securityContext.getCallerPrincipal(); +// Objects.requireNonNull(principal, "Client not authenticated!"); +// +// //Check grant_type params +// String grantType = params.getFirst("grant_type"); +// Objects.requireNonNull(grantType, "grant_type params is required"); +// //authorization_code, password, refresh, client_credentials +// if (!supportedGrantTypes.contains(grantType)) { +// throw new RuntimeException("grant_type parameter should be one of the following :" + supportedGrantTypes); +// } +// AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get(); +// TokenResponse tokenResponse = authorizationGrantTypeHandler.createAccessToken(principal.getName(), params); +// Response response = Response.ok(tokenResponse) +// .header("Cache-Control", "no-store") +// .header("Pragma", "no-cache") +// .build(); +// return response; +// } +//} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/liberty/config/server.xml b/oauth2-framework-impl/oauth2-authorization-server/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..97d9ec4a28 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/liberty/config/server.xml @@ -0,0 +1,32 @@ + + + + + localConnector-1.0 + cdi-2.0 + jaxrs-2.1 + jpa-2.2 + appSecurity-3.0 + jsp-2.3 + mpConfig-1.3 + + + + + + + + + + + + + + + + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/microprofile-config.properties b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 0000000000..d9c68bc111 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/microprofile-config.properties @@ -0,0 +1,2 @@ +signingkey=/META-INF/private-key.pem +verificationkey=/META-INF/public-key.pem diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/persistence.xml b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..a10ad3c886 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + + jdbc/OAuth2_DS + + + + + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/private-key.pem b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/private-key.pem new file mode 100644 index 0000000000..6e36cb4d78 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/private-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDYizUyvwY6qMd0 +ZkYPzP9mLTJOSczW8WtAbjhrgxk5LORIjcdv/aB1BAzDEOCX4UC+Rbs9YwaekIvW +7dL/t6xPzsA7+9tMt27TqUxXigWEFQG73w/WbEVzCG09IHqG7Ztjb6aGL+8pfcu+ +SLvOtXWrctHNbr35BYC5yBQaos9bH+nLYbh2Ff+emrpg7Kwoeis6MY6RgZIL/lxt +3beZt1NQhLEvB9t6XoSkyLQKSjT/OC8XOa4OYI4OfOSFqEUEp+8dKe3svZbQUNJf +KKehx78xx0rfwH+iBsFKkHdvt1ZHtINvYedAfGrc5rWnesunzOW7OKMAiIXAJSRA +rn9Iv5/fAgMBAAECggEAYHKwgSfAGIRwQhIDhqoh31qmG2SXjez9fjcZfhloNKUg +EIjFmcX3n+br4D42Kq+zbIwWd6MRobJz9oj6/9bJMsq9qHnnFWZmQHQZgqwBBPFu +UkVqAnE7BZ9tOFqs+EgAe+uQ2hejiHF1PA2dSNZd0L1VYRDAIJgo25aYDb0Sal0c +qaFmK1XzPnSIhgnopKP/TmUfALjeshtGvh6WkiXHTY2VKJlyLEiGd3/1tBZnzwSQ +QiS/2zfXL7lO0SYRA10m1BmtqGi3wSKIXUA6tNulmpXEMnYk4RtsqBClOanzQIm7 +f4Ie59AtUUlDdHzRmhxBaDprgAI/FdCxXkseLzk5sQKBgQDyptOhJ/VQ5tkgffJW +X2QwGIaNdvNCEL4GlgXKAWNkCzT4h+Q/2wFoKhaN2JH2YZwKCRwG/UZh4Hq22fdx +fa/DP8PK3zlX0c9dWQOtmBOe0/nG28kq9iqziP3ILLNuelfaMhxtRkUmR652VCzx +qazZmjoo2MxtA6BMiK3Vx5aikwKBgQDkdLalVveHKTVkrplQYNapQAtAwjlsNnMt +VJh6nLo3eOg1xBNA7JrYqx7sXRQInUGAyNKvgQL/lCQdMkTzyetLjJGsiFSEgeot +RMsDXBrJFYZiErbpQungpaevwAymaGi++nbCzhw1/n3AvVUhRKNknX8Ms0UKlLRZ +TCktCTChBQKBgGA7ZzzHgxPFqaCoMl6s0Cf+4gXigdDWoPYtszgM2uUHSMez5QKq +EWHFJ1Kz7BdBWMfmGvZupeYVR7WStf6NcRJHDJg9dRlt/QYxUjMbV9Sqjqmd6qce +H4s6LiOgDr0mygafzwRLVQs8bGVDNtvUhdd6wcwHRvOI957CqeZZlFT/AoGBAN2P +j79EW6U6wuyVJF0+vZDBauhwNQ6MtCEnZQWs0DCSUuop8d5KWVZ+huwGzTIZiPhk +S2goP4cs3eVu5k5k6oyHlJP2V7l24WzrxdPJVLTl6kFdEwWgfn//SGR7ZglRQxzM +fbcp+1QmL0FonZI5JhmjYR8pEXFUjJ/57AkgW4gdAoGASV3TlaNd+reb2l0kETqp +HrzzMIYkM2faZ8LmpcEO0wz606SK468bnl6SqVBYT2J0bkqCpEmPBtWs/OFCWd6x +93NndSfJk57/7AqNxfVyZWp2sjRzt5vZ4KPlRVvMHIGeJNbIV7RqUr6XGu+u3ZrS +B7SqwKZqdHVSULG9nMK7Iz8= +-----END PRIVATE KEY----- diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/public-key.pem b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/public-key.pem new file mode 100644 index 0000000000..f53ceca446 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/META-INF/public-key.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Is1Mr8GOqjHdGZGD8z/ +Zi0yTknM1vFrQG44a4MZOSzkSI3Hb/2gdQQMwxDgl+FAvkW7PWMGnpCL1u3S/7es +T87AO/vbTLdu06lMV4oFhBUBu98P1mxFcwhtPSB6hu2bY2+mhi/vKX3Lvki7zrV1 +q3LRzW69+QWAucgUGqLPWx/py2G4dhX/npq6YOysKHorOjGOkYGSC/5cbd23mbdT +UISxLwfbel6EpMi0Cko0/zgvFzmuDmCODnzkhahFBKfvHSnt7L2W0FDSXyinoce/ +McdK38B/ogbBSpB3b7dWR7SDb2HnQHxq3Oa1p3rLp8zluzijAIiFwCUkQK5/SL+f +3wIDAQAB +-----END PUBLIC KEY----- diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/data.sql b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/data.sql new file mode 100644 index 0000000000..ecda0fa2ad --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/resources/data.sql @@ -0,0 +1,3 @@ +INSERT INTO `users` (`user_id`, `password`, `roles`, `scopes`) VALUES ('appuser', 'appusersecret', 'USER', 'resource.read resource.write'); + +INSERT INTO `clients` (`client_id`, `client_secret`, `redirect_uri`,`scope`,`authorized_grant_types`) VALUES ('webappclient', 'webappclientsecret', 'http://localhost:9180/callback', 'resource.read resource.write', 'authorization_code refresh_token'); \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/WEB-INF/beans.xml b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..29595ff490 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,6 @@ + + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp new file mode 100644 index 0000000000..1004b5b8b7 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp @@ -0,0 +1,54 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + + Authorization + + + + +
+

Want to Authorize scopes for client : ${client.clientId} ?

+
+ +
+ + + + + + + + + +
Scopes : + + ${scope}
+
+
+ + +
+
+ +
+ + + diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/error.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/error.jsp new file mode 100644 index 0000000000..edb0bf28b7 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/error.jsp @@ -0,0 +1,25 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> + + + + + + Error + + + + + + +
+

${error}

+
+ + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login-error.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login-error.jsp new file mode 100644 index 0000000000..e69de29bb2 diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login.jsp new file mode 100644 index 0000000000..1d2dd93fd0 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/login.jsp @@ -0,0 +1,49 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> + + + + + Login Form + + + + +
+

Login Form

+
+
+ + + + + + + + + + + + + +
Username
Password
+
+ +
+ + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-client/pom.xml b/oauth2-framework-impl/oauth2-client/pom.xml new file mode 100644 index 0000000000..e46a44268e --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + oauth2-client + war + + + com.baeldung.oauth2 + oauth2-framework-impl + 1.0-SNAPSHOT + + + + 9180 + 9543 + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + + diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AuthorizationCodeServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AuthorizationCodeServlet.java new file mode 100644 index 0000000000..a5fdaf07f2 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AuthorizationCodeServlet.java @@ -0,0 +1,39 @@ +package com.baeldung.oauth2.client; + +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.UUID; + +@WebServlet(urlPatterns = "/authorize") +public class AuthorizationCodeServlet extends HttpServlet { + + @Inject + private Config config; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + //... + request.getSession().removeAttribute("tokenResponse"); + String state = UUID.randomUUID().toString(); + request.getSession().setAttribute("CLIENT_LOCAL_STATE", state); + + String authorizationUri = config.getValue("provider.authorizationUri", String.class); + String clientId = config.getValue("client.clientId", String.class); + String redirectUri = config.getValue("client.redirectUri", String.class); + String scope = config.getValue("client.scope", String.class); + + String authorizationLocation = authorizationUri + "?response_type=code" + + "&client_id=" + clientId + + "&redirect_uri=" + redirectUri + + "&scope=" + scope + + "&state=" + state; + response.sendRedirect(authorizationLocation); + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java new file mode 100644 index 0000000000..87aa8bc668 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java @@ -0,0 +1,76 @@ +package com.baeldung.oauth2.client; + +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.json.JsonObject; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import java.io.IOException; +import java.util.Base64; + +@WebServlet(urlPatterns = "/callback") +public class CallbackServlet extends HttpServlet { + + @Inject + private Config config; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + //Error: + String error = request.getParameter("error"); + if (error != null) { + request.setAttribute("error", error); + dispatch("/", request, response); + return; + } + String localState = (String) request.getSession().getAttribute("CLIENT_LOCAL_STATE"); + if (!localState.equals(request.getParameter("state"))) { + request.setAttribute("error", "The state attribute doesn't match !!"); + dispatch("/", request, response); + return; + } + + String code = request.getParameter("code"); + + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(config.getValue("provider.tokenUri", String.class)); + + Form form = new Form(); + form.param("grant_type", "authorization_code"); + form.param("code", code); + form.param("redirect_uri", config.getValue("client.redirectUri", String.class)); + + JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) + .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue()) + .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); + + request.getSession().setAttribute("tokenResponse", tokenResponse); + dispatch("/", request, response); + } + + private void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + RequestDispatcher requestDispatcher = request.getRequestDispatcher(location); + requestDispatcher.forward(request, response); + } + + private String getAuthorizationHeaderValue() { + String clientId = config.getValue("client.clientId", String.class); + String clientSecret = config.getValue("client.clientSecret", String.class); + String token = clientId + ":" + clientSecret; + String encodedString = Base64.getEncoder().encodeToString(token.getBytes()); + return "Basic " + encodedString; + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/DownstreamCallServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/DownstreamCallServlet.java new file mode 100644 index 0000000000..bbe850917b --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/DownstreamCallServlet.java @@ -0,0 +1,49 @@ +package com.baeldung.oauth2.client; + +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.json.JsonObject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.client.*; +import java.io.IOException; +import java.io.PrintWriter; + +@WebServlet(urlPatterns = "/downstream") +public class DownstreamCallServlet extends HttpServlet { + + @Inject + private Config config; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { + resp.setContentType("text/html;charset=UTF-8"); + String action = request.getParameter("action"); + Client client = ClientBuilder.newClient(); + WebTarget webTarget = client.target(config.getValue("resourceServerUri", String.class)); + WebTarget resourceWebTarget; + String response = null; + JsonObject tokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse"); + if ("read".equals(action)) { + resourceWebTarget = webTarget.path("resource/read"); + Invocation.Builder invocationBuilder = resourceWebTarget.request(); + response = invocationBuilder + .header("authorization", tokenResponse.getString("access_token")) + .get(String.class); + } else if ("write".equals(action)) { + resourceWebTarget = webTarget.path("resource/write"); + Invocation.Builder invocationBuilder = resourceWebTarget.request(); + response = invocationBuilder + .header("authorization", tokenResponse.getString("access_token")) + .post(Entity.text("body string"), String.class); + } + PrintWriter out = resp.getWriter(); + out.println(response); + out.flush(); + out.close(); + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/liberty/config/server.xml b/oauth2-framework-impl/oauth2-client/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..26dc730361 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/liberty/config/server.xml @@ -0,0 +1,19 @@ + + + + + localConnector-1.0 + cdi-2.0 + jsp-2.3 + mpConfig-1.3 + jaxrsClient-2.1 + jsonp-1.1 + + + + + + + + + diff --git a/oauth2-framework-impl/oauth2-client/src/main/resources/META-INF/microprofile-config.properties b/oauth2-framework-impl/oauth2-client/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 0000000000..d66f4f6a74 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/resources/META-INF/microprofile-config.properties @@ -0,0 +1,12 @@ +#Client registration +client.clientId=webappclient +client.clientSecret=webappclientsecret +client.redirectUri=http://localhost:9180/callback +client.scope=resource.read resource.write + +#Provider +provider.authorizationUri=http://127.0.0.1:9080/authorize +provider.tokenUri=http://127.0.0.1:9080/token + +#Resource Server +resourceServerUri=http://localhost:9280/api \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/beans.xml b/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..29595ff490 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,6 @@ + + + diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/web.xml b/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..0203894c1b --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,5 @@ + + + index.jsp + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp new file mode 100644 index 0000000000..23fec70f33 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp @@ -0,0 +1,97 @@ +<%@ page import="org.eclipse.microprofile.config.Config" %> +<%@ page import="org.eclipse.microprofile.config.ConfigProvider" %> + + + + + + OAuth2 Client + + + + + +<% + Config config1 = ConfigProvider.getConfig(); +%> + +
"> + Error : ${error} +
+ +
+

OAuth2 Authorization Server

+
+

Client Registration :

+
    +
  • client_id: <%=config1.getValue("client.clientId", String.class)%> +
  • +
  • client_secret: <%=config1.getValue("client.clientSecret", String.class)%> +
  • +
  • redirect_uri: <%=config1.getValue("client.redirectUri", String.class)%> +
  • +
  • scope: <%=config1.getValue("client.scope", String.class)%> +
  • +
+

Authorization Server :

+
    +
  • authorization_uri: <%=config1.getValue("provider.authorizationUri", String.class)%> +
  • +
  • token_uri: <%=config1.getValue("provider.tokenUri", String.class)%> +
  • +
+
+
+

OAuth2 Client

+
+

Token Request :

+ + +

Token Response:

+
    +
  • access_token: ${tokenResponse.getString("access_token")}
  • +
  • scope: ${tokenResponse.getString("scope")}
  • +
  • Expires in (s): ${tokenResponse.getInt("expires_in")}
  • +
+
+
+

OAuth2 Resource Server Call

+
+ + +
+ + + \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-resource-server/pom.xml b/oauth2-framework-impl/oauth2-resource-server/pom.xml new file mode 100644 index 0000000000..9b58c33472 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + oauth2-resource-server + war + + + com.baeldung.oauth2 + oauth2-framework-impl + 1.0-SNAPSHOT + + + + 9280 + 8643 + http://localhost:9080 + http://localhost:9280 + + + + + org.eclipse.microprofile.jwt + microprofile-jwt-auth-api + 1.1 + provided + + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + + + diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/OAuth2ResourceServerApplication.java b/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/OAuth2ResourceServerApplication.java new file mode 100644 index 0000000000..835e80a416 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/OAuth2ResourceServerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.oauth2.resource.server; + +import org.eclipse.microprofile.auth.LoginConfig; + +import javax.annotation.security.DeclareRoles; +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/api") +@DeclareRoles({"resource.read", "resource.write"}) +@LoginConfig(authMethod = "MP-JWT") +public class OAuth2ResourceServerApplication extends Application { +} diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/secure/ProtectedResource.java b/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/secure/ProtectedResource.java new file mode 100644 index 0000000000..300de83c6d --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/java/com/baeldung/oauth2/resource/server/secure/ProtectedResource.java @@ -0,0 +1,38 @@ +package com.baeldung.oauth2.resource.server.secure; + +import org.eclipse.microprofile.jwt.JsonWebToken; + +import javax.annotation.security.RolesAllowed; +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.core.Response; +import java.util.UUID; + +@Path("/resource") +@RequestScoped +public class ProtectedResource { + + @Inject + private JsonWebToken principal; + + @GET + @RolesAllowed("resource.read") + @Path("/read") + public Response read() { + //DoStaff + return Response.ok("Hello, " + principal.getName()).build(); + } + + @POST + @RolesAllowed("resource.write") + @Path("/write") + public Response write() { + //DoStaff + return Response.ok("Hello, " + principal.getName()) + .header("location", UUID.randomUUID().toString()) + .build(); + } +} diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/liberty/config/server.xml b/oauth2-framework-impl/oauth2-resource-server/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c54d698359 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/liberty/config/server.xml @@ -0,0 +1,20 @@ + + + + + localConnector-1.0 + cdi-2.0 + jaxrs-2.1 + jsonp-1.1 + mpConfig-1.3 + mpJwt-1.1 + + + + + + + + + + diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/microprofile-config.properties b/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/microprofile-config.properties new file mode 100644 index 0000000000..be6919ec50 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/microprofile-config.properties @@ -0,0 +1,2 @@ +mp.jwt.verify.publickey.location=/META-INF/public-key.pem +mp.jwt.verify.issuer=http://localhost:9080 \ No newline at end of file diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/public-key.pem b/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/public-key.pem new file mode 100644 index 0000000000..f53ceca446 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/resources/META-INF/public-key.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Is1Mr8GOqjHdGZGD8z/ +Zi0yTknM1vFrQG44a4MZOSzkSI3Hb/2gdQQMwxDgl+FAvkW7PWMGnpCL1u3S/7es +T87AO/vbTLdu06lMV4oFhBUBu98P1mxFcwhtPSB6hu2bY2+mhi/vKX3Lvki7zrV1 +q3LRzW69+QWAucgUGqLPWx/py2G4dhX/npq6YOysKHorOjGOkYGSC/5cbd23mbdT +UISxLwfbel6EpMi0Cko0/zgvFzmuDmCODnzkhahFBKfvHSnt7L2W0FDSXyinoce/ +McdK38B/ogbBSpB3b7dWR7SDb2HnQHxq3Oa1p3rLp8zluzijAIiFwCUkQK5/SL+f +3wIDAQAB +-----END PUBLIC KEY----- diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/WEB-INF/beans.xml b/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..2777559c20 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,6 @@ + + + diff --git a/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/index.html b/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/index.html new file mode 100644 index 0000000000..7ea29c1097 --- /dev/null +++ b/oauth2-framework-impl/oauth2-resource-server/src/main/webapp/index.html @@ -0,0 +1,37 @@ + + + + + Eclipse MicroProfile demo + + + +

MicroProfile

+ +Hello JAX-RS endpoint
+ + +

Config

+Injected config values
+Config values by lookup
+ + + + + + + + + +

JWT Auth

+Look at readme.md on how to test protected endpoint. + + + + + + + + + + \ No newline at end of file diff --git a/oauth2-framework-impl/pom.xml b/oauth2-framework-impl/pom.xml new file mode 100644 index 0000000000..281103660b --- /dev/null +++ b/oauth2-framework-impl/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + com.baeldung.oauth2 + oauth2-framework-impl + 1.0-SNAPSHOT + pom + + + 1.8 + 1.8 + false + RELEASE + 2.6.4 + + + + + javax + javaee-web-api + 8.0 + provided + + + org.eclipse.microprofile.config + microprofile-config-api + 1.3 + provided + + + + + ${project.artifactId} + + + ${basedir}/src/main/resources + + **/*.* + + + + true + ${basedir}/src/main/liberty + + **/*.* + + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${openliberty.maven.version} + + + package-server + package + + create-server + install-apps + + + target/wlp-package + + + + + + io.openliberty + openliberty-webProfile8 + ${openliberty.version} + zip + + target/classes/config/server.xml + ${project.build.directory}/${project.build.finalName}.war + project + ${project.basedir}/src/main/liberty/server + apps + true + + + + + + + oauth2-authorization-server + oauth2-resource-server + oauth2-client + + From 81358eefbb18a723f3a6336b07a19373b8e842d3 Mon Sep 17 00:00:00 2001 From: Drazen Nikolic Date: Sun, 30 Jun 2019 18:46:48 +0200 Subject: [PATCH 064/352] BAEL-2486: Added link to published article in README of examples module. (#7225) --- spring-5-data-reactive/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-5-data-reactive/README.md b/spring-5-data-reactive/README.md index f8886ac18b..f3205c23bc 100644 --- a/spring-5-data-reactive/README.md +++ b/spring-5-data-reactive/README.md @@ -6,3 +6,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles - [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) - [Spring Data Reactive Repositories with MongoDB](http://www.baeldung.com/spring-data-mongodb-reactive) +- [Spring Data MongoDB Tailable Cursors](https://www.baeldung.com/spring-data-mongodb-tailable-cursors) From c280f9ee4eb54417399d0eb2347626fbc775324e Mon Sep 17 00:00:00 2001 From: amit2103 Date: Mon, 1 Jul 2019 00:23:02 +0530 Subject: [PATCH 065/352] [BAEL-14274] - Fixed article code for https://www.baeldung.com/spring-security-method-security --- .../java/org/baeldung/methodsecurity/TestMethodSecurity.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java index 309ee3076d..009d9af9fc 100644 --- a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java +++ b/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java @@ -80,7 +80,7 @@ public class TestMethodSecurity { @Test @WithMockUser(username = "JOHN", authorities = { "SYS_ADMIN" }) - public void givenAuthoritySysAdmin_whenCallGetUsernameInLowerCase_thenReturnUsername() { + public void givenAuthoritySysAdmin_whenCallGetUsernameLC_thenReturnUsername() { String username = userRoleService.getUsernameLC(); assertEquals("john", username); } From a79e249b61911dfa658c611cc89d6225be33530d Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 30 Jun 2019 16:27:50 -0500 Subject: [PATCH 066/352] BAEL-2985 fix Spring Boot apps in spring-data-rest (#7224) * BAEL-2246: add link back to article * BAEL-2174: rename core-java-net module to core-java-networking * BAEL-2174: add link back to article * BAEL-2363 BAEL-2337 BAEL-1996 BAEL-2277 add links back to articles * BAEL-2367: add link back to article * BAEL-2335: add link back to article * BAEL-2413: add link back to article * Update README.MD * BAEL-2577: add link back to article * BAEL-2490: add link back to article * BAEL-2471: add link back to article * BAEL-2583: add link back to article * BAEL-2738: add link back to article * BAEL-2711: Add spring-boot-angular module to root pom * BAEL-2544 BAEL-2711 BAEL-2575 BAEL-2657 Add links back to articles * BAEL-2736: Add link back to article * BAEL-2789: Add link back to article * BAEL-2489: add link back to article * BAEL-2840: add link back to article * BAEL-2655: add link back to article * BAEL-2884: add link back to article * BAEL-2985: Fix Spring Boot Apps in spring-data-rest module --- .../{ => books}/SpringDataRestApplication.java | 2 +- .../com/baeldung/{ => books}/config/DbConfig.java | 6 +++--- .../com/baeldung/{ => books}/config/MvcConfig.java | 7 ++++--- .../com/baeldung/{ => books}/config/RestConfig.java | 7 ++++--- .../{ => books}/config/ValidatorEventRegister.java | 2 +- .../baeldung/{ => books}/dialect/SQLiteDialect.java | 2 +- .../dialect/SQLiteIdentityColumnSupport.java | 2 +- .../{ => books}/events/AuthorEventHandler.java | 7 ++++--- .../{ => books}/events/BookEventHandler.java | 8 +++++--- .../handlers/RestResponseEntityExceptionHandler.java | 2 +- .../com/baeldung/{ => books}/models/Address.java | 2 +- .../java/com/baeldung/{ => books}/models/Author.java | 2 +- .../java/com/baeldung/{ => books}/models/Book.java | 2 +- .../com/baeldung/{ => books}/models/Library.java | 2 +- .../com/baeldung/{ => books}/models/Subject.java | 2 +- .../com/baeldung/{ => books}/models/WebsiteUser.java | 2 +- .../baeldung/{ => books}/projections/CustomBook.java | 6 +++--- .../{ => books}/repositories/AddressRepository.java | 4 ++-- .../{ => books}/repositories/AuthorRepository.java | 4 ++-- .../{ => books}/repositories/BookRepository.java | 6 +++--- .../{ => books}/repositories/LibraryRepository.java | 4 ++-- .../{ => books}/repositories/SubjectRepository.java | 5 +++-- .../{ => books}/repositories/UserRepository.java | 5 +++-- .../{ => books}/validators/WebsiteUserValidator.java | 4 ++-- .../events/AuthorEventHandlerUnitTest.java | 6 ++++-- .../{ => books}/events/BookEventHandlerUnitTest.java | 8 +++++--- .../projections}/SpringDataProjectionLiveTest.java | 12 ++++++------ .../SpringDataRestValidatorIntegrationTest.java | 6 +++--- .../test/UserControllerIntegrationTest.java | 2 +- .../org/baeldung/SpringContextIntegrationTest.java | 2 +- 30 files changed, 71 insertions(+), 60 deletions(-) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/SpringDataRestApplication.java (91%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/config/DbConfig.java (94%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/config/MvcConfig.java (85%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/config/RestConfig.java (86%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/config/ValidatorEventRegister.java (94%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/dialect/SQLiteDialect.java (98%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/dialect/SQLiteIdentityColumnSupport.java (94%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/events/AuthorEventHandler.java (89%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/events/BookEventHandler.java (86%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/exception/handlers/RestResponseEntityExceptionHandler.java (94%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/models/Address.java (96%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/models/Author.java (97%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/models/Book.java (97%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/models/Library.java (97%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/models/Subject.java (94%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/models/WebsiteUser.java (95%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/projections/CustomBook.java (77%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/repositories/AddressRepository.java (62%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/repositories/AuthorRepository.java (62%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/repositories/BookRepository.java (67%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/repositories/LibraryRepository.java (62%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/repositories/SubjectRepository.java (85%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/repositories/UserRepository.java (91%) rename spring-data-rest/src/main/java/com/baeldung/{ => books}/validators/WebsiteUserValidator.java (87%) rename spring-data-rest/src/test/java/com/baeldung/{ => books}/events/AuthorEventHandlerUnitTest.java (86%) rename spring-data-rest/src/test/java/com/baeldung/{ => books}/events/BookEventHandlerUnitTest.java (81%) rename spring-data-rest/src/test/java/com/baeldung/{projection => books/projections}/SpringDataProjectionLiveTest.java (91%) rename spring-data-rest/src/test/java/com/baeldung/{ => books}/validator/SpringDataRestValidatorIntegrationTest.java (97%) diff --git a/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java b/spring-data-rest/src/main/java/com/baeldung/books/SpringDataRestApplication.java similarity index 91% rename from spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java rename to spring-data-rest/src/main/java/com/baeldung/books/SpringDataRestApplication.java index 702acb5b65..097a6aabd7 100644 --- a/spring-data-rest/src/main/java/com/baeldung/SpringDataRestApplication.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/SpringDataRestApplication.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.books; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java b/spring-data-rest/src/main/java/com/baeldung/books/config/DbConfig.java similarity index 94% rename from spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java rename to spring-data-rest/src/main/java/com/baeldung/books/config/DbConfig.java index 3ca728ec94..20008eb583 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/DbConfig.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/config/DbConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.config; +package com.baeldung.books.config; import java.util.Properties; @@ -16,7 +16,7 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; @Configuration -@EnableJpaRepositories(basePackages = "com.baeldung.repositories") +@EnableJpaRepositories(basePackages = "com.baeldung.books.repositories") // @PropertySource("persistence-h2.properties") // @PropertySource("persistence-hsqldb.properties") // @PropertySource("persistence-derby.properties") @@ -40,7 +40,7 @@ public class DbConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.models" }); + em.setPackagesToScan(new String[] { "com.baeldung.books.models" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java b/spring-data-rest/src/main/java/com/baeldung/books/config/MvcConfig.java similarity index 85% rename from spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java rename to spring-data-rest/src/main/java/com/baeldung/books/config/MvcConfig.java index 9d0d3a6687..69e984ad06 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/config/MvcConfig.java @@ -1,13 +1,14 @@ -package com.baeldung.config; +package com.baeldung.books.config; -import com.baeldung.events.AuthorEventHandler; -import com.baeldung.events.BookEventHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import com.baeldung.books.events.AuthorEventHandler; +import com.baeldung.books.events.BookEventHandler; + @Configuration @EnableWebMvc public class MvcConfig implements WebMvcConfigurer { diff --git a/spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java b/spring-data-rest/src/main/java/com/baeldung/books/config/RestConfig.java similarity index 86% rename from spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java rename to spring-data-rest/src/main/java/com/baeldung/books/config/RestConfig.java index 47cb95693b..1c6f04331e 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/RestConfig.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/config/RestConfig.java @@ -1,7 +1,8 @@ -package com.baeldung.config; +package com.baeldung.books.config; + +import com.baeldung.books.models.WebsiteUser; +import com.baeldung.books.projections.CustomBook; -import com.baeldung.models.WebsiteUser; -import com.baeldung.projections.CustomBook; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.core.mapping.ExposureConfiguration; diff --git a/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java b/spring-data-rest/src/main/java/com/baeldung/books/config/ValidatorEventRegister.java similarity index 94% rename from spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java rename to spring-data-rest/src/main/java/com/baeldung/books/config/ValidatorEventRegister.java index 632ad9183a..bbaf9a2771 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/ValidatorEventRegister.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/config/ValidatorEventRegister.java @@ -1,4 +1,4 @@ -package com.baeldung.config; +package com.baeldung.books.config; import java.util.Arrays; import java.util.List; diff --git a/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteDialect.java b/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java similarity index 98% rename from spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteDialect.java rename to spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java index 4512f7d34d..6e840eec43 100644 --- a/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteDialect.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java @@ -1,4 +1,4 @@ -package com.baeldung.dialect; +package com.baeldung.books.dialect; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.identity.IdentityColumnSupport; diff --git a/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteIdentityColumnSupport.java b/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java similarity index 94% rename from spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteIdentityColumnSupport.java rename to spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java index cf6e3a9a97..682d82c6f1 100644 --- a/spring-data-rest/src/main/java/com/baeldung/dialect/SQLiteIdentityColumnSupport.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java @@ -1,4 +1,4 @@ -package com.baeldung.dialect; +package com.baeldung.books.dialect; import org.hibernate.MappingException; import org.hibernate.dialect.identity.IdentityColumnSupportImpl; diff --git a/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java b/spring-data-rest/src/main/java/com/baeldung/books/events/AuthorEventHandler.java similarity index 89% rename from spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java rename to spring-data-rest/src/main/java/com/baeldung/books/events/AuthorEventHandler.java index 485dc8e221..b390a529ba 100644 --- a/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/events/AuthorEventHandler.java @@ -1,9 +1,10 @@ -package com.baeldung.events; +package com.baeldung.books.events; -import com.baeldung.models.Author; -import com.baeldung.models.Book; import org.springframework.data.rest.core.annotation.*; +import com.baeldung.books.models.Author; +import com.baeldung.books.models.Book; + import java.util.logging.Logger; @RepositoryEventHandler diff --git a/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java b/spring-data-rest/src/main/java/com/baeldung/books/events/BookEventHandler.java similarity index 86% rename from spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java rename to spring-data-rest/src/main/java/com/baeldung/books/events/BookEventHandler.java index 36ae62b926..0afb3a6279 100644 --- a/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/events/BookEventHandler.java @@ -1,13 +1,15 @@ -package com.baeldung.events; +package com.baeldung.books.events; import java.util.logging.Logger; -import com.baeldung.models.Author; -import com.baeldung.models.Book; + import org.apache.commons.logging.Log; import org.springframework.data.rest.core.annotation.HandleAfterDelete; import org.springframework.data.rest.core.annotation.HandleBeforeCreate; import org.springframework.data.rest.core.annotation.RepositoryEventHandler; +import com.baeldung.books.models.Author; +import com.baeldung.books.models.Book; + @RepositoryEventHandler public class BookEventHandler { Logger logger = Logger.getLogger("Class BookEventHandler"); diff --git a/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java b/spring-data-rest/src/main/java/com/baeldung/books/exception/handlers/RestResponseEntityExceptionHandler.java similarity index 94% rename from spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java rename to spring-data-rest/src/main/java/com/baeldung/books/exception/handlers/RestResponseEntityExceptionHandler.java index a3ef91f6d6..4a961e5250 100644 --- a/spring-data-rest/src/main/java/com/baeldung/exception/handlers/RestResponseEntityExceptionHandler.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/exception/handlers/RestResponseEntityExceptionHandler.java @@ -1,4 +1,4 @@ -package com.baeldung.exception.handlers; +package com.baeldung.books.exception.handlers; import org.springframework.data.rest.core.RepositoryConstraintViolationException; import org.springframework.http.HttpHeaders; diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Address.java b/spring-data-rest/src/main/java/com/baeldung/books/models/Address.java similarity index 96% rename from spring-data-rest/src/main/java/com/baeldung/models/Address.java rename to spring-data-rest/src/main/java/com/baeldung/books/models/Address.java index 713af58ae6..3c36db0f3c 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Address.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/models/Address.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.books.models; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Author.java b/spring-data-rest/src/main/java/com/baeldung/books/models/Author.java similarity index 97% rename from spring-data-rest/src/main/java/com/baeldung/models/Author.java rename to spring-data-rest/src/main/java/com/baeldung/books/models/Author.java index 3f43af9c47..aec2e62ebf 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Author.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/models/Author.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.books.models; import java.util.List; diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Book.java b/spring-data-rest/src/main/java/com/baeldung/books/models/Book.java similarity index 97% rename from spring-data-rest/src/main/java/com/baeldung/models/Book.java rename to spring-data-rest/src/main/java/com/baeldung/books/models/Book.java index 07b0d08b84..7451b04b3b 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Book.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/models/Book.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.books.models; import java.util.List; diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Library.java b/spring-data-rest/src/main/java/com/baeldung/books/models/Library.java similarity index 97% rename from spring-data-rest/src/main/java/com/baeldung/models/Library.java rename to spring-data-rest/src/main/java/com/baeldung/books/models/Library.java index 091975f5d0..5f95169a9b 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Library.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/models/Library.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.books.models; import java.util.List; diff --git a/spring-data-rest/src/main/java/com/baeldung/models/Subject.java b/spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java similarity index 94% rename from spring-data-rest/src/main/java/com/baeldung/models/Subject.java rename to spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java index 4e5fa82148..11a4425fdd 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/Subject.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.books.models; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-data-rest/src/main/java/com/baeldung/models/WebsiteUser.java b/spring-data-rest/src/main/java/com/baeldung/books/models/WebsiteUser.java similarity index 95% rename from spring-data-rest/src/main/java/com/baeldung/models/WebsiteUser.java rename to spring-data-rest/src/main/java/com/baeldung/books/models/WebsiteUser.java index 4eb9773e36..e632623019 100644 --- a/spring-data-rest/src/main/java/com/baeldung/models/WebsiteUser.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/models/WebsiteUser.java @@ -1,4 +1,4 @@ -package com.baeldung.models; +package com.baeldung.books.models; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java b/spring-data-rest/src/main/java/com/baeldung/books/projections/CustomBook.java similarity index 77% rename from spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java rename to spring-data-rest/src/main/java/com/baeldung/books/projections/CustomBook.java index 3dc6938f5c..5fe78c869d 100644 --- a/spring-data-rest/src/main/java/com/baeldung/projections/CustomBook.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/projections/CustomBook.java @@ -1,12 +1,12 @@ -package com.baeldung.projections; +package com.baeldung.books.projections; import java.util.List; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.rest.core.config.Projection; -import com.baeldung.models.Author; -import com.baeldung.models.Book; +import com.baeldung.books.models.Author; +import com.baeldung.books.models.Book; @Projection(name = "customBook", types = { Book.class }) public interface CustomBook { diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/AddressRepository.java b/spring-data-rest/src/main/java/com/baeldung/books/repositories/AddressRepository.java similarity index 62% rename from spring-data-rest/src/main/java/com/baeldung/repositories/AddressRepository.java rename to spring-data-rest/src/main/java/com/baeldung/books/repositories/AddressRepository.java index 1cc7527e80..5e3900f439 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/AddressRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/repositories/AddressRepository.java @@ -1,8 +1,8 @@ -package com.baeldung.repositories; +package com.baeldung.books.repositories; import org.springframework.data.repository.CrudRepository; -import com.baeldung.models.Address; +import com.baeldung.books.models.Address; public interface AddressRepository extends CrudRepository { diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/AuthorRepository.java b/spring-data-rest/src/main/java/com/baeldung/books/repositories/AuthorRepository.java similarity index 62% rename from spring-data-rest/src/main/java/com/baeldung/repositories/AuthorRepository.java rename to spring-data-rest/src/main/java/com/baeldung/books/repositories/AuthorRepository.java index 2d470367ef..837e13b1d2 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/AuthorRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/repositories/AuthorRepository.java @@ -1,8 +1,8 @@ -package com.baeldung.repositories; +package com.baeldung.books.repositories; import org.springframework.data.repository.CrudRepository; -import com.baeldung.models.Author; +import com.baeldung.books.models.Author; public interface AuthorRepository extends CrudRepository { diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java b/spring-data-rest/src/main/java/com/baeldung/books/repositories/BookRepository.java similarity index 67% rename from spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java rename to spring-data-rest/src/main/java/com/baeldung/books/repositories/BookRepository.java index eee44f35d4..5d7e277526 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/BookRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/repositories/BookRepository.java @@ -1,10 +1,10 @@ -package com.baeldung.repositories; +package com.baeldung.books.repositories; import org.springframework.data.repository.CrudRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; -import com.baeldung.models.Book; -import com.baeldung.projections.CustomBook; +import com.baeldung.books.models.Book; +import com.baeldung.books.projections.CustomBook; @RepositoryRestResource(excerptProjection = CustomBook.class) public interface BookRepository extends CrudRepository { diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/LibraryRepository.java b/spring-data-rest/src/main/java/com/baeldung/books/repositories/LibraryRepository.java similarity index 62% rename from spring-data-rest/src/main/java/com/baeldung/repositories/LibraryRepository.java rename to spring-data-rest/src/main/java/com/baeldung/books/repositories/LibraryRepository.java index c00787f03c..92518339a0 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/LibraryRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/repositories/LibraryRepository.java @@ -1,8 +1,8 @@ -package com.baeldung.repositories; +package com.baeldung.books.repositories; import org.springframework.data.repository.CrudRepository; -import com.baeldung.models.Library; +import com.baeldung.books.models.Library; public interface LibraryRepository extends CrudRepository { diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/SubjectRepository.java b/spring-data-rest/src/main/java/com/baeldung/books/repositories/SubjectRepository.java similarity index 85% rename from spring-data-rest/src/main/java/com/baeldung/repositories/SubjectRepository.java rename to spring-data-rest/src/main/java/com/baeldung/books/repositories/SubjectRepository.java index 76e34b0799..187b01f222 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/SubjectRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/repositories/SubjectRepository.java @@ -1,11 +1,12 @@ -package com.baeldung.repositories; +package com.baeldung.books.repositories; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RestResource; -import com.baeldung.models.Subject; + +import com.baeldung.books.models.Subject; public interface SubjectRepository extends PagingAndSortingRepository { diff --git a/spring-data-rest/src/main/java/com/baeldung/repositories/UserRepository.java b/spring-data-rest/src/main/java/com/baeldung/books/repositories/UserRepository.java similarity index 91% rename from spring-data-rest/src/main/java/com/baeldung/repositories/UserRepository.java rename to spring-data-rest/src/main/java/com/baeldung/books/repositories/UserRepository.java index a3fed1c318..f0823338bc 100644 --- a/spring-data-rest/src/main/java/com/baeldung/repositories/UserRepository.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/repositories/UserRepository.java @@ -1,11 +1,12 @@ -package com.baeldung.repositories; +package com.baeldung.books.repositories; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; import org.springframework.web.bind.annotation.CrossOrigin; -import com.baeldung.models.WebsiteUser; + +import com.baeldung.books.models.WebsiteUser; @CrossOrigin @RepositoryRestResource(collectionResourceRel = "users", path = "users") diff --git a/spring-data-rest/src/main/java/com/baeldung/validators/WebsiteUserValidator.java b/spring-data-rest/src/main/java/com/baeldung/books/validators/WebsiteUserValidator.java similarity index 87% rename from spring-data-rest/src/main/java/com/baeldung/validators/WebsiteUserValidator.java rename to spring-data-rest/src/main/java/com/baeldung/books/validators/WebsiteUserValidator.java index 0380332708..ad7511c2ba 100644 --- a/spring-data-rest/src/main/java/com/baeldung/validators/WebsiteUserValidator.java +++ b/spring-data-rest/src/main/java/com/baeldung/books/validators/WebsiteUserValidator.java @@ -1,10 +1,10 @@ -package com.baeldung.validators; +package com.baeldung.books.validators; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; -import com.baeldung.models.WebsiteUser; +import com.baeldung.books.models.WebsiteUser; @Component("beforeCreateWebsiteUserValidator") public class WebsiteUserValidator implements Validator { diff --git a/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java b/spring-data-rest/src/test/java/com/baeldung/books/events/AuthorEventHandlerUnitTest.java similarity index 86% rename from spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java rename to spring-data-rest/src/test/java/com/baeldung/books/events/AuthorEventHandlerUnitTest.java index c01d5882a0..719c4d7c86 100644 --- a/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/books/events/AuthorEventHandlerUnitTest.java @@ -1,6 +1,8 @@ -package com.baeldung.events; +package com.baeldung.books.events; + +import com.baeldung.books.events.AuthorEventHandler; +import com.baeldung.books.models.Author; -import com.baeldung.models.Author; import org.junit.Test; import org.mockito.Mockito; import org.springframework.data.rest.core.annotation.RepositoryEventHandler; diff --git a/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java b/spring-data-rest/src/test/java/com/baeldung/books/events/BookEventHandlerUnitTest.java similarity index 81% rename from spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java rename to spring-data-rest/src/test/java/com/baeldung/books/events/BookEventHandlerUnitTest.java index d6b8b3b25e..4b9d77afa2 100644 --- a/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/books/events/BookEventHandlerUnitTest.java @@ -1,7 +1,9 @@ -package com.baeldung.events; +package com.baeldung.books.events; + +import com.baeldung.books.events.BookEventHandler; +import com.baeldung.books.models.Author; +import com.baeldung.books.models.Book; -import com.baeldung.models.Author; -import com.baeldung.models.Book; import org.junit.Test; import org.mockito.Mockito; diff --git a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java b/spring-data-rest/src/test/java/com/baeldung/books/projections/SpringDataProjectionLiveTest.java similarity index 91% rename from spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java rename to spring-data-rest/src/test/java/com/baeldung/books/projections/SpringDataProjectionLiveTest.java index 274ae3bc1d..98b5831b96 100644 --- a/spring-data-rest/src/test/java/com/baeldung/projection/SpringDataProjectionLiveTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/books/projections/SpringDataProjectionLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.projection; +package com.baeldung.books.projections; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -16,11 +16,11 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.SpringDataRestApplication; -import com.baeldung.models.Author; -import com.baeldung.models.Book; -import com.baeldung.repositories.AuthorRepository; -import com.baeldung.repositories.BookRepository; +import com.baeldung.books.SpringDataRestApplication; +import com.baeldung.books.models.Author; +import com.baeldung.books.models.Book; +import com.baeldung.books.repositories.AuthorRepository; +import com.baeldung.books.repositories.BookRepository; @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringDataRestApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) diff --git a/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java b/spring-data-rest/src/test/java/com/baeldung/books/validator/SpringDataRestValidatorIntegrationTest.java similarity index 97% rename from spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java rename to spring-data-rest/src/test/java/com/baeldung/books/validator/SpringDataRestValidatorIntegrationTest.java index 6da76d6a33..75733475e7 100644 --- a/spring-data-rest/src/test/java/com/baeldung/validator/SpringDataRestValidatorIntegrationTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/books/validator/SpringDataRestValidatorIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.validator; +package com.baeldung.books.validator; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -19,8 +19,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.SpringDataRestApplication; -import com.baeldung.models.WebsiteUser; +import com.baeldung.books.SpringDataRestApplication; +import com.baeldung.books.models.WebsiteUser; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) diff --git a/spring-data-rest/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java b/spring-data-rest/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java index e1aff7e09d..d7ef361783 100644 --- a/spring-data-rest/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/springdatawebsupport/application/test/UserControllerIntegrationTest.java @@ -42,7 +42,7 @@ public class UserControllerIntegrationTest { @Test public void whenGetRequestToUserEndPointWithNameRequestParameter_thenCorrectResponse() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/user").param("name", "John").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()) + mockMvc.perform(MockMvcRequestBuilders.get("/users").param("name", "John").contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$['content'][0].['name']").value("John")); } diff --git a/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 0380e3dc2f..c2682855b8 100644 --- a/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-data-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.SpringDataRestApplication; +import com.baeldung.books.SpringDataRestApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringDataRestApplication.class) From d289cfa87e4e530255bec38c95cf6cef7dbfc93a Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 30 Jun 2019 16:56:39 -0500 Subject: [PATCH 067/352] BAEL-2898 BAEL-3057 BAEL-3020 update README files (#7228) * BAEL-2246: add link back to article * BAEL-2174: rename core-java-net module to core-java-networking * BAEL-2174: add link back to article * BAEL-2363 BAEL-2337 BAEL-1996 BAEL-2277 add links back to articles * BAEL-2367: add link back to article * BAEL-2335: add link back to article * BAEL-2413: add link back to article * Update README.MD * BAEL-2577: add link back to article * BAEL-2490: add link back to article * BAEL-2471: add link back to article * BAEL-2583: add link back to article * BAEL-2738: add link back to article * BAEL-2711: Add spring-boot-angular module to root pom * BAEL-2544 BAEL-2711 BAEL-2575 BAEL-2657 Add links back to articles * BAEL-2736: Add link back to article * BAEL-2789: Add link back to article * BAEL-2489: add link back to article * BAEL-2840: add link back to article * BAEL-2655: add link back to article * BAEL-2884: add link back to article * BAEL-2985: Fix Spring Boot Apps in spring-data-rest module * BAEL-2898 BAEL-3057 BAEL-3020 add links back to articles --- algorithms-miscellaneous-3/README.md | 1 + core-groovy-2/README.md | 3 ++- libraries-2/README.md | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index 4dd4b66ff2..7a83a97c5b 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -4,3 +4,4 @@ - [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine) - [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic) - [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity) +- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted) diff --git a/core-groovy-2/README.md b/core-groovy-2/README.md index 1d35669cd7..d6fc6fc2f7 100644 --- a/core-groovy-2/README.md +++ b/core-groovy-2/README.md @@ -5,4 +5,5 @@ - [String Matching in Groovy](http://www.baeldung.com/) - [Template Engines in Groovy](https://www.baeldung.com/groovy-template-engines) - [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword) -- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching) \ No newline at end of file +- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching) +- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml) \ No newline at end of file diff --git a/libraries-2/README.md b/libraries-2/README.md index 8243b9f82c..cdeed10b3f 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -4,4 +4,4 @@ - [A Guide to jBPM with Java](https://www.baeldung.com/jbpm-java) - [Guide to Classgraph Library](https://www.baeldung.com/classgraph) - [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program) - +- [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors) From 1ba4b23099c33aef663ce30b0ea1b7ca4ba1667f Mon Sep 17 00:00:00 2001 From: Johnathan Gilday Date: Sun, 30 Jun 2019 21:45:57 -0400 Subject: [PATCH 068/352] BAEL-2121 XStream RCE --- xstream/pom.xml | 5 +- .../src/main/java/com/baeldung/rce/App.java | 92 +++++++++++++++++++ .../main/java/com/baeldung/rce/Person.java | 43 +++++++++ .../java/com/baeldung/rce/AppUnitTest.java | 65 +++++++++++++ .../rce/AttackExploitedException.java | 7 ++ .../rce/AttackExploitedExceptionThrower.java | 13 +++ .../baeldung/rce/XStreamBasicsUnitTest.java | 82 +++++++++++++++++ xstream/src/test/resources/attack.xml | 12 +++ .../src/test/resources/calculator-attack.xml | 16 ++++ 9 files changed, 333 insertions(+), 2 deletions(-) create mode 100644 xstream/src/main/java/com/baeldung/rce/App.java create mode 100644 xstream/src/main/java/com/baeldung/rce/Person.java create mode 100644 xstream/src/test/java/com/baeldung/rce/AppUnitTest.java create mode 100644 xstream/src/test/java/com/baeldung/rce/AttackExploitedException.java create mode 100644 xstream/src/test/java/com/baeldung/rce/AttackExploitedExceptionThrower.java create mode 100644 xstream/src/test/java/com/baeldung/rce/XStreamBasicsUnitTest.java create mode 100644 xstream/src/test/resources/attack.xml create mode 100644 xstream/src/test/resources/calculator-attack.xml diff --git a/xstream/pom.xml b/xstream/pom.xml index f75e10fc7d..b98e258599 100644 --- a/xstream/pom.xml +++ b/xstream/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../pom.xml @@ -28,8 +29,8 @@ - 1.4.9 + 1.4.10 1.3.8 - \ No newline at end of file + diff --git a/xstream/src/main/java/com/baeldung/rce/App.java b/xstream/src/main/java/com/baeldung/rce/App.java new file mode 100644 index 0000000000..3720c7fa93 --- /dev/null +++ b/xstream/src/main/java/com/baeldung/rce/App.java @@ -0,0 +1,92 @@ +package com.baeldung.rce; + +import com.sun.net.httpserver.HttpServer; +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.security.NoTypePermission; +import com.thoughtworks.xstream.security.NullPermission; +import com.thoughtworks.xstream.security.PrimitiveTypePermission; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.HashSet; +import java.util.Set; + +/** + * Web application which is intentionally vulnerable to an XStream remote code + * exploitation (RCE). + * + *

+ * This test application is meant to maintain a set of {@link Person} models. It + * exposes a "/persons" endpoint which supports the following operations: + * + *

    + *
  1. {@code POST} XML for adding a new {@link Person} to the set + *
  2. {@code GET} for retrieving the set of {@link Person} models as XML + *
+ * + * The {@code POST} handler is vulnerable to an RCE exploit. + */ +public final class App { + + public static App createHardened(int port) { + final XStream xstream = new XStream(); + xstream.addPermission(NoTypePermission.NONE); + xstream.addPermission(NullPermission.NULL); + xstream.addPermission(PrimitiveTypePermission.PRIMITIVES); + xstream.allowTypes(new Class[] { Person.class }); + return new App(port, xstream); + } + + public static App createVulnerable(int port) { + return new App(port, new XStream()); + } + + private final int port; + private final Set persons; + private final XStream xstream; + private HttpServer server; + + private App(int port, XStream xstream) { + this.port = port; + persons = new HashSet<>(); + // this app is vulnerable because XStream security is not configured + this.xstream = xstream; + this.xstream.alias("person", Person.class); + } + + void start() throws IOException { + server = HttpServer.create(new InetSocketAddress("localhost", port), 0); + server.createContext("/persons", exchange -> { + switch (exchange.getRequestMethod()) { + case "POST": + final Person person = (Person) xstream.fromXML(exchange.getRequestBody()); + persons.add(person); + exchange.sendResponseHeaders(201, 0); + exchange.close(); + break; + case "GET": + exchange.sendResponseHeaders(200, 0); + xstream.toXML(persons, exchange.getResponseBody()); + exchange.close(); + break; + default: + exchange.sendResponseHeaders(405, 0); + exchange.close(); + } + }); + server.start(); + } + + void stop() { + if (server != null) { + server.stop(0); + } + } + + int port() { + if (server == null) + throw new IllegalStateException("Server not started"); + return server.getAddress() + .getPort(); + } +} diff --git a/xstream/src/main/java/com/baeldung/rce/Person.java b/xstream/src/main/java/com/baeldung/rce/Person.java new file mode 100644 index 0000000000..336c47798b --- /dev/null +++ b/xstream/src/main/java/com/baeldung/rce/Person.java @@ -0,0 +1,43 @@ +package com.baeldung.rce; + +import java.util.Objects; + +/** Person model */ +public final class Person { + + private String first; + private String last; + + public String getFirst() { + return first; + } + + public void setFirst(String first) { + this.first = first; + } + + public String getLast() { + return last; + } + + public void setLast(String last) { + this.last = last; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Person)) { + return false; + } + Person person = (Person) o; + return Objects.equals(first, person.first) && Objects.equals(last, person.last); + } + + @Override + public int hashCode() { + return Objects.hash(first, last); + } +} diff --git a/xstream/src/test/java/com/baeldung/rce/AppUnitTest.java b/xstream/src/test/java/com/baeldung/rce/AppUnitTest.java new file mode 100644 index 0000000000..3b541ae099 --- /dev/null +++ b/xstream/src/test/java/com/baeldung/rce/AppUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.rce; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.SocketException; +import java.net.URL; + +import static org.junit.Assert.assertTrue; + +/** + * Unit test which demonstrates a remote code exploit against the {@link App} + * server. Sends an XML request containing an attack payload to the {@code POST} + * endpoint. + */ +public final class AppUnitTest { + + private App app; + + /** start a new web server */ + @Before + public void before() throws IOException { + app = App.createVulnerable(0); + app.start(); + } + + /** stop the web server */ + @After + public void after() { + if (app != null) + app.stop(); + } + + /** + * Test passes when an {@link IOException} is thrown because this indicates that + * the attacker caused the application to fail in some way. This does not + * actually confirm that the exploit took place, because the RCE is a + * side-effect that is difficult to observe. + */ + @Test(expected = SocketException.class) + public void givenAppIsVulneable_whenExecuteRemoteCodeWhichThrowsException_thenThrowsException() throws IOException { + // POST the attack.xml to the application's /persons endpoint + final URL url = new URL("http://localhost:" + app.port() + "/persons"); + final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setUseCaches(false); + connection.setRequestProperty("Content-Type", "application/xml"); + connection.connect(); + try (OutputStream os = connection.getOutputStream(); InputStream is = AppUnitTest.class.getResourceAsStream("/attack.xml")) { + byte[] buffer = new byte[1024]; + while (is.read(buffer) > 0) { + os.write(buffer); + } + } + final int rc = connection.getResponseCode(); + connection.disconnect(); + assertTrue(rc >= 400); + } +} diff --git a/xstream/src/test/java/com/baeldung/rce/AttackExploitedException.java b/xstream/src/test/java/com/baeldung/rce/AttackExploitedException.java new file mode 100644 index 0000000000..16c906abfc --- /dev/null +++ b/xstream/src/test/java/com/baeldung/rce/AttackExploitedException.java @@ -0,0 +1,7 @@ +package com.baeldung.rce; + +/** + * Indicates a successful remote code execution attack has taken place. + */ +final class AttackExploitedException extends RuntimeException { +} diff --git a/xstream/src/test/java/com/baeldung/rce/AttackExploitedExceptionThrower.java b/xstream/src/test/java/com/baeldung/rce/AttackExploitedExceptionThrower.java new file mode 100644 index 0000000000..16ed143f7a --- /dev/null +++ b/xstream/src/test/java/com/baeldung/rce/AttackExploitedExceptionThrower.java @@ -0,0 +1,13 @@ +package com.baeldung.rce; + +/** + * Class which contains an action to throw {@link AttackExploitedException}. + * This helper is used by {@link AppTest} to determine when the remote code + * exploit has taken place. + */ +final class AttackExploitedExceptionThrower { + + public void throwAttackExploitedException() { + throw new AttackExploitedException(); + } +} diff --git a/xstream/src/test/java/com/baeldung/rce/XStreamBasicsUnitTest.java b/xstream/src/test/java/com/baeldung/rce/XStreamBasicsUnitTest.java new file mode 100644 index 0000000000..d762813b22 --- /dev/null +++ b/xstream/src/test/java/com/baeldung/rce/XStreamBasicsUnitTest.java @@ -0,0 +1,82 @@ +package com.baeldung.rce; + +import com.thoughtworks.xstream.XStream; + +import org.junit.Before; +import org.junit.Test; + +import java.util.Collections; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +/** + * Demonstrates XStream basics + */ +public final class XStreamBasicsUnitTest { + + private XStream xstream; + + @Before + public void before() { + xstream = new XStream(); + xstream.alias("person", Person.class); + } + + @Test + public void whenWritePerson_thenWritesExpectedXml() { + Person person = new Person(); + person.setFirst("John"); + person.setLast("Smith"); + + String xml = xstream.toXML(person); + + // @formatter:off + String expected = "" + + "\n" + + " John\n" + + " Smith\n" + + ""; + // @formatter:on + assertEquals(expected, xml); + + } + + @Test + public void whenReadXmlAsPerson_thenReturnsNewPerson() { + // @formatter:off + String xml = "" + + "" + + " John" + + " Smith" + + ""; + // @formatter:on + + Person person = (Person) xstream.fromXML(xml); + + Person expected = new Person(); + expected.setFirst("John"); + expected.setLast("Smith"); + assertEquals(person, expected); + } + + @Test + public void givenXmlRepresentationOfMap_whenDeserialize_thenBuildsMap() { + // @formatter:off + String xml = "" + + "" + + " " + + " foo" + + " 10" + + " " + + ""; + // @formatter:on + @SuppressWarnings("unchecked") + Map actual = (Map) xstream.fromXML(xml); + + final Map expected = Collections.singletonMap("foo", 10); + + assertEquals(expected, actual); + } + +} diff --git a/xstream/src/test/resources/attack.xml b/xstream/src/test/resources/attack.xml new file mode 100644 index 0000000000..8a5713648c --- /dev/null +++ b/xstream/src/test/resources/attack.xml @@ -0,0 +1,12 @@ + + foo + + java.lang.Comparable + + + + throwAttackExploitedException + + + diff --git a/xstream/src/test/resources/calculator-attack.xml b/xstream/src/test/resources/calculator-attack.xml new file mode 100644 index 0000000000..ae24843dc6 --- /dev/null +++ b/xstream/src/test/resources/calculator-attack.xml @@ -0,0 +1,16 @@ + + foo + + java.lang.Comparable + + + + open + /Applications/Calculator.app + + + start + + + From ad919054df4a9952a3e30dcfe64a9b82d5759725 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Mon, 1 Jul 2019 16:20:28 +0530 Subject: [PATCH 069/352] Back-link added --- persistence-modules/hibernate5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index 68008bc8fe..65322f0cea 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -33,3 +33,4 @@ - [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions) - [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache) - [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) +- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) From c79bc226684d1e32ccb8e0c9fcf91d2449c26897 Mon Sep 17 00:00:00 2001 From: Catalin Burcea Date: Mon, 1 Jul 2019 14:16:19 +0300 Subject: [PATCH 070/352] added examples about how to reverse a string in java (#7219) --- .../string/reverse/ReverseStringExamples.java | 56 +++++++++++++++ .../ReverseStringExamplesUnitTest.java | 70 +++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java create mode 100644 java-strings-2/src/test/java/com/baeldung/string/reverse/ReverseStringExamplesUnitTest.java diff --git a/java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java b/java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java new file mode 100644 index 0000000000..1a58d09598 --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/reverse/ReverseStringExamples.java @@ -0,0 +1,56 @@ +package com.baeldung.string.reverse; + +import org.apache.commons.lang3.StringUtils; + +public class ReverseStringExamples { + + public static String reverse(String input) { + if (input == null) { + return null; + } + + String output = ""; + + for (int i = input.length() - 1; i >= 0; i--) { + output = output + input.charAt(i); + } + + return output; + } + + public static String reverseUsingStringBuilder(String input) { + if (input == null) { + return null; + } + + StringBuilder output = new StringBuilder(input).reverse(); + + return output.toString(); + } + + public static String reverseUsingApacheCommons(String input) { + return StringUtils.reverse(input); + } + + public static String reverseTheOrderOfWords(String sentence) { + if (sentence == null) { + return null; + } + + StringBuilder output = new StringBuilder(); + String[] words = sentence.split(" "); + + for (int i = words.length - 1; i >= 0; i--) { + output.append(words[i]); + output.append(" "); + } + + return output.toString() + .trim(); + } + + public static String reverseTheOrderOfWordsUsingApacheCommons(String sentence) { + return StringUtils.reverseDelimited(sentence, ' '); + } + +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/reverse/ReverseStringExamplesUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/reverse/ReverseStringExamplesUnitTest.java new file mode 100644 index 0000000000..020ead02db --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/reverse/ReverseStringExamplesUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.string.reverse; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ReverseStringExamplesUnitTest { + + private static final String STRING_INPUT = "cat"; + private static final String STRING_INPUT_REVERSED = "tac"; + private static final String SENTENCE = "The quick brown fox jumps over the lazy dog"; + private static final String REVERSED_WORDS_SENTENCE = "dog lazy the over jumps fox brown quick The"; + + @Test + public void whenReverseIsCalled_ThenCorrectStringIsReturned() { + String reversed = ReverseStringExamples.reverse(STRING_INPUT); + String reversedNull = ReverseStringExamples.reverse(null); + String reversedEmpty = ReverseStringExamples.reverse(StringUtils.EMPTY); + + assertEquals(STRING_INPUT_REVERSED, reversed); + assertEquals(null, reversedNull); + assertEquals(StringUtils.EMPTY, reversedEmpty); + } + + @Test + public void whenReverseUsingStringBuilderIsCalled_ThenCorrectStringIsReturned() throws Exception { + String reversed = ReverseStringExamples.reverseUsingStringBuilder(STRING_INPUT); + String reversedNull = ReverseStringExamples.reverseUsingStringBuilder(null); + String reversedEmpty = ReverseStringExamples.reverseUsingStringBuilder(StringUtils.EMPTY); + + assertEquals(STRING_INPUT_REVERSED, reversed); + assertEquals(null, reversedNull); + assertEquals(StringUtils.EMPTY, reversedEmpty); + } + + @Test + public void whenReverseUsingApacheCommonsIsCalled_ThenCorrectStringIsReturned() throws Exception { + String reversed = ReverseStringExamples.reverseUsingApacheCommons(STRING_INPUT); + String reversedNull = ReverseStringExamples.reverseUsingApacheCommons(null); + String reversedEmpty = ReverseStringExamples.reverseUsingApacheCommons(StringUtils.EMPTY); + + assertEquals(STRING_INPUT_REVERSED, reversed); + assertEquals(null, reversedNull); + assertEquals(StringUtils.EMPTY, reversedEmpty); + } + + @Test + public void whenReverseTheOrderOfWordsIsCalled_ThenCorrectStringIsReturned() { + String reversed = ReverseStringExamples.reverseTheOrderOfWords(SENTENCE); + String reversedNull = ReverseStringExamples.reverseTheOrderOfWords(null); + String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWords(StringUtils.EMPTY); + + assertEquals(REVERSED_WORDS_SENTENCE, reversed); + assertEquals(null, reversedNull); + assertEquals(StringUtils.EMPTY, reversedEmpty); + } + + @Test + public void whenReverseTheOrderOfWordsUsingApacheCommonsIsCalled_ThenCorrectStringIsReturned() { + String reversed = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(SENTENCE); + String reversedNull = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(null); + String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(StringUtils.EMPTY); + + assertEquals(REVERSED_WORDS_SENTENCE, reversed); + assertEquals(null, reversedNull); + assertEquals(StringUtils.EMPTY, reversedEmpty); + } + +} From ce206fade423f59a4c72f202750264e6ae1cdd4e Mon Sep 17 00:00:00 2001 From: gpq5 Date: Tue, 2 Jul 2019 00:40:57 +0530 Subject: [PATCH 071/352] fix for comparison issue with double --- .../com/baeldung/jackson/json/compare/JsonCompareUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java index 2f2c18e248..4cadac073c 100644 --- a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java +++ b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java @@ -82,7 +82,7 @@ public class JsonCompareUnitTest { if ((o1 instanceof NumericNode) && (o2 instanceof NumericNode)) { Double d1 = ((NumericNode) o1).asDouble(); Double d2 = ((NumericNode) o2).asDouble(); - if (d1.equals(d2)) { + if (d1.compareTo(d2) == 0) { return 0; } } From 00c4774774e3cc1c68874bafd91e26a965c1781e Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sat, 15 Jun 2019 19:02:55 -0300 Subject: [PATCH 072/352] Moved Content Negotiation article code from spring-mvc-java to spring-mvc-basics --- spring-mvc-basics/README.md | 3 +- spring-mvc-basics/pom.xml | 1 - .../java/com/baeldung/model/Employee.java | 61 ++++++++++++++++++ .../baeldung/spring/web/config/WebConfig.java | 17 +++++ .../web/controller/EmployeeController.java | 31 +++++++++ .../src/main/resources/application.properties | 8 ++- ...llerContentNegotiationIntegrationTest.java | 63 +++++++++++++++++++ spring-mvc-java/README.md | 1 - .../baeldung/spring/web/config/WebConfig.java | 6 -- .../controller/EmployeeIntegrationTest.java | 51 --------------- 10 files changed, 181 insertions(+), 61 deletions(-) create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java delete mode 100644 spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 997e6a88df..9593fd6222 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -10,4 +10,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) -- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) \ No newline at end of file +- [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) +- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) \ No newline at end of file diff --git a/spring-mvc-basics/pom.xml b/spring-mvc-basics/pom.xml index d04bdda8f6..8c52c60b65 100644 --- a/spring-mvc-basics/pom.xml +++ b/spring-mvc-basics/pom.xml @@ -30,7 +30,6 @@ javax.servlet jstl - ${jstl.version} org.springframework.boot diff --git a/spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java b/spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java new file mode 100644 index 0000000000..fb0a452219 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/Employee.java @@ -0,0 +1,61 @@ +package com.baeldung.model; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Employee { + + private long id; + private String name; + private String contactNumber; + private String workingArea; + + public Employee() { + super(); + } + + public Employee(final long id, final String name, final String contactNumber, final String workingArea) { + this.id = id; + this.name = name; + this.contactNumber = contactNumber; + this.workingArea = workingArea; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getContactNumber() { + return contactNumber; + } + + public void setContactNumber(final String contactNumber) { + this.contactNumber = contactNumber; + } + + public String getWorkingArea() { + return workingArea; + } + + public void setWorkingArea(final String workingArea) { + this.workingArea = workingArea; + } + + @Override + public String toString() { + return "Employee [id=" + id + ", name=" + name + ", contactNumber=" + contactNumber + ", workingArea=" + workingArea + "]"; + } + +} diff --git a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java index a56dfe550f..9a321f65a2 100644 --- a/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -3,7 +3,9 @@ package com.baeldung.spring.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; +import org.springframework.http.MediaType; import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @@ -47,4 +49,19 @@ public class WebConfig implements WebMvcConfigurer { bean.setOrder(1); return bean; } + + /** + * Spring Boot allows configuring Content Negotiation using properties + */ + @Override + public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { + configurer.favorPathExtension(true) + .favorParameter(true) + .parameterName("mediaType") + .ignoreAcceptHeader(false) + .useRegisteredExtensionsOnly(false) + .defaultContentType(MediaType.APPLICATION_JSON) + .mediaType("xml", MediaType.APPLICATION_XML) + .mediaType("json", MediaType.APPLICATION_JSON); + } } \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java new file mode 100644 index 0000000000..00bbbfbe41 --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -0,0 +1,31 @@ +package com.baeldung.web.controller; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.model.Employee; + +@Controller +public class EmployeeController { + + Map employeeMap = new HashMap<>(); + + @ModelAttribute("employees") + public void initEmployees() { + employeeMap.put(1L, new Employee(1L, "John", "223334411", "rh")); + employeeMap.put(2L, new Employee(2L, "Peter", "22001543", "informatics")); + employeeMap.put(3L, new Employee(3L, "Mike", "223334411", "admin")); + } + + @RequestMapping(value = "/employee/{Id}",produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + public @ResponseBody Employee getEmployeeById(@PathVariable final Long Id) { + return employeeMap.get(Id); + } +} diff --git a/spring-mvc-basics/src/main/resources/application.properties b/spring-mvc-basics/src/main/resources/application.properties index 4de974142e..b8a9be0b40 100644 --- a/spring-mvc-basics/src/main/resources/application.properties +++ b/spring-mvc-basics/src/main/resources/application.properties @@ -1 +1,7 @@ -server.servlet.context-path=/spring-mvc-basics \ No newline at end of file +server.servlet.context-path=/spring-mvc-basics + +### Content Negotiation (already defined programatically) +spring.mvc.pathmatch.use-suffix-pattern=true +#spring.mvc.contentnegotiation.favor-path-extension=true +#spring.mvc.contentnegotiation.favor-parameter=true +#spring.mvc.contentnegotiation.parameter-name=mediaType diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java new file mode 100644 index 0000000000..6500955d23 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerContentNegotiationIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +public class EmployeeControllerContentNegotiationIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenEndpointUsingJsonSuffixCalled_thenJsonResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1.json")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void whenEndpointUsingXmlSuffixCalled_thenXmlResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1.xml")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)); + } + + @Test + public void whenEndpointUsingJsonParameterCalled_thenJsonResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1?mediaType=json")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void whenEndpointUsingXmlParameterCalled_thenXmlResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1?mediaType=xml")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)); + } + + @Test + public void whenEndpointUsingJsonAcceptHeaderCalled_thenJsonResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); + } + + @Test + public void whenEndpointUsingXmlAcceptHeaderCalled_thenXmlResponseObtained() throws Exception { + this.mockMvc.perform(get("/employee/1").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML_VALUE)) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE)); + } +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 8ba9b5fd1e..8a302e6fa3 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -13,7 +13,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Quick Guide to Spring MVC Matrix Variables](http://www.baeldung.com/spring-mvc-matrix-variables) - [Intro to WebSockets with Spring](http://www.baeldung.com/websockets-spring) - [File Upload with Spring MVC](http://www.baeldung.com/spring-file-upload) -- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) - [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) - [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 96b50f2c37..44fef92917 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -17,7 +17,6 @@ import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; @@ -94,11 +93,6 @@ public class WebConfig implements WebMvcConfigurer { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } - @Override - public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { - configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useRegisteredExtensionsOnly(false).defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", - MediaType.APPLICATION_JSON); - } @Bean(name = "multipartResolver") public CommonsMultipartResolver multipartResolver() { diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java deleted file mode 100644 index 0c2aa3de1b..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/EmployeeIntegrationTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.web.controller; - -import org.junit.Before; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -import com.baeldung.model.Employee; -import com.baeldung.spring.web.config.WebConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = WebConfig.class) -public class EmployeeIntegrationTest { - - @Autowired - private EmployeeController employeeController; - - @Before - public void setup() { - employeeController.initEmployees(); - } - - @Test - public void whenInitEmployees_thenVerifyValuesInitiation() { - - Employee employee1 = employeeController.employeeMap.get(1L); - Employee employee2 = employeeController.employeeMap.get(2L); - Employee employee3 = employeeController.employeeMap.get(3L); - - Assert.assertTrue(employee1.getId() == 1L); - Assert.assertTrue(employee1.getName().equals("John")); - Assert.assertTrue(employee1.getContactNumber().equals("223334411")); - Assert.assertTrue(employee1.getWorkingArea().equals("rh")); - - Assert.assertTrue(employee2.getId() == 2L); - Assert.assertTrue(employee2.getName().equals("Peter")); - Assert.assertTrue(employee2.getContactNumber().equals("22001543")); - Assert.assertTrue(employee2.getWorkingArea().equals("informatics")); - - Assert.assertTrue(employee3.getId() == 3L); - Assert.assertTrue(employee3.getName().equals("Mike")); - Assert.assertTrue(employee3.getContactNumber().equals("223334411")); - Assert.assertTrue(employee3.getWorkingArea().equals("admin")); - } - -} From e84ea4d4c50ab8d14470188857663ba2abd9dc19 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 1 Jul 2019 18:32:49 -0300 Subject: [PATCH 073/352] Moved RequestMapping Shortcut annotations article code from spring-mvc-java to spring-mvc-basics --- spring-mvc-basics/README.md | 3 +- .../RequestMappingShortcutsController.java | 47 +++++++++ ...RequestMapingShortcutsIntegrationTest.java | 97 +++++++++++++++++++ spring-mvc-java/README.md | 1 - .../RequestMappingShortcutsController.java | 47 --------- ...RequestMapingShortcutsIntegrationTest.java | 92 ------------------ 6 files changed, 146 insertions(+), 141 deletions(-) create mode 100644 spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java delete mode 100644 spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java delete mode 100644 spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 9593fd6222..ed3d052306 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -11,4 +11,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) - [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) -- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) \ No newline at end of file +- [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) +- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java new file mode 100644 index 0000000000..e91a914c6d --- /dev/null +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java @@ -0,0 +1,47 @@ +package com.baeldung.web.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RequestMappingShortcutsController { + + @GetMapping("/get") + public @ResponseBody ResponseEntity get() { + return new ResponseEntity("GET Response", HttpStatus.OK); + } + + @GetMapping("/get/{id}") + public @ResponseBody ResponseEntity getById(@PathVariable String id) { + return new ResponseEntity("GET Response : " + id, HttpStatus.OK); + } + + @PostMapping("/post") + public @ResponseBody ResponseEntity post() { + return new ResponseEntity("POST Response", HttpStatus.OK); + } + + @PutMapping("/put") + public @ResponseBody ResponseEntity put() { + return new ResponseEntity("PUT Response", HttpStatus.OK); + } + + @DeleteMapping("/delete") + public @ResponseBody ResponseEntity delete() { + return new ResponseEntity("DELETE Response", HttpStatus.OK); + } + + @PatchMapping("/patch") + public @ResponseBody ResponseEntity patch() { + return new ResponseEntity("PATCH Response", HttpStatus.OK); + } + +} diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java new file mode 100644 index 0000000000..3fbb5da75e --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java @@ -0,0 +1,97 @@ +package com.baeldung.web.controller; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultMatcher; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class RequestMapingShortcutsIntegrationTest { + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new RequestMappingShortcutsController()) + .build(); + } + + @Test + public void giventUrl_whenGetRequest_thenFindGetResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/get"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("GET Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenPostRequest_thenFindPostResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/post"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("POST Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenPutRequest_thenFindPutResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put("/put"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("PUT Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenDeleteRequest_thenFindDeleteResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete("/delete"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("DELETE Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + + @Test + public void giventUrl_whenPatchRequest_thenFindPatchResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch("/patch"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content() + .string("PATCH Response"); + + this.mockMvc.perform(builder) + .andExpect(contentMatcher) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + + } + +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 8a302e6fa3..6ae700ee03 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -15,7 +15,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [File Upload with Spring MVC](http://www.baeldung.com/spring-file-upload) - [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) -- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) - [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java deleted file mode 100644 index 5d4cbe9d78..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.web.controller; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PatchMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class RequestMappingShortcutsController { - - @GetMapping("/get") - public @ResponseBody ResponseEntity get() { - return new ResponseEntity("GET Response", HttpStatus.OK); - } - - @GetMapping("/get/{id}") - public @ResponseBody ResponseEntity getById(@PathVariable String id) { - return new ResponseEntity("GET Response : " + id, HttpStatus.OK); - } - - @PostMapping("/post") - public @ResponseBody ResponseEntity post() { - return new ResponseEntity("POST Response", HttpStatus.OK); - } - - @PutMapping("/put") - public @ResponseBody ResponseEntity put() { - return new ResponseEntity("PUT Response", HttpStatus.OK); - } - - @DeleteMapping("/delete") - public @ResponseBody ResponseEntity delete() { - return new ResponseEntity("DELETE Response", HttpStatus.OK); - } - - @PatchMapping("/patch") - public @ResponseBody ResponseEntity patch() { - return new ResponseEntity("PATCH Response", HttpStatus.OK); - } - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java deleted file mode 100644 index fb21905027..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsIntegrationTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.baeldung.web.controller; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultMatcher; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.baeldung.spring.web.config.WebConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = WebConfig.class) -public class RequestMapingShortcutsIntegrationTest { - - @Autowired - private WebApplicationContext ctx; - - private MockMvc mockMvc; - - @Before - public void setup () { - DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.ctx); - this.mockMvc = builder.build(); - } - - @Test - public void giventUrl_whenGetRequest_thenFindGetResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/get"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("GET Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenPostRequest_thenFindPostResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/post"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("POST Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenPutRequest_thenFindPutResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put("/put"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PUT Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenDeleteRequest_thenFindDeleteResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete("/delete"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("DELETE Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - - @Test - public void giventUrl_whenPatchRequest_thenFindPatchResponse() throws Exception { - - MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch("/patch"); - - ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PATCH Response"); - - this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); - - } - -} From e77faf8d99fe2f26cd22cdea1546b77b7f1e2eaa Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 1 Jul 2019 19:35:33 -0300 Subject: [PATCH 074/352] Moved MVC Custom Valitation article code from spring-mvc-java to spring-mvc-basics module --- spring-mvc-basics/README.md | 3 +- .../ContactNumberConstraint.java | 48 +++++------ .../ContactNumberValidator.java | 34 ++++---- .../customvalidator/FieldsValueMatch.java | 0 .../FieldsValueMatchValidator.java | 0 .../java/com/baeldung/model/NewUserForm.java | 5 +- .../com/baeldung/model/ValidatedPhone.java | 44 +++++----- .../web/controller/NewUserController.java | 0 .../controller/ValidatedPhoneController.java | 64 +++++++------- .../main/webapp/WEB-INF/view/phoneHome.jsp | 76 ++++++++--------- .../ClassValidationMvcIntegrationTest.java | 55 ++++++------ .../CustomMVCValidatorIntegrationTest.java | 84 ++++++++++--------- spring-mvc-java/README.md | 1 - 13 files changed, 207 insertions(+), 207 deletions(-) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java (89%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java (97%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/model/NewUserForm.java (82%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/model/ValidatedPhone.java (94%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/NewUserController.java (100%) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java (96%) rename {spring-mvc-java => spring-mvc-basics}/src/main/webapp/WEB-INF/view/phoneHome.jsp (89%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java (51%) rename {spring-mvc-java => spring-mvc-basics}/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java (63%) diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index ed3d052306..1d5fc98f95 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -12,4 +12,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) - [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) - [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) -- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) \ No newline at end of file +- [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) +- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java similarity index 89% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java index dbd38c1122..42e441f8f9 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberConstraint.java @@ -1,24 +1,24 @@ -package com.baeldung.customvalidator; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import javax.validation.Constraint; -import javax.validation.Payload; - -@Documented -@Constraint(validatedBy = ContactNumberValidator.class) -@Target({ElementType.METHOD, ElementType.FIELD}) -@Retention(RetentionPolicy.RUNTIME) -public @interface ContactNumberConstraint { - - String message() default "Invalid phone number"; - - Class[] groups() default {}; - - Class[] payload() default {}; - -} +package com.baeldung.customvalidator; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.validation.Constraint; +import javax.validation.Payload; + +@Documented +@Constraint(validatedBy = ContactNumberValidator.class) +@Target({ ElementType.METHOD, ElementType.FIELD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ContactNumberConstraint { + + String message() default "Invalid phone number"; + + Class[] groups() default {}; + + Class[] payload() default {}; + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java similarity index 97% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java index dea6b9099b..fe14f3ccf1 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/ContactNumberValidator.java @@ -1,17 +1,17 @@ -package com.baeldung.customvalidator; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - -public class ContactNumberValidator implements ConstraintValidator { - - @Override - public void initialize(ContactNumberConstraint contactNumber) { - } - - @Override - public boolean isValid(String contactField, ConstraintValidatorContext cxt) { - return contactField != null && contactField.matches("[0-9]+") && (contactField.length() > 8) && (contactField.length() < 14); - } - -} +package com.baeldung.customvalidator; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +public class ContactNumberValidator implements ConstraintValidator { + + @Override + public void initialize(ContactNumberConstraint contactNumber) { + } + + @Override + public boolean isValid(String contactField, ConstraintValidatorContext cxt) { + return contactField != null && contactField.matches("[0-9]+") && (contactField.length() > 8) && (contactField.length() < 14); + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatch.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java b/spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java rename to spring-mvc-basics/src/main/java/com/baeldung/customvalidator/FieldsValueMatchValidator.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/NewUserForm.java b/spring-mvc-basics/src/main/java/com/baeldung/model/NewUserForm.java similarity index 82% rename from spring-mvc-java/src/main/java/com/baeldung/model/NewUserForm.java rename to spring-mvc-basics/src/main/java/com/baeldung/model/NewUserForm.java index 12969b6002..b4fe82ab4a 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/NewUserForm.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/NewUserForm.java @@ -2,10 +2,7 @@ package com.baeldung.model; import com.baeldung.customvalidator.FieldsValueMatch; -@FieldsValueMatch.List({ - @FieldsValueMatch(field = "password", fieldMatch = "verifyPassword", message = "Passwords do not match!"), - @FieldsValueMatch(field = "email", fieldMatch = "verifyEmail", message = "Email addresses do not match!") -}) +@FieldsValueMatch.List({ @FieldsValueMatch(field = "password", fieldMatch = "verifyPassword", message = "Passwords do not match!"), @FieldsValueMatch(field = "email", fieldMatch = "verifyEmail", message = "Email addresses do not match!") }) public class NewUserForm { private String email; private String verifyEmail; diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/ValidatedPhone.java b/spring-mvc-basics/src/main/java/com/baeldung/model/ValidatedPhone.java similarity index 94% rename from spring-mvc-java/src/main/java/com/baeldung/model/ValidatedPhone.java rename to spring-mvc-basics/src/main/java/com/baeldung/model/ValidatedPhone.java index be702a8517..8cea915e6e 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/model/ValidatedPhone.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/model/ValidatedPhone.java @@ -1,22 +1,22 @@ -package com.baeldung.model; - -import com.baeldung.customvalidator.ContactNumberConstraint; - -public class ValidatedPhone { - - @ContactNumberConstraint - private String phone; - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - @Override - public String toString() { - return phone; - } -} +package com.baeldung.model; + +import com.baeldung.customvalidator.ContactNumberConstraint; + +public class ValidatedPhone { + + @ContactNumberConstraint + private String phone; + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + @Override + public String toString() { + return phone; + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/NewUserController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/NewUserController.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/NewUserController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/NewUserController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java similarity index 96% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java rename to spring-mvc-basics/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java index 9b3a6b3a4c..73e1e4bb25 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java @@ -1,32 +1,32 @@ -package com.baeldung.web.controller; - -import com.baeldung.model.ValidatedPhone; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; - -import javax.validation.Valid; - -@Controller -public class ValidatedPhoneController { - - @GetMapping("/validatePhone") - public String loadFormPage(Model m) { - m.addAttribute("validatedPhone", new ValidatedPhone()); - return "phoneHome"; - } - - @PostMapping("/addValidatePhone") - public String submitForm(@Valid ValidatedPhone validatedPhone, BindingResult result, Model m) { - if (result.hasErrors()) { - return "phoneHome"; - } - - m.addAttribute("message", "Successfully saved phone: " + validatedPhone.toString()); - return "phoneHome"; - } - - -} +package com.baeldung.web.controller; + +import javax.validation.Valid; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; + +import com.baeldung.model.ValidatedPhone; + +@Controller +public class ValidatedPhoneController { + + @GetMapping("/validatePhone") + public String loadFormPage(Model m) { + m.addAttribute("validatedPhone", new ValidatedPhone()); + return "phoneHome"; + } + + @PostMapping("/addValidatePhone") + public String submitForm(@Valid ValidatedPhone validatedPhone, BindingResult result, Model m) { + if (result.hasErrors()) { + return "phoneHome"; + } + + m.addAttribute("message", "Successfully saved phone: " + validatedPhone.toString()); + return "phoneHome"; + } + +} diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/phoneHome.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/phoneHome.jsp similarity index 89% rename from spring-mvc-java/src/main/webapp/WEB-INF/view/phoneHome.jsp rename to spring-mvc-basics/src/main/webapp/WEB-INF/view/phoneHome.jsp index b873e9bc5f..ebc9052639 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/phoneHome.jsp +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/phoneHome.jsp @@ -1,38 +1,38 @@ -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> - - - - - Sample Form - - - - -
- -

Phone Number

-
${message}
- - - - - - -
- - -
-
- - +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> + + + + + Sample Form + + + + +
+ +

Phone Number

+
${message}
+ + + + + + +
+ + +
+
+ + diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java similarity index 51% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java index 2cd225a775..24182f492a 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/ClassValidationMvcIntegrationTest.java @@ -5,46 +5,47 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; public class ClassValidationMvcIntegrationTest { - private MockMvc mockMvc; - - @Before - public void setup(){ - this.mockMvc = MockMvcBuilders.standaloneSetup(new NewUserController()).build(); + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new NewUserController()) + .build(); } - + @Test public void givenMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/user") - .accept(MediaType.TEXT_HTML) - .param("email", "john@yahoo.com") - .param("verifyEmail", "john@yahoo.com") - .param("password", "pass") - .param("verifyPassword", "pass")) - .andExpect(model().attribute("message", "Valid form")) - .andExpect(view().name("userHome")) - .andExpect(status().isOk()) - .andDo(print()); + .accept(MediaType.TEXT_HTML) + .param("email", "john@yahoo.com") + .param("verifyEmail", "john@yahoo.com") + .param("password", "pass") + .param("verifyPassword", "pass")) + .andExpect(model().attribute("message", "Valid form")) + .andExpect(view().name("userHome")) + .andExpect(status().isOk()) + .andDo(print()); } - + @Test public void givenNotMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/user") - .accept(MediaType.TEXT_HTML) - .param("email", "john@yahoo.com") - .param("verifyEmail", "john@yahoo.commmm") - .param("password", "pass") - .param("verifyPassword", "passsss")) - .andExpect(model().errorCount(2)) - .andExpect(view().name("userHome")) - .andExpect(status().isOk()) - .andDo(print()); + .accept(MediaType.TEXT_HTML) + .param("email", "john@yahoo.com") + .param("verifyEmail", "john@yahoo.commmm") + .param("password", "pass") + .param("verifyPassword", "passsss")) + .andExpect(model().errorCount(2)) + .andExpect(view().name("userHome")) + .andExpect(status().isOk()) + .andDo(print()); } } diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java similarity index 63% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java rename to spring-mvc-basics/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java index 013cf9c91d..11b72e1650 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/CustomMVCValidatorIntegrationTest.java @@ -1,41 +1,43 @@ -package com.baeldung.web.controller; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -public class CustomMVCValidatorIntegrationTest { - - private MockMvc mockMvc; - - @Before - public void setup(){ - this.mockMvc = MockMvcBuilders.standaloneSetup(new ValidatedPhoneController()).build(); - } - - @Test - public void givenPhonePageUri_whenMockMvc_thenReturnsPhonePage() throws Exception{ - this.mockMvc.perform(get("/validatePhone")).andExpect(view().name("phoneHome")); - } - - @Test - public void givenPhoneURIWithPostAndFormData_whenMockMVC_thenVerifyErrorResponse() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/addValidatePhone"). - accept(MediaType.TEXT_HTML). - param("phoneInput", "123")). - andExpect(model().attributeHasFieldErrorCode("validatedPhone", "phone","ContactNumberConstraint")). - andExpect(view().name("phoneHome")). - andExpect(status().isOk()). - andDo(print()); - } - -} +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +public class CustomMVCValidatorIntegrationTest { + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.standaloneSetup(new ValidatedPhoneController()) + .build(); + } + + @Test + public void givenPhonePageUri_whenMockMvc_thenReturnsPhonePage() throws Exception { + this.mockMvc.perform(get("/validatePhone")) + .andExpect(view().name("phoneHome")); + } + + @Test + public void givenPhoneURIWithPostAndFormData_whenMockMVC_thenVerifyErrorResponse() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/addValidatePhone") + .accept(MediaType.TEXT_HTML) + .param("phoneInput", "123")) + .andExpect(model().attributeHasFieldErrorCode("validatedPhone", "phone", "ContactNumberConstraint")) + .andExpect(view().name("phoneHome")) + .andExpect(status().isOk()) + .andDo(print()); + } + +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 6ae700ee03..15daac97a5 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -16,7 +16,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) -- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) - [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) - [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) From bb2765c4e33d09b2398be17d92860af38c3b6875 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 1 Jul 2019 20:26:45 -0300 Subject: [PATCH 075/352] Moved Using @ResponseStatus article from spring-mvc-java to spring-mvc-basics module --- spring-mvc-basics/README.md | 3 ++- spring-mvc-java/README.md | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 1d5fc98f95..80db309df2 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -13,4 +13,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) - [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) - [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) -- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) \ No newline at end of file +- [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) +- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) \ No newline at end of file diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 15daac97a5..d8a79b9759 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -21,6 +21,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) -- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) From dc3c7937172b51303389255f8d6c6cb15352f8dc Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 1 Jul 2019 22:08:02 -0300 Subject: [PATCH 076/352] Moved ModeAttribute article from spring-mvc-java to spring-mvc-basics module --- spring-mvc-basics/README.md | 3 +- .../web/controller/EmployeeController.java | 31 ++++++++++++++++- .../main/webapp/WEB-INF/view/employeeHome.jsp | 33 +++++++++++++++++++ .../main/webapp/WEB-INF/view/employeeView.jsp | 25 ++++++++++++++ spring-mvc-java/README.md | 1 - .../web/controller/EmployeeController.java | 26 ++++++++------- .../main/webapp/WEB-INF/view/employeeHome.jsp | 2 +- .../main/webapp/WEB-INF/view/employeeView.jsp | 5 --- 8 files changed, 106 insertions(+), 20 deletions(-) create mode 100644 spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp create mode 100644 spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index 80db309df2..afb71ce63d 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -14,4 +14,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) - [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) - [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) -- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) \ No newline at end of file +- [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) +- [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) \ No newline at end of file diff --git a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java index 00bbbfbe41..cbea4c98c6 100644 --- a/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -4,11 +4,15 @@ import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.ui.ModelMap; +import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; import com.baeldung.model.Employee; @@ -24,8 +28,33 @@ public class EmployeeController { employeeMap.put(3L, new Employee(3L, "Mike", "223334411", "admin")); } - @RequestMapping(value = "/employee/{Id}",produces = { "application/json", "application/xml" }, method = RequestMethod.GET) + @RequestMapping(value = "/employee", method = RequestMethod.GET) + public ModelAndView showForm() { + return new ModelAndView("employeeHome", "employee", new Employee()); + } + + @RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) public @ResponseBody Employee getEmployeeById(@PathVariable final Long Id) { return employeeMap.get(Id); } + + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + if (result.hasErrors()) { + return "error"; + } + model.addAttribute("name", employee.getName()); + model.addAttribute("contactNumber", employee.getContactNumber()); + model.addAttribute("workingArea", employee.getWorkingArea()); + model.addAttribute("id", employee.getId()); + + employeeMap.put(employee.getId(), employee); + + return "employeeView"; + } + + @ModelAttribute + public void addAttributes(final Model model) { + model.addAttribute("msg", "Welcome to the Netherlands!"); + } } diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp new file mode 100644 index 0000000000..fa5812faea --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeHome.jsp @@ -0,0 +1,33 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +Form Example - Register an Employee + + +

Welcome, Enter The Employee Details

+ + + + + + + + + + + + + + + + + + +
Name
Id
Contact Number
+
+ + + + \ No newline at end of file diff --git a/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp new file mode 100644 index 0000000000..9a9b879a35 --- /dev/null +++ b/spring-mvc-basics/src/main/webapp/WEB-INF/view/employeeView.jsp @@ -0,0 +1,25 @@ +<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> + + +Spring MVC Form Handling + + + +

Submitted Employee Information

+

${msg}

+ + + + + + + + + + + + + +
Name :${name}
ID :${id}
Contact Number :${contactNumber}
+ + \ No newline at end of file diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index d8a79b9759..f12c904229 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -18,7 +18,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) - [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) -- [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java index ef76059567..251287dff8 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/EmployeeController.java @@ -1,20 +1,29 @@ package com.baeldung.web.controller; -import com.baeldung.model.Employee; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.MatrixVariable; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; -import java.util.*; +import com.baeldung.model.Employee; @SessionAttributes("employees") @Controller -@ControllerAdvice public class EmployeeController { Map employeeMap = new HashMap<>(); @@ -35,7 +44,7 @@ public class EmployeeController { public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) { return employeeMap.get(Id); } - + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { if (result.hasErrors()) { @@ -51,11 +60,6 @@ public class EmployeeController { return "employeeView"; } - @ModelAttribute - public void addAttributes(final Model model) { - model.addAttribute("msg", "Welcome to the Netherlands!"); - } - @RequestMapping(value = "/employees/{name}", method = RequestMethod.GET) @ResponseBody public ResponseEntity> getEmployeeByNameAndBeginContactNumber(@PathVariable final String name, @MatrixVariable final String beginContactNumber) { diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp index 8a32fd12b6..268f0a055a 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeHome.jsp @@ -8,7 +8,7 @@

Welcome, Enter The Employee Details

- + diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp index 627a9d9ddb..1457bc5fc8 100644 --- a/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp +++ b/spring-mvc-java/src/main/webapp/WEB-INF/view/employeeView.jsp @@ -6,7 +6,6 @@

Submitted Employee Information

-

${msg}

Name
@@ -20,10 +19,6 @@ - - - -
Name :Contact Number : ${contactNumber}
Working Area :${workingArea}
\ No newline at end of file From e239fb97633c05393917395b0a17dfadb5c5f826 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 1 Jul 2019 22:30:44 -0300 Subject: [PATCH 077/352] Added Integration test for ModelAttribute article --- ...ntrollerModelAttributeIntegrationTest.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java diff --git a/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java new file mode 100644 index 0000000000..5195adabd5 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/web/controller/EmployeeControllerModelAttributeIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.web.controller; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import java.util.Arrays; +import java.util.Collection; + +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +public class EmployeeControllerModelAttributeIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void givenUrlEncodedFormData_whenAddEmployeeEndpointCalled_thenModelContainsMsgAttribute() throws Exception { + Collection formData = Arrays.asList(new BasicNameValuePair("name", "employeeName"), new BasicNameValuePair("id", "99"), new BasicNameValuePair("contactNumber", "123456789")); + String urlEncodedFormData = EntityUtils.toString(new UrlEncodedFormEntity(formData)); + + mockMvc.perform(post("/addEmployee").contentType(MediaType.APPLICATION_FORM_URLENCODED) + .content(urlEncodedFormData)) + .andExpect(status().isOk()) + .andExpect(view().name("employeeView")) + .andExpect(model().attribute("msg", "Welcome to the Netherlands!")); + } +} From b886923aa9700f61ba896afa5cfc5b93b611cfee Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Tue, 2 Jul 2019 13:37:46 +0530 Subject: [PATCH 078/352] Back-link added --- core-java-modules/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/README.md b/core-java-modules/README.md index 7a7d0a7a1b..9ce6057f32 100644 --- a/core-java-modules/README.md +++ b/core-java-modules/README.md @@ -3,3 +3,4 @@ - [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms) - [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel) - [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception) +- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) From 43fd64c938cea0680aec898da7eb0f9b4df24dac Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Tue, 2 Jul 2019 13:40:43 +0530 Subject: [PATCH 079/352] Back-link added --- spring-boot-autoconfiguration/README.MD | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-boot-autoconfiguration/README.MD b/spring-boot-autoconfiguration/README.MD index a71af54dff..dc9cad539a 100644 --- a/spring-boot-autoconfiguration/README.MD +++ b/spring-boot-autoconfiguration/README.MD @@ -3,4 +3,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Create a Custom Auto-Configuration with Spring Boot](http://www.baeldung.com/spring-boot-custom-auto-configuration) \ No newline at end of file +- [Create a Custom Auto-Configuration with Spring Boot](http://www.baeldung.com/spring-boot-custom-auto-configuration) +- [Guide to ApplicationContextRunner in Spring Boot](https://www.baeldung.com/spring-boot-context-runner) From 2f7638fd37c020813ad3fac31604785926a944ad Mon Sep 17 00:00:00 2001 From: Lukasz Rys Date: Tue, 2 Jul 2019 13:08:35 +0200 Subject: [PATCH 080/352] [ BAEL-2515 ]: Move override tutorial classes to spring-testing module (#7232) --- spring-boot-testing/README.MD | 1 - .../src/test/resources/application-test.properties | 5 +---- .../src/test/resources/application.properties | 6 +----- testing-modules/spring-testing/README.md | 1 + testing-modules/spring-testing/pom.xml | 1 - .../java/com/baeldung/overrideproperties/Application.java | 0 .../overrideproperties/resolver/PropertySourceResolver.java | 0 .../ContextPropertySourceResolverIntegrationTest.java | 0 .../ProfilePropertySourceResolverIntegrationTest.java | 0 .../PropertyOverrideContextInitializer.java | 0 .../SpringBootPropertySourceResolverIntegrationTest.java | 0 .../TestResourcePropertySourceResolverIntegrationTest.java | 0 .../src/test/resources/application-test.properties | 2 ++ .../src/test/resources/application.properties | 3 +++ .../test/resources/context-override-application.properties | 0 15 files changed, 8 insertions(+), 11 deletions(-) rename {spring-boot-testing => testing-modules/spring-testing}/src/main/java/com/baeldung/overrideproperties/Application.java (100%) rename {spring-boot-testing => testing-modules/spring-testing}/src/main/java/com/baeldung/overrideproperties/resolver/PropertySourceResolver.java (100%) rename {spring-boot-testing => testing-modules/spring-testing}/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java (100%) rename {spring-boot-testing => testing-modules/spring-testing}/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java (100%) rename {spring-boot-testing => testing-modules/spring-testing}/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java (100%) rename {spring-boot-testing => testing-modules/spring-testing}/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java (100%) rename {spring-boot-testing => testing-modules/spring-testing}/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java (100%) create mode 100644 testing-modules/spring-testing/src/test/resources/application-test.properties create mode 100644 testing-modules/spring-testing/src/test/resources/application.properties rename {spring-boot-testing => testing-modules/spring-testing}/src/test/resources/context-override-application.properties (100%) diff --git a/spring-boot-testing/README.MD b/spring-boot-testing/README.MD index d303179ef6..99d7db5743 100644 --- a/spring-boot-testing/README.MD +++ b/spring-boot-testing/README.MD @@ -6,4 +6,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Testing with Spring and Spock](https://www.baeldung.com/spring-spock-testing) - [Exclude Auto-Configuration Classes in Spring Boot Tests](https://www.baeldung.com/spring-boot-exclude-auto-configuration-test) - [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level) -- [Override properties in Spring] diff --git a/spring-boot-testing/src/test/resources/application-test.properties b/spring-boot-testing/src/test/resources/application-test.properties index da187d8086..a2c9b6d480 100644 --- a/spring-boot-testing/src/test/resources/application-test.properties +++ b/spring-boot-testing/src/test/resources/application-test.properties @@ -1,5 +1,2 @@ # test properties -spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration - -# override properties -example.firstProperty=profile \ No newline at end of file +spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration \ No newline at end of file diff --git a/spring-boot-testing/src/test/resources/application.properties b/spring-boot-testing/src/test/resources/application.properties index e71b24a4e1..9a8b496a8b 100644 --- a/spring-boot-testing/src/test/resources/application.properties +++ b/spring-boot-testing/src/test/resources/application.properties @@ -1,7 +1,3 @@ # security spring.security.user.name=john -spring.security.user.password=123 - -# override properties -example.firstProperty=file -example.secondProperty=file \ No newline at end of file +spring.security.user.password=123 \ No newline at end of file diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index 8eb282643a..07888d7cdf 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -4,3 +4,4 @@ - [A Quick Guide to @TestPropertySource](https://www.baeldung.com/spring-test-property-source) - [Guide to ReflectionTestUtils for Unit Testing](https://www.baeldung.com/spring-reflection-test-utils) - [How to Test the @Scheduled Annotation](https://www.baeldung.com/spring-testing-scheduled-annotation) +- [Override properties in Spring]() \ No newline at end of file diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index 10d34f169b..0eca9b6a7e 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -26,7 +26,6 @@ org.springframework.boot spring-boot-starter LATEST - test
org.springframework.boot diff --git a/spring-boot-testing/src/main/java/com/baeldung/overrideproperties/Application.java b/testing-modules/spring-testing/src/main/java/com/baeldung/overrideproperties/Application.java similarity index 100% rename from spring-boot-testing/src/main/java/com/baeldung/overrideproperties/Application.java rename to testing-modules/spring-testing/src/main/java/com/baeldung/overrideproperties/Application.java diff --git a/spring-boot-testing/src/main/java/com/baeldung/overrideproperties/resolver/PropertySourceResolver.java b/testing-modules/spring-testing/src/main/java/com/baeldung/overrideproperties/resolver/PropertySourceResolver.java similarity index 100% rename from spring-boot-testing/src/main/java/com/baeldung/overrideproperties/resolver/PropertySourceResolver.java rename to testing-modules/spring-testing/src/main/java/com/baeldung/overrideproperties/resolver/PropertySourceResolver.java diff --git a/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java similarity index 100% rename from spring-boot-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java rename to testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ContextPropertySourceResolverIntegrationTest.java diff --git a/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java similarity index 100% rename from spring-boot-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java rename to testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/ProfilePropertySourceResolverIntegrationTest.java diff --git a/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java similarity index 100% rename from spring-boot-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java rename to testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/PropertyOverrideContextInitializer.java diff --git a/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java similarity index 100% rename from spring-boot-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java rename to testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/SpringBootPropertySourceResolverIntegrationTest.java diff --git a/spring-boot-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java similarity index 100% rename from spring-boot-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java rename to testing-modules/spring-testing/src/test/java/com/baeldung/overrideproperties/TestResourcePropertySourceResolverIntegrationTest.java diff --git a/testing-modules/spring-testing/src/test/resources/application-test.properties b/testing-modules/spring-testing/src/test/resources/application-test.properties new file mode 100644 index 0000000000..54c5bda7e8 --- /dev/null +++ b/testing-modules/spring-testing/src/test/resources/application-test.properties @@ -0,0 +1,2 @@ +# override properties +example.firstProperty=profile \ No newline at end of file diff --git a/testing-modules/spring-testing/src/test/resources/application.properties b/testing-modules/spring-testing/src/test/resources/application.properties new file mode 100644 index 0000000000..6c74aa2995 --- /dev/null +++ b/testing-modules/spring-testing/src/test/resources/application.properties @@ -0,0 +1,3 @@ +# override properties +example.firstProperty=file +example.secondProperty=file \ No newline at end of file diff --git a/spring-boot-testing/src/test/resources/context-override-application.properties b/testing-modules/spring-testing/src/test/resources/context-override-application.properties similarity index 100% rename from spring-boot-testing/src/test/resources/context-override-application.properties rename to testing-modules/spring-testing/src/test/resources/context-override-application.properties From 5d3d79ca84d8f99ecf8b386b5ddd52e154afa165 Mon Sep 17 00:00:00 2001 From: cdjole Date: Tue, 2 Jul 2019 18:02:23 +0200 Subject: [PATCH 081/352] String made of substring test update (#7234) --- .../string/repetition/SubstringRepetitionUnitTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java-strings-2/src/test/java/com/baeldung/string/repetition/SubstringRepetitionUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/repetition/SubstringRepetitionUnitTest.java index fbd948d2be..f382a24a7f 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/repetition/SubstringRepetitionUnitTest.java +++ b/java-strings-2/src/test/java/com/baeldung/string/repetition/SubstringRepetitionUnitTest.java @@ -9,11 +9,11 @@ public class SubstringRepetitionUnitTest { private String validString = "aa"; private String validStringTwo = "ababab"; - private String validStringThree = "aabcaabcaabcaabc"; + private String validStringThree = "baeldungbaeldung"; private String invalidString = "aca"; private String invalidStringTwo = "ababa"; - private String invalidStringThree = "abcdab"; + private String invalidStringThree = "baeldungnonrepeatedbaeldung"; @Test public void givenValidStrings_whenCheckIfContainsOnlySubstrings_thenReturnsTrue() { From ceb3d9ba789a11d696afde71e5599ec4282ad09c Mon Sep 17 00:00:00 2001 From: gpq5 Date: Tue, 2 Jul 2019 23:25:24 +0530 Subject: [PATCH 082/352] added another example of custom comparator --- .../json/compare/JsonCompareUnitTest.java | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java index 4cadac073c..03d7c63e36 100644 --- a/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java +++ b/jackson-2/src/test/java/com/baeldung/jackson/json/compare/JsonCompareUnitTest.java @@ -12,6 +12,7 @@ import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.NumericNode; +import com.fasterxml.jackson.databind.node.TextNode; public class JsonCompareUnitTest { @@ -58,7 +59,7 @@ public class JsonCompareUnitTest { } @Test - public void givenTwoJsonDataObjects_whenComparedUsingCustomComparator_thenEqual() throws IOException { + public void givenTwoJsonDataObjects_whenComparedUsingCustomNumericNodeComparator_thenEqual() throws IOException { ObjectMapper mapper = new ObjectMapper(); String s1 = "{\"name\": \"John\",\"score\":5.0}"; @@ -89,4 +90,37 @@ public class JsonCompareUnitTest { return 1; } } + + @Test + public void givenTwoJsonDataObjects_whenComparedUsingCustomTextNodeComparator_thenEqual() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + + String s1 = "{\"name\": \"JOHN\",\"score\":5}"; + String s2 = "{\"name\": \"John\",\"score\":5}"; + JsonNode actualObj1 = mapper.readTree(s1); + JsonNode actualObj2 = mapper.readTree(s2); + + TextNodeComparator cmp = new TextNodeComparator(); + + assertNotEquals(actualObj1, actualObj2); + assertTrue(actualObj1.equals(cmp, actualObj2)); + + } + + public class TextNodeComparator implements Comparator { + @Override + public int compare(JsonNode o1, JsonNode o2) { + if (o1.equals(o2)) { + return 0; + } + if ((o1 instanceof TextNode) && (o2 instanceof TextNode)) { + String s1 = ((TextNode) o1).asText(); + String s2 = ((TextNode) o2).asText(); + if (s1.equalsIgnoreCase(s2)) { + return 0; + } + } + return 1; + } + } } From 7c4019e3845022dc45cf8db56fe21569422aca6e Mon Sep 17 00:00:00 2001 From: Sam Millington Date: Tue, 2 Jul 2019 21:01:30 +0100 Subject: [PATCH 083/352] [BAEL-2959] A Guide to MapDB code (#7042) * [BAEL-2959] A Guide to MapDB code * [BAEL-2959] fixes * [BAEL-2959] made VOLUME_LOCATION static in SortedTableMapUnitTest * moved mapdb files from libraries to libraries-2 * [BAEL-2959] formatting fixes * updated pom.xml --- libraries-2/pom.xml | 269 +++++++++--------- .../baeldung/mapdb/CollectionsUnitTest.java | 33 +++ .../com/baeldung/mapdb/HTreeMapUnitTest.java | 38 +++ .../baeldung/mapdb/HelloBaeldungUnitTest.java | 49 ++++ .../baeldung/mapdb/InMemoryModesUnitTest.java | 62 ++++ .../mapdb/SortedTableMapUnitTest.java | 47 +++ .../baeldung/mapdb/TransactionsUnitTest.java | 41 +++ libraries/pom.xml | 4 + 8 files changed, 405 insertions(+), 138 deletions(-) create mode 100644 libraries-2/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java create mode 100644 libraries-2/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java create mode 100644 libraries-2/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java create mode 100644 libraries-2/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java create mode 100644 libraries-2/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java create mode 100644 libraries-2/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 02e1da017a..efcb03f528 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -1,70 +1,71 @@ - - 4.0.0 - libraries2 - libraries2 - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - jboss-public-repository-group - JBoss Public Repository Group - http://repository.jboss.org/nexus/content/groups/public/ - - true - never - - - true - daily - - - - - - - com.pivovarit - parallel-collectors - 1.1.0 - - - org.assertj - assertj-core - ${assertj.version} - - - io.github.classgraph - classgraph - ${classgraph.version} - - - org.jbpm - jbpm-test - ${jbpm.version} - - - info.picocli - picocli - ${picocli.version} - + 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"> + 4.0.0 + libraries2 + libraries2 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + jboss-public-repository-group + JBoss Public Repository Group + http://repository.jboss.org/nexus/content/groups/public/ + + true + never + + + true + daily + + + + + + org.mapdb + mapdb + ${mapdb.version} + + + com.pivovarit + parallel-collectors + 1.1.0 + + + org.assertj + assertj-core + ${assertj.version} + + + io.github.classgraph + classgraph + ${classgraph.version} + + + org.jbpm + jbpm-test + ${jbpm.version} + + + info.picocli + picocli + ${picocli.version} + org.ejml ejml-all ${ejml.version} - - org.nd4j - nd4j-native - ${nd4j.version} - + + org.nd4j + nd4j-native + ${nd4j.version} + org.la4j la4j @@ -75,87 +76,79 @@ colt ${colt.version} - - org.springframework.boot - spring-boot-starter - ${spring-boot-starter.version} - - - net.openhft - chronicle-map - ${chronicle.map.version} - - - com.sun.java - tools - - - - - - - com.squareup.okhttp3 - okhttp - 3.14.2 - - - - com.fasterxml.jackson.core - jackson-databind - 2.9.9 - - - - com.google.code.gson - gson - 2.8.5 - - - - com.squareup.okhttp3 - mockwebserver - 3.14.2 - test - - + + org.springframework.boot + spring-boot-starter + ${spring-boot-starter.version} + + + net.openhft + chronicle-map + ${chronicle.map.version} + + + com.sun.java + tools + + + + + + com.squareup.okhttp3 + okhttp + 3.14.2 + + + com.fasterxml.jackson.core + jackson-databind + 2.9.9 + + + com.google.code.gson + gson + 2.8.5 + + + com.squareup.okhttp3 + mockwebserver + 3.14.2 + test + edu.uci.ics crawler4j ${crawler4j.version} - - - - com.github.jknack - handlebars - 4.1.2 - - - - - org.openjdk.jmh - jmh-core - ${jmh.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh.version} - - - - - - 3.6.2 - 4.8.28 - 6.0.0.Final - 3.9.6 - 3.17.2 + + + com.github.jknack + handlebars + 4.1.2 + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + 3.0.7 + 3.6.2 + 4.8.28 + 6.0.0.Final + 3.9.6 + 3.17.2 4.4.0 - 2.1.4.RELEASE - 0.38 - 1.0.0-beta4 - 1.2.0 - 0.6.0 - 1.19 - + 2.1.4.RELEASE + 0.38 + 1.0.0-beta4 + 1.2.0 + 0.6.0 + 1.19 + diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java new file mode 100644 index 0000000000..6f5141b054 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.mapdb; + +import org.junit.Test; +import org.mapdb.DB; +import org.mapdb.DBMaker; +import org.mapdb.Serializer; + +import java.util.NavigableSet; + +import static junit.framework.Assert.assertEquals; + +public class CollectionsUnitTest { + + @Test + public void givenSetCreatedInDB_whenMultipleElementsAdded_checkOnlyOneExists() { + + DB db = DBMaker.memoryDB().make(); + + NavigableSet set = db. + treeSet("mySet") + .serializer(Serializer.STRING) + .createOrOpen(); + + String myString = "Baeldung!"; + + set.add(myString); + set.add(myString); + + assertEquals(1, set.size()); + + db.close(); + } +} diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java new file mode 100644 index 0000000000..3b7cac04fb --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.mapdb; + +import org.jetbrains.annotations.NotNull; +import org.junit.Test; +import org.mapdb.*; + +import java.io.IOException; + +import static junit.framework.Assert.assertEquals; + +public class HTreeMapUnitTest { + + @Test + public void givenValidDB_whenHTreeMapAddedToAndRetrieved_CheckedRetrievalCorrect() { + + DB db = DBMaker.memoryDB().make(); + + HTreeMap hTreeMap = db + .hashMap("myTreMap") + .keySerializer(Serializer.STRING) + .valueSerializer(Serializer.STRING) + .create(); + + hTreeMap.put("key1", "value1"); + hTreeMap.put("key2", "value2"); + + assertEquals(2, hTreeMap.size()); + + //add another value with the same key + + hTreeMap.put("key1", "value3"); + + assertEquals(2, hTreeMap.size()); + assertEquals("value3", hTreeMap.get("key1")); + + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java new file mode 100644 index 0000000000..952efd0639 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.mapdb; + +import org.junit.Test; +import org.mapdb.DB; +import org.mapdb.DBMaker; +import org.mapdb.HTreeMap; + +import java.util.concurrent.ConcurrentMap; + +import static junit.framework.Assert.assertEquals; + +public class HelloBaeldungUnitTest { + + @Test + public void givenInMemoryDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() { + + DB db = DBMaker.memoryDB().make(); + + String welcomeMessageKey = "Welcome Message"; + String welcomeMessageString = "Hello Baeldung!"; + + HTreeMap myMap = db.hashMap("myMap").createOrOpen(); + myMap.put(welcomeMessageKey, welcomeMessageString); + + String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey); + + db.close(); + + assertEquals(welcomeMessageString, welcomeMessageFromDB); + } + + @Test + public void givenInFileDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() { + + DB db = DBMaker.fileDB("file.db").make(); + + String welcomeMessageKey = "Welcome Message"; + String welcomeMessageString = "Hello Baeldung!"; + + HTreeMap myMap = db.hashMap("myMap").createOrOpen(); + myMap.put(welcomeMessageKey, welcomeMessageString); + + String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey); + + db.close(); + + assertEquals(welcomeMessageString, welcomeMessageFromDB); + } +} diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java new file mode 100644 index 0000000000..9c53f9c792 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.mapdb; + +import org.junit.Test; +import org.mapdb.DB; +import org.mapdb.DBMaker; +import org.mapdb.HTreeMap; +import org.mapdb.Serializer; + +import static junit.framework.Assert.assertEquals; + +public class InMemoryModesUnitTest { + + @Test + public void givenDBCreatedOnHeap_whenUsed_checkUsageCorrect() { + + DB heapDB = DBMaker.heapDB().make(); + + HTreeMap map = heapDB + .hashMap("myMap") + .keySerializer(Serializer.INTEGER) + .valueSerializer(Serializer.STRING) + .createOrOpen(); + + map.put(1, "ONE"); + + assertEquals("ONE", map.get(1)); + + } + + @Test + public void givenDBCreatedBaseOnByteArray_whenUsed_checkUsageCorrect() { + + DB heapDB = DBMaker.memoryDB().make(); + + HTreeMap map = heapDB + .hashMap("myMap") + .keySerializer(Serializer.INTEGER) + .valueSerializer(Serializer.STRING) + .createOrOpen(); + + map.put(1, "ONE"); + + assertEquals("ONE", map.get(1)); + } + + @Test + public void givenDBCreatedBaseOnDirectByteBuffer_whenUsed_checkUsageCorrect() { + + DB heapDB = DBMaker.memoryDirectDB().make(); + + HTreeMap map = heapDB + .hashMap("myMap") + .keySerializer(Serializer.INTEGER) + .valueSerializer(Serializer.STRING) + .createOrOpen(); + + map.put(1, "ONE"); + + assertEquals("ONE", map.get(1)); + } + +} diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java new file mode 100644 index 0000000000..83ba917393 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.mapdb; + +import org.junit.Test; +import org.mapdb.Serializer; +import org.mapdb.SortedTableMap; +import org.mapdb.volume.MappedFileVol; +import org.mapdb.volume.Volume; + +import static junit.framework.Assert.assertEquals; + +public class SortedTableMapUnitTest { + + private static final String VOLUME_LOCATION = "sortedTableMapVol.db"; + + @Test + public void givenValidSortedTableMapSetup_whenQueried_checkValuesCorrect() { + + //create memory mapped volume, readonly false + Volume vol = MappedFileVol.FACTORY.makeVolume(VOLUME_LOCATION, false); + + //create sink to feed the map with data + SortedTableMap.Sink sink = + SortedTableMap.create( + vol, + Serializer.INTEGER, + Serializer.STRING + ).createFromSink(); + + //add content + for(int i = 0; i < 100; i++){ + sink.put(i, "Value " + Integer.toString(i)); + } + + sink.create(); + + //now open in read-only mode + Volume openVol = MappedFileVol.FACTORY.makeVolume(VOLUME_LOCATION, true); + + SortedTableMap sortedTableMap = SortedTableMap.open( + openVol, + Serializer.INTEGER, + Serializer.STRING + ); + + assertEquals(100, sortedTableMap.size()); + } +} diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java new file mode 100644 index 0000000000..4de9db10e8 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.mapdb; + +import org.junit.Test; +import org.mapdb.DB; +import org.mapdb.DBMaker; +import org.mapdb.Serializer; + +import java.util.NavigableSet; + +import static junit.framework.Assert.assertEquals; + +public class TransactionsUnitTest { + + @Test + public void givenValidDBSetup_whenTransactionCommittedAndRolledBack_checkPreviousStateAchieved() { + + DB db = DBMaker.memoryDB().transactionEnable().make(); + + NavigableSet set = db + .treeSet("mySet") + .serializer(Serializer.STRING) + .createOrOpen(); + + set.add("One"); + set.add("Two"); + + db.commit(); + + assertEquals(2, set.size()); + + set.add("Three"); + + assertEquals(3, set.size()); + + db.rollback(); + + assertEquals(2, set.size()); + + db.close(); + } +} diff --git a/libraries/pom.xml b/libraries/pom.xml index 7823732224..886dd3c4a2 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -19,6 +19,9 @@ ${typesafe-akka.version} + + + com.typesafe.akka akka-testkit_2.12 @@ -837,6 +840,7 @@ 1.4.196 1.0 + 4.5.3 2.9.7 2.92 From d67b026d29b63001c48dd6e99b4fec15a2662122 Mon Sep 17 00:00:00 2001 From: Pazis Date: Wed, 3 Jul 2019 05:50:41 +0430 Subject: [PATCH 084/352] BAEL-2962 Java Multi-line String (#7166) * added readme * hexagonal architecture implemented * Java Multiline String --- .../string/multiline/MultiLineString.java | 67 +++++++++++++++++++ .../src/main/resources/stephenking.txt | 4 ++ .../string/MultiLineStringUnitTest.java | 22 ++++++ 3 files changed, 93 insertions(+) create mode 100644 java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java create mode 100644 java-strings-2/src/main/resources/stephenking.txt create mode 100644 java-strings-2/src/test/java/com/baeldung/string/MultiLineStringUnitTest.java diff --git a/java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java b/java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java new file mode 100644 index 0000000000..1bde2dcb63 --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/multiline/MultiLineString.java @@ -0,0 +1,67 @@ +package com.baeldung.string.multiline; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.file.Files; +import java.nio.file.Paths; + +import com.google.common.base.Joiner; +import com.google.common.collect.ImmutableList; + +public class MultiLineString { + + String newLine = System.getProperty("line.separator"); + + public String stringConcatenation() { + return "Get busy living" + .concat(newLine) + .concat("or") + .concat(newLine) + .concat("get busy dying.") + .concat(newLine) + .concat("--Stephen King"); + } + + public String stringJoin() { + return String.join(newLine, + "Get busy living", + "or", + "get busy dying.", + "--Stephen King"); + } + + public String stringBuilder() { + return new StringBuilder() + .append("Get busy living") + .append(newLine) + .append("or") + .append(newLine) + .append("get busy dying.") + .append(newLine) + .append("--Stephen King") + .toString(); + } + + public String stringWriter() { + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + printWriter.println("Get busy living"); + printWriter.println("or"); + printWriter.println("get busy dying."); + printWriter.println("--Stephen King"); + return stringWriter.toString(); + } + + public String guavaJoiner() { + return Joiner.on(newLine).join(ImmutableList.of("Get busy living", + "or", + "get busy dying.", + "--Stephen King")); + } + + public String loadFromFile() throws IOException { + return new String(Files.readAllBytes(Paths.get("src/main/resources/stephenking.txt"))); + } + +} diff --git a/java-strings-2/src/main/resources/stephenking.txt b/java-strings-2/src/main/resources/stephenking.txt new file mode 100644 index 0000000000..f31b4a28bd --- /dev/null +++ b/java-strings-2/src/main/resources/stephenking.txt @@ -0,0 +1,4 @@ +Get busy living +or +get busy dying. +--Stephen King \ No newline at end of file diff --git a/java-strings-2/src/test/java/com/baeldung/string/MultiLineStringUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/MultiLineStringUnitTest.java new file mode 100644 index 0000000000..b458fae79b --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/MultiLineStringUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.string; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import com.baeldung.string.multiline.MultiLineString; + +public class MultiLineStringUnitTest { + + + @Test + public void whenCompareMultiLineStrings_thenTheyAreAllTheSame() throws IOException { + MultiLineString ms = new MultiLineString(); + assertEquals(ms.stringConcatenation(), ms.stringJoin()); + assertEquals(ms.stringJoin(), ms.stringBuilder()); + assertEquals(ms.stringBuilder(), ms.guavaJoiner()); + assertEquals(ms.guavaJoiner(), ms.loadFromFile()); + } + +} From c5179b6ec856acdc32e140f6c5f1b57d8c1ab6ff Mon Sep 17 00:00:00 2001 From: Michael Sievers Date: Wed, 3 Jul 2019 04:01:53 +0200 Subject: [PATCH 085/352] [BAEL-3019] Add sample code for empty and blank string checks (#7176) * [BAEL-3019] Add sample code for empty and blank string checks * [BAEL-3019] Add article link to module README * [BAEL-3019] Remove blank line in the beginning of certain tests * [BAEL-3019] Unroll tests and adhere to givenXXX_thenXXX naming convention * Revert "[BAEL-3019] Add article link to module README" This reverts commit 675295fafa53861d2bd3eb0e766665a58adda97d. * [BAEL-3019] Bump guava version for 'java-strings-2' to 28.0-jre --- java-strings-2/pom.xml | 22 ++- .../string/emptystrings/EmptyStringCheck.java | 8 + .../emptystrings/Java5EmptyStringCheck.java | 8 + .../PlainJavaBlankStringCheck.java | 8 + .../SomeClassWithValidations.java | 14 ++ .../emptystrings/EmptyStringsUnitTest.java | 142 ++++++++++++++++++ 6 files changed, 201 insertions(+), 1 deletion(-) create mode 100644 java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java create mode 100644 java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java create mode 100644 java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java create mode 100644 java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java create mode 100644 java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java diff --git a/java-strings-2/pom.xml b/java-strings-2/pom.xml index 9c27429139..7342953d15 100755 --- a/java-strings-2/pom.xml +++ b/java-strings-2/pom.xml @@ -57,6 +57,26 @@ commons-text ${commons-text.version} + + javax.validation + validation-api + 2.0.0.Final + + + org.hibernate.validator + hibernate-validator + 6.0.2.Final + + + javax.el + javax.el-api + 3.0.0 + + + org.glassfish.web + javax.el + 2.2.6 + @@ -86,7 +106,7 @@ 3.8.1 61.1 - 27.0.1-jre + 28.0-jre 1.4 diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java new file mode 100644 index 0000000000..6d3234a4ec --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/EmptyStringCheck.java @@ -0,0 +1,8 @@ +package com.baeldung.string.emptystrings; + +class EmptyStringCheck { + + boolean isEmptyString(String string) { + return string == null || string.isEmpty(); + } +} diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java new file mode 100644 index 0000000000..096b83acea --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/Java5EmptyStringCheck.java @@ -0,0 +1,8 @@ +package com.baeldung.string.emptystrings; + +class Java5EmptyStringCheck { + + boolean isEmptyString(String string) { + return string == null || string.length() == 0; + } +} diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java new file mode 100644 index 0000000000..26e281c9b7 --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/PlainJavaBlankStringCheck.java @@ -0,0 +1,8 @@ +package com.baeldung.string.emptystrings; + +class PlainJavaBlankStringCheck { + + boolean isBlankString(String string) { + return string == null || string.trim().isEmpty(); + } +} diff --git a/java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java new file mode 100644 index 0000000000..8c484efb43 --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/emptystrings/SomeClassWithValidations.java @@ -0,0 +1,14 @@ +package com.baeldung.string.emptystrings; + +import javax.validation.constraints.Pattern; + +class SomeClassWithValidations { + + @Pattern(regexp = "\\A(?!\\s*\\Z).+") + private String someString; + + SomeClassWithValidations setSomeString(String someString) { + this.someString = someString; + return this; + } +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java new file mode 100644 index 0000000000..96b1d681dd --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/emptystrings/EmptyStringsUnitTest.java @@ -0,0 +1,142 @@ +package com.baeldung.string.emptystrings; + +import static org.hamcrest.Matchers.iterableWithSize; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import com.google.common.base.Strings; + +public class EmptyStringsUnitTest { + + private String emptyString = ""; + private String blankString = " \n\t "; + private String nonEmptyString = " someString "; + + /* + * EmptyStringCheck + */ + @Test + public void givenSomeEmptyString_thenEmptyStringCheckIsEmptyStringReturnsTrue() { + assertTrue(new EmptyStringCheck().isEmptyString(emptyString)); + } + + @Test + public void givenSomeNonEmptyString_thenEmptyStringCheckIsEmptyStringReturnsFalse() { + assertFalse(new EmptyStringCheck().isEmptyString(nonEmptyString)); + } + + @Test + public void givenSomeBlankString_thenEmptyStringCheckIsEmptyStringReturnsFalse() { + assertFalse(new EmptyStringCheck().isEmptyString(blankString)); + } + + /* + * Java5EmptyStringCheck + */ + @Test + public void givenSomeEmptyString_thenJava5EmptyStringCheckIsEmptyStringReturnsTrue() { + assertTrue(new Java5EmptyStringCheck().isEmptyString(emptyString)); + } + + @Test + public void givenSomeNonEmptyString_thenJava5EmptyStringCheckIsEmptyStringReturnsFalse() { + assertFalse(new Java5EmptyStringCheck().isEmptyString(nonEmptyString)); + } + + @Test + public void givenSomeBlankString_thenJava5EmptyStringCheckIsEmptyStringReturnsFalse() { + assertFalse(new Java5EmptyStringCheck().isEmptyString(blankString)); + } + + /* + * PlainJavaBlankStringCheck + */ + @Test + public void givenSomeEmptyString_thenPlainJavaBlankStringCheckIsBlankStringReturnsTrue() { + assertTrue(new PlainJavaBlankStringCheck().isBlankString(emptyString)); + } + + @Test + public void givenSomeNonEmptyString_thenPlainJavaBlankStringCheckIsBlankStringReturnsFalse() { + assertFalse(new PlainJavaBlankStringCheck().isBlankString(nonEmptyString)); + } + + @Test + public void givenSomeBlankString_thenPlainJavaBlankStringCheckIsBlankStringReturnsTrue() { + assertTrue(new PlainJavaBlankStringCheck().isBlankString(blankString)); + } + + /* + * Apache Commons Lang StringUtils + */ + @Test + public void givenSomeEmptyString_thenStringUtilsIsBlankReturnsTrue() { + assertTrue(StringUtils.isBlank(emptyString)); + } + + @Test + public void givenSomeNonEmptyString_thenStringUtilsIsBlankReturnsFalse() { + assertFalse(StringUtils.isBlank(nonEmptyString)); + } + + @Test + public void givenSomeBlankString_thenStringUtilsIsBlankReturnsTrue() { + assertTrue(StringUtils.isBlank(blankString)); + } + + /* + * Google Guava Strings + */ + @Test + public void givenSomeEmptyString_thenStringsIsNullOrEmptyStringReturnsTrue() { + assertTrue(Strings.isNullOrEmpty(emptyString)); + } + + @Test + public void givenSomeNonEmptyString_thenStringsIsNullOrEmptyStringReturnsFalse() { + assertFalse(Strings.isNullOrEmpty(nonEmptyString)); + } + + @Test + public void givenSomeBlankString_thenStringsIsNullOrEmptyStringReturnsFalse() { + assertFalse(Strings.isNullOrEmpty(blankString)); + } + + /* + * Bean Validation + */ + private ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + private Validator validator = factory.getValidator(); + + @Test + public void givenSomeEmptyString_thenBeanValidationReturnsViolations() { + SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(emptyString); + Set> violations = validator.validate(someClassWithValidations); + assertThat(violations, iterableWithSize(1)); + } + + @Test + public void givenSomeNonEmptyString_thenBeanValidationValidatesWithoutViolations() { + SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(nonEmptyString); + Set> violations = validator.validate(someClassWithValidations); + assertThat(violations, iterableWithSize(0)); + } + + @Test + public void givenSomeBlankString_thenBeanValidationReturnsViolations() { + SomeClassWithValidations someClassWithValidations = new SomeClassWithValidations().setSomeString(blankString); + Set> violations = validator.validate(someClassWithValidations); + assertThat(violations, iterableWithSize(1)); + } +} From c828d6083ed6af6dde213c5c6b4ea9aba3ad8b57 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:15:17 +0530 Subject: [PATCH 086/352] Back-link added --- java-collections-conversions/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/java-collections-conversions/README.md b/java-collections-conversions/README.md index 31fead3c42..0dec3563ff 100644 --- a/java-collections-conversions/README.md +++ b/java-collections-conversions/README.md @@ -10,4 +10,5 @@ - [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string) - [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map) - [Array to String Conversions](https://www.baeldung.com/java-array-to-string) -- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist) \ No newline at end of file +- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist) +- [Java 8 Collectors toMap](https://www.baeldung.com/java-collectors-tomap) From 524e50f5dea9ccaca7e03bcb6d64f6f955ab1975 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:17:10 +0530 Subject: [PATCH 087/352] Back-link added --- testing-modules/spring-testing/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index 8eb282643a..12c8edfded 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -4,3 +4,4 @@ - [A Quick Guide to @TestPropertySource](https://www.baeldung.com/spring-test-property-source) - [Guide to ReflectionTestUtils for Unit Testing](https://www.baeldung.com/spring-reflection-test-utils) - [How to Test the @Scheduled Annotation](https://www.baeldung.com/spring-testing-scheduled-annotation) +- [Using SpringJUnit4ClassRunner with Parameterized](https://www.baeldung.com/springjunit4classrunner-parameterized) From 69b272888fffa7cfad5790a80031018b5c37afc5 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:19:52 +0530 Subject: [PATCH 088/352] Back-link added --- libraries-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries-2/README.md b/libraries-2/README.md index cdeed10b3f..862d7395fe 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -5,3 +5,4 @@ - [Guide to Classgraph Library](https://www.baeldung.com/classgraph) - [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program) - [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors) +- [A Guide to Crawler4j](https://www.baeldung.com/crawler4j) From 3d16af291f34f1bc21d1fffbf8be88b6a01b8f74 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:21:15 +0530 Subject: [PATCH 089/352] Back-link added --- libraries-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries-2/README.md b/libraries-2/README.md index 862d7395fe..78fd9c8573 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -6,3 +6,4 @@ - [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program) - [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors) - [A Guide to Crawler4j](https://www.baeldung.com/crawler4j) +- [Decode an OkHttp JSON Response](https://www.baeldung.com/okhttp-json-response) From cc7260465aac5517f9fdc60035b5a3d2e0bf7379 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:23:34 +0530 Subject: [PATCH 090/352] Back-link added --- spring-session/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-session/README.md b/spring-session/README.md index 505d043e75..c9875beadf 100644 --- a/spring-session/README.md +++ b/spring-session/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [Guide to Spring Session](https://www.baeldung.com/spring-session) - [Spring Session with JDBC](https://www.baeldung.com/spring-session-jdbc) +- [Spring Session with MongoDB](https://www.baeldung.com/spring-session-mongodb) From c9126ae52b26cd95f7d1e57912a41a3772aecf26 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:25:15 +0530 Subject: [PATCH 091/352] Back-link added --- persistence-modules/hibernate-mapping/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 203cb2f8e4..0df13653b9 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -3,3 +3,4 @@ - [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps) - [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) +- [Hibernate Validator Specific Constraints](https://www.baeldung.com/hibernate-validator-constraints) From cb82c9828bfe6219ba4c43e6bda6825c031af210 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:26:49 +0530 Subject: [PATCH 092/352] Back-link added --- core-java-modules/core-java-optional/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-optional/README.md b/core-java-modules/core-java-optional/README.md index 12a6fd1a56..b6848b5d33 100644 --- a/core-java-modules/core-java-optional/README.md +++ b/core-java-modules/core-java-optional/README.md @@ -2,4 +2,5 @@ ## Core Java Optional -### Relevant Articles: \ No newline at end of file +### Relevant Articles: +- [Java Optional as Return Type](https://www.baeldung.com/java-optional-return) From 8bc56f4e3930e5f0e9d2f4403452606eb65549a0 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:32:23 +0530 Subject: [PATCH 093/352] Back-link added --- core-groovy-2/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-groovy-2/README.md b/core-groovy-2/README.md index d6fc6fc2f7..33df8b107b 100644 --- a/core-groovy-2/README.md +++ b/core-groovy-2/README.md @@ -6,4 +6,5 @@ - [Template Engines in Groovy](https://www.baeldung.com/groovy-template-engines) - [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword) - [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching) -- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml) \ No newline at end of file +- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml) +- [Integrating Groovy into Java Applications](https://www.baeldung.com/groovy-java-applications) From 9a34e576c95bc881481b6d829e5eec7cd048dd26 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:37:42 +0530 Subject: [PATCH 094/352] Back-link added --- core-java-modules/core-java-collections-set/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-set/README.md b/core-java-modules/core-java-collections-set/README.md index 2e09e920dc..618b4e932c 100644 --- a/core-java-modules/core-java-collections-set/README.md +++ b/core-java-modules/core-java-collections-set/README.md @@ -10,3 +10,4 @@ - [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset) - [Guide to EnumSet](https://www.baeldung.com/java-enumset) - [Set Operations in Java](https://www.baeldung.com/java-set-operations) +- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets) From d4f0f099482d701b81df336c44873a3bb650d4f3 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:37:52 +0530 Subject: [PATCH 095/352] Back-link added --- core-java-modules/core-java-10/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-10/README.md b/core-java-modules/core-java-10/README.md index f0a25712a7..8fb4f8a7dd 100644 --- a/core-java-modules/core-java-10/README.md +++ b/core-java-modules/core-java-10/README.md @@ -5,3 +5,4 @@ - [Guide to Java 10](http://www.baeldung.com/java-10-overview) - [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) - [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler) +- [Copying Sets in Java](https://www.baeldung.com/java-copy-sets) From 44e2cc65cadb5d5bc59fb723e76bacf37583bacd Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:42:59 +0530 Subject: [PATCH 096/352] Back-link added --- algorithms-miscellaneous-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index 7a83a97c5b..edf9a71502 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -5,3 +5,4 @@ - [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic) - [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity) - [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted) +- [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle) From d1251f762b543a0a240c1b38200235598c49aafc Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:58:11 +0530 Subject: [PATCH 097/352] Back-link added --- core-java-modules/core-java-nio/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-nio/README.md b/core-java-modules/core-java-nio/README.md index e73a9850ad..9034c3b3b1 100644 --- a/core-java-modules/core-java-nio/README.md +++ b/core-java-modules/core-java-nio/README.md @@ -1,3 +1,3 @@ ## Relevant articles: -- [Determine File Creating Date in Java](https://www.baeldung.com/file-creation-date-java) +- [Determine File Creating Date in Java](https://www.baeldung.com/java-file-creation-date) From 5acc605d39fed716a56430430be68f8a412b58b2 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:04:33 +0530 Subject: [PATCH 098/352] Back-link added --- java-collections-conversions/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-collections-conversions/README.md b/java-collections-conversions/README.md index 0dec3563ff..bec7df6c55 100644 --- a/java-collections-conversions/README.md +++ b/java-collections-conversions/README.md @@ -12,3 +12,4 @@ - [Array to String Conversions](https://www.baeldung.com/java-array-to-string) - [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist) - [Java 8 Collectors toMap](https://www.baeldung.com/java-collectors-tomap) +- [Converting Iterable to Collection in Java](https://www.baeldung.com/java-iterable-to-collection) From 8d383d5f8a241fa0aa5a48c997c6fbafe6070822 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:05:53 +0530 Subject: [PATCH 099/352] Back-link added --- jackson-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jackson-2/README.md b/jackson-2/README.md index ee9f8458a0..d8c233a00e 100644 --- a/jackson-2/README.md +++ b/jackson-2/README.md @@ -9,4 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field) - [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml) - [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model) - +- [Converting JSON to CSV in Java](https://www.baeldung.com/java-converting-json-to-csv) From 8b7ad99af9cc6d421e9998bd869a1523e29b8e04 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:06:59 +0530 Subject: [PATCH 100/352] Back-link added --- testing-modules/junit-5-basics/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/junit-5-basics/README.md b/testing-modules/junit-5-basics/README.md index 6e44a9c071..c09c030780 100644 --- a/testing-modules/junit-5-basics/README.md +++ b/testing-modules/junit-5-basics/README.md @@ -2,3 +2,4 @@ - [Get the Path of the /src/test/resources Directory in JUnit](https://www.baeldung.com/junit-src-test-resources-directory-path) - [Tagging and Filtering JUnit Tests](https://www.baeldung.com/junit-filtering-tests) +- [JUnit 5 Temporary Directory Support](https://www.baeldung.com/junit-5-temporary-directory) From c2563fa0536ef7b89dec9e94245e1f4f24ace4b2 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:08:23 +0530 Subject: [PATCH 101/352] Back-link added --- spring-resttemplate/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-resttemplate/README.md b/spring-resttemplate/README.md index c2c4965231..97a89ff7aa 100644 --- a/spring-resttemplate/README.md +++ b/spring-resttemplate/README.md @@ -10,3 +10,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) - [Mocking a RestTemplate in Spring](https://www.baeldung.com/spring-mock-rest-template) - [RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json) +- [Download a Large File Through a Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-download-large-file) From 241c4ee443ce8bdf407df64cb15601acd9b59b02 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:11:33 +0530 Subject: [PATCH 102/352] Back-link added --- ratpack/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/ratpack/README.md b/ratpack/README.md index 14bc3f6c74..78e2f8ccfc 100644 --- a/ratpack/README.md +++ b/ratpack/README.md @@ -6,3 +6,4 @@ - [Ratpack with Hystrix](http://www.baeldung.com/ratpack-hystrix) - [Ratpack HTTP Client](https://www.baeldung.com/ratpack-http-client) - [Ratpack with RxJava](https://www.baeldung.com/ratpack-rxjava) +- [Ratpack with Groovy](https://www.baeldung.com/ratpack-groovy) From 7136f07e7a5e93d15188f079e48d282fe60f7be8 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:13:37 +0530 Subject: [PATCH 103/352] Back-link added --- spring-static-resources/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-static-resources/README.md b/spring-static-resources/README.md index c12e0272d4..64f017b5dd 100644 --- a/spring-static-resources/README.md +++ b/spring-static-resources/README.md @@ -2,3 +2,4 @@ - [Cachable Static Assets with Spring MVC](http://www.baeldung.com/cachable-static-assets-with-spring-mvc) - [Minification of JS and CSS Assets with Maven](http://www.baeldung.com/maven-minification-of-js-and-css-assets) - [Serve Static Resources with Spring](http://www.baeldung.com/spring-mvc-static-resources) +- [Load a Resource as a String in Spring](https://www.baeldung.com/spring-load-resource-as-string) From ce001ff4bbdd200e1df998bdcb17e4cb611da983 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:14:57 +0530 Subject: [PATCH 104/352] Back-link added --- algorithms-miscellaneous-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index edf9a71502..71541cd2b3 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -6,3 +6,4 @@ - [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity) - [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted) - [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle) +- [A Guide to the Folding Technique](https://www.baeldung.com/folding-hashing-technique) From b485df68e43a3889128b1abbf3ef93f9d87f6bae Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:19:57 +0530 Subject: [PATCH 105/352] Back-link added --- autovalue/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/autovalue/README.md b/autovalue/README.md index c6a08359ef..f33ff6899f 100644 --- a/autovalue/README.md +++ b/autovalue/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue) - [Introduction to AutoFactory](http://www.baeldung.com/autofactory) +- [Google AutoService](https://www.baeldung.com/google-autoservice) From 2c4a1a98301acaea469cd6244c2e1e01b18c0885 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:22:56 +0530 Subject: [PATCH 106/352] Back-link added --- core-java-modules/core-java-lang-oop-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-oop-2/README.md b/core-java-modules/core-java-lang-oop-2/README.md index 2e36d251ca..72c3c6742b 100644 --- a/core-java-modules/core-java-lang-oop-2/README.md +++ b/core-java-modules/core-java-lang-oop-2/README.md @@ -6,3 +6,4 @@ - [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors) - [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error) - [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes) +- [Raw Types in Java](https://www.baeldung.com/raw-types-java) From 6d5cd34665bbf37624408f036e84522889b9bf7e Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:25:04 +0530 Subject: [PATCH 107/352] Back-link added --- java-streams-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java-streams-2/README.md b/java-streams-2/README.md index 83ef97686f..b7f1ec11d7 100644 --- a/java-streams-2/README.md +++ b/java-streams-2/README.md @@ -1,3 +1,3 @@ ### Relevant Articles: - [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce) - +- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach) From f79e3b067623cb557414d621b449726a0e2c7c0d Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:29:43 +0530 Subject: [PATCH 108/352] Back-link added --- java-collections-conversions/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-collections-conversions/README.md b/java-collections-conversions/README.md index bec7df6c55..614f20f186 100644 --- a/java-collections-conversions/README.md +++ b/java-collections-conversions/README.md @@ -13,3 +13,4 @@ - [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist) - [Java 8 Collectors toMap](https://www.baeldung.com/java-collectors-tomap) - [Converting Iterable to Collection in Java](https://www.baeldung.com/java-iterable-to-collection) +- [Converting Iterator to List](https://www.baeldung.com/java-convert-iterator-to-list) From ccddf1ba82d86a9c77ea1a0172924520337c4326 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:32:14 +0530 Subject: [PATCH 109/352] Back-link added --- java-streams-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-streams-2/README.md b/java-streams-2/README.md index b7f1ec11d7..851d3d71e2 100644 --- a/java-streams-2/README.md +++ b/java-streams-2/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce) - [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach) +- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert) From 45a6be9c854886cfc23a5c4748845369953ed094 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:35:22 +0530 Subject: [PATCH 110/352] Back-link added --- core-java-modules/core-java-8-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md index d53b731878..245fa93ba7 100644 --- a/core-java-modules/core-java-8-2/README.md +++ b/core-java-modules/core-java-8-2/README.md @@ -6,3 +6,4 @@ - [Anonymous Classes in Java](http://www.baeldung.com/) - [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) - [Run JAR Application With Command Line Arguments](https://www.baeldung.com/java-run-jar-with-arguments) +- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit) From 15b0bd9f9b32115227bebfde1710d5ba0bf980b7 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:38:55 +0530 Subject: [PATCH 111/352] Back-link added --- spring-boot/README.MD | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index d7af3f4614..435398904f 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -37,3 +37,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) - [Entity To DTO Conversion for a Spring REST API](https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application) +- [Guide to @EnableConfigurationProperties](https://www.baeldung.com/spring-enable-config-properties) From f10889579d360dc13e31c6dfa827ac20b8770161 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:40:27 +0530 Subject: [PATCH 112/352] Back-link added --- core-java-modules/core-java-8/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-8/README.md b/core-java-modules/core-java-8/README.md index d11d2debce..b2ae48ea11 100644 --- a/core-java-modules/core-java-8/README.md +++ b/core-java-modules/core-java-8/README.md @@ -40,3 +40,4 @@ - [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain) - [Method References in Java](https://www.baeldung.com/java-method-references) - [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation) +- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach) From b910336c2701a16e7346f887c6726d69ff47416c Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Wed, 3 Jul 2019 16:16:43 +0300 Subject: [PATCH 113/352] BAEL-2995 - possible lossy conversion - new module java-numbers-2 created --- java-numbers-2/.gitignore | 26 ++++ java-numbers-2/README.md | 6 + java-numbers-2/pom.xml | 135 ++++++++++++++++++ .../ConversionTechniquesUnitTest.java | 0 pom.xml | 2 + 5 files changed, 169 insertions(+) create mode 100644 java-numbers-2/.gitignore create mode 100644 java-numbers-2/README.md create mode 100644 java-numbers-2/pom.xml rename {java-numbers => java-numbers-2}/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java (100%) diff --git a/java-numbers-2/.gitignore b/java-numbers-2/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/java-numbers-2/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/java-numbers-2/README.md b/java-numbers-2/README.md new file mode 100644 index 0000000000..7df6cbd5a2 --- /dev/null +++ b/java-numbers-2/README.md @@ -0,0 +1,6 @@ +========= + +## Java Number 2 + +### Relevant Articles: +- [Lossy Conversion in Java](http://www.baeldung.com/lossy-conversion) \ No newline at end of file diff --git a/java-numbers-2/pom.xml b/java-numbers-2/pom.xml new file mode 100644 index 0000000000..963d281548 --- /dev/null +++ b/java-numbers-2/pom.xml @@ -0,0 +1,135 @@ + + 4.0.0 + java-numbers-2 + 0.1.0-SNAPSHOT + java-numbers-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + log4j + log4j + ${log4j.version} + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.decimal4j + decimal4j + ${decimal4j.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + java-numbers + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + 1.8 + 1.8 + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + 3.6.1 + 1.0.3 + 3.5 + + 3.6.1 + + 1.7.21 + 1.1.7 + + 2.21.0 + 3.0.0-M1 + 3.0.2 + + diff --git a/java-numbers/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java similarity index 100% rename from java-numbers/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java rename to java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java diff --git a/pom.xml b/pom.xml index 9760e06bc1..18a7e5f9a8 100644 --- a/pom.xml +++ b/pom.xml @@ -461,6 +461,7 @@ java-lite java-numbers + java-numbers-2 java-rmi java-spi java-streams @@ -1142,6 +1143,7 @@ java-ee-8-security-api java-lite java-numbers + java-numbers-2 java-rmi java-spi java-streams From e5c3dbb67ca8e1a9cee6c863149ad1bac1b8e676 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Wed, 3 Jul 2019 16:22:08 +0300 Subject: [PATCH 114/352] BAEL-2995 - possible lossy conversion - fixes --- java-numbers-2/pom.xml | 2 +- .../ConversionTechniquesUnitTest.java | 28 +++++++++++-------- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/java-numbers-2/pom.xml b/java-numbers-2/pom.xml index 963d281548..57f1154f53 100644 --- a/java-numbers-2/pom.xml +++ b/java-numbers-2/pom.xml @@ -64,7 +64,7 @@ - java-numbers + java-numbers-2 src/main/resources diff --git a/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java index 9ed714e853..80236af044 100644 --- a/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java +++ b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java @@ -9,6 +9,11 @@ public class ConversionTechniquesUnitTest { @Test public void testPrimitiveConversion() { + + long longNum = 24; + short shortNum = (short) longNum; + + assertEquals(shortNum, 24); double doubleNum = 15.6; int integerNum = (int) doubleNum; @@ -16,17 +21,6 @@ public class ConversionTechniquesUnitTest { assertEquals(integerNum, 15); } - @Test - public void testWrapperConversion() { - - Double doubleNum = 10.3; - double dbl = doubleNum.doubleValue(); - int intgr = (int) dbl; - Integer intNum = Integer.valueOf(intgr); - - assertTrue(intNum == 10); - } - @Test public void testWrapperToPrimitiveConversion() { @@ -53,4 +47,16 @@ public class ConversionTechniquesUnitTest { assertEquals(longNum, 16); } + + @Test + public void testWrapperConversion() { + + Double doubleNum = 10.3; + double dbl = doubleNum.doubleValue(); //unboxing + int intgr = (int) dbl; //downcasting + Integer intNum = Integer.valueOf(intgr); + + assertTrue(intNum == 10); + } + } From 2f72e467eb627c920e7dd1d42ce4d27cdd40355c Mon Sep 17 00:00:00 2001 From: Ashley Frieze Date: Wed, 3 Jul 2019 16:19:18 +0100 Subject: [PATCH 115/352] Disabling Java Streams 2 in integration build as in main build --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 45b6818e66..d67622feb7 100644 --- a/pom.xml +++ b/pom.xml @@ -1147,7 +1147,7 @@ java-rmi java-spi java-streams - java-streams-2 + java-strings java-strings-2 java-vavr-stream From 9b4f63704a374bc44d7c1609b5f52e714bc94b81 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Wed, 3 Jul 2019 20:06:46 +0200 Subject: [PATCH 116/352] BAEL-3001 --- .../com/baeldung/random/SecureRandomDemo.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/random/SecureRandomDemo.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/random/SecureRandomDemo.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/random/SecureRandomDemo.java new file mode 100644 index 0000000000..02f815f5a7 --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/random/SecureRandomDemo.java @@ -0,0 +1,36 @@ +package com.baeldung.random; + +import java.security.SecureRandom; +import java.security.NoSuchAlgorithmException; +import java.util.stream.IntStream; +import java.util.stream.LongStream; +import java.util.stream.DoubleStream; + +public interface SecureRandomDemo { + + public static void generateSecureRandomValues() { + SecureRandom sr = new SecureRandom(); + + int randomInt = sr.nextInt(); + long randomLong = sr.nextLong(); + float randomFloat = sr.nextFloat(); + double randomDouble = sr.nextDouble(); + boolean randomBoolean = sr.nextBoolean(); + + IntStream randomIntStream = sr.ints(); + LongStream randomLongStream = sr.longs(); + DoubleStream randomDoubleStream = sr.doubles(); + + byte[] values = new byte[124]; + sr.nextBytes(values); + } + + public static SecureRandom getSecureRandomForAlgorithm(String algorithm) throws NoSuchAlgorithmException { + if (algorithm == null || algorithm.isEmpty()) { + return new SecureRandom(); + } + + return SecureRandom.getInstance(algorithm); + } + +} From 1a3bf2a24f805ac616db4dee84de58bbd787c26f Mon Sep 17 00:00:00 2001 From: amit2103 Date: Fri, 5 Jul 2019 00:15:40 +0530 Subject: [PATCH 117/352] [BAEL-10984] - Updated vaadin article with new version and added removed examples --- vaadin/pom.xml | 31 +- .../com/baeldung/introduction/VaadinUI.java | 278 ++++++++++++++++++ 2 files changed, 305 insertions(+), 4 deletions(-) create mode 100644 vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java diff --git a/vaadin/pom.xml b/vaadin/pom.xml index 648343fcd8..089ebe67c1 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -33,7 +33,26 @@ javax.servlet-api provided - + + com.vaadin + vaadin-server + ${vaadin-server.version} + + + com.vaadin + vaadin-push + ${vaadin-push.version} + + + com.vaadin + vaadin-client-compiled + ${vaadin-client-compiled.version} + + + com.vaadin + vaadin-themes + ${vaadin-themes.version} + org.springframework.boot spring-boot-starter-data-jpa @@ -155,9 +174,13 @@ - 10.0.11 - 10.0.11 - 10.0.11 + 13.0.9 + 13.0.9 + 13.0.9 + 8.8.5 + 8.8.5 + 8.8.5 + 8.8.5 9.3.9.v20160517 UTF-8 1.8 diff --git a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java new file mode 100644 index 0000000000..68be53b1b3 --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java @@ -0,0 +1,278 @@ +package com.baeldung.introduction; + +import java.time.Instant; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.servlet.annotation.WebServlet; + +import com.vaadin.annotations.Push; +import com.vaadin.annotations.Theme; +import com.vaadin.annotations.VaadinServletConfiguration; +import com.vaadin.data.Binder; +import com.vaadin.data.validator.StringLengthValidator; +import com.vaadin.icons.VaadinIcons; +import com.vaadin.server.ExternalResource; +import com.vaadin.server.VaadinRequest; +import com.vaadin.server.VaadinServlet; +import com.vaadin.ui.Button; +import com.vaadin.ui.CheckBox; +import com.vaadin.ui.ComboBox; +import com.vaadin.ui.DateField; +import com.vaadin.ui.FormLayout; +import com.vaadin.ui.Grid; +import com.vaadin.ui.GridLayout; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.InlineDateField; +import com.vaadin.ui.Label; +import com.vaadin.ui.Link; +import com.vaadin.ui.ListSelect; +import com.vaadin.ui.NativeButton; +import com.vaadin.ui.NativeSelect; +import com.vaadin.ui.Panel; +import com.vaadin.ui.PasswordField; +import com.vaadin.ui.RichTextArea; +import com.vaadin.ui.TextArea; +import com.vaadin.ui.TextField; +import com.vaadin.ui.TwinColSelect; +import com.vaadin.ui.UI; +import com.vaadin.ui.VerticalLayout; + +@SuppressWarnings("serial") +@Push +@Theme("mytheme") +public class VaadinUI extends UI { + + private Label currentTime; + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + protected void init(VaadinRequest vaadinRequest) { + final VerticalLayout verticalLayout = new VerticalLayout(); + verticalLayout.setSpacing(true); + verticalLayout.setMargin(true); + final GridLayout gridLayout = new GridLayout(3, 2); + gridLayout.setSpacing(true); + gridLayout.setMargin(true); + final HorizontalLayout horizontalLayout = new HorizontalLayout(); + horizontalLayout.setSpacing(true); + horizontalLayout.setMargin(true); + final FormLayout formLayout = new FormLayout(); + formLayout.setSpacing(true); + formLayout.setMargin(true); + final GridLayout buttonLayout = new GridLayout(3, 5); + buttonLayout.setMargin(true); + buttonLayout.setSpacing(true); + + final Label label = new Label(); + label.setId("Label"); + label.setValue("Label Value"); + label.setCaption("Label"); + gridLayout.addComponent(label); + + final Link link = new Link("Baeldung", new ExternalResource("http://www.baeldung.com/")); + link.setId("Link"); + link.setTargetName("_blank"); + gridLayout.addComponent(link); + + final TextField textField = new TextField(); + textField.setId("TextField"); + textField.setCaption("TextField:"); + textField.setValue("TextField Value"); + textField.setIcon(VaadinIcons.USER); + gridLayout.addComponent(textField); + + final TextArea textArea = new TextArea(); + textArea.setCaption("TextArea"); + textArea.setId("TextArea"); + textArea.setValue("TextArea Value"); + gridLayout.addComponent(textArea); + + final DateField dateField = new DateField("DateField", LocalDate.ofEpochDay(0)); + dateField.setId("DateField"); + gridLayout.addComponent(dateField); + + final PasswordField passwordField = new PasswordField(); + passwordField.setId("PasswordField"); + passwordField.setCaption("PasswordField:"); + passwordField.setValue("password"); + gridLayout.addComponent(passwordField); + + final RichTextArea richTextArea = new RichTextArea(); + richTextArea.setCaption("Rich Text Area"); + richTextArea.setValue("

RichTextArea

"); + richTextArea.setSizeFull(); + + Panel richTextPanel = new Panel(); + richTextPanel.setContent(richTextArea); + + final InlineDateField inlineDateField = new InlineDateField(); + inlineDateField.setValue(LocalDate.ofEpochDay(0)); + inlineDateField.setCaption("Inline Date Field"); + horizontalLayout.addComponent(inlineDateField); + + Button normalButton = new Button("Normal Button"); + normalButton.setId("NormalButton"); + normalButton.addClickListener(e -> { + label.setValue("CLICK"); + }); + buttonLayout.addComponent(normalButton); + + Button tinyButton = new Button("Tiny Button"); + tinyButton.addStyleName("tiny"); + buttonLayout.addComponent(tinyButton); + + Button smallButton = new Button("Small Button"); + smallButton.addStyleName("small"); + buttonLayout.addComponent(smallButton); + + Button largeButton = new Button("Large Button"); + largeButton.addStyleName("large"); + buttonLayout.addComponent(largeButton); + + Button hugeButton = new Button("Huge Button"); + hugeButton.addStyleName("huge"); + buttonLayout.addComponent(hugeButton); + + Button disabledButton = new Button("Disabled Button"); + disabledButton.setDescription("This button cannot be clicked"); + disabledButton.setEnabled(false); + buttonLayout.addComponent(disabledButton); + + Button dangerButton = new Button("Danger Button"); + dangerButton.addStyleName("danger"); + buttonLayout.addComponent(dangerButton); + + Button friendlyButton = new Button("Friendly Button"); + friendlyButton.addStyleName("friendly"); + buttonLayout.addComponent(friendlyButton); + + Button primaryButton = new Button("Primary Button"); + primaryButton.addStyleName("primary"); + buttonLayout.addComponent(primaryButton); + + NativeButton nativeButton = new NativeButton("Native Button"); + buttonLayout.addComponent(nativeButton); + + Button iconButton = new Button("Icon Button"); + iconButton.setIcon(VaadinIcons.ALIGN_LEFT); + buttonLayout.addComponent(iconButton); + + Button borderlessButton = new Button("BorderLess Button"); + borderlessButton.addStyleName("borderless"); + buttonLayout.addComponent(borderlessButton); + + Button linkButton = new Button("Link Button"); + linkButton.addStyleName("link"); + buttonLayout.addComponent(linkButton); + + Button quietButton = new Button("Quiet Button"); + quietButton.addStyleName("quiet"); + buttonLayout.addComponent(quietButton); + + horizontalLayout.addComponent(buttonLayout); + + final CheckBox checkbox = new CheckBox("CheckBox"); + checkbox.setValue(true); + checkbox.addValueChangeListener(e -> checkbox.setValue(!checkbox.getValue())); + formLayout.addComponent(checkbox); + + List numbers = new ArrayList(); + numbers.add("One"); + numbers.add("Ten"); + numbers.add("Eleven"); + ComboBox comboBox = new ComboBox("ComboBox"); + comboBox.setItems(numbers); + formLayout.addComponent(comboBox); + + ListSelect listSelect = new ListSelect("ListSelect"); + listSelect.setItems(numbers); + listSelect.setRows(2); + formLayout.addComponent(listSelect); + + NativeSelect nativeSelect = new NativeSelect("NativeSelect"); + nativeSelect.setItems(numbers); + formLayout.addComponent(nativeSelect); + + TwinColSelect twinColSelect = new TwinColSelect("TwinColSelect"); + twinColSelect.setItems(numbers); + + Grid grid = new Grid("Grid"); + grid.setColumns("Column1", "Column2", "Column3"); + grid.setItems("Item1", "Item2", "Item3"); + grid.setItems("Item4", "Item5", "Item6"); + + Panel panel = new Panel("Panel"); + panel.setContent(grid); + panel.setSizeUndefined(); + + Panel serverPushPanel = new Panel("Server Push"); + FormLayout timeLayout = new FormLayout(); + timeLayout.setSpacing(true); + timeLayout.setMargin(true); + currentTime = new Label("No TIME..."); + timeLayout.addComponent(currentTime); + serverPushPanel.setContent(timeLayout); + serverPushPanel.setSizeUndefined(); + ScheduledExecutorService scheduleExecutor = Executors.newScheduledThreadPool(1); + Runnable task = () -> { + currentTime.setValue("Current Time : " + Instant.now()); + }; + scheduleExecutor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS); + + FormLayout dataBindingLayout = new FormLayout(); + dataBindingLayout.setSpacing(true); + dataBindingLayout.setMargin(true); + + Binder binder = new Binder<>(); + BindData bindData = new BindData("BindData"); + binder.readBean(bindData); + TextField bindedTextField = new TextField(); + bindedTextField.setWidth("250px"); + binder.forField(bindedTextField).bind(BindData::getBindName, BindData::setBindName); + dataBindingLayout.addComponent(bindedTextField); + + FormLayout validatorLayout = new FormLayout(); + validatorLayout.setSpacing(true); + validatorLayout.setMargin(true); + + HorizontalLayout textValidatorLayout = new HorizontalLayout(); + textValidatorLayout.setSpacing(true); + textValidatorLayout.setMargin(true); + + + BindData stringValidatorBindData = new BindData(""); + TextField stringValidator = new TextField(); + Binder stringValidatorBinder = new Binder<>(); + stringValidatorBinder.setBean(stringValidatorBindData); + stringValidatorBinder.forField(stringValidator) + .withValidator(new StringLengthValidator("String must have 2-5 characters lenght", 2, 5)) + .bind(BindData::getBindName, BindData::setBindName); + + textValidatorLayout.addComponent(stringValidator); + Button buttonStringValidator = new Button("Validate String"); + buttonStringValidator.addClickListener(e -> stringValidatorBinder.validate()); + textValidatorLayout.addComponent(buttonStringValidator); + + validatorLayout.addComponent(textValidatorLayout); + verticalLayout.addComponent(gridLayout); + verticalLayout.addComponent(richTextPanel); + verticalLayout.addComponent(horizontalLayout); + verticalLayout.addComponent(formLayout); + verticalLayout.addComponent(twinColSelect); + verticalLayout.addComponent(panel); + verticalLayout.addComponent(serverPushPanel); + verticalLayout.addComponent(dataBindingLayout); + verticalLayout.addComponent(validatorLayout); + setContent(verticalLayout); + } + + @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true) + @VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false) + public static class MyUIServlet extends VaadinServlet { + } +} \ No newline at end of file From 33476d699173707cda8389cc22c0817abd736f09 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Fri, 5 Jul 2019 11:46:09 +0300 Subject: [PATCH 118/352] Removed readme file --- java-numbers-2/README.md | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 java-numbers-2/README.md diff --git a/java-numbers-2/README.md b/java-numbers-2/README.md deleted file mode 100644 index 7df6cbd5a2..0000000000 --- a/java-numbers-2/README.md +++ /dev/null @@ -1,6 +0,0 @@ -========= - -## Java Number 2 - -### Relevant Articles: -- [Lossy Conversion in Java](http://www.baeldung.com/lossy-conversion) \ No newline at end of file From a3e08f7ce0e00a620da8aec922d09a7ab028a06f Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Fri, 5 Jul 2019 18:34:01 +0300 Subject: [PATCH 119/352] BAEL-2995 - possible lossy conversion - fixes --- .../ConversionTechniquesUnitTest.java | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java index 80236af044..071ea4f9ab 100644 --- a/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java +++ b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java @@ -13,12 +13,28 @@ public class ConversionTechniquesUnitTest { long longNum = 24; short shortNum = (short) longNum; - assertEquals(shortNum, 24); + assertEquals(24, shortNum); double doubleNum = 15.6; int integerNum = (int) doubleNum; - assertEquals(integerNum, 15); + assertEquals(15, integerNum); + + long largeLongNum = 32768; + long smallLongNum = -32769; + short shortNum1 = (short) largeLongNum; + short shortNum2 = (short) smallLongNum; + + assertEquals(-32768, shortNum1); + assertEquals(32767, shortNum2); + + long maxLong = Long.MAX_VALUE; + long minLong = Long.MIN_VALUE; + int minInt = (int) maxLong; + int maxInt = (int) minLong; + + assertEquals(-1, minInt); + assertEquals(0, maxInt); } @Test @@ -27,16 +43,12 @@ public class ConversionTechniquesUnitTest { Float floatNum = 17.564f; long longNum = floatNum.longValue(); - assertEquals(longNum, 17l); + assertEquals(17, longNum); Double doubleNum = 15.9999; - int intNum = doubleNum.intValue(); + longNum = doubleNum.longValue(); - assertEquals(intNum, 15); - - longNum = Math.round(doubleNum); - - assertEquals(longNum, 16); + assertEquals(15, longNum); } @Test @@ -45,7 +57,7 @@ public class ConversionTechniquesUnitTest { Double doubleNum = 15.9999; long longNum = Math.round(doubleNum); - assertEquals(longNum, 16); + assertEquals(16, longNum); } @Test From 6db4ca2698692b11da4a728eafb9bafde398eed8 Mon Sep 17 00:00:00 2001 From: Pavan Shankar Koli Date: Fri, 5 Jul 2019 23:10:41 +0530 Subject: [PATCH 120/352] BAEL-2578 Created separate module --- pom.xml | 1 + .../pom.xml | 27 +++++++++++++++++++ .../spring-data-jpa/pom.xml | 5 ++-- .../java/com/baeldung/jpa/SpringDataJPA.java | 3 ++- .../spring-data-mongodb/pom.xml | 5 ++-- .../spring-data-redis/pom.xml | 5 ++-- 6 files changed, 36 insertions(+), 10 deletions(-) create mode 100644 spring-data-disable-auto-configuration/pom.xml diff --git a/pom.xml b/pom.xml index 982c52c54e..b642cfbeb1 100644 --- a/pom.xml +++ b/pom.xml @@ -1312,6 +1312,7 @@ spring-boot-ops-2 spring-boot-rest spring-boot-data + spring-data-disable-auto-configuration spring-boot-parent spring-boot-property-exp spring-boot-security diff --git a/spring-data-disable-auto-configuration/pom.xml b/spring-data-disable-auto-configuration/pom.xml new file mode 100644 index 0000000000..91086262cf --- /dev/null +++ b/spring-data-disable-auto-configuration/pom.xml @@ -0,0 +1,27 @@ + + + + 4.0.0 + com.baeldung + spring-data-disable-auto-configuration + 1.0.0-SNAPSHOT + spring-data-disable-auto-configuration + spring-data-disable-auto-configuration + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + spring-data-jpa + spring-data-mongodb + spring-data-redis + + + diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/pom.xml b/spring-data-disable-auto-configuration/spring-data-jpa/pom.xml index db431fb7fa..35113c379a 100644 --- a/spring-data-disable-auto-configuration/spring-data-jpa/pom.xml +++ b/spring-data-disable-auto-configuration/spring-data-jpa/pom.xml @@ -11,10 +11,9 @@ Spring Data with JPA - parent-boot-2 + spring-data-disable-auto-configuration com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-2 + 1.0.0-SNAPSHOT diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/src/main/java/com/baeldung/jpa/SpringDataJPA.java b/spring-data-disable-auto-configuration/spring-data-jpa/src/main/java/com/baeldung/jpa/SpringDataJPA.java index bec1b18010..211b5dc8b4 100644 --- a/spring-data-disable-auto-configuration/spring-data-jpa/src/main/java/com/baeldung/jpa/SpringDataJPA.java +++ b/spring-data-disable-auto-configuration/spring-data-jpa/src/main/java/com/baeldung/jpa/SpringDataJPA.java @@ -6,7 +6,8 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; -@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) public class SpringDataJPA { public static void main(String[] args) { diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/pom.xml b/spring-data-disable-auto-configuration/spring-data-mongodb/pom.xml index 95bf32545b..ad707632c5 100644 --- a/spring-data-disable-auto-configuration/spring-data-mongodb/pom.xml +++ b/spring-data-disable-auto-configuration/spring-data-mongodb/pom.xml @@ -11,10 +11,9 @@ Spring Data with MongoDB - parent-boot-2 + spring-data-disable-auto-configuration com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-2 + 1.0.0-SNAPSHOT diff --git a/spring-data-disable-auto-configuration/spring-data-redis/pom.xml b/spring-data-disable-auto-configuration/spring-data-redis/pom.xml index 7c997033ed..3b5db228c5 100644 --- a/spring-data-disable-auto-configuration/spring-data-redis/pom.xml +++ b/spring-data-disable-auto-configuration/spring-data-redis/pom.xml @@ -11,10 +11,9 @@ Spring Data with Redis - parent-boot-2 + spring-data-disable-auto-configuration com.baeldung - 0.0.1-SNAPSHOT - ../../parent-boot-2 + 1.0.0-SNAPSHOT From 0cf2895db0de8fe6b335d3d5dc09c07c137a8c91 Mon Sep 17 00:00:00 2001 From: Arho Huttunen Date: Fri, 5 Jul 2019 21:04:20 +0300 Subject: [PATCH 121/352] BAEL-2911 JUnit Custom Display Name Generator API --- .../displayname/ReplaceUnderscoresGeneratorUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/ReplaceUnderscoresGeneratorUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/ReplaceUnderscoresGeneratorUnitTest.java index d6e023cfe8..429d6bac2a 100644 --- a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/ReplaceUnderscoresGeneratorUnitTest.java +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/displayname/ReplaceUnderscoresGeneratorUnitTest.java @@ -9,7 +9,7 @@ class ReplaceUnderscoresGeneratorUnitTest { class when_doing_something { @Test - void then_should_happen_something() { + void then_something_should_happen() { } @Test From 3b8bb69b10fbfd01c4343b9a0211f15139e5254c Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 6 Jul 2019 01:20:09 +0300 Subject: [PATCH 122/352] property conversion --- .../ConfigPropertiesDemoApplication.java | 2 +- .../org/baeldung/properties/Employee.java | 30 ++++++ .../properties/EmployeeConverter.java | 16 ++++ .../properties/PropertyConversion.java | 92 +++++++++++++++++++ .../PropertiesConversionIntegrationTest.java | 43 +++++++++ .../src/test/resources/conversion.properties | 11 +++ 6 files changed, 193 insertions(+), 1 deletion(-) create mode 100644 spring-boot/src/main/java/org/baeldung/properties/Employee.java create mode 100644 spring-boot/src/main/java/org/baeldung/properties/EmployeeConverter.java create mode 100644 spring-boot/src/main/java/org/baeldung/properties/PropertyConversion.java create mode 100644 spring-boot/src/test/java/org/baeldung/properties/PropertiesConversionIntegrationTest.java create mode 100644 spring-boot/src/test/resources/conversion.properties diff --git a/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java index 395d68060b..1fbf0e0040 100644 --- a/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -5,7 +5,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication -@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class }) +@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class, PropertyConversion.class, EmployeeConverter.class }) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) diff --git a/spring-boot/src/main/java/org/baeldung/properties/Employee.java b/spring-boot/src/main/java/org/baeldung/properties/Employee.java new file mode 100644 index 0000000000..33715d38a5 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/Employee.java @@ -0,0 +1,30 @@ +package org.baeldung.properties; + +public class Employee { + + private String name; + private double salary; + + public Employee(String name, double salary) { + super(); + this.name = name; + this.salary = salary; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/spring-boot/src/main/java/org/baeldung/properties/EmployeeConverter.java b/spring-boot/src/main/java/org/baeldung/properties/EmployeeConverter.java new file mode 100644 index 0000000000..57b8128d2b --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/EmployeeConverter.java @@ -0,0 +1,16 @@ +package org.baeldung.properties; + +import org.springframework.boot.context.properties.ConfigurationPropertiesBinding; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationPropertiesBinding +public class EmployeeConverter implements Converter { + + @Override + public Employee convert(String from) { + String[] data = from.split(","); + return new Employee(data[0], Double.parseDouble(data[1])); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/properties/PropertyConversion.java b/spring-boot/src/main/java/org/baeldung/properties/PropertyConversion.java new file mode 100644 index 0000000000..6b70e16e76 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/properties/PropertyConversion.java @@ -0,0 +1,92 @@ +package org.baeldung.properties; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.convert.DataSizeUnit; +import org.springframework.boot.convert.DurationUnit; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.util.unit.DataSize; +import org.springframework.util.unit.DataUnit; + +@Configuration +@PropertySource("classpath:conversion.properties") +@ConfigurationProperties(prefix = "conversion") +public class PropertyConversion { + private Duration timeInDefaultUnit; + + private Duration timeInNano; + + @DurationUnit(ChronoUnit.DAYS) + private Duration timeInDays; + + private DataSize sizeInDefaultUnit; + + private DataSize sizeInGB; + + @DataSizeUnit(DataUnit.TERABYTES) + private DataSize sizeInTB; + + private Employee employee; + + // Getters and setters + + public Duration getTimeInDefaultUnit() { + return timeInDefaultUnit; + } + + public void setTimeInDefaultUnit(Duration timeInDefaultUnit) { + this.timeInDefaultUnit = timeInDefaultUnit; + } + + public Duration getTimeInNano() { + return timeInNano; + } + + public void setTimeInNano(Duration timeInNano) { + this.timeInNano = timeInNano; + } + + public Duration getTimeInDays() { + return timeInDays; + } + + public void setTimeInDays(Duration timeInDays) { + this.timeInDays = timeInDays; + } + + public DataSize getSizeInDefaultUnit() { + return sizeInDefaultUnit; + } + + public void setSizeInDefaultUnit(DataSize sizeInDefaultUnit) { + this.sizeInDefaultUnit = sizeInDefaultUnit; + } + + public DataSize getSizeInGB() { + return sizeInGB; + } + + public void setSizeInGB(DataSize sizeInGB) { + this.sizeInGB = sizeInGB; + } + + public DataSize getSizeInTB() { + return sizeInTB; + } + + public void setSizeInTB(DataSize sizeInTB) { + this.sizeInTB = sizeInTB; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + +} diff --git a/spring-boot/src/test/java/org/baeldung/properties/PropertiesConversionIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/properties/PropertiesConversionIntegrationTest.java new file mode 100644 index 0000000000..2baae80570 --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/properties/PropertiesConversionIntegrationTest.java @@ -0,0 +1,43 @@ +package org.baeldung.properties; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.Duration; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.util.unit.DataSize; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigPropertiesDemoApplication.class) +@TestPropertySource("classpath:conversion.properties") +public class PropertiesConversionIntegrationTest { + + @Autowired + private PropertyConversion properties; + + @Test + public void whenUseTimeUnitPropertyConversion_thenSuccess() throws Exception { + assertEquals(Duration.ofMillis(10), properties.getTimeInDefaultUnit()); + assertEquals(Duration.ofNanos(9), properties.getTimeInNano()); + assertEquals(Duration.ofDays(2), properties.getTimeInDays()); + } + + @Test + public void whenUseDataSizePropertyConversion_thenSuccess() throws Exception { + assertEquals(DataSize.ofBytes(300), properties.getSizeInDefaultUnit()); + assertEquals(DataSize.ofGigabytes(2), properties.getSizeInGB()); + assertEquals(DataSize.ofTerabytes(4), properties.getSizeInTB()); + } + + @Test + public void whenUseCustomPropertyConverter_thenSuccess() throws Exception { + assertEquals("john", properties.getEmployee().getName()); + assertEquals(2000.0, properties.getEmployee().getSalary()); + } + +} diff --git a/spring-boot/src/test/resources/conversion.properties b/spring-boot/src/test/resources/conversion.properties new file mode 100644 index 0000000000..640442ec33 --- /dev/null +++ b/spring-boot/src/test/resources/conversion.properties @@ -0,0 +1,11 @@ +###### time unit +conversion.timeInDefaultUnit=10 +conversion.timeInNano=9ns +conversion.timeInDays=2 + +###### data size +conversion.sizeInDefaultUnit=300 +conversion.sizeInGB=2GB +conversion.sizeInTB=4 + +conversion.employee=john,2000 \ No newline at end of file From c4ccb08b55beb937459b6d115d6a43a49cce6d0c Mon Sep 17 00:00:00 2001 From: Michael Sievers Date: Sat, 6 Jul 2019 05:13:53 +0200 Subject: [PATCH 123/352] [BAEL-3019] Add article link to java-strings-2 module README (#7246) --- java-strings-2/README.MD | 1 + 1 file changed, 1 insertion(+) diff --git a/java-strings-2/README.MD b/java-strings-2/README.MD index 85832fde37..6548c48f2c 100644 --- a/java-strings-2/README.MD +++ b/java-strings-2/README.MD @@ -3,3 +3,4 @@ - [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) - [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) - [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) +- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) From 02cb552470098b847cf1c1f8a8db02fcd19e30f2 Mon Sep 17 00:00:00 2001 From: Harsha Veeravalli Date: Fri, 5 Jul 2019 23:16:20 -0400 Subject: [PATCH 124/352] [BAEL-2999] Improve Jagged Arrays article (#7201) * Hexagonal Architecture in Java * Hexagonal Architecture in Java - incorporated feedback * BAEL-2999 * Removing the evaluation article code. * Corrected indentation for continuations --- .../java/com/baeldung/array/JaggedArray.java | 49 ----------- .../baeldung/array/MultiDimensionalArray.java | 83 ++++++++++++++++++ .../baeldung/array/JaggedArrayUnitTest.java | 53 ------------ .../array/MultiDimensionalArrayUnitTest.java | 86 +++++++++++++++++++ 4 files changed, 169 insertions(+), 102 deletions(-) delete mode 100644 core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/JaggedArray.java create mode 100644 core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java delete mode 100644 core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java create mode 100644 core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/JaggedArray.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/JaggedArray.java deleted file mode 100644 index 36cfc88b95..0000000000 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/JaggedArray.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.array; - -import java.util.Arrays; -import java.util.Scanner; - -public class JaggedArray { - - int[][] shortHandFormInitialization() { - int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; - return jaggedArr; - } - - int[][] declarationAndThenInitialization() { - int[][] jaggedArr = new int[3][]; - jaggedArr[0] = new int[] { 1, 2 }; - jaggedArr[1] = new int[] { 3, 4, 5 }; - jaggedArr[2] = new int[] { 6, 7, 8, 9 }; - return jaggedArr; - } - - int[][] declarationAndThenInitializationUsingUserInputs() { - int[][] jaggedArr = new int[3][]; - jaggedArr[0] = new int[2]; - jaggedArr[1] = new int[3]; - jaggedArr[2] = new int[4]; - initializeElements(jaggedArr); - return jaggedArr; - } - - void initializeElements(int[][] jaggedArr) { - Scanner sc = new Scanner(System.in); - for (int outer = 0; outer < jaggedArr.length; outer++) { - for (int inner = 0; inner < jaggedArr[outer].length; inner++) { - jaggedArr[outer][inner] = sc.nextInt(); - } - } - } - - void printElements(int[][] jaggedArr) { - for (int index = 0; index < jaggedArr.length; index++) { - System.out.println(Arrays.toString(jaggedArr[index])); - } - } - - int[] getElementAtGivenIndex(int[][] jaggedArr, int index) { - return jaggedArr[index]; - } - -} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java new file mode 100644 index 0000000000..4e01b99a14 --- /dev/null +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/MultiDimensionalArray.java @@ -0,0 +1,83 @@ +package com.baeldung.array; + +import java.util.Arrays; +import java.util.Scanner; + +public class MultiDimensionalArray { + + int[][] shortHandFormInitialization() { + int[][] multiDimensionalArray = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + return multiDimensionalArray; + } + + int[][] declarationAndThenInitialization() { + int[][] multiDimensionalArray = new int[3][]; + multiDimensionalArray[0] = new int[] { 1, 2 }; + multiDimensionalArray[1] = new int[] { 3, 4, 5 }; + multiDimensionalArray[2] = new int[] { 6, 7, 8, 9 }; + return multiDimensionalArray; + } + + int[][] declarationAndThenInitializationUsingUserInputs() { + int[][] multiDimensionalArray = new int[3][]; + multiDimensionalArray[0] = new int[2]; + multiDimensionalArray[1] = new int[3]; + multiDimensionalArray[2] = new int[4]; + initializeElements(multiDimensionalArray); + return multiDimensionalArray; + } + + void initializeElements(int[][] multiDimensionalArray) { + Scanner sc = new Scanner(System.in); + for (int outer = 0; outer < multiDimensionalArray.length; outer++) { + for (int inner = 0; inner < multiDimensionalArray[outer].length; inner++) { + multiDimensionalArray[outer][inner] = sc.nextInt(); + } + } + } + + void initialize2DArray(int[][] multiDimensionalArray) { + for (int[] array : multiDimensionalArray) { + Arrays.fill(array, 7); + } + } + + void printElements(int[][] multiDimensionalArray) { + for (int index = 0; index < multiDimensionalArray.length; index++) { + System.out.println(Arrays.toString(multiDimensionalArray[index])); + } + } + + int[] getElementAtGivenIndex(int[][] multiDimensionalArray, int index) { + return multiDimensionalArray[index]; + } + + int[] findLengthOfElements(int[][] multiDimensionalArray) { + int[] arrayOfLengths = new int[multiDimensionalArray.length]; + for (int i = 0; i < multiDimensionalArray.length; i++) { + arrayOfLengths[i] = multiDimensionalArray[i].length; + } + return arrayOfLengths; + } + + Integer[] findLengthOfElements(Integer[][] multiDimensionalArray) { + return Arrays.stream(multiDimensionalArray) + .map(array -> array.length) + .toArray(Integer[]::new); + } + + int[][] copy2DArray(int[][] arrayOfArrays) { + int[][] copied2DArray = new int[arrayOfArrays.length][]; + for (int i = 0; i < arrayOfArrays.length; i++) { + int[] array = arrayOfArrays[i]; + copied2DArray[i] = Arrays.copyOf(array, array.length); + } + return copied2DArray; + } + + Integer[][] copy2DArray(Integer[][] arrayOfArrays) { + return Arrays.stream(arrayOfArrays) + .map(array -> Arrays.copyOf(array, array.length)) + .toArray(Integer[][]::new); + } +} diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java deleted file mode 100644 index a4dd7e25c3..0000000000 --- a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.array; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.PrintStream; - -import org.junit.Test; - -public class JaggedArrayUnitTest { - - private JaggedArray obj = new JaggedArray(); - - @Test - public void whenInitializedUsingShortHandForm_thenCorrect() { - assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization()); - } - - @Test - public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() { - assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization()); - } - - @Test - public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() { - InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes()); - System.setIn(is); - assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs()); - System.setIn(System.in); - } - - @Test - public void givenJaggedArrayAndAnIndex_thenReturnArrayAtGivenIndex() { - int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; - assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(jaggedArr, 0)); - assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(jaggedArr, 1)); - assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(jaggedArr, 2)); - } - - @Test - public void givenJaggedArray_whenUsingArraysAPI_thenVerifyPrintedElements() { - int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; - ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - obj.printElements(jaggedArr); - assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", "")); - System.setOut(System.out); - } - -} diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java new file mode 100644 index 0000000000..8980eaa9dc --- /dev/null +++ b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/MultiDimensionalArrayUnitTest.java @@ -0,0 +1,86 @@ +package com.baeldung.array; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.PrintStream; + +import org.junit.Test; + +public class MultiDimensionalArrayUnitTest { + + private MultiDimensionalArray obj = new MultiDimensionalArray(); + + @Test + public void whenInitializedUsingShortHandForm_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization()); + } + + @Test + public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization()); + } + + @Test + public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() { + InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes()); + System.setIn(is); + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs()); + System.setIn(System.in); + } + + @Test + public void givenMultiDimensionalArrayAndAnIndex_thenReturnArrayAtGivenIndex() { + int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(multiDimensionalArr, 0)); + assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(multiDimensionalArr, 1)); + assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(multiDimensionalArr, 2)); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysAPI_thenVerifyPrintedElements() { + int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + obj.printElements(multiDimensionalArr); + assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", "")); + System.setOut(System.out); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysFill_thenVerifyInitialize2DArray() { + int[][] multiDimensionalArr = new int[3][]; + multiDimensionalArr[0] = new int[2]; + multiDimensionalArr[1] = new int[3]; + multiDimensionalArr[2] = new int[4]; + obj.initialize2DArray(multiDimensionalArr); + assertArrayEquals(new int[][] {{7,7}, {7,7,7}, {7,7,7,7}}, multiDimensionalArr); + } + + @Test + public void givenMultiDimensionalArray_whenUsingIteration_thenVerifyFindLengthOfElements() { + int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(new int[]{2,3,4}, obj.findLengthOfElements(multiDimensionalArr)); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysStream_thenVerifyFindLengthOfElements() { + Integer[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(new Integer[]{2,3,4}, obj.findLengthOfElements(multiDimensionalArr)); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysCopyOf_thenVerifyCopy2DArray() { + int[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(multiDimensionalArr, obj.copy2DArray(multiDimensionalArr)); + } + + @Test + public void givenMultiDimensionalArray_whenUsingArraysStream_thenVerifyCopy2DArray() { + Integer[][] multiDimensionalArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(multiDimensionalArr, obj.copy2DArray(multiDimensionalArr)); + } +} From 404d9b65be6346bafa04c706447d0572d24f127e Mon Sep 17 00:00:00 2001 From: Nivedan Bamal <50937743+Nivedan-Bamal@users.noreply.github.com> Date: Fri, 5 Jul 2019 23:22:54 -0400 Subject: [PATCH 125/352] Adds 'Removing an element from an Array' examples (#7105) * Adds 'Removing an element from an Array' examples * updated pom version for commons-lang3 to 3.9 --- core-java-modules/core-java-arrays/pom.xml | 2 +- .../array/RemoveElementFromAnArray.java | 27 ++++++ .../RemoveElementFromAnArrayUnitTest.java | 85 +++++++++++++++++++ 3 files changed, 113 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java create mode 100644 core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays/pom.xml b/core-java-modules/core-java-arrays/pom.xml index b713c196b5..23db608abc 100644 --- a/core-java-modules/core-java-arrays/pom.xml +++ b/core-java-modules/core-java-arrays/pom.xml @@ -389,7 +389,7 @@ - 3.8.1 + 3.9 1.19 1.19 diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java new file mode 100644 index 0000000000..62a1a0ee58 --- /dev/null +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/RemoveElementFromAnArray.java @@ -0,0 +1,27 @@ +package com.baeldung.array; + +import org.apache.commons.lang3.ArrayUtils; + +public class RemoveElementFromAnArray { + + public int[] removeAnElementWithAGivenIndex(int[] array, int index) { + return ArrayUtils.remove(array, index); + } + + public int[] removeAllElementsWithGivenIndices(int[] array, int... indicies) { + return ArrayUtils.removeAll(array, indicies); + } + + public int[] removeFirstOccurrenceOfGivenElement(int[] array, int element) { + return ArrayUtils.removeElement(array, element); + } + + public int[] removeAllGivenElements(int[] array, int... elements) { + return ArrayUtils.removeElements(array, elements); + } + + public int[] removeAllOccurrencesOfAGivenElement(int[] array, int element) { + return ArrayUtils.removeAllOccurences(array, element); + } + +} diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java new file mode 100644 index 0000000000..ea52cd17d9 --- /dev/null +++ b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/RemoveElementFromAnArrayUnitTest.java @@ -0,0 +1,85 @@ +package com.baeldung.array; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.commons.lang3.ArrayUtils; +import org.junit.jupiter.api.Test; + +class RemoveElementFromAnArrayUnitTest { + + private final RemoveElementFromAnArray sut = new RemoveElementFromAnArray(); + private final int[] inputArray = new int[] { 40, 10, 20, 30, 40, 50 }; + + @Test + void testRemoveAnElementWithAGivenIndex() { + int index = 2; + int[] modifiedArray = sut.removeAnElementWithAGivenIndex(inputArray, index); + + assertFalse(ArrayUtils.contains(modifiedArray, inputArray[index])); + } + + @Test + void testRemoveAllElementsWithGivenIndices() { + int first = 0; + int last = inputArray.length - 1; + int[] modifiedArray = sut.removeAllElementsWithGivenIndices(inputArray, first, last); + + assertFalse(ArrayUtils.contains(modifiedArray, inputArray[first]) && ArrayUtils.contains(modifiedArray, inputArray[last])); + } + + @Test + void testRemoveElement_WhenArrayIsNull_ThrowsIndexOutOfBoundEx() { + int index = 2; + + assertThrows(IndexOutOfBoundsException.class, () -> { + sut.removeAnElementWithAGivenIndex(null, index); + }); + + assertThrows(IndexOutOfBoundsException.class, () -> { + sut.removeAllElementsWithGivenIndices(null, index); + }); + } + + @Test + void testRemoveFirstOccurrenceOfGivenElement() { + int element = 40; + int[] modifiedArray = sut.removeFirstOccurrenceOfGivenElement(inputArray, element); + + int indexInInputArray = ArrayUtils.indexOf(inputArray, element); + int indexInModifiedArray = ArrayUtils.indexOf(modifiedArray, element); + assertFalse(indexInInputArray == indexInModifiedArray); + } + + @Test + void testRemoveAllGivenElements() { + int duplicateElement = 40; + int[] elements = new int[] { duplicateElement, 10, 50 }; + int[] modifiedArray = sut.removeAllGivenElements(inputArray, elements); + + assertTrue(ArrayUtils.contains(modifiedArray, duplicateElement)); + assertFalse(ArrayUtils.contains(modifiedArray, elements[1])); + assertFalse(ArrayUtils.contains(modifiedArray, elements[2])); + } + + @Test + void testRemoveAllOccurrencesOfAGivenElement() { + int element = 40; + int[] modifiedArray = sut.removeAllOccurrencesOfAGivenElement(inputArray, element); + + assertFalse(ArrayUtils.contains(modifiedArray, element)); + } + + @Test + void testRemoveElement_WhenArrayIsNull_ReturnsNull() { + int element = 20; + + assertEquals(null, sut.removeFirstOccurrenceOfGivenElement(null, element)); + assertEquals(null, sut.removeAllGivenElements(null, element)); + assertEquals(null, sut.removeAllOccurrencesOfAGivenElement(null, element)); + + } + +} From cda387711f41bad751fba4b7f1611b84a24b6e84 Mon Sep 17 00:00:00 2001 From: Ger Roza Date: Sat, 6 Jul 2019 00:42:56 -0300 Subject: [PATCH 126/352] [BAEL-15425] Update Spring Security Database article (#7227) * Simplified and updated module, pom and or.baeldung.custom project * *disabled csrf in custom package for existing junit live test * fixed Integration test for new simplified spring context * Reverted pom file to its original version * modifications to address PR comments: * enabling CSRF * using annotations to obtain principal * using requestmapping shorthands --- .../custom/config/SecurityConfig.java | 47 +------ .../baeldung/custom/web/MainController.java | 24 +++- ...stomUserDetailsServiceIntegrationTest.java | 125 ++++++++++-------- 3 files changed, 87 insertions(+), 109 deletions(-) diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java index f2da5af92c..739e4d3417 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java @@ -1,57 +1,12 @@ package org.baeldung.custom.config; -import org.baeldung.custom.security.MyUserDetailsService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration -@EnableWebSecurity -@ComponentScan("org.baeldung.security") -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private MyUserDetailsService userDetailsService; - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.authenticationProvider(authenticationProvider()); - } - - @Override - public void configure(WebSecurity web) throws Exception { - web.ignoring().antMatchers("/resources/**"); - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http.authorizeRequests() - .antMatchers("/login").permitAll() - .antMatchers("/admin").hasRole("ADMIN") - .anyRequest().authenticated() - .and().formLogin().permitAll() - .and().csrf().disable(); - ; - // @formatter:on - } - - @Bean - public DaoAuthenticationProvider authenticationProvider() { - final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); - authProvider.setUserDetailsService(userDetailsService); - authProvider.setPasswordEncoder(encoder()); - return authProvider; - } +public class SecurityConfig { @Bean public PasswordEncoder encoder() { diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java index 6572954427..74de45d1a8 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java @@ -3,14 +3,16 @@ package org.baeldung.custom.web; import org.baeldung.custom.persistence.dao.OrganizationRepository; import org.baeldung.custom.persistence.model.Foo; import org.baeldung.custom.persistence.model.Organization; +import org.baeldung.custom.security.MyUserPrincipal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @@ -23,14 +25,14 @@ public class MainController { // @PostAuthorize("hasPermission(returnObject, 'read')") @PreAuthorize("hasPermission(#id, 'Foo', 'read')") - @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") + @GetMapping("/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { return new Foo("Sample"); } @PreAuthorize("hasPermission(#foo, 'write')") - @RequestMapping(method = RequestMethod.POST, value = "/foos") + @PostMapping("/foos") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Foo create(@RequestBody final Foo foo) { @@ -40,7 +42,7 @@ public class MainController { // @PreAuthorize("hasAuthority('FOO_READ_PRIVILEGE')") - @RequestMapping(method = RequestMethod.GET, value = "/foos") + @GetMapping("/foos") @ResponseBody public Foo findFooByName(@RequestParam final String name) { return new Foo(name); @@ -49,10 +51,18 @@ public class MainController { // @PreAuthorize("isMember(#id)") - @RequestMapping(method = RequestMethod.GET, value = "/organizations/{id}") + @GetMapping("/organizations/{id}") @ResponseBody public Organization findOrgById(@PathVariable final long id) { - return organizationRepository.findById(id).orElse(null); + return organizationRepository.findById(id) + .orElse(null); + } + + @PreAuthorize("hasPermission(#id, 'Foo', 'read')") + @GetMapping("/user") + @ResponseBody + public MyUserPrincipal retrieveUserDetails(@AuthenticationPrincipal MyUserPrincipal principal) { + return principal; } } diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java index fb25175902..d16acc729a 100644 --- a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java @@ -1,76 +1,89 @@ package org.baeldung.web; -import static org.junit.Assert.assertEquals; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.apache.http.HttpHeaders; import org.baeldung.custom.Application; -import org.baeldung.custom.config.MvcConfig; -import org.baeldung.custom.config.SecurityConfig; -import org.baeldung.custom.persistence.dao.UserRepository; -import org.baeldung.custom.persistence.model.User; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.baeldung.custom.persistence.model.Foo; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.security.test.context.support.WithUserDetails; +import org.springframework.test.web.servlet.MockMvc; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = {Application.class}) -@WebAppConfiguration +import com.fasterxml.jackson.databind.ObjectMapper; + +@SpringBootTest(classes = { Application.class }) +@AutoConfigureMockMvc public class CustomUserDetailsServiceIntegrationTest { - private static final String USERNAME = "user"; - private static final String PASSWORD = "pass"; - private static final String USERNAME2 = "user2"; - @Autowired - private UserRepository myUserRepository; - - @Autowired - private AuthenticationProvider authenticationProvider; - - @Autowired - private PasswordEncoder passwordEncoder; - - // + private MockMvc mvc; @Test - public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { - User user = new User(); - user.setUsername(USERNAME); - user.setPassword(passwordEncoder.encode(PASSWORD)); - - myUserRepository.save(user); - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); - Authentication authentication = authenticationProvider.authenticate(auth); - - assertEquals(authentication.getName(), USERNAME); + @WithUserDetails("john") + public void givenUserWithReadPermissions_whenRequestUserInfo_thenRetrieveUserData() throws Exception { + this.mvc.perform(get("/user").with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.user.privileges[0].name").value("FOO_READ_PRIVILEGE")) + .andExpect(jsonPath("$.user.organization.name").value("FirstOrg")) + .andExpect(jsonPath("$.user.username").value("john")); } - @Test(expected = BadCredentialsException.class) - public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { - User user = new User(); - user.setUsername(USERNAME); - user.setPassword(passwordEncoder.encode(PASSWORD)); - - myUserRepository.save(user); - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); - authenticationProvider.authenticate(auth); + @Test + @WithUserDetails("tom") + public void givenUserWithWritePermissions_whenRequestUserInfo_thenRetrieveUserData() throws Exception { + this.mvc.perform(get("/user").with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.user.privileges").isArray()) + .andExpect(jsonPath("$.user.organization.name").value("SecondOrg")) + .andExpect(jsonPath("$.user.username").value("tom")); } - // + @Test + @WithUserDetails("john") + public void givenUserWithReadPermissions_whenRequestFoo_thenRetrieveSampleFoo() throws Exception { + this.mvc.perform(get("/foos/1").with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.name").value("Sample")); + } - @After - public void tearDown() { - myUserRepository.removeUserByUsername(USERNAME); + @Test + @WithAnonymousUser + public void givenAnonymous_whenRequestFoo_thenRetrieveUnauthorized() throws Exception { + this.mvc.perform(get("/foos/1").with(csrf())) + .andExpect(status().isUnauthorized()); + } + + @Test + @WithUserDetails("john") + public void givenUserWithReadPermissions_whenCreateNewFoo_thenForbiddenStatusRetrieved() throws Exception { + this.mvc.perform(post("/foos").with(csrf()) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .content(asJsonString(new Foo()))) + .andExpect(status().isForbidden()); + } + + @Test + @WithUserDetails("tom") + public void givenUserWithWritePermissions_whenCreateNewFoo_thenOkStatusRetrieved() throws Exception { + this.mvc.perform(post("/foos").with(csrf()) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .content(asJsonString(new Foo()))) + .andExpect(status().isCreated()); + } + + private static String asJsonString(final Object obj) throws Exception { + final ObjectMapper mapper = new ObjectMapper(); + final String jsonContent = mapper.writeValueAsString(obj); + return jsonContent; } } From 982e32e49cdbd058003595ffb26fd55f8580c8d9 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 6 Jul 2019 18:24:07 +0530 Subject: [PATCH 127/352] [BAEL-14774] - Updated Hibernate @OneToMany article code --- persistence-modules/hibernate-mapping/pom.xml | 9 ++++++++- .../oneToMany/config/HibernateAnnotationUtil.java | 15 ++++++--------- .../oneToMany/main/HibernateManyisOwningSide.java | 0 .../main/HibernateOneToManyAnnotationMain.java | 0 .../oneToMany/main/HibernateOneisOwningSide.java | 0 .../baeldung/hibernate/oneToMany/model/Cart.java | 0 .../hibernate/oneToMany/model/CartOIO.java | 0 .../baeldung/hibernate/oneToMany/model/Items.java | 0 .../hibernate/oneToMany/model/ItemsOIO.java | 0 .../main/resources/hibernate-annotation.cfg.xml | 10 +++++----- .../{test => main}/resources/hibernate.properties | 0 .../src/main/resources/one_to_many.sql | 0 ...ateOneToManyAnnotationMainIntegrationTest.java | 0 13 files changed, 19 insertions(+), 15 deletions(-) rename persistence-modules/{spring-hibernate4 => hibernate-mapping}/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java (65%) rename persistence-modules/{spring-hibernate4 => hibernate-mapping}/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java (100%) rename persistence-modules/{spring-hibernate4 => hibernate-mapping}/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java (100%) rename persistence-modules/{spring-hibernate4 => hibernate-mapping}/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java (100%) rename persistence-modules/{spring-hibernate4 => hibernate-mapping}/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java (100%) rename persistence-modules/{spring-hibernate4 => hibernate-mapping}/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java (100%) rename persistence-modules/{spring-hibernate4 => hibernate-mapping}/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java (100%) rename persistence-modules/{spring-hibernate4 => hibernate-mapping}/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java (100%) rename persistence-modules/{spring-hibernate4 => hibernate-mapping}/src/main/resources/hibernate-annotation.cfg.xml (67%) rename persistence-modules/hibernate-mapping/src/{test => main}/resources/hibernate.properties (100%) rename persistence-modules/{spring-hibernate4 => hibernate-mapping}/src/main/resources/one_to_many.sql (100%) rename persistence-modules/{spring-hibernate4 => hibernate-mapping}/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java (100%) diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index bb8ebdab65..bf404e5a9c 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -31,6 +31,12 @@ h2 ${h2.version}
+ + org.hsqldb + hsqldb + ${hsqldb.version} + test + org.hibernate @@ -59,7 +65,7 @@ hibernate-mapping - src/test/resources + src/main/resources true @@ -70,6 +76,7 @@ 3.8.0 6.0.16.Final 3.0.1-b11 + 2.3.4 diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java similarity index 65% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java index e522dab48d..46e6824f42 100644 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java @@ -1,8 +1,9 @@ package com.baeldung.hibernate.oneToMany.config; import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateAnnotationUtil { @@ -12,16 +13,12 @@ public class HibernateAnnotationUtil { private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate-annotation.cfg.xml - Configuration configuration = new Configuration(); - configuration.configure("hibernate-annotation.cfg.xml"); - System.out.println("Hibernate Annotation Configuration loaded"); - - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); - System.out.println("Hibernate Annotation serviceRegistry created"); - - SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build(); + Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build(); + SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); return sessionFactory; + } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); ex.printStackTrace(); diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java rename to persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java diff --git a/persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml b/persistence-modules/hibernate-mapping/src/main/resources/hibernate-annotation.cfg.xml similarity index 67% rename from persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml rename to persistence-modules/hibernate-mapping/src/main/resources/hibernate-annotation.cfg.xml index 14d853d3fd..9b97c03935 100644 --- a/persistence-modules/spring-hibernate4/src/main/resources/hibernate-annotation.cfg.xml +++ b/persistence-modules/hibernate-mapping/src/main/resources/hibernate-annotation.cfg.xml @@ -4,11 +4,11 @@ "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd"> - com.mysql.jdbc.Driver - mypassword - jdbc:mysql://localhost:3306/spring_hibernate_one_to_many?createDatabaseIfNotExist=true - myuser - org.hibernate.dialect.MySQLDialect + org.h2.Driver + + jdbc:h2:mem:spring_hibernate_one_to_many + sa + org.hibernate.dialect.H2Dialect create thread true diff --git a/persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties b/persistence-modules/hibernate-mapping/src/main/resources/hibernate.properties similarity index 100% rename from persistence-modules/hibernate-mapping/src/test/resources/hibernate.properties rename to persistence-modules/hibernate-mapping/src/main/resources/hibernate.properties diff --git a/persistence-modules/spring-hibernate4/src/main/resources/one_to_many.sql b/persistence-modules/hibernate-mapping/src/main/resources/one_to_many.sql similarity index 100% rename from persistence-modules/spring-hibernate4/src/main/resources/one_to_many.sql rename to persistence-modules/hibernate-mapping/src/main/resources/one_to_many.sql diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java similarity index 100% rename from persistence-modules/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java rename to persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java From 42e643a1cf2d8c947f547505b707aab1c3d6071b Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 6 Jul 2019 18:29:05 +0530 Subject: [PATCH 128/352] [BAEL-14774] - Moved article to hibernate-mapping module in README --- persistence-modules/hibernate-mapping/README.md | 1 + persistence-modules/spring-hibernate4/README.md | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 203cb2f8e4..c8c49a7838 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -3,3 +3,4 @@ - [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps) - [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) +- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md index 6f8d83aa9d..426944c149 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -9,7 +9,6 @@ - [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial) - [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) - [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading) -- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) - [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) ### Quick Start From 2913643e812e9613d2f826b372148e0eb08d8f77 Mon Sep 17 00:00:00 2001 From: ashleyfrieze Date: Sat, 6 Jul 2019 14:05:03 +0100 Subject: [PATCH 129/352] Add examples for BiFunction and BinaryOperator (#7252) Rename the test methods --- core-java-modules/core-java-8-2/pom.xml | 7 + .../BiFunctionalInterfacesUnitTest.java | 164 ++++++++++++++++++ 2 files changed, 171 insertions(+) create mode 100644 core-java-modules/core-java-8-2/src/test/java/com/baeldung/bifunction/BiFunctionalInterfacesUnitTest.java diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml index cc184de529..17f0eea20f 100644 --- a/core-java-modules/core-java-8-2/pom.xml +++ b/core-java-modules/core-java-8-2/pom.xml @@ -22,6 +22,7 @@ 1.8 1.8 64.2 + 3.12.2 @@ -30,6 +31,12 @@ icu4j ${icu.version} + + org.assertj + assertj-core + ${assertj.version} + test + diff --git a/core-java-modules/core-java-8-2/src/test/java/com/baeldung/bifunction/BiFunctionalInterfacesUnitTest.java b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/bifunction/BiFunctionalInterfacesUnitTest.java new file mode 100644 index 0000000000..ea63409c88 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/bifunction/BiFunctionalInterfacesUnitTest.java @@ -0,0 +1,164 @@ +package com.baeldung.bifunction; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.function.BiFunction; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BiFunctionalInterfacesUnitTest { + @Test + public void givenStreamValues_whenMappedToNewValues() { + List mapped = Stream.of("hello", "world") + .map(word -> word + "!") + .collect(Collectors.toList()); + + assertThat(mapped).containsExactly("hello!", "world!"); + } + + @Test + public void givenStreamValues_whenReducedWithPrefixingOperation() { + String result = Stream.of("hello", "world") + .reduce("", (a, b) -> b + "-" + a); + + assertThat(result).isEqualTo("world-hello-"); + } + + @Test + public void givenStreamValues_whenReducedWithPrefixingLambda_thenHasNoTrailingDash() { + String result = Stream.of("hello", "world") + .reduce("", (a, b) -> combineWithoutTrailingDash(a, b)); + + assertThat(result).isEqualTo("world-hello"); + } + + private String combineWithoutTrailingDash(String a, String b) { + if (a.isEmpty()) { + return b; + } + return b + "-" + a; + } + + @Test + public void givenStreamValues_whenReducedWithPrefixingMethodReference_thenHasNoTrailingDash() { + String result = Stream.of("hello", "world") + .reduce("", this::combineWithoutTrailingDash); + + assertThat(result).isEqualTo("world-hello"); + } + + @Test + public void givenTwoLists_whenCombined() { + List list1 = Arrays.asList("a", "b", "c"); + List list2 = Arrays.asList(1, 2, 3); + + List result = new ArrayList<>(); + for (int i=0; i < list1.size(); i++) { + result.add(list1.get(i) + list2.get(i)); + } + + assertThat(result).containsExactly("a1", "b2", "c3"); + } + + @Test + public void givenTwoLists_whenCombinedWithGeneralPurposeCombiner() { + List list1 = Arrays.asList("a", "b", "c"); + List list2 = Arrays.asList(1, 2, 3); + + List result = listCombiner(list1, list2, (a, b) -> a + b); + + assertThat(result).containsExactly("a1", "b2", "c3"); + } + + private static List listCombiner(List list1, + List list2, + BiFunction combiner) { + List result = new ArrayList<>(); + for (int i = 0; i < list1.size(); i++) { + result.add(combiner.apply(list1.get(i), list2.get(i))); + } + return result; + } + + @Test + public void givenTwoLists_whenComparedWithCombiningFunction() { + List list1 = Arrays.asList(1.0d, 2.1d, 3.3d); + List list2 = Arrays.asList(0.1f, 0.2f, 4f); + + // algorithm to determine if the value in list1 > value in list 2 + List result = listCombiner(list1, list2, (a, b) -> a > b); + + assertThat(result).containsExactly(true, true, false); + } + + @Test + public void givenTwoLists_whenComparedWithCombiningFunctionByMethodReference() { + List list1 = Arrays.asList(1.0d, 2.1d, 3.3d); + List list2 = Arrays.asList(0.1f, 0.2f, 4f); + + // algorithm to determine if the value in list1 > value in list 2 + List result = listCombiner(list1, list2, this::firstIsGreaterThanSecond); + + assertThat(result).containsExactly(true, true, false); + } + + private boolean firstIsGreaterThanSecond(Double a, Float b) { + return a > b; + } + + @Test + public void givenTwoLists_whenComparedForEqualityByCombiningFunction() { + List list1 = Arrays.asList(0.1f, 0.2f, 4f); + List list2 = Arrays.asList(0.1f, 0.2f, 4f); + + List result = listCombiner(list1, list2, (a, b) -> a.equals(b)); + + assertThat(result).containsExactly(true, true, true); + } + + @Test + public void givenTwoLists_whenComparedForEqualityByCombiningFunctionWithMethodReference() { + List list1 = Arrays.asList(0.1f, 0.2f, 4f); + List list2 = Arrays.asList(0.1f, 0.2f, 4f); + + List result = listCombiner(list1, list2, Float::equals); + + assertThat(result).containsExactly(true, true, true); + } + + @Test + public void givenTwoLists_whenComparedWithCombiningFunctionWithCompareTo() { + List list1 = Arrays.asList(1.0d, 2.1d, 3.3d); + List list2 = Arrays.asList(0.1d, 0.2d, 4d); + + List result = listCombiner(list1, list2, Double::compareTo); + + assertThat(result).containsExactly(1, 1, -1); + } + + /** + * Allows you to to pass in a lambda or method reference and then + * get access to the BiFunction it is meant to become + */ + private static BiFunction asBiFunction(BiFunction function) { + return function; + } + + @Test + public void givenTwoLists_whenComparedWithCombiningFunctionWithComposedBiFunction() { + List list1 = Arrays.asList(1.0d, 2.1d, 3.3d); + List list2 = Arrays.asList(0.1d, 0.2d, 4d); + + List result = listCombiner(list1, list2, + asBiFunction(Double::compareTo) + .andThen(i -> i > 0)); + + assertThat(result).containsExactly(true, true, false); + } +} From 0fd6c0a724792299bff8ace4c5932260aee6be61 Mon Sep 17 00:00:00 2001 From: Pavan Shankar Koli Date: Sat, 6 Jul 2019 19:32:35 +0530 Subject: [PATCH 130/352] BAEL-2578 Moved code under spring-boot-data module --- pom.xml | 1 - spring-boot-data/pom.xml | 24 +++++++++ .../disableautoconfig}/SpringDataJPA.java | 2 +- .../disableautoconfig}/SpringDataMongoDB.java | 4 +- .../disableautoconfig}/SpringDataRedis.java | 4 +- .../SpringDataJPAIntegrationTest.java | 2 +- .../SpringDataMongoDBIntegrationTest.java | 4 +- .../SpringDataRedisIntegrationTest.java | 4 +- .../pom.xml | 27 ---------- .../spring-data-jpa/README.md | 3 -- .../spring-data-jpa/pom.xml | 49 ------------------- .../src/main/resources/application.properties | 1 - .../src/main/resources/logback.xml | 13 ----- .../spring-data-mongodb/README.md | 4 -- .../spring-data-mongodb/pom.xml | 42 ---------------- .../src/main/resources/application.properties | 1 - .../src/main/resources/logback.xml | 13 ----- .../spring-data-redis/README.md | 4 -- .../spring-data-redis/pom.xml | 42 ---------------- .../src/main/resources/application.properties | 1 - .../src/main/resources/logback.xml | 13 ----- 21 files changed, 34 insertions(+), 224 deletions(-) rename {spring-data-disable-auto-configuration/spring-data-jpa/src/main/java/com/baeldung/jpa => spring-boot-data/src/main/java/com/baeldung/disableautoconfig}/SpringDataJPA.java (94%) rename {spring-data-disable-auto-configuration/spring-data-mongodb/src/main/java/com/baeldung/mongodb => spring-boot-data/src/main/java/com/baeldung/disableautoconfig}/SpringDataMongoDB.java (82%) rename {spring-data-disable-auto-configuration/spring-data-redis/src/main/java/com/baeldung/redis => spring-boot-data/src/main/java/com/baeldung/disableautoconfig}/SpringDataRedis.java (82%) rename {spring-data-disable-auto-configuration/spring-data-jpa/src/test/java/com/baeldung/jpa => spring-boot-data/src/test/java/com/baeldung/disableautoconfig}/SpringDataJPAIntegrationTest.java (95%) rename {spring-data-disable-auto-configuration/spring-data-mongodb/src/test/java/com/baeldung/mongodb => spring-boot-data/src/test/java/com/baeldung/disableautoconfig}/SpringDataMongoDBIntegrationTest.java (89%) rename {spring-data-disable-auto-configuration/spring-data-redis/src/test/java/com/baeldung/redis => spring-boot-data/src/test/java/com/baeldung/disableautoconfig}/SpringDataRedisIntegrationTest.java (89%) delete mode 100644 spring-data-disable-auto-configuration/pom.xml delete mode 100644 spring-data-disable-auto-configuration/spring-data-jpa/README.md delete mode 100644 spring-data-disable-auto-configuration/spring-data-jpa/pom.xml delete mode 100644 spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/application.properties delete mode 100644 spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/logback.xml delete mode 100644 spring-data-disable-auto-configuration/spring-data-mongodb/README.md delete mode 100644 spring-data-disable-auto-configuration/spring-data-mongodb/pom.xml delete mode 100644 spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/application.properties delete mode 100644 spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/logback.xml delete mode 100644 spring-data-disable-auto-configuration/spring-data-redis/README.md delete mode 100644 spring-data-disable-auto-configuration/spring-data-redis/pom.xml delete mode 100644 spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/application.properties delete mode 100644 spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/logback.xml diff --git a/pom.xml b/pom.xml index b642cfbeb1..982c52c54e 100644 --- a/pom.xml +++ b/pom.xml @@ -1312,7 +1312,6 @@ spring-boot-ops-2 spring-boot-rest spring-boot-data - spring-data-disable-auto-configuration spring-boot-parent spring-boot-property-exp spring-boot-security diff --git a/spring-boot-data/pom.xml b/spring-boot-data/pom.xml index 8735a54e7b..9c11e09f4a 100644 --- a/spring-boot-data/pom.xml +++ b/spring-boot-data/pom.xml @@ -15,6 +15,30 @@ + + org.springframework.boot + spring-boot-starter-data-redis + 2.1.6.RELEASE + + + + org.springframework.boot + spring-boot-starter-data-mongodb + 2.1.6.RELEASE + + + + org.springframework.boot + spring-boot-starter-data-jpa + 2.1.6.RELEASE + + + + com.h2database + h2 + 1.4.197 + + org.springframework.boot spring-boot-starter-web diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/src/main/java/com/baeldung/jpa/SpringDataJPA.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java similarity index 94% rename from spring-data-disable-auto-configuration/spring-data-jpa/src/main/java/com/baeldung/jpa/SpringDataJPA.java rename to spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java index 211b5dc8b4..8e4ee76a25 100644 --- a/spring-data-disable-auto-configuration/spring-data-jpa/src/main/java/com/baeldung/jpa/SpringDataJPA.java +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataJPA.java @@ -1,4 +1,4 @@ -package com.baeldung.jpa; +package com.baeldung.disableautoconfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/java/com/baeldung/mongodb/SpringDataMongoDB.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java similarity index 82% rename from spring-data-disable-auto-configuration/spring-data-mongodb/src/main/java/com/baeldung/mongodb/SpringDataMongoDB.java rename to spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java index a38eddb0e8..5e1cafa932 100644 --- a/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/java/com/baeldung/mongodb/SpringDataMongoDB.java +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java @@ -1,4 +1,4 @@ -package com.baeldung.mongodb; +package com.baeldung.disableautoconfig; import org.springframework.boot.SpringApplication; @@ -10,6 +10,6 @@ import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; public class SpringDataMongoDB { public static void main(String[] args) { - SpringApplication.run(SpringMongoDB.class, args); + SpringApplication.run(SpringDataMongoDB.class, args); } } diff --git a/spring-data-disable-auto-configuration/spring-data-redis/src/main/java/com/baeldung/redis/SpringDataRedis.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java similarity index 82% rename from spring-data-disable-auto-configuration/spring-data-redis/src/main/java/com/baeldung/redis/SpringDataRedis.java rename to spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java index d5a682834b..9ec831c446 100644 --- a/spring-data-disable-auto-configuration/spring-data-redis/src/main/java/com/baeldung/redis/SpringDataRedis.java +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataRedis.java @@ -1,4 +1,4 @@ -package com.baeldung.redis; +package com.baeldung.disableautoconfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -9,6 +9,6 @@ import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoCo public class SpringDataRedis { public static void main(String[] args) { - SpringApplication.run(SpringRedis.class, args); + SpringApplication.run(SpringDataRedis.class, args); } } diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/src/test/java/com/baeldung/jpa/SpringDataJPAIntegrationTest.java b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java similarity index 95% rename from spring-data-disable-auto-configuration/spring-data-jpa/src/test/java/com/baeldung/jpa/SpringDataJPAIntegrationTest.java rename to spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java index 170f60f861..a465979b3c 100644 --- a/spring-data-disable-auto-configuration/spring-data-jpa/src/test/java/com/baeldung/jpa/SpringDataJPAIntegrationTest.java +++ b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataJPAIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jpa; +package com.baeldung.disableautoconfig; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/src/test/java/com/baeldung/mongodb/SpringDataMongoDBIntegrationTest.java b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java similarity index 89% rename from spring-data-disable-auto-configuration/spring-data-mongodb/src/test/java/com/baeldung/mongodb/SpringDataMongoDBIntegrationTest.java rename to spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java index 33f5620c32..bdfadf76ce 100644 --- a/spring-data-disable-auto-configuration/spring-data-mongodb/src/test/java/com/baeldung/mongodb/SpringDataMongoDBIntegrationTest.java +++ b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataMongoDBIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.mongodb; +package com.baeldung.disableautoconfig; import org.junit.Test; import org.junit.runner.RunWith; @@ -11,7 +11,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringMongoDB.class) +@SpringBootTest(classes = SpringDataMongoDB.class) public class SpringDataMongoDBIntegrationTest { @Autowired diff --git a/spring-data-disable-auto-configuration/spring-data-redis/src/test/java/com/baeldung/redis/SpringDataRedisIntegrationTest.java b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java similarity index 89% rename from spring-data-disable-auto-configuration/spring-data-redis/src/test/java/com/baeldung/redis/SpringDataRedisIntegrationTest.java rename to spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java index e142713417..10133cace3 100644 --- a/spring-data-disable-auto-configuration/spring-data-redis/src/test/java/com/baeldung/redis/SpringDataRedisIntegrationTest.java +++ b/spring-boot-data/src/test/java/com/baeldung/disableautoconfig/SpringDataRedisIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.redis; +package com.baeldung.disableautoconfig; import org.junit.Test; import org.junit.runner.RunWith; @@ -11,7 +11,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringRedis.class) +@SpringBootTest(classes = SpringDataRedis.class) public class SpringDataRedisIntegrationTest { @Autowired diff --git a/spring-data-disable-auto-configuration/pom.xml b/spring-data-disable-auto-configuration/pom.xml deleted file mode 100644 index 91086262cf..0000000000 --- a/spring-data-disable-auto-configuration/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - 4.0.0 - com.baeldung - spring-data-disable-auto-configuration - 1.0.0-SNAPSHOT - spring-data-disable-auto-configuration - spring-data-disable-auto-configuration - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - .. - - - - spring-data-jpa - spring-data-mongodb - spring-data-redis - - - diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/README.md b/spring-data-disable-auto-configuration/spring-data-jpa/README.md deleted file mode 100644 index 23117c9903..0000000000 --- a/spring-data-disable-auto-configuration/spring-data-jpa/README.md +++ /dev/null @@ -1,3 +0,0 @@ -This module is for Jira BAEL-2578 - -### Relevant Articles: diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/pom.xml b/spring-data-disable-auto-configuration/spring-data-jpa/pom.xml deleted file mode 100644 index 35113c379a..0000000000 --- a/spring-data-disable-auto-configuration/spring-data-jpa/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-data-jpa - 0.0.1-SNAPSHOT - spring-data-jpa - jar - Spring Data with JPA - - - spring-data-disable-auto-configuration - com.baeldung - 1.0.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-data-jpa - 2.1.6.RELEASE - - - - com.h2database - h2 - 1.4.197 - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/application.properties b/spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/application.properties deleted file mode 100644 index fc33388896..0000000000 --- a/spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/logback.xml b/spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-data-disable-auto-configuration/spring-data-jpa/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/README.md b/spring-data-disable-auto-configuration/spring-data-mongodb/README.md deleted file mode 100644 index b91f5eda5a..0000000000 --- a/spring-data-disable-auto-configuration/spring-data-mongodb/README.md +++ /dev/null @@ -1,4 +0,0 @@ -This module is for Jira BAEL-2578 - - -### Relevant Articles: diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/pom.xml b/spring-data-disable-auto-configuration/spring-data-mongodb/pom.xml deleted file mode 100644 index ad707632c5..0000000000 --- a/spring-data-disable-auto-configuration/spring-data-mongodb/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-data-mongodb - 0.0.1-SNAPSHOT - spring-data-mongodb - jar - Spring Data with MongoDB - - - spring-data-disable-auto-configuration - com.baeldung - 1.0.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-data-mongodb - 2.1.6.RELEASE - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/application.properties b/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/application.properties deleted file mode 100644 index 9f190ed8ae..0000000000 --- a/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/logback.xml b/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-data-disable-auto-configuration/spring-data-mongodb/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-redis/README.md b/spring-data-disable-auto-configuration/spring-data-redis/README.md deleted file mode 100644 index b91f5eda5a..0000000000 --- a/spring-data-disable-auto-configuration/spring-data-redis/README.md +++ /dev/null @@ -1,4 +0,0 @@ -This module is for Jira BAEL-2578 - - -### Relevant Articles: diff --git a/spring-data-disable-auto-configuration/spring-data-redis/pom.xml b/spring-data-disable-auto-configuration/spring-data-redis/pom.xml deleted file mode 100644 index 3b5db228c5..0000000000 --- a/spring-data-disable-auto-configuration/spring-data-redis/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-data-redis - 0.0.1-SNAPSHOT - spring-data-redis - jar - Spring Data with Redis - - - spring-data-disable-auto-configuration - com.baeldung - 1.0.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-data-redis - 2.1.6.RELEASE - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/application.properties b/spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/application.properties deleted file mode 100644 index 8c5a8dbbfd..0000000000 --- a/spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration, org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration \ No newline at end of file diff --git a/spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/logback.xml b/spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-data-disable-auto-configuration/spring-data-redis/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file From 8b87952f5b3d8d1d092a102c72d11e990912e124 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Sat, 6 Jul 2019 17:12:58 +0300 Subject: [PATCH 131/352] BAEL-2995 - possible lossy conversion - assert fix --- .../ConversionTechniquesUnitTest.java | 24 +++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java index 071ea4f9ab..6659c379b0 100644 --- a/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java +++ b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java @@ -12,29 +12,27 @@ public class ConversionTechniquesUnitTest { long longNum = 24; short shortNum = (short) longNum; - assertEquals(24, shortNum); double doubleNum = 15.6; int integerNum = (int) doubleNum; - assertEquals(15, integerNum); long largeLongNum = 32768; - long smallLongNum = -32769; short shortNum1 = (short) largeLongNum; - short shortNum2 = (short) smallLongNum; - assertEquals(-32768, shortNum1); + + long smallLongNum = -32769; + short shortNum2 = (short) smallLongNum; assertEquals(32767, shortNum2); long maxLong = Long.MAX_VALUE; - long minLong = Long.MIN_VALUE; - int minInt = (int) maxLong; - int maxInt = (int) minLong; + int int1 = (int) maxLong; + assertEquals(-1, int1); - assertEquals(-1, minInt); - assertEquals(0, maxInt); + long minLong = Long.MIN_VALUE; + int int2 = (int) minLong; + assertEquals(0, int2); } @Test @@ -42,12 +40,10 @@ public class ConversionTechniquesUnitTest { Float floatNum = 17.564f; long longNum = floatNum.longValue(); - assertEquals(17, longNum); Double doubleNum = 15.9999; longNum = doubleNum.longValue(); - assertEquals(15, longNum); } @@ -56,7 +52,6 @@ public class ConversionTechniquesUnitTest { Double doubleNum = 15.9999; long longNum = Math.round(doubleNum); - assertEquals(16, longNum); } @@ -67,8 +62,7 @@ public class ConversionTechniquesUnitTest { double dbl = doubleNum.doubleValue(); //unboxing int intgr = (int) dbl; //downcasting Integer intNum = Integer.valueOf(intgr); - - assertTrue(intNum == 10); + assertEquals(Integer.valueOf(10), intNum); } } From 88586cc09f5120e0b0fbfadc8453b3708e1082ca Mon Sep 17 00:00:00 2001 From: codehunter34 <31874661+codehunter34@users.noreply.github.com> Date: Sat, 6 Jul 2019 12:41:48 -0400 Subject: [PATCH 132/352] BAEL-2850: Difference between vs (#7249) --- .../baeldung/components/AccountService.java | 8 +++++++ .../com/baeldung/components/UserService.java | 16 +++++++++++++ spring-5/src/main/resources/beans.xml | 15 ++++++++++++ ...SpringXMLConfigurationIntegrationTest.java | 23 +++++++++++++++++++ 4 files changed, 62 insertions(+) create mode 100644 spring-5/src/main/java/com/baeldung/components/AccountService.java create mode 100644 spring-5/src/main/java/com/baeldung/components/UserService.java create mode 100644 spring-5/src/main/resources/beans.xml create mode 100644 spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java diff --git a/spring-5/src/main/java/com/baeldung/components/AccountService.java b/spring-5/src/main/java/com/baeldung/components/AccountService.java new file mode 100644 index 0000000000..c2f09c735e --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/components/AccountService.java @@ -0,0 +1,8 @@ +package com.baeldung.components; + +import org.springframework.stereotype.Component; + +@Component +public class AccountService { + +} diff --git a/spring-5/src/main/java/com/baeldung/components/UserService.java b/spring-5/src/main/java/com/baeldung/components/UserService.java new file mode 100644 index 0000000000..80e5e0c632 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/components/UserService.java @@ -0,0 +1,16 @@ +package com.baeldung.components; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class UserService { + + @Autowired + private AccountService accountService; + + public AccountService getAccountService() { + return accountService; + } + +} diff --git a/spring-5/src/main/resources/beans.xml b/spring-5/src/main/resources/beans.xml new file mode 100644 index 0000000000..004745b817 --- /dev/null +++ b/spring-5/src/main/resources/beans.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java new file mode 100644 index 0000000000..4ecad9c43e --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.components.AccountService; +import com.baeldung.components.UserService; + +public class SpringXMLConfigurationIntegrationTest { + + @Test + public void givenContextAnnotationConfigOrContextComponentScan_whenDependenciesAndBeansAnnotated_thenNoXMLNeeded() { + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:beans.xml"); + UserService userService = context.getBean(UserService.class); + AccountService accountService = context.getBean(AccountService.class); + Assert.assertNotNull(userService); + Assert.assertNotNull(accountService); + Assert.assertNotNull(userService.getAccountService()); + } + +} From 73ea42d0aeb109fd0817c9189e00b8124092080c Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 7 Jul 2019 01:08:17 +0530 Subject: [PATCH 133/352] [BAEL-15321] - Extracted versions into properties --- algorithms-miscellaneous-1/pom.xml | 3 ++- apache-avro/pom.xml | 2 +- .../core-java-collections-set/pom.xml | 5 +++-- core-java-modules/core-java-exceptions/pom.xml | 2 +- .../multimodulemavenproject/pom.xml | 5 +++-- core-java-modules/pre-jpms/pom.xml | 2 +- jackson-2/pom.xml | 6 +++--- java-dates-2/pom.xml | 3 ++- java-math/pom.xml | 3 ++- libraries-2/pom.xml | 17 +++++++++++------ maven/versions-maven-plugin/original/pom.xml | 12 ++++++++---- patterns/dip/pom.xml | 5 +++-- persistence-modules/elasticsearch/pom.xml | 8 ++++++-- persistence-modules/hibernate-mapping/pom.xml | 6 ++++-- persistence-modules/hibernate-ogm/pom.xml | 16 +++++++++++----- persistence-modules/hibernate5/pom.xml | 8 +++++--- persistence-modules/java-jpa/pom.xml | 3 ++- persistence-modules/spring-data-jpa-2/pom.xml | 6 +++++- persistence-modules/spring-data-jpa/pom.xml | 9 ++++++--- pom.xml | 1 + spring-boot-mvc/pom.xml | 3 ++- spring-cloud/spring-cloud-functions/pom.xml | 5 +++-- spring-mvc-xml/pom.xml | 5 ++--- testing-modules/mockito/pom.xml | 3 ++- testing-modules/spring-testing/pom.xml | 3 ++- xml/pom.xml | 9 ++++++--- 26 files changed, 97 insertions(+), 53 deletions(-) diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml index 30130208f8..affa66f147 100644 --- a/algorithms-miscellaneous-1/pom.xml +++ b/algorithms-miscellaneous-1/pom.xml @@ -42,7 +42,7 @@ com.github.dpaukov combinatoricslib3 - 3.3.0 + ${combinatoricslib3.version} @@ -83,6 +83,7 @@ 3.9.0 1.11 27.0.1-jre + 3.3.0 \ No newline at end of file diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml index 5d170f0a81..e6fb4d24ff 100644 --- a/apache-avro/pom.xml +++ b/apache-avro/pom.xml @@ -17,7 +17,7 @@ junit junit - 4.10 + ${junit.version} test diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index 4435f8b151..8e2f7707f2 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -27,17 +27,18 @@ com.google.code.gson gson - 2.8.5 + ${gson.version} commons-lang commons-lang - 2.6 + ${commons-lang.version} 4.3 27.1-jre + 2.8.5 \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions/pom.xml b/core-java-modules/core-java-exceptions/pom.xml index 37f65882c3..7bc0aa5b4e 100644 --- a/core-java-modules/core-java-exceptions/pom.xml +++ b/core-java-modules/core-java-exceptions/pom.xml @@ -22,7 +22,7 @@ junit junit - 4.12 + ${junit.version} test diff --git a/core-java-modules/multimodulemavenproject/pom.xml b/core-java-modules/multimodulemavenproject/pom.xml index 3d56f1356b..d2fb02deb0 100644 --- a/core-java-modules/multimodulemavenproject/pom.xml +++ b/core-java-modules/multimodulemavenproject/pom.xml @@ -19,13 +19,13 @@ junit junit - 4.12 + ${junit.version} test org.assertj assertj-core - 3.12.2 + ${assertj-core.version} test @@ -58,5 +58,6 @@ UTF-8 + 3.12.2 diff --git a/core-java-modules/pre-jpms/pom.xml b/core-java-modules/pre-jpms/pom.xml index 169cd21f3e..94180ac6c9 100644 --- a/core-java-modules/pre-jpms/pom.xml +++ b/core-java-modules/pre-jpms/pom.xml @@ -18,7 +18,7 @@ org.slf4j slf4j-api - 1.7.25 + ${org.slf4j.version} diff --git a/jackson-2/pom.xml b/jackson-2/pom.xml index 6a975f1de7..2fff1f8706 100644 --- a/jackson-2/pom.xml +++ b/jackson-2/pom.xml @@ -26,21 +26,21 @@ com.fasterxml.jackson.dataformat jackson-dataformat-yaml - 2.9.8 + ${jackson.version} com.fasterxml.jackson.dataformat jackson-dataformat-csv - 2.9.8 + ${jackson.version} com.fasterxml.jackson.datatype jackson-datatype-jsr310 - 2.9.8 + ${jackson.version} diff --git a/java-dates-2/pom.xml b/java-dates-2/pom.xml index 2f861ff5f4..c1419514ef 100644 --- a/java-dates-2/pom.xml +++ b/java-dates-2/pom.xml @@ -25,7 +25,7 @@ commons-validator commons-validator - 1.6 + ${commons-validator.version} @@ -63,6 +63,7 @@ 3.6.1 2.10 + 1.6 1.9 1.9 diff --git a/java-math/pom.xml b/java-math/pom.xml index 159d053df3..f71577b707 100644 --- a/java-math/pom.xml +++ b/java-math/pom.xml @@ -42,7 +42,7 @@ com.github.dpaukov combinatoricslib3 - 3.3.0 + ${combinatoricslib3.version} @@ -63,6 +63,7 @@ 3.9.0 1.11 27.0.1-jre + 3.3.0 \ No newline at end of file diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 7bd3f5b355..13b7ccef7b 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -34,7 +34,7 @@ com.pivovarit parallel-collectors - 1.1.0 + ${parallel-collectors.version} org.assertj @@ -96,22 +96,22 @@ com.squareup.okhttp3 okhttp - 3.14.2 + ${okhttp.version} com.fasterxml.jackson.core jackson-databind - 2.9.9 + ${jackson.version} com.google.code.gson gson - 2.8.5 + ${gson.version} com.squareup.okhttp3 mockwebserver - 3.14.2 + ${mockwebserver.version} test @@ -122,7 +122,7 @@ com.github.jknack handlebars - 4.1.2 + ${handlebars.version} @@ -156,5 +156,10 @@ 0.6.0 1.19 0.28.3 + 1.1.0 + 3.14.2 + 2.8.5 + 3.14.2 + 4.1.2 diff --git a/maven/versions-maven-plugin/original/pom.xml b/maven/versions-maven-plugin/original/pom.xml index 7608e4d168..df8ee9a20e 100644 --- a/maven/versions-maven-plugin/original/pom.xml +++ b/maven/versions-maven-plugin/original/pom.xml @@ -11,19 +11,19 @@ commons-io commons-io - 2.3 + ${commons-io.version} org.apache.commons commons-collections4 - 4.0 + ${commons-collections4.version} org.apache.commons commons-lang3 - 3.0 + ${commons-lang3.version} @@ -35,7 +35,7 @@ commons-beanutils commons-beanutils - 1.9.1-SNAPSHOT + ${commons-beanutils.version} @@ -71,6 +71,10 @@ 1.15 + 2.3 + 4.0 + 3.0 + 1.9.1 \ No newline at end of file diff --git a/patterns/dip/pom.xml b/patterns/dip/pom.xml index dac3f824f2..bc793c0090 100644 --- a/patterns/dip/pom.xml +++ b/patterns/dip/pom.xml @@ -19,13 +19,13 @@ junit junit - 4.12 + ${junit.version} test org.assertj assertj-core - 3.12.1 + ${assertj-core.version} test @@ -34,6 +34,7 @@ UTF-8 11 11 + 3.12.1 diff --git a/persistence-modules/elasticsearch/pom.xml b/persistence-modules/elasticsearch/pom.xml index ceed88aa24..f7bfdb44de 100644 --- a/persistence-modules/elasticsearch/pom.xml +++ b/persistence-modules/elasticsearch/pom.xml @@ -20,12 +20,16 @@ io.searchbox jest - 6.3.1 + ${jest.version} com.fasterxml.jackson.core jackson-databind - 2.9.6 + ${jackson.version} + + + 6.3.1 + diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index bb8ebdab65..6845295812 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -45,12 +45,12 @@ javax.money money-api - 1.0.3 + ${money-api.version} org.javamoney moneta - 1.3 + ${moneta.version} pom @@ -70,6 +70,8 @@ 3.8.0 6.0.16.Final 3.0.1-b11 + 1.0.3 + 1.3 diff --git a/persistence-modules/hibernate-ogm/pom.xml b/persistence-modules/hibernate-ogm/pom.xml index 2ccac03bd3..7ac29b1720 100644 --- a/persistence-modules/hibernate-ogm/pom.xml +++ b/persistence-modules/hibernate-ogm/pom.xml @@ -19,31 +19,31 @@ org.hibernate.ogm hibernate-ogm-mongodb - 5.4.0.Final + ${hibernate.version} org.hibernate.ogm hibernate-ogm-neo4j - 5.4.0.Final + ${hibernate.version} org.jboss.narayana.jta narayana-jta - 5.5.23.Final + ${narayana-jta.version} junit junit - 4.12 + ${junit.version} test org.easytesting fest-assert - 1.4 + ${fest-assert.version} test @@ -57,4 +57,10 @@
+ + + 5.4.0.Final + 1.4 + 5.5.23.Final + \ No newline at end of file diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 7a9fdc0d34..bf4b2d27ec 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -60,7 +60,7 @@ org.hibernate hibernate-testing - 5.2.2.Final + ${hibernate.version} com.fasterxml.jackson.core @@ -70,7 +70,7 @@ net.bytebuddy byte-buddy - 1.9.5 + ${byte-buddy.version} @@ -91,7 +91,7 @@ javax.xml.bind jaxb-api - 2.3.0 + ${jaxb-api.version} @@ -120,6 +120,8 @@ 3.8.0 1.21 0.9 + 1.9.5 + 2.3.0 diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml index 51cc401332..978679cfe6 100644 --- a/persistence-modules/java-jpa/pom.xml +++ b/persistence-modules/java-jpa/pom.xml @@ -34,7 +34,7 @@ javax.persistence javax.persistence-api - 2.2 + ${javax.persistence-api.version} @@ -108,6 +108,7 @@ 5.4.0.Final 2.7.4-RC1 42.2.5 + 2.2 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/pom.xml b/persistence-modules/spring-data-jpa-2/pom.xml index fbc19810ef..08be64670b 100644 --- a/persistence-modules/spring-data-jpa-2/pom.xml +++ b/persistence-modules/spring-data-jpa-2/pom.xml @@ -29,7 +29,7 @@ net.ttddyy datasource-proxy - 1.4.1 + ${datasource-proxy.version} @@ -42,4 +42,8 @@ spring-oxm + + + 1.4.1 + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/pom.xml b/persistence-modules/spring-data-jpa/pom.xml index a7788065c9..af92f331d1 100644 --- a/persistence-modules/spring-data-jpa/pom.xml +++ b/persistence-modules/spring-data-jpa/pom.xml @@ -37,14 +37,14 @@ org.testcontainers postgresql - 1.10.6 + ${testcontainers.postgresql.version} test org.postgresql postgresql - 42.2.5 + ${postgresql.version} @@ -66,7 +66,7 @@ com.google.guava guava - 21.0 + ${guava.version} @@ -92,6 +92,9 @@ com.baeldung.boot.Application + 1.10.6 + 42.2.5 + 21.0 \ No newline at end of file diff --git a/pom.xml b/pom.xml index d67622feb7..f3ddb5d17b 100644 --- a/pom.xml +++ b/pom.xml @@ -1552,6 +1552,7 @@ 1.6.0 2.21.0 2.5 + 2.6 1.4 3.0.0 3.1.0 diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index e17c1d39b9..fee725847f 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -40,7 +40,7 @@ org.glassfish javax.faces - 2.3.7 + ${javax.faces.version} @@ -108,6 +108,7 @@ 2.9.2 1.10.0 + 2.3.7 com.baeldung.springbootmvc.SpringBootMvcApplication diff --git a/spring-cloud/spring-cloud-functions/pom.xml b/spring-cloud/spring-cloud-functions/pom.xml index 7a44e4ae0f..82147cea28 100644 --- a/spring-cloud/spring-cloud-functions/pom.xml +++ b/spring-cloud/spring-cloud-functions/pom.xml @@ -29,7 +29,7 @@ org.springframework.cloud spring-cloud-starter-function-web - 1.0.1.RELEASE + ${spring-cloud-function.version} com.amazonaws @@ -40,7 +40,7 @@ com.amazonaws aws-lambda-java-core - 1.1.0 + ${aws-lambda-java-core.version} provided @@ -87,6 +87,7 @@ UTF-8 1.0.1.RELEASE 2.0.2 + 1.1.0 2.0.4.RELEASE diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index 46af321d1b..c978bdd983 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -82,7 +82,7 @@ org.glassfish javax.el - 3.0.1-b08 + ${javax.el.version} @@ -131,12 +131,11 @@ 6.0.10.Final 1.2 3.1.0 - 2.9.6 + 3.0.1-b08 19.0 3.5 - 2.5 2.8.0 diff --git a/testing-modules/mockito/pom.xml b/testing-modules/mockito/pom.xml index acdd7eb2ac..19dbaa0dc1 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -33,7 +33,7 @@ org.eclipse.persistence javax.persistence - 2.1.1 + ${javax.persistence.version} @@ -99,6 +99,7 @@ 1.7.0 2.0.0.0 + 2.1.1 \ No newline at end of file diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index 0eca9b6a7e..f4d7b5dc66 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -51,7 +51,7 @@ org.eclipse.persistence javax.persistence - 2.1.1 + ${javax.persistence.version} org.springframework.data @@ -95,6 +95,7 @@ 5.4.0 5.1.4.RELEASE 4.0.1 + 2.1.1 \ No newline at end of file diff --git a/xml/pom.xml b/xml/pom.xml index ba6a734dc9..e9b89c71fc 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -33,17 +33,17 @@ javax.xml jaxb-api - 2.1 + ${jaxb-api.version} javax.xml jaxp-api - 1.4.2 + ${jaxp-api.version} javax.xml.stream stax-api - 1.0-2 + ${stax-api.version} @@ -252,6 +252,9 @@ 2.5 4.1 1.2.4.5 + 2.1 + 1.4.2 + 1.0-2 3.5 From 7b958a21f23f99f9b7fce1ad2fd68dd1f251cb21 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 6 Jul 2019 23:29:08 +0300 Subject: [PATCH 134/352] Create README.md --- kotlin-quasar/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 kotlin-quasar/README.md diff --git a/kotlin-quasar/README.md b/kotlin-quasar/README.md new file mode 100644 index 0000000000..b3b84e0446 --- /dev/null +++ b/kotlin-quasar/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Introduction to Quasar in Kotlin](https://www.baeldung.com/kotlin-quasar) From 97e469b47bc4180d3b72a79d898dfe90a3061d9f Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 6 Jul 2019 23:30:17 +0300 Subject: [PATCH 135/352] Create README.md --- spring-boot-parent/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 spring-boot-parent/README.md diff --git a/spring-boot-parent/README.md b/spring-boot-parent/README.md new file mode 100644 index 0000000000..c3bb4c700d --- /dev/null +++ b/spring-boot-parent/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [The Spring Boot Starter Parent](https://www.baeldung.com/spring-boot-starter-parent) From a7130514a831871f6cdcbb26aa6da861389481ed Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 6 Jul 2019 23:31:33 +0300 Subject: [PATCH 136/352] Create README.md --- persistence-modules/elasticsearch/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 persistence-modules/elasticsearch/README.md diff --git a/persistence-modules/elasticsearch/README.md b/persistence-modules/elasticsearch/README.md new file mode 100644 index 0000000000..691e855314 --- /dev/null +++ b/persistence-modules/elasticsearch/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Jest – Elasticsearch Java Client](https://www.baeldung.com/elasticsearch-jest) From 26b9a36068aa127959f1e9b87bc645c802b637da Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 6 Jul 2019 23:32:18 +0300 Subject: [PATCH 137/352] Create README.md --- spring-boot-performance/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 spring-boot-performance/README.md diff --git a/spring-boot-performance/README.md b/spring-boot-performance/README.md new file mode 100644 index 0000000000..015dd759a8 --- /dev/null +++ b/spring-boot-performance/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Lazy Initialization in Spring Boot 2](https://www.baeldung.com/spring-boot-lazy-initialization) From 3cf08197b19d7bd4a21a4154ef14ff574f3a9167 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 6 Jul 2019 23:35:20 +0300 Subject: [PATCH 138/352] Update README.md --- libraries-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries-2/README.md b/libraries-2/README.md index cdeed10b3f..347d41688e 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -5,3 +5,4 @@ - [Guide to Classgraph Library](https://www.baeldung.com/classgraph) - [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program) - [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors) +- [Templating with Handlebars](https://www.baeldung.com/handlebars) From eb5af9a078bd20640e6b9c33828e5512abb59bbb Mon Sep 17 00:00:00 2001 From: Erik Pragt Date: Sun, 7 Jul 2019 11:42:34 +0200 Subject: [PATCH 139/352] BAEL-2791 Update Spring WebFlux article to 2.1.6.RELEASE, and updated other dependencies to latest versions. --- parent-boot-2/pom.xml | 46 +++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index 4b81e27333..f0e921bf37 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -1,9 +1,9 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 parent-boot-2 0.0.1-SNAPSHOT - parent-boot-2 + parent-boot-2 pom Parent for all Spring Boot 2 modules @@ -13,7 +13,7 @@ 1.0.0-SNAPSHOT - + org.springframework.boot @@ -28,7 +28,7 @@ io.rest-assured rest-assured - + org.springframework.boot spring-boot-starter-test @@ -36,22 +36,22 @@ - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - ${start-class} - - - - - - - + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + ${start-class} + + + + + + + thin-jar @@ -75,9 +75,9 @@ - 3.1.0 + 3.3.0 - 1.0.21.RELEASE - 2.1.3.RELEASE + 1.0.22.RELEASE + 2.1.6.RELEASE From f85dbec8f716907fdd7ff24b5fa0bb8eed7daf86 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 7 Jul 2019 15:22:11 +0530 Subject: [PATCH 140/352] [BAEL-15318] - Make sure the tutorials build doesn't generate any un-committed or un-ignored artifacts --- .gitignore | 3 ++- spring-apache-camel/.gitignore | 1 + .../src/test/destination-folder/2016-12-18 22-00-11File1.txt | 0 .../src/test/destination-folder/2016-12-18 22-00-11File2.txt | 0 spring-batch/.gitignore | 1 + spring-mvc-kotlin/.gitignore | 1 + spring-userservice/.gitignore | 1 + vertx-and-rxjava/.gitignore | 1 + 8 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 spring-apache-camel/.gitignore delete mode 100644 spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File1.txt delete mode 100644 spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File2.txt create mode 100644 spring-batch/.gitignore create mode 100644 spring-mvc-kotlin/.gitignore create mode 100644 spring-userservice/.gitignore create mode 100644 vertx-and-rxjava/.gitignore diff --git a/.gitignore b/.gitignore index 50cb889e5b..5be11c71ff 100644 --- a/.gitignore +++ b/.gitignore @@ -77,4 +77,5 @@ apache-avro/src/main/java/com/baeldung/avro/model/ jta/transaction-logs/ software-security/sql-injection-samples/derby.log spring-soap/src/main/java/com/baeldung/springsoap/gen/ -/report-*.json \ No newline at end of file +/report-*.json +transaction.log \ No newline at end of file diff --git a/spring-apache-camel/.gitignore b/spring-apache-camel/.gitignore new file mode 100644 index 0000000000..eac473ac50 --- /dev/null +++ b/spring-apache-camel/.gitignore @@ -0,0 +1 @@ +/src/test/destination-folder/* \ No newline at end of file diff --git a/spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File1.txt b/spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File1.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File2.txt b/spring-apache-camel/src/test/destination-folder/2016-12-18 22-00-11File2.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-batch/.gitignore b/spring-batch/.gitignore new file mode 100644 index 0000000000..0ef6d10b38 --- /dev/null +++ b/spring-batch/.gitignore @@ -0,0 +1 @@ +output.csv \ No newline at end of file diff --git a/spring-mvc-kotlin/.gitignore b/spring-mvc-kotlin/.gitignore new file mode 100644 index 0000000000..416395ffea --- /dev/null +++ b/spring-mvc-kotlin/.gitignore @@ -0,0 +1 @@ +transaction.log \ No newline at end of file diff --git a/spring-userservice/.gitignore b/spring-userservice/.gitignore new file mode 100644 index 0000000000..afe61e7c0c --- /dev/null +++ b/spring-userservice/.gitignore @@ -0,0 +1 @@ +derby.log \ No newline at end of file diff --git a/vertx-and-rxjava/.gitignore b/vertx-and-rxjava/.gitignore new file mode 100644 index 0000000000..3aba11e2fd --- /dev/null +++ b/vertx-and-rxjava/.gitignore @@ -0,0 +1 @@ +/.vertx \ No newline at end of file From 1888a2f7e8948cd760132ce55b8e24b48406d016 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sun, 7 Jul 2019 13:46:24 +0300 Subject: [PATCH 141/352] change package to com.baeldung --- .../baeldung/properties/conversion}/Employee.java | 2 +- .../properties/conversion}/EmployeeConverter.java | 2 +- .../PropertiesConversionApplication.java | 14 ++++++++++++++ .../properties/conversion}/PropertyConversion.java | 2 +- .../ConfigPropertiesDemoApplication.java | 4 +--- .../PropertiesConversionIntegrationTest.java | 7 +++++-- 6 files changed, 23 insertions(+), 8 deletions(-) rename spring-boot/src/main/java/{org/baeldung/properties => com/baeldung/properties/conversion}/Employee.java (91%) rename spring-boot/src/main/java/{org/baeldung/properties => com/baeldung/properties/conversion}/EmployeeConverter.java (91%) create mode 100644 spring-boot/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java rename spring-boot/src/main/java/{org/baeldung/properties => com/baeldung/properties/conversion}/PropertyConversion.java (98%) rename spring-boot/src/test/java/{org/baeldung/properties => com/baeldung/properties/conversion}/PropertiesConversionIntegrationTest.java (86%) diff --git a/spring-boot/src/main/java/org/baeldung/properties/Employee.java b/spring-boot/src/main/java/com/baeldung/properties/conversion/Employee.java similarity index 91% rename from spring-boot/src/main/java/org/baeldung/properties/Employee.java rename to spring-boot/src/main/java/com/baeldung/properties/conversion/Employee.java index 33715d38a5..52c7881dfc 100644 --- a/spring-boot/src/main/java/org/baeldung/properties/Employee.java +++ b/spring-boot/src/main/java/com/baeldung/properties/conversion/Employee.java @@ -1,4 +1,4 @@ -package org.baeldung.properties; +package com.baeldung.properties.conversion; public class Employee { diff --git a/spring-boot/src/main/java/org/baeldung/properties/EmployeeConverter.java b/spring-boot/src/main/java/com/baeldung/properties/conversion/EmployeeConverter.java similarity index 91% rename from spring-boot/src/main/java/org/baeldung/properties/EmployeeConverter.java rename to spring-boot/src/main/java/com/baeldung/properties/conversion/EmployeeConverter.java index 57b8128d2b..6ec19cae72 100644 --- a/spring-boot/src/main/java/org/baeldung/properties/EmployeeConverter.java +++ b/spring-boot/src/main/java/com/baeldung/properties/conversion/EmployeeConverter.java @@ -1,4 +1,4 @@ -package org.baeldung.properties; +package com.baeldung.properties.conversion; import org.springframework.boot.context.properties.ConfigurationPropertiesBinding; import org.springframework.core.convert.converter.Converter; diff --git a/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java b/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java new file mode 100644 index 0000000000..f00a26e9c4 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.properties.conversion; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackageClasses = { PropertyConversion.class, EmployeeConverter.class }) +public class PropertiesConversionApplication { + public static void main(String[] args) { + SpringApplication.run(PropertiesConversionApplication.class, args); + } + +} diff --git a/spring-boot/src/main/java/org/baeldung/properties/PropertyConversion.java b/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertyConversion.java similarity index 98% rename from spring-boot/src/main/java/org/baeldung/properties/PropertyConversion.java rename to spring-boot/src/main/java/com/baeldung/properties/conversion/PropertyConversion.java index 6b70e16e76..b9c890306f 100644 --- a/spring-boot/src/main/java/org/baeldung/properties/PropertyConversion.java +++ b/spring-boot/src/main/java/com/baeldung/properties/conversion/PropertyConversion.java @@ -1,4 +1,4 @@ -package org.baeldung.properties; +package com.baeldung.properties.conversion; import java.time.Duration; import java.time.temporal.ChronoUnit; diff --git a/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java index cad4188926..7b8f2c3411 100644 --- a/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot/src/main/java/org/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -8,9 +8,7 @@ import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackageClasses = {ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class, - AdditionalConfiguration.class, - PropertyConversion.class, - EmployeeConverter.class}) + AdditionalConfiguration.class}) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) diff --git a/spring-boot/src/test/java/org/baeldung/properties/PropertiesConversionIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/properties/conversion/PropertiesConversionIntegrationTest.java similarity index 86% rename from spring-boot/src/test/java/org/baeldung/properties/PropertiesConversionIntegrationTest.java rename to spring-boot/src/test/java/com/baeldung/properties/conversion/PropertiesConversionIntegrationTest.java index 2baae80570..53bad329ea 100644 --- a/spring-boot/src/test/java/org/baeldung/properties/PropertiesConversionIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/properties/conversion/PropertiesConversionIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.properties; +package com.baeldung.properties.conversion; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -12,8 +12,11 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.unit.DataSize; +import com.baeldung.properties.conversion.PropertiesConversionApplication; +import com.baeldung.properties.conversion.PropertyConversion; + @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigPropertiesDemoApplication.class) +@SpringBootTest(classes = PropertiesConversionApplication.class) @TestPropertySource("classpath:conversion.properties") public class PropertiesConversionIntegrationTest { From d6b33e11e267c11d454683d282b6679bd63bf9a3 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sun, 7 Jul 2019 14:14:48 +0300 Subject: [PATCH 142/352] change package to com.baeldung --- .../baeldung/java/collections/IterableToCollectionUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename java-collections-conversions/src/test/java/{org => com}/baeldung/java/collections/IterableToCollectionUnitTest.java (98%) diff --git a/java-collections-conversions/src/test/java/org/baeldung/java/collections/IterableToCollectionUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java similarity index 98% rename from java-collections-conversions/src/test/java/org/baeldung/java/collections/IterableToCollectionUnitTest.java rename to java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java index f2c80429d1..0283191b74 100644 --- a/java-collections-conversions/src/test/java/org/baeldung/java/collections/IterableToCollectionUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/java/collections/IterableToCollectionUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.collections; +package com.baeldung.java.collections; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertThat; From 37e402eb6035ae312d8d33aa137d54b684fb3f3a Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 7 Jul 2019 23:59:01 +0530 Subject: [PATCH 143/352] [BAEL-15322] - Fix formatting of POMs --- apache-olingo/olingo2/pom.xml | 26 +++--- apache-spark/pom.xml | 2 + bootique/pom.xml | 1 - core-groovy-2/pom.xml | 27 +++--- core-java-modules/core-java-8-2/pom.xml | 18 ++-- .../core-java-collections-set/pom.xml | 40 ++++----- .../core-java-exceptions/pom.xml | 8 +- .../consumermodule/pom.xml | 16 ++-- .../consumermodule/pom.xml | 11 +-- core-java-modules/core-java-nio/pom.xml | 8 +- core-java-modules/core-java-optional/pom.xml | 37 ++++---- core-java-modules/core-java/pom.xml | 1 - .../entitymodule/pom.xml | 9 +- .../mainappmodule/pom.xml | 9 +- .../multimodulemavenproject/pom.xml | 14 +-- .../userdaomodule/pom.xml | 27 +++--- core-java-modules/pre-jpms/pom.xml | 3 +- jws/pom.xml | 2 +- libraries-2/pom.xml | 4 + libraries/pom.xml | 5 -- .../daomodule/pom.xml | 11 +-- .../entitiymodule/pom.xml | 12 +-- .../mainppmodule/pom.xml | 11 +-- .../multimodule-maven-project/pom.xml | 15 ++-- .../userdaomodule/pom.xml | 12 +-- maven-java-11/pom.xml | 9 +- maven/pom.xml | 5 +- maven/versions-maven-plugin/pom.xml | 8 +- msf4j/pom.xml | 1 + optaplanner/pom.xml | 5 -- parent-boot-performance/pom.xml | 15 ++-- patterns/design-patterns/pom.xml | 1 + persistence-modules/hibernate-mapping/pom.xml | 7 +- persistence-modules/java-jpa/pom.xml | 1 + persistence-modules/java-mongodb/pom.xml | 2 - .../jpa-hibernate-cascade-type/pom.xml | 8 +- .../sql-injection-samples/pom.xml | 7 -- spf4j/spf4j-aspects-app/pom.xml | 4 + spf4j/spf4j-core-app/pom.xml | 4 + spring-5-security-cognito/pom.xml | 1 - spring-5-webflux/pom.xml | 11 +-- spring-boot-angular/pom.xml | 7 +- spring-boot-flowable/pom.xml | 4 + spring-boot-mvc-birt/pom.xml | 1 + spring-boot-ops-2/pom.xml | 9 +- spring-boot-performance/pom.xml | 10 +-- .../spring-cloud-bootstrap/gateway/pom.xml | 1 + .../spring-cloud-config/client/pom.xml | 3 +- .../spring-cloud-config/server/pom.xml | 3 +- .../spring-cloud-contract-producer/pom.xml | 1 + spring-cloud/spring-cloud-eureka/pom.xml | 12 +-- spring-cloud/spring-cloud-openfeign/pom.xml | 12 ++- .../spring-cloud-security/auth-client/pom.xml | 24 +++--- spring-core-2/pom.xml | 6 +- spring-mvc-java/pom.xml | 25 +++--- spring-security-kerberos/pom.xml | 3 + spring-session/spring-session-mongodb/pom.xml | 10 +-- spring-soap/pom.xml | 10 +-- spring-thymeleaf-2/pom.xml | 10 +-- testing-modules/gatling/pom.xml | 86 +++++++++---------- .../mocks/mock-comparisons/pom.xml | 1 - xmlunit-2/pom.xml | 1 - 62 files changed, 333 insertions(+), 324 deletions(-) diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml index 1efd4ea602..320f56b717 100644 --- a/apache-olingo/olingo2/pom.xml +++ b/apache-olingo/olingo2/pom.xml @@ -3,37 +3,28 @@ 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"> 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.1.3.RELEASE - - org.baeldung.examples.olingo2 olingo2-sample 0.0.1-SNAPSHOT olingo2-sample Sample Olingo 2 Project - - 1.8 - 2.0.11 - + + org.springframework.boot + spring-boot-starter-parent + 2.1.3.RELEASE + + - org.springframework.boot spring-boot-starter-jersey - - org.springframework.boot spring-boot-starter-data-jpa - - com.h2database h2 @@ -90,4 +81,9 @@ + + 1.8 + 2.0.11 + + diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index f0f002a7e9..b8c1962dd4 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -49,6 +49,7 @@ ${com.datastax.spark.spark-cassandra-connector-java.version} + @@ -78,6 +79,7 @@ + 2.3.0 2.3.0 diff --git a/bootique/pom.xml b/bootique/pom.xml index 4ae8703074..4dd9ba4833 100644 --- a/bootique/pom.xml +++ b/bootique/pom.xml @@ -65,7 +65,6 @@ com.baeldung.bootique.App 0.23 - 2.4.3 diff --git a/core-groovy-2/pom.xml b/core-groovy-2/pom.xml index b945546c8a..53b3e6a7ec 100644 --- a/core-groovy-2/pom.xml +++ b/core-groovy-2/pom.xml @@ -157,20 +157,19 @@ - - bintray - Groovy Bintray - https://dl.bintray.com/groovy/maven - - - never - - - false - - - - + + bintray + Groovy Bintray + https://dl.bintray.com/groovy/maven + + + never + + + false + + + 1.0.0 diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml index 17f0eea20f..07bb3b7543 100644 --- a/core-java-modules/core-java-8-2/pom.xml +++ b/core-java-modules/core-java-8-2/pom.xml @@ -9,7 +9,6 @@ core-java-8-2 jar - com.baeldung parent-java @@ -17,14 +16,6 @@ ../../parent-java - - UTF-8 - 1.8 - 1.8 - 64.2 - 3.12.2 - - com.ibm.icu @@ -51,6 +42,13 @@ - + + + UTF-8 + 1.8 + 1.8 + 64.2 + 3.12.2 + diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index 8e2f7707f2..101ed79de0 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -14,26 +14,26 @@ - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - com.google.code.gson - gson - ${gson.version} - - - commons-lang - commons-lang - ${commons-lang.version} - + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + com.google.code.gson + gson + ${gson.version} + + + commons-lang + commons-lang + ${commons-lang.version} + diff --git a/core-java-modules/core-java-exceptions/pom.xml b/core-java-modules/core-java-exceptions/pom.xml index 7bc0aa5b4e..2e5200944a 100644 --- a/core-java-modules/core-java-exceptions/pom.xml +++ b/core-java-modules/core-java-exceptions/pom.xml @@ -14,10 +14,6 @@ ../../parent-java - - 3.9 - - junit @@ -32,4 +28,8 @@ + + 3.9 + + diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml index 6a41ec0d1a..059075318a 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule/pom.xml @@ -11,6 +11,14 @@ 1.0 + + + com.baeldung.servicemodule + servicemodule + 1.0 + + + @@ -19,12 +27,4 @@ - - - - com.baeldung.servicemodule - servicemodule - 1.0 - - diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml index 828fe7de6a..757d9229df 100644 --- a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml +++ b/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule/pom.xml @@ -2,17 +2,18 @@ - - com.baeldung.decoupling-pattern2 - decoupling-pattern2 - 1.0-SNAPSHOT - 4.0.0 com.baeldung.consumermodule consumermodule 1.0 + + com.baeldung.decoupling-pattern2 + decoupling-pattern2 + 1.0-SNAPSHOT + + com.baeldung.servicemodule diff --git a/core-java-modules/core-java-nio/pom.xml b/core-java-modules/core-java-nio/pom.xml index 36d6848998..31433e632f 100644 --- a/core-java-modules/core-java-nio/pom.xml +++ b/core-java-modules/core-java-nio/pom.xml @@ -8,9 +8,9 @@ jar - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java \ No newline at end of file diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml index f2478c2c87..f60e3ba03d 100644 --- a/core-java-modules/core-java-optional/pom.xml +++ b/core-java-modules/core-java-optional/pom.xml @@ -1,22 +1,14 @@ - 4.0.0 - - com.baeldung.core-java-modules - core-java-modules - 1.0.0-SNAPSHOT - - core-java-optional - 0.1.0-SNAPSHOT - jar - - - UTF-8 - 1.8 - 1.8 - 5.4.0.Final - 1.4.197 - 2.9.8 - + 4.0.0 + core-java-optional + 0.1.0-SNAPSHOT + jar + + + com.baeldung.core-java-modules + core-java-modules + 1.0.0-SNAPSHOT + @@ -50,4 +42,13 @@ + + + UTF-8 + 1.8 + 1.8 + 5.4.0.Final + 1.4.197 + 2.9.8 + \ No newline at end of file diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml index 7942f3e7e2..2f33212c38 100644 --- a/core-java-modules/core-java/pom.xml +++ b/core-java-modules/core-java/pom.xml @@ -13,7 +13,6 @@ ../../parent-java - commons-io diff --git a/core-java-modules/multimodulemavenproject/entitymodule/pom.xml b/core-java-modules/multimodulemavenproject/entitymodule/pom.xml index 1fd672d03e..b90a7ed068 100644 --- a/core-java-modules/multimodulemavenproject/entitymodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/entitymodule/pom.xml @@ -1,15 +1,16 @@ 4.0.0 + com.baeldung.entitymodule + entitymodule + 1.0 + jar + com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - com.baeldung.entitymodule - entitymodule - 1.0 - jar diff --git a/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml b/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml index 26e6a15b1e..1f44a1690c 100644 --- a/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/mainappmodule/pom.xml @@ -1,15 +1,16 @@ 4.0.0 + com.baeldung.mainappmodule + mainappmodule + 1.0 + jar + com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - com.baeldung.mainappmodule - mainappmodule - 1.0 - jar diff --git a/core-java-modules/multimodulemavenproject/pom.xml b/core-java-modules/multimodulemavenproject/pom.xml index d2fb02deb0..ad347a4179 100644 --- a/core-java-modules/multimodulemavenproject/pom.xml +++ b/core-java-modules/multimodulemavenproject/pom.xml @@ -14,6 +14,13 @@ ../../ + + entitymodule + daomodule + userdaomodule + mainappmodule + + @@ -49,13 +56,6 @@ - - entitymodule - daomodule - userdaomodule - mainappmodule - - UTF-8 3.12.2 diff --git a/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml b/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml index 63968452db..d3543d5864 100644 --- a/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/userdaomodule/pom.xml @@ -1,24 +1,16 @@ 4.0.0 + com.baeldung.userdaomodule + userdaomodule + 1.0 + jar + com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - com.baeldung.userdaomodule - userdaomodule - 1.0 - jar - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - @@ -33,6 +25,15 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + 9 9 diff --git a/core-java-modules/pre-jpms/pom.xml b/core-java-modules/pre-jpms/pom.xml index 94180ac6c9..380d94fbf1 100644 --- a/core-java-modules/pre-jpms/pom.xml +++ b/core-java-modules/pre-jpms/pom.xml @@ -21,6 +21,7 @@ ${org.slf4j.version} + pre-jpms @@ -65,9 +66,9 @@ - + UTF-8 diff --git a/jws/pom.xml b/jws/pom.xml index 2c89b687f8..6bc790e7ee 100644 --- a/jws/pom.xml +++ b/jws/pom.xml @@ -34,6 +34,7 @@ + ${project.artifactId} org.apache.maven.plugins @@ -78,7 +79,6 @@ - ${project.artifactId} diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 13b7ccef7b..ff73888b69 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -5,11 +5,13 @@ 4.0.0 libraries2 libraries2 + com.baeldung parent-modules 1.0.0-SNAPSHOT + jboss-public-repository-group @@ -25,6 +27,7 @@ + org.mapdb @@ -141,6 +144,7 @@ ${mesos.library.version} + 3.0.7 3.6.2 diff --git a/libraries/pom.xml b/libraries/pom.xml index 0efb404458..8e787bdc22 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -18,17 +18,12 @@ akka-actor_2.12 ${typesafe-akka.version} - - - - com.typesafe.akka akka-testkit_2.12 ${typesafe-akka.version} test - org.beykery diff --git a/maven-java-11/multimodule-maven-project/daomodule/pom.xml b/maven-java-11/multimodule-maven-project/daomodule/pom.xml index de9be656d4..5520c5a90a 100644 --- a/maven-java-11/multimodule-maven-project/daomodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/daomodule/pom.xml @@ -1,14 +1,15 @@ 4.0.0 - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - com.baeldung.daomodule daomodule jar 1.0 daomodule + + + com.baeldung.multimodule-maven-project + multimodule-maven-project + 1.0 + diff --git a/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml b/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml index 8e700e62b5..747722e912 100644 --- a/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml @@ -1,16 +1,18 @@ 4.0.0 - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - com.baeldung.entitymodule entitymodule jar 1.0 entitymodule + + + com.baeldung.multimodule-maven-project + multimodule-maven-project + 1.0 + + 11 11 diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml b/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml index d2c94527f1..3e5ec122ff 100644 --- a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml @@ -1,16 +1,17 @@ 4.0.0 - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - com.baeldung.mainappmodule mainappmodule 1.0 jar mainappmodule + + + com.baeldung.multimodule-maven-project + multimodule-maven-project + 1.0 + diff --git a/maven-java-11/multimodule-maven-project/pom.xml b/maven-java-11/multimodule-maven-project/pom.xml index f22541738c..7e2eb0dd7b 100644 --- a/maven-java-11/multimodule-maven-project/pom.xml +++ b/maven-java-11/multimodule-maven-project/pom.xml @@ -6,12 +6,20 @@ 1.0 pom multimodule-maven-project + com.baeldung.maven-java-11 maven-java-11 1.0 + + entitymodule + daomodule + userdaomodule + mainappmodule + + @@ -45,13 +53,6 @@ - - entitymodule - daomodule - userdaomodule - mainappmodule - - UTF-8 diff --git a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml index b4fe7f0398..68e7ae9b82 100644 --- a/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/userdaomodule/pom.xml @@ -1,16 +1,18 @@ 4.0.0 - - com.baeldung.multimodule-maven-project - multimodule-maven-project - 1.0 - com.baeldung.userdaomodule userdaomodule 1.0 jar userdaomodule + + + com.baeldung.multimodule-maven-project + multimodule-maven-project + 1.0 + + com.baeldung.entitymodule diff --git a/maven-java-11/pom.xml b/maven-java-11/pom.xml index ff95840523..5ae4c00892 100644 --- a/maven-java-11/pom.xml +++ b/maven-java-11/pom.xml @@ -6,14 +6,17 @@ 1.0 pom maven-java-11 + - parent-modules - com.baeldung - 1.0.0-SNAPSHOT + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + multimodule-maven-project + UTF-8 11 diff --git a/maven/pom.xml b/maven/pom.xml index 942bf683e2..ecb031fc11 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -4,12 +4,13 @@ com.baeldung maven 0.0.1-SNAPSHOT + maven + pom + custom-rule maven-enforcer - maven - pom diff --git a/maven/versions-maven-plugin/pom.xml b/maven/versions-maven-plugin/pom.xml index dc0cba75f9..e0714bf0e0 100644 --- a/maven/versions-maven-plugin/pom.xml +++ b/maven/versions-maven-plugin/pom.xml @@ -6,10 +6,6 @@ versions-maven-plugin 0.0.1-SNAPSHOT versions-maven-plugin - - - 1.15 - @@ -73,5 +69,9 @@ + + + 1.15 + \ No newline at end of file diff --git a/msf4j/pom.xml b/msf4j/pom.xml index 4a6f63159d..2a862ac289 100644 --- a/msf4j/pom.xml +++ b/msf4j/pom.xml @@ -23,6 +23,7 @@ + org.wso2.msf4j diff --git a/optaplanner/pom.xml b/optaplanner/pom.xml index fbce0ea072..93b1e68264 100644 --- a/optaplanner/pom.xml +++ b/optaplanner/pom.xml @@ -18,11 +18,6 @@ optaplanner-core 7.9.0.Final - - - - - \ No newline at end of file diff --git a/parent-boot-performance/pom.xml b/parent-boot-performance/pom.xml index b1c6854eae..b7d12e2ba4 100644 --- a/parent-boot-performance/pom.xml +++ b/parent-boot-performance/pom.xml @@ -13,13 +13,6 @@ 1.0.0-SNAPSHOT - - 3.1.0 - - 1.0.21.RELEASE - 2.2.0.M3 - - @@ -31,6 +24,7 @@ + io.rest-assured @@ -88,4 +82,11 @@ + + + 3.1.0 + + 1.0.21.RELEASE + 2.2.0.M3 + diff --git a/patterns/design-patterns/pom.xml b/patterns/design-patterns/pom.xml index ac201ad653..e6bff64f9e 100644 --- a/patterns/design-patterns/pom.xml +++ b/patterns/design-patterns/pom.xml @@ -48,6 +48,7 @@ ${grep4j.version} + UTF-8 1.8 diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index 6845295812..509c54ca75 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -2,6 +2,9 @@ + hibernate-mapping + 1.0.0-SNAPSHOT + 4.0.0 com.baeldung @@ -10,10 +13,6 @@ .. - hibernate-mapping - 1.0.0-SNAPSHOT - 4.0.0 - org.hibernate diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml index 978679cfe6..ced049d281 100644 --- a/persistence-modules/java-jpa/pom.xml +++ b/persistence-modules/java-jpa/pom.xml @@ -104,6 +104,7 @@ + 5.4.0.Final 2.7.4-RC1 diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml index 0f5efedb96..dc4503c95e 100644 --- a/persistence-modules/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -22,8 +22,6 @@ ${flapdoodle.version} test - - org.mongodb mongo-java-driver diff --git a/persistence-modules/jpa-hibernate-cascade-type/pom.xml b/persistence-modules/jpa-hibernate-cascade-type/pom.xml index 8cfc2a5fa2..a45f297a6b 100644 --- a/persistence-modules/jpa-hibernate-cascade-type/pom.xml +++ b/persistence-modules/jpa-hibernate-cascade-type/pom.xml @@ -2,6 +2,10 @@ + jpa-hibernate-cascade-type + 4.0.0 + 1.0.0-SNAPSHOT + com.baeldung parent-modules @@ -9,10 +13,6 @@ ../../ - jpa-hibernate-cascade-type - 4.0.0 - 1.0.0-SNAPSHOT - org.hibernate diff --git a/software-security/sql-injection-samples/pom.xml b/software-security/sql-injection-samples/pom.xml index b12b479614..5c3256319e 100644 --- a/software-security/sql-injection-samples/pom.xml +++ b/software-security/sql-injection-samples/pom.xml @@ -16,13 +16,10 @@ - - org.springframework.boot spring-boot-starter-jdbc - org.apache.derby derby @@ -43,18 +40,14 @@ lombok provided - org.springframework.boot spring-boot-starter-data-jpa - org.hibernate hibernate-jpamodelgen - - org.springframework.boot spring-boot-devtools diff --git a/spf4j/spf4j-aspects-app/pom.xml b/spf4j/spf4j-aspects-app/pom.xml index 9fccec673a..1c707f4d87 100644 --- a/spf4j/spf4j-aspects-app/pom.xml +++ b/spf4j/spf4j-aspects-app/pom.xml @@ -6,12 +6,14 @@ 0.0.1-SNAPSHOT jar spf4j-aspects-app + parent-modules com.baeldung 1.0.0-SNAPSHOT ../../ + org.spf4j @@ -29,6 +31,7 @@ ${org.slf4j.version} + spf4j-aspects-app @@ -75,6 +78,7 @@ + UTF-8 8.6.10 diff --git a/spf4j/spf4j-core-app/pom.xml b/spf4j/spf4j-core-app/pom.xml index ae346065ef..9f490d9f06 100644 --- a/spf4j/spf4j-core-app/pom.xml +++ b/spf4j/spf4j-core-app/pom.xml @@ -6,12 +6,14 @@ 0.0.1-SNAPSHOT jar spf4j-core-app + parent-modules com.baeldung 1.0.0-SNAPSHOT ../../ + org.spf4j @@ -29,6 +31,7 @@ ${org.slf4j.version} + spf4j-core-app @@ -75,6 +78,7 @@ + UTF-8 8.6.10 diff --git a/spring-5-security-cognito/pom.xml b/spring-5-security-cognito/pom.xml index c7314d6f9f..431c9b8d9c 100644 --- a/spring-5-security-cognito/pom.xml +++ b/spring-5-security-cognito/pom.xml @@ -48,7 +48,6 @@ org.springframework.security spring-security-oauth2-jose - org.springframework spring-test diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index c1f537d2fe..6317723467 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -28,11 +28,6 @@ - - 1.8 - 2.2.0.M3 - - org.springframework.boot @@ -86,6 +81,7 @@ https://repo.spring.io/milestone + spring-snapshots @@ -101,4 +97,9 @@ https://repo.spring.io/milestone + + + 1.8 + 2.2.0.M3 + diff --git a/spring-boot-angular/pom.xml b/spring-boot-angular/pom.xml index 6ea98eb3d0..62a2701dd0 100644 --- a/spring-boot-angular/pom.xml +++ b/spring-boot-angular/pom.xml @@ -6,15 +6,13 @@ spring-boot-angular 1.0 jar + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT ../../parent-boot-2 - - 1.8 - @@ -47,4 +45,7 @@ + + 1.8 + diff --git a/spring-boot-flowable/pom.xml b/spring-boot-flowable/pom.xml index f9531a1e6a..f7fc943389 100644 --- a/spring-boot-flowable/pom.xml +++ b/spring-boot-flowable/pom.xml @@ -7,12 +7,14 @@ war spring-boot-flowable Spring Boot Flowable Module + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT ../parent-boot-2 + org.springframework.boot @@ -44,6 +46,7 @@ test + @@ -52,6 +55,7 @@ + 6.4.1 diff --git a/spring-boot-mvc-birt/pom.xml b/spring-boot-mvc-birt/pom.xml index 8f41e8410a..6feb2a7611 100644 --- a/spring-boot-mvc-birt/pom.xml +++ b/spring-boot-mvc-birt/pom.xml @@ -9,6 +9,7 @@ 0.0.1-SNAPSHOT jar Module For Spring Boot Integration with BIRT + org.springframework.boot spring-boot-starter-parent diff --git a/spring-boot-ops-2/pom.xml b/spring-boot-ops-2/pom.xml index dc5280df48..74fcd79169 100644 --- a/spring-boot-ops-2/pom.xml +++ b/spring-boot-ops-2/pom.xml @@ -3,6 +3,10 @@ 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"> 4.0.0 + com.baeldung + spring-boot-ops-2 + 0.0.1-SNAPSHOT + spring-boot-ops-2 parent-boot-2 @@ -11,11 +15,6 @@ ../parent-boot-2 - com.baeldung - spring-boot-ops-2 - 0.0.1-SNAPSHOT - spring-boot-ops-2 - org.springframework.boot diff --git a/spring-boot-performance/pom.xml b/spring-boot-performance/pom.xml index bbee7493cc..f51df8bc0c 100644 --- a/spring-boot-performance/pom.xml +++ b/spring-boot-performance/pom.xml @@ -14,11 +14,6 @@ ../parent-boot-performance - - - com.baeldung.lazyinitialization.Application - - org.springframework.boot @@ -42,4 +37,9 @@ + + + + com.baeldung.lazyinitialization.Application + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml index 4f9c60a26a..6cbaa5ac2d 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml @@ -97,6 +97,7 @@ + Dalston.RELEASE diff --git a/spring-cloud/spring-cloud-config/client/pom.xml b/spring-cloud/spring-cloud-config/client/pom.xml index c55f9bc471..14b0d2f9b1 100644 --- a/spring-cloud/spring-cloud-config/client/pom.xml +++ b/spring-cloud/spring-cloud-config/client/pom.xml @@ -20,8 +20,7 @@ org.springframework.boot spring-boot-starter-web - - + org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud/spring-cloud-config/server/pom.xml b/spring-cloud/spring-cloud-config/server/pom.xml index b4be7663e2..674749a48d 100644 --- a/spring-cloud/spring-cloud-config/server/pom.xml +++ b/spring-cloud/spring-cloud-config/server/pom.xml @@ -24,8 +24,7 @@ org.springframework.boot spring-boot-starter-web - - + org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml index dffbd29206..7a0fa7db10 100644 --- a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/pom.xml @@ -31,6 +31,7 @@ spring-boot-starter-data-rest + diff --git a/spring-cloud/spring-cloud-eureka/pom.xml b/spring-cloud/spring-cloud-eureka/pom.xml index e8e3d67805..5afb006d41 100644 --- a/spring-cloud/spring-cloud-eureka/pom.xml +++ b/spring-cloud/spring-cloud-eureka/pom.xml @@ -9,18 +9,18 @@ Spring Cloud Eureka Server and Sample Clients pom - - spring-cloud-eureka-server - spring-cloud-eureka-client - spring-cloud-eureka-feign-client - - com.baeldung.spring.cloud spring-cloud 1.0.0-SNAPSHOT .. + + + spring-cloud-eureka-server + spring-cloud-eureka-client + spring-cloud-eureka-feign-client + diff --git a/spring-cloud/spring-cloud-openfeign/pom.xml b/spring-cloud/spring-cloud-openfeign/pom.xml index 002a333749..92de33572b 100644 --- a/spring-cloud/spring-cloud-openfeign/pom.xml +++ b/spring-cloud/spring-cloud-openfeign/pom.xml @@ -9,7 +9,6 @@ openfeign OpenFeign project for Spring Boot - parent-boot-2 com.baeldung @@ -17,12 +16,6 @@ ../../parent-boot-2 - - 2.0.1.RELEASE - Finchley.SR2 - - - org.springframework.cloud @@ -58,4 +51,9 @@ + + 2.0.1.RELEASE + Finchley.SR2 + + diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index 4152552640..c414e584e5 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -13,6 +13,18 @@ 1.0.0-SNAPSHOT + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + org.springframework.boot @@ -78,18 +90,6 @@ - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - 2.2.0 Greenwich.SR1 diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index 8e4c539e3b..bb4ca9701b 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -2,15 +2,15 @@ + 4.0.0 + spring-core-2 + com.baeldung parent-spring-5 0.0.1-SNAPSHOT ../parent-spring-5 - 4.0.0 - - spring-core-2 diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 853d8db64c..e5dd5ad9e1 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -15,8 +15,8 @@ - - org.springframework + + org.springframework spring-webmvc ${spring.version} @@ -34,7 +34,6 @@ javax.servlet jstl ${jstl.version} - @@ -134,17 +133,17 @@ gson 2.8.5 - - org.springframework - spring-websocket - ${spring.version} - + + org.springframework + spring-websocket + ${spring.version} + - - org.springframework - spring-messaging - ${spring.version} - + + org.springframework + spring-messaging + ${spring.version} + diff --git a/spring-security-kerberos/pom.xml b/spring-security-kerberos/pom.xml index 35c4ba4926..d98d0ff508 100644 --- a/spring-security-kerberos/pom.xml +++ b/spring-security-kerberos/pom.xml @@ -7,12 +7,14 @@ 0.1-SNAPSHOT spring-security-kerberos war + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT ../parent-boot-1 + org.springframework.boot @@ -50,6 +52,7 @@ test + diff --git a/spring-session/spring-session-mongodb/pom.xml b/spring-session/spring-session-mongodb/pom.xml index 16fbaccc84..dc055ff32d 100644 --- a/spring-session/spring-session-mongodb/pom.xml +++ b/spring-session/spring-session-mongodb/pom.xml @@ -42,11 +42,6 @@ - - 2.1.3.RELEASE - 2.1.5.RELEASE - - @@ -56,4 +51,9 @@ + + 2.1.3.RELEASE + 2.1.5.RELEASE + + \ No newline at end of file diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index ba05eddf5d..16f19b681f 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -13,11 +13,6 @@ ../parent-boot-2 - - 1.8 - 2.1.2.RELEASE - - @@ -66,4 +61,9 @@ + + 1.8 + 2.1.2.RELEASE + + diff --git a/spring-thymeleaf-2/pom.xml b/spring-thymeleaf-2/pom.xml index bc1147cb14..1b95cac43c 100644 --- a/spring-thymeleaf-2/pom.xml +++ b/spring-thymeleaf-2/pom.xml @@ -23,11 +23,6 @@ - - 1.8 - 1.8 - - @@ -37,4 +32,9 @@ spring-thymeleaf-2 + + + 1.8 + 1.8 + diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml index 158da176c6..e708d939e4 100644 --- a/testing-modules/gatling/pom.xml +++ b/testing-modules/gatling/pom.xml @@ -14,6 +14,31 @@ 1.0.0-SNAPSHOT ../../ + + + + + io.gatling + gatling-app + ${gatling.version} + + + io.gatling + gatling-recorder + ${gatling.version} + + + io.gatling.highcharts + gatling-charts-highcharts + ${gatling.version} + + + org.scala-lang + scala-library + ${scala.version} + + + @@ -77,52 +102,27 @@ simulation - - io.gatling - gatling-maven-plugin - ${gatling-maven-plugin.version} - - - test - - execute - - - true - - - - - - + + io.gatling + gatling-maven-plugin + ${gatling-maven-plugin.version} + + + test + + execute + + + true + + + + + + - - - - io.gatling - gatling-app - ${gatling.version} - - - io.gatling - gatling-recorder - ${gatling.version} - - - io.gatling.highcharts - gatling-charts-highcharts - ${gatling.version} - - - org.scala-lang - scala-library - ${scala.version} - - - - 1.8 1.8 diff --git a/testing-modules/mocks/mock-comparisons/pom.xml b/testing-modules/mocks/mock-comparisons/pom.xml index ae36280300..e454f124ce 100644 --- a/testing-modules/mocks/mock-comparisons/pom.xml +++ b/testing-modules/mocks/mock-comparisons/pom.xml @@ -49,7 +49,6 @@ 2.21.0 3.5.1 1.41 - diff --git a/xmlunit-2/pom.xml b/xmlunit-2/pom.xml index faefeca7a1..9e146ccf33 100644 --- a/xmlunit-2/pom.xml +++ b/xmlunit-2/pom.xml @@ -23,7 +23,6 @@ xmlunit-core ${xmlunit.version} - From a46a730ffe862e76bb0d55f24c3db93afd9c434d Mon Sep 17 00:00:00 2001 From: Pavan Shankar Koli Date: Mon, 8 Jul 2019 08:58:23 +0530 Subject: [PATCH 144/352] BAEL-2578 Remove white spaces --- .../java/com/baeldung/disableautoconfig/SpringDataMongoDB.java | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java index 5e1cafa932..865c137a8d 100644 --- a/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java +++ b/spring-boot-data/src/main/java/com/baeldung/disableautoconfig/SpringDataMongoDB.java @@ -1,6 +1,5 @@ package com.baeldung.disableautoconfig; - import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; From aebb5cb88e2d492dcf646a310cad4fc1b7ce541e Mon Sep 17 00:00:00 2001 From: Erik Pragt Date: Mon, 8 Jul 2019 16:23:20 -0500 Subject: [PATCH 145/352] BAEL-14772 Update Spring Data MongoDB article to latest dependencies --- persistence-modules/spring-data-mongodb/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index 7156cdf071..33ad3a5267 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -21,7 +21,7 @@ org.springframework.data spring-data-releasetrain - Lovelace-SR3 + Lovelace-SR9 pom @@ -95,7 +95,7 @@ - 2.1.2.RELEASE + 2.1.9.RELEASE 4.1.4 1.1.3 1.9.2 From e1bad1ab5376c960ea12e14fb7deceb908a814ce Mon Sep 17 00:00:00 2001 From: Erik Pragt Date: Mon, 8 Jul 2019 16:53:05 -0500 Subject: [PATCH 146/352] BAEL-2883 Fix tests in spring-cloud projects part 3 --- .../basic/SpringContextIntegrationTest.java | 16 ++++++++++++++++ spring-cloud/spring-cloud-aws/.attach_pid23938 | 0 .../gateway/SpringContextIntegrationTest.java | 16 ++++++++++++++++ 3 files changed, 32 insertions(+) create mode 100644 spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextIntegrationTest.java delete mode 100644 spring-cloud/spring-cloud-aws/.attach_pid23938 create mode 100644 spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextIntegrationTest.java diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..818e313c98 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-aws/.attach_pid23938 b/spring-cloud/spring-cloud-aws/.attach_pid23938 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..dc635cd003 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.bootstrap.gateway; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} From d84e1bd4cf6044973f0240374f26519d4b2bd919 Mon Sep 17 00:00:00 2001 From: Erik Pragt Date: Mon, 8 Jul 2019 17:34:55 -0500 Subject: [PATCH 147/352] BAEL-3036 Update Cors with Spring article and create the code --- .../main/java/com/baeldung/cors/Account.java | 9 +++++++ .../com/baeldung/cors/AccountController.java | 24 ++++++++++++++++++ .../java/com/baeldung/cors/WebConfig.java | 16 ++++++++++++ .../main/webapp/WEB-INF/spring-web-config.xml | 25 +++++++++++++++++++ 4 files changed, 74 insertions(+) create mode 100644 spring-rest-simple/src/main/java/com/baeldung/cors/Account.java create mode 100644 spring-rest-simple/src/main/java/com/baeldung/cors/AccountController.java create mode 100644 spring-rest-simple/src/main/java/com/baeldung/cors/WebConfig.java create mode 100644 spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml diff --git a/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java b/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java new file mode 100644 index 0000000000..dc6a541a46 --- /dev/null +++ b/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java @@ -0,0 +1,9 @@ +package com.baeldung.cors; + +public class Account { + private Long id; + + public Account(Long id) { + this.id = id; + } +} diff --git a/spring-rest-simple/src/main/java/com/baeldung/cors/AccountController.java b/spring-rest-simple/src/main/java/com/baeldung/cors/AccountController.java new file mode 100644 index 0000000000..c387eb2121 --- /dev/null +++ b/spring-rest-simple/src/main/java/com/baeldung/cors/AccountController.java @@ -0,0 +1,24 @@ +package com.baeldung.cors; + +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@CrossOrigin(maxAge = 3600) +@RestController +@RequestMapping("/account") +public class AccountController { + + @CrossOrigin("http://example.com") + @RequestMapping("/{id}") + public Account retrieve(@PathVariable Long id) { + return new Account(id); + } + + @RequestMapping(method = RequestMethod.DELETE, path = "/{id}") + public void remove(@PathVariable Long id) { + // ... + } +} \ No newline at end of file diff --git a/spring-rest-simple/src/main/java/com/baeldung/cors/WebConfig.java b/spring-rest-simple/src/main/java/com/baeldung/cors/WebConfig.java new file mode 100644 index 0000000000..dc579ce4ba --- /dev/null +++ b/spring-rest-simple/src/main/java/com/baeldung/cors/WebConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.cors; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@EnableWebMvc +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**"); + } +} \ No newline at end of file diff --git a/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml b/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml new file mode 100644 index 0000000000..07d50ae1d6 --- /dev/null +++ b/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + From 76c32dcd9b002867fe5229a980c81855c378ca4c Mon Sep 17 00:00:00 2001 From: Erik Pragt Date: Mon, 8 Jul 2019 18:16:25 -0500 Subject: [PATCH 148/352] BAEL-2940 Update Spring ComponentScanning. Moved componentscan code to new module. --- pom.xml | 1 + spring-boot-di/pom.xml | 55 +++++++++++++++++++ .../com/baeldung/SpringBootDiApplication.java | 12 ++++ .../baeldung/componentscan/ExampleBean.java | 0 .../springapp/SpringComponentScanApp.java | 4 -- .../componentscan/springapp/animals/Cat.java | 0 .../componentscan/springapp/animals/Dog.java | 0 .../componentscan/springapp/flowers/Rose.java | 0 .../SpringBootComponentScanApp.java | 3 - .../springbootapp/animals/Cat.java | 0 .../springbootapp/animals/Dog.java | 0 .../springbootapp/flowers/Rose.java | 0 spring-boot/.attach_pid12812 | 0 13 files changed, 68 insertions(+), 7 deletions(-) create mode 100644 spring-boot-di/pom.xml create mode 100644 spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java rename {spring-boot => spring-boot-di}/src/main/java/com/baeldung/componentscan/ExampleBean.java (100%) rename {spring-boot => spring-boot-di}/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java (88%) rename {spring-boot => spring-boot-di}/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java (100%) rename {spring-boot => spring-boot-di}/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java (100%) rename {spring-boot => spring-boot-di}/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java (100%) rename {spring-boot => spring-boot-di}/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java (88%) rename {spring-boot => spring-boot-di}/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java (100%) rename {spring-boot => spring-boot-di}/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java (100%) rename {spring-boot => spring-boot-di}/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java (100%) delete mode 100644 spring-boot/.attach_pid12812 diff --git a/pom.xml b/pom.xml index b4fed5150d..2d1e2b5291 100644 --- a/pom.xml +++ b/pom.xml @@ -839,6 +839,7 @@ spring-boot-camel spring-boot-client spring-boot-custom-starter + spring-boot-di greeter-spring-boot-autoconfigure greeter-spring-boot-sample-app persistence-modules/spring-boot-h2/spring-boot-h2-database diff --git a/spring-boot-di/pom.xml b/spring-boot-di/pom.xml new file mode 100644 index 0000000000..ec40c04566 --- /dev/null +++ b/spring-boot-di/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + spring-boot-mvc + spring-boot-mvc + jar + Module For Spring Boot DI + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.SpringBootDiApplication + JAR + + + + + + + com.baeldung.SpringBootDiApplication + + + diff --git a/spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java b/spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java new file mode 100644 index 0000000000..b9d2d7ecef --- /dev/null +++ b/spring-boot-di/src/main/java/com/baeldung/SpringBootDiApplication.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootDiApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootDiApplication.class, args); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/ExampleBean.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/ExampleBean.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/ExampleBean.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java similarity index 88% rename from spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java index 2377ed7a56..83b91f7860 100644 --- a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java +++ b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/SpringComponentScanApp.java @@ -1,10 +1,6 @@ package com.baeldung.componentscan.springapp; -import org.springframework.context.annotation.FilterType; -import org.springframework.stereotype.Component; - import com.baeldung.componentscan.ExampleBean; -import com.baeldung.componentscan.springapp.flowers.Rose; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Cat.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/animals/Dog.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springapp/flowers/Rose.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java similarity index 88% rename from spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java index ba29a4e1f5..4362caefbb 100644 --- a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java +++ b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/SpringBootComponentScanApp.java @@ -1,14 +1,11 @@ package com.baeldung.componentscan.springbootapp; import org.springframework.boot.SpringApplication; -import org.springframework.context.annotation.FilterType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import com.baeldung.componentscan.ExampleBean; -import com.baeldung.componentscan.springbootapp.flowers.Rose; @SpringBootApplication //@ComponentScan(basePackages = "com.baeldung.componentscan.springbootapp.animals") diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Cat.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/animals/Dog.java diff --git a/spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java b/spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java rename to spring-boot-di/src/main/java/com/baeldung/componentscan/springbootapp/flowers/Rose.java diff --git a/spring-boot/.attach_pid12812 b/spring-boot/.attach_pid12812 deleted file mode 100644 index e69de29bb2..0000000000 From 4b27a2f33c4061b4ea4c7793d20c77da47ea5a27 Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Tue, 9 Jul 2019 05:36:57 +0100 Subject: [PATCH 149/352] Code samples for advanced quasar article (#7271) --- kotlin-quasar/pom.xml | 23 ++ .../com/baeldung/quasar/ActorsBehaviorTest.kt | 157 +++++++++ .../kotlin/com/baeldung/quasar/ActorsTest.kt | 298 ++++++++++++++++++ .../baeldung/quasar/ReactiveStreamsTest.kt | 135 ++++++++ 4 files changed, 613 insertions(+) create mode 100644 kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt create mode 100644 kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt create mode 100644 kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt diff --git a/kotlin-quasar/pom.xml b/kotlin-quasar/pom.xml index 44feabd183..a3e5a1ec25 100644 --- a/kotlin-quasar/pom.xml +++ b/kotlin-quasar/pom.xml @@ -45,6 +45,27 @@ junit 4.12 + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + ch.qos.logback + logback-core + ${logback.version} + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + @@ -116,5 +137,7 @@ 0.8.0 1.3.31 + 1.7.21 + 1.1.7 diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt new file mode 100644 index 0000000000..b4d0288a64 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt @@ -0,0 +1,157 @@ +package com.baeldung.quasar + +import co.paralleluniverse.actors.Actor +import co.paralleluniverse.actors.ActorRef +import co.paralleluniverse.actors.behaviors.* +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.strands.SuspendableCallable +import org.junit.Test +import org.slf4j.LoggerFactory +import java.lang.Exception + +class ActorsBehaviorTest { + companion object { + private val LOG = LoggerFactory.getLogger(ActorsBehaviorTest::class.java) + } + + @Test + fun requestReplyHelper() { + data class TestMessage(val input: Int) : RequestMessage() + + val actor = object : Actor("requestReplyActor", null) { + @Suspendable + override fun doRun(): Void? { + while (true) { + val msg = receive() + LOG.info("Processing message: {}", msg) + + RequestReplyHelper.reply(msg, msg.input * 100) + } + } + } + + val actorRef = actor.spawn() + + val result = RequestReplyHelper.call(actorRef, TestMessage(50)) + LOG.info("Received reply: {}", result) + } + + @Test + fun server() { + val actor = ServerActor(object : AbstractServerHandler() { + @Suspendable + override fun handleCall(from: ActorRef<*>?, id: Any?, m: Int?): String { + LOG.info("Called with message: {} from {} with ID {}", m, from, id) + return m.toString() ?: "None" + } + + @Suspendable + override fun handleCast(from: ActorRef<*>?, id: Any?, m: Float?) { + LOG.info("Cast message: {} from {} with ID {}", m, from, id) + } + }) + + val server = actor.spawn() + + LOG.info("Call result: {}", server.call(5)) + server.cast(2.5f) + + server.shutdown() + } + + interface Summer { + fun sum(a: Int, b: Int) : Int + } + + @Test + fun proxyServer() { + val actor = ProxyServerActor(false, object : Summer { + @Synchronized + override fun sum(a: Int, b: Int): Int { + Exception().printStackTrace() + LOG.info("Adding together {} and {}", a, b) + return a + b + } + }) + + val summerActor = actor.spawn() + + val result = (summerActor as Summer).sum(1, 2) + LOG.info("Result: {}", result) + + summerActor.shutdown() + } + + @Test + fun eventSource() { + val actor = EventSourceActor() + val eventSource = actor.spawn() + + eventSource.addHandler { msg -> + LOG.info("Sent message: {}", msg) + } + + val name = "Outside Value" + eventSource.addHandler { msg -> + LOG.info("Also Sent message: {} {}", msg, name) + } + + eventSource.send("Hello") + + eventSource.shutdown() + } + + @Test + fun finiteStateMachine() { + val actor = object : FiniteStateMachineActor() { + @Suspendable + override fun initialState(): SuspendableCallable> { + LOG.info("Starting") + return SuspendableCallable { lockedState() } + } + + @Suspendable + fun lockedState() : SuspendableCallable> { + return receive {msg -> + when (msg) { + "PUSH" -> { + LOG.info("Still locked") + lockedState() + } + "COIN" -> { + LOG.info("Unlocking...") + unlockedState() + } + else -> TERMINATE + } + } + } + + @Suspendable + fun unlockedState() : SuspendableCallable> { + return receive {msg -> + when (msg) { + "PUSH" -> { + LOG.info("Locking") + lockedState() + } + "COIN" -> { + LOG.info("Unlocked") + unlockedState() + } + else -> TERMINATE + } + } + } + } + + val actorRef = actor.spawn() + + listOf("PUSH", "COIN", "COIN", "PUSH", "PUSH").forEach { + LOG.info(it) + actorRef.sendSync(it) + } + + actorRef.shutdown() + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt new file mode 100644 index 0000000000..819a149af3 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt @@ -0,0 +1,298 @@ +package com.baeldung.quasar + +import co.paralleluniverse.actors.* +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.strands.channels.Channels +import org.junit.Assert +import org.junit.Test +import org.slf4j.LoggerFactory +import java.util.concurrent.TimeUnit + +class ActorsTest { + companion object { + private val LOG = LoggerFactory.getLogger(ActorsTest::class.java) + } + + @Test + fun createNoopActor() { + val actor = object : Actor("noopActor", MailboxConfig(5, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + return "Hello" + } + } + + actor.spawn() + + println("Noop Actor: ${actor.get()}") + } + + @Test + fun registerActor() { + val actor = object : Actor("registerActor", null) { + @Suspendable + override fun doRun(): String { + return "Hello" + } + } + + val actorRef = actor.spawn() + actor.register() + + val retrievedRef = ActorRegistry.getActor>("registerActor") + + Assert.assertEquals(actorRef, retrievedRef) + actor.join() + } + + @Test + fun registerActorNewName() { + val actor = object : Actor(null, null) { + @Suspendable + override fun doRun(): String { + return "Hello" + } + } + + val actorRef = actor.spawn() + actor.register("renamedActor") + + val retrievedRef = ActorRegistry.getActor>("renamedActor") + + Assert.assertEquals(actorRef, retrievedRef) + actor.join() + } + + @Test + fun retrieveUnknownActor() { + val retrievedRef = ActorRegistry.getActor>("unknownActor", 1, TimeUnit.SECONDS) + + Assert.assertNull(retrievedRef) + } + + @Test + fun createSimpleActor() { + val actor = object : Actor("simpleActor", null) { + @Suspendable + override fun doRun(): Void? { + val msg = receive() + LOG.info("SimpleActor Received Message: {}", msg) + + return null + } + } + + val actorRef = actor.spawn() + + actorRef.send(1) + + actor.join() + } + + @Test + fun createLoopingActor() { + val actor = object : Actor("loopingActor", null) { + @Suspendable + override fun doRun(): Void? { + while (true) { + val msg = receive() + + if (msg > 0) { + LOG.info("LoopingActor Received Message: {}", msg) + } else { + break + } + } + + return null + } + } + + val actorRef = actor.spawn() + + actorRef.send(3) + actorRef.send(2) + actorRef.send(1) + actorRef.send(0) + + actor.join() + } + + @Test + fun actorBacklog() { + val actor = object : Actor("backlogActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + TimeUnit.MILLISECONDS.sleep(500); + LOG.info("Backlog Actor Received: {}", receive()) + + try { + receive() + } catch (e: Throwable) { + LOG.info("==== Exception throws by receive() ====") + e.printStackTrace() + } + + return "No Exception" + } + } + + val actorRef = actor.spawn() + + actorRef.send(1) + actorRef.send(2) + + try { + LOG.info("Backlog Actor: {}", actor.get()) + } catch (e: Exception) { + // Expected + LOG.info("==== Exception throws by get() ====") + e.printStackTrace() + } + } + + @Test + fun actorBacklogTrySend() { + val actor = object : Actor("backlogTrySendActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + TimeUnit.MILLISECONDS.sleep(500); + LOG.info("Backlog TrySend Actor Received: {}", receive()) + + return "No Exception" + } + } + + val actorRef = actor.spawn() + + LOG.info("Backlog TrySend 1: {}", actorRef.trySend(1)) + LOG.info("Backlog TrySend 1: {}", actorRef.trySend(2)) + + actor.join() + } + + @Test + fun actorTimeoutReceive() { + val actor = object : Actor("TimeoutReceiveActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + LOG.info("Timeout Actor Received: {}", receive(500, TimeUnit.MILLISECONDS)) + + return "Finished" + } + } + + val actorRef = actor.spawn() + + TimeUnit.MILLISECONDS.sleep(300) + actorRef.trySend(1) + + actor.join() + } + + + @Test + fun actorNonBlockingReceive() { + val actor = object : Actor("NonBlockingReceiveActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { + @Suspendable + override fun doRun(): String { + LOG.info("NonBlocking Actor Received #1: {}", tryReceive()) + TimeUnit.MILLISECONDS.sleep(500) + LOG.info("NonBlocking Actor Received #2: {}", tryReceive()) + + return "Finished" + } + } + + val actorRef = actor.spawn() + + TimeUnit.MILLISECONDS.sleep(300) + actorRef.trySend(1) + + actor.join() + } + + @Test + fun evenActor() { + val actor = object : Actor("EvenActor", null) { + @Suspendable + override fun filterMessage(m: Any?): Int? { + return when (m) { + is Int -> { + if (m % 2 == 0) { + m * 10 + } else { + null + } + } + else -> super.filterMessage(m) + } + } + + @Suspendable + override fun doRun(): Void? { + while (true) { + val msg = receive() + + if (msg > 0) { + LOG.info("EvenActor Received Message: {}", msg) + } else { + break + } + } + + return null + } + } + + val actorRef = actor.spawn() + + actorRef.send(3) + actorRef.send(2) + actorRef.send(1) + actorRef.send(0) + + actor.join() + } + + @Test + fun watchingActors() { + val watched = object : Actor("WatchedActor", null) { + @Suspendable + override fun doRun(): Void? { + LOG.info("WatchedActor Starting") + receive(500, TimeUnit.MILLISECONDS) + LOG.info("WatchedActor Finishing") + return null + } + } + + val watcher = object : Actor("WatcherActor", null) { + @Suspendable + override fun doRun(): Void? { + LOG.info("WatcherActor Listening") + try { + LOG.info("WatcherActor received Message: {}", receive(2, TimeUnit.SECONDS)) + } catch (e: Exception) { + LOG.info("WatcherActor Received Exception", e) + } + return null + } + + @Suspendable + override fun handleLifecycleMessage(m: LifecycleMessage?): Int? { + LOG.info("WatcherActor Received Lifecycle Message: {}", m) + return super.handleLifecycleMessage(m) + } + } + + val watcherRef = watcher.spawn() + TimeUnit.MILLISECONDS.sleep(200) + + val watchedRef = watched.spawn() + watcher.link(watchedRef) + + watched.join() + watcher.join() + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt new file mode 100644 index 0000000000..83e06bf7d6 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt @@ -0,0 +1,135 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.kotlin.fiber +import co.paralleluniverse.strands.channels.Channels +import co.paralleluniverse.strands.channels.Topic +import co.paralleluniverse.strands.channels.reactivestreams.ReactiveStreams +import org.junit.Test +import org.reactivestreams.Subscriber +import org.reactivestreams.Subscription +import org.slf4j.LoggerFactory +import java.util.concurrent.TimeUnit + +class ReactiveStreamsTest { + companion object { + private val LOG = LoggerFactory.getLogger(ReactiveStreamsTest::class.java) + } + + @Test + fun publisher() { + val inputChannel = Channels.newChannel(1); + + val publisher = ReactiveStreams.toPublisher(inputChannel) + publisher.subscribe(object : Subscriber { + @Suspendable + override fun onComplete() { + LOG.info("onComplete") + } + + @Suspendable + override fun onSubscribe(s: Subscription) { + LOG.info("onSubscribe: {}", s) + s.request(2) + } + + @Suspendable + override fun onNext(t: String?) { + LOG.info("onNext: {}", t) + } + + @Suspendable + override fun onError(t: Throwable?) { + LOG.info("onError: {}", t) + } + }) + + inputChannel.send("Hello") + inputChannel.send("World") + + TimeUnit.SECONDS.sleep(1) + + inputChannel.close() + } + + @Test + fun publisherTopic() { + val inputTopic = Topic() + + val publisher = ReactiveStreams.toPublisher(inputTopic) + publisher.subscribe(object : Subscriber { + @Suspendable + override fun onComplete() { + LOG.info("onComplete 1") + } + + @Suspendable + override fun onSubscribe(s: Subscription) { + LOG.info("onSubscribe 1: {}", s) + s.request(2) + } + + @Suspendable + override fun onNext(t: String?) { + LOG.info("onNext 1: {}", t) + } + + @Suspendable + override fun onError(t: Throwable?) { + LOG.info("onError 1: {}", t) + } + }) + publisher.subscribe(object : Subscriber { + @Suspendable + override fun onComplete() { + LOG.info("onComplete 2") + } + + @Suspendable + override fun onSubscribe(s: Subscription) { + LOG.info("onSubscribe 2: {}", s) + s.request(2) + } + + @Suspendable + override fun onNext(t: String?) { + LOG.info("onNext 2: {}", t) + } + + @Suspendable + override fun onError(t: Throwable?) { + LOG.info("onError 2: {}", t) + } + }) + + inputTopic.send("Hello") + inputTopic.send("World") + + TimeUnit.SECONDS.sleep(1) + + inputTopic.close() + } + + @Test + fun subscribe() { + val inputChannel = Channels.newChannel(10); + val publisher = ReactiveStreams.toPublisher(inputChannel) + + val channel = ReactiveStreams.subscribe(10, Channels.OverflowPolicy.THROW, publisher) + + fiber @Suspendable { + while (!channel.isClosed) { + val message = channel.receive() + LOG.info("Received: {}", message) + } + LOG.info("Stopped receiving messages") + } + + inputChannel.send("Hello") + inputChannel.send("World") + + TimeUnit.SECONDS.sleep(1) + + inputChannel.close() + } +} From 325c0a4d07c7619010960bcb186a7284f29127ee Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Tue, 9 Jul 2019 10:57:55 +0300 Subject: [PATCH 150/352] BAEL-2995 - possible lossy conversion - variable names fixed --- .../ConversionTechniquesUnitTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java index 6659c379b0..2001f39359 100644 --- a/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java +++ b/java-numbers-2/src/test/java/com/baeldung/lossyconversion/ConversionTechniquesUnitTest.java @@ -19,20 +19,20 @@ public class ConversionTechniquesUnitTest { assertEquals(15, integerNum); long largeLongNum = 32768; - short shortNum1 = (short) largeLongNum; - assertEquals(-32768, shortNum1); + short minShortNum = (short) largeLongNum; + assertEquals(-32768, minShortNum); long smallLongNum = -32769; - short shortNum2 = (short) smallLongNum; - assertEquals(32767, shortNum2); + short maxShortNum = (short) smallLongNum; + assertEquals(32767, maxShortNum); long maxLong = Long.MAX_VALUE; - int int1 = (int) maxLong; - assertEquals(-1, int1); + int minInt = (int) maxLong; + assertEquals(-1, minInt); long minLong = Long.MIN_VALUE; - int int2 = (int) minLong; - assertEquals(0, int2); + int maxInt = (int) minLong; + assertEquals(0, maxInt); } @Test From 0d6d9129c4eefa93a4667597ad60ab225293fd2c Mon Sep 17 00:00:00 2001 From: Erik Pragt Date: Tue, 9 Jul 2019 06:18:29 -0500 Subject: [PATCH 151/352] BAEL-3035 Update Spring Kafka module and article from 2.2.2 to 2.2.7 (#7266) --- spring-kafka/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index 2fb4c776fe..3d08aaa928 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -33,7 +33,7 @@ - 2.2.2.RELEASE + 2.2.7.RELEASE \ No newline at end of file From 51e1014b26ead1fe5f77f3ea1513f67d7dc44c54 Mon Sep 17 00:00:00 2001 From: Priyesh Mashelkar Date: Tue, 9 Jul 2019 12:30:29 +0100 Subject: [PATCH 152/352] Mocking a void method with EasyMock Issue: BAEL-2952 --- testing-modules/easymock/pom.xml | 26 ++++++++++ .../testing/easymock/ForecastProcessor.java | 28 +++++++++++ .../baeldung/testing/easymock/Location.java | 33 +++++++++++++ .../easymock/ServiceUnavailableException.java | 7 +++ .../testing/easymock/WeatherService.java | 5 ++ .../easymock/ForecastProcessorUnitTest.java | 49 +++++++++++++++++++ testing-modules/pom.xml | 1 + 7 files changed, 149 insertions(+) create mode 100644 testing-modules/easymock/pom.xml create mode 100644 testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ForecastProcessor.java create mode 100644 testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/Location.java create mode 100644 testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ServiceUnavailableException.java create mode 100644 testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/WeatherService.java create mode 100644 testing-modules/easymock/src/test/java/com/baeldung/testing/easymock/ForecastProcessorUnitTest.java diff --git a/testing-modules/easymock/pom.xml b/testing-modules/easymock/pom.xml new file mode 100644 index 0000000000..2b16dd3a1f --- /dev/null +++ b/testing-modules/easymock/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + + com.baeldung + testing-modules + 1.0.0-SNAPSHOT + + easymock + easymock + http://maven.apache.org + + UTF-8 + + + + org.easymock + easymock + 4.0.2 + test + + + diff --git a/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ForecastProcessor.java b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ForecastProcessor.java new file mode 100644 index 0000000000..482e985e5b --- /dev/null +++ b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ForecastProcessor.java @@ -0,0 +1,28 @@ +package com.baeldung.testing.easymock; + +import java.math.BigDecimal; + +public class ForecastProcessor { + private WeatherService weatherService; + + public BigDecimal getMaximumTemperature(String locationName) { + + Location location = new Location(locationName); + + try { + weatherService.populateTemperature(location); + } catch (ServiceUnavailableException e) { + return null; + } + + return location.getMaximumTemparature(); + } + + public WeatherService getWeatherService() { + return weatherService; + } + + public void setWeatherService(WeatherService weatherService) { + this.weatherService = weatherService; + } +} diff --git a/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/Location.java b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/Location.java new file mode 100644 index 0000000000..5f318acd5c --- /dev/null +++ b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/Location.java @@ -0,0 +1,33 @@ +package com.baeldung.testing.easymock; + +import java.math.BigDecimal; + +public class Location { + private String name; + private BigDecimal minimumTemperature; + private BigDecimal maximumTemparature; + + public Location(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public BigDecimal getMinimumTemperature() { + return minimumTemperature; + } + + public void setMinimumTemperature(BigDecimal minimumTemperature) { + this.minimumTemperature = minimumTemperature; + } + + public BigDecimal getMaximumTemparature() { + return maximumTemparature; + } + + public void setMaximumTemparature(BigDecimal maximumTemparature) { + this.maximumTemparature = maximumTemparature; + } +} diff --git a/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ServiceUnavailableException.java b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ServiceUnavailableException.java new file mode 100644 index 0000000000..abab4bdee8 --- /dev/null +++ b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/ServiceUnavailableException.java @@ -0,0 +1,7 @@ +package com.baeldung.testing.easymock; + +public class ServiceUnavailableException extends Exception { + + private static final long serialVersionUID = 6961151537340723535L; + +} diff --git a/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/WeatherService.java b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/WeatherService.java new file mode 100644 index 0000000000..1c6b11b17b --- /dev/null +++ b/testing-modules/easymock/src/main/java/com/baeldung/testing/easymock/WeatherService.java @@ -0,0 +1,5 @@ +package com.baeldung.testing.easymock; + +public interface WeatherService { + void populateTemperature(Location location) throws ServiceUnavailableException; +} diff --git a/testing-modules/easymock/src/test/java/com/baeldung/testing/easymock/ForecastProcessorUnitTest.java b/testing-modules/easymock/src/test/java/com/baeldung/testing/easymock/ForecastProcessorUnitTest.java new file mode 100644 index 0000000000..fa8fa847ae --- /dev/null +++ b/testing-modules/easymock/src/test/java/com/baeldung/testing/easymock/ForecastProcessorUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.testing.easymock; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.math.BigDecimal; + +import org.easymock.EasyMock; +import org.easymock.EasyMockRule; +import org.easymock.Mock; +import org.easymock.TestSubject; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +public class ForecastProcessorUnitTest { + private static int MAX_TEMP = 90; + + @Rule + public EasyMockRule rule = new EasyMockRule(this); + + @TestSubject + private ForecastProcessor forecastProcessor = new ForecastProcessor(); + + @Mock + private WeatherService mockWeatherService; + + @Before + public void setUp() { + forecastProcessor.setWeatherService(mockWeatherService); + } + + @SuppressWarnings("unchecked") + @Test + public void givenLocationName_whenWeatherServicePopulatesTemperatures_thenMaxTempReturned() throws ServiceUnavailableException { + mockWeatherService.populateTemperature(EasyMock.anyObject(Location.class)); + EasyMock.expectLastCall() + .andAnswer(() -> { + Location passedLocation = (Location) EasyMock.getCurrentArguments()[0]; + passedLocation.setMaximumTemparature(new BigDecimal(MAX_TEMP)); + passedLocation.setMinimumTemperature(new BigDecimal(MAX_TEMP - 10)); + return null; + }); + EasyMock.replay(mockWeatherService); + BigDecimal maxTemperature = forecastProcessor.getMaximumTemperature("New York"); + EasyMock.verify(mockWeatherService); + assertThat(maxTemperature, equalTo(new BigDecimal(MAX_TEMP))); + } +} diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index 95a19c2557..bc6e23a6b7 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -33,6 +33,7 @@ testing testng junit-5-basics + easymock junit-5-advanced From a238394e5f94b1aa45c790e0a8f7d5c988f82434 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 10 Jul 2019 08:56:11 +0300 Subject: [PATCH 153/352] Update README.md --- spring-rest-simple/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-rest-simple/README.md b/spring-rest-simple/README.md index 882d0ac301..c01f27bd98 100644 --- a/spring-rest-simple/README.md +++ b/spring-rest-simple/README.md @@ -5,3 +5,4 @@ - [Spring RequestMapping](http://www.baeldung.com/spring-requestmapping) - [Spring and Apache FileUpload](http://www.baeldung.com/spring-apache-file-upload) - [Test a REST API with curl](http://www.baeldung.com/curl-rest) +- [CORS with Spring](https://www.baeldung.com/spring-cors) From 8510c6172485725b13b0ef234c88383493440e9a Mon Sep 17 00:00:00 2001 From: amit2103 Date: Wed, 10 Jul 2019 12:16:50 +0530 Subject: [PATCH 154/352] [BAEL-15319] - Check modules that don't use our standard parents --- apache-olingo/olingo2/pom.xml | 12 ++++++------ ...a => Olingo2SampleApplicationUnitTest.java} | 2 +- apache-pulsar/pom.xml | 7 +++++++ ...ConsumerTest.java => ConsumerUnitTest.java} | 2 +- ...ProducerTest.java => ProducerUnitTest.java} | 2 +- ...java => ExclusiveSubscriptionUnitTest.java} | 2 +- ....java => FailoverSubscriptionUnitTest.java} | 2 +- .../multimodulemavenproject/daomodule/pom.xml | 9 +++++---- custom-pmd/pom.xml | 6 ++++++ flyway-cdi-extension/pom.xml | 7 +++++++ kotlin-quasar/pom.xml | 6 ++++++ .../maven-polyglot-json-app/pom.json | 8 ++++---- .../maven-polyglot-json-extension/pom.xml | 12 ++++++++++-- maven-polyglot/maven-polyglot-yml-app/pom.yml | 6 ++++++ maven/pom.xml | 6 ++++++ spring-boot-mvc-birt/pom.xml | 9 +++++---- testing-modules/easymock/pom.xml | 18 +++++++++++------- 17 files changed, 84 insertions(+), 32 deletions(-) rename apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/{Olingo2SampleApplicationTests.java => Olingo2SampleApplicationUnitTest.java} (86%) rename apache-pulsar/src/main/java/com/baeldung/{ConsumerTest.java => ConsumerUnitTest.java} (98%) mode change 100755 => 100644 rename apache-pulsar/src/main/java/com/baeldung/{ProducerTest.java => ProducerUnitTest.java} (98%) mode change 100755 => 100644 rename apache-pulsar/src/main/java/com/baeldung/subscriptions/{ExclusiveSubscriptionTest.java => ExclusiveSubscriptionUnitTest.java} (98%) rename apache-pulsar/src/main/java/com/baeldung/subscriptions/{FailoverSubscriptionTest.java => FailoverSubscriptionUnitTest.java} (98%) diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml index 320f56b717..e3647b9c57 100644 --- a/apache-olingo/olingo2/pom.xml +++ b/apache-olingo/olingo2/pom.xml @@ -9,12 +9,12 @@ olingo2-sample Sample Olingo 2 Project - - org.springframework.boot - spring-boot-starter-parent - 2.1.3.RELEASE - - + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + diff --git a/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java b/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java similarity index 86% rename from apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java rename to apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java index 687f6ab1ff..7cb685e3e9 100644 --- a/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java +++ b/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationUnitTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class Olingo2SampleApplicationTests { +public class Olingo2SampleApplicationUnitTest { @Test public void contextLoads() { diff --git a/apache-pulsar/pom.xml b/apache-pulsar/pom.xml index 11df6d0b87..8a0882dae1 100644 --- a/apache-pulsar/pom.xml +++ b/apache-pulsar/pom.xml @@ -7,6 +7,13 @@ 0.0.1 apache-pulsar + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + org.apache.pulsar diff --git a/apache-pulsar/src/main/java/com/baeldung/ConsumerTest.java b/apache-pulsar/src/main/java/com/baeldung/ConsumerUnitTest.java old mode 100755 new mode 100644 similarity index 98% rename from apache-pulsar/src/main/java/com/baeldung/ConsumerTest.java rename to apache-pulsar/src/main/java/com/baeldung/ConsumerUnitTest.java index 72dc10b542..82a0028837 --- a/apache-pulsar/src/main/java/com/baeldung/ConsumerTest.java +++ b/apache-pulsar/src/main/java/com/baeldung/ConsumerUnitTest.java @@ -7,7 +7,7 @@ import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.client.api.SubscriptionType; -public class ConsumerTest { +public class ConsumerUnitTest { private static final String SERVICE_URL = "pulsar://localhost:6650"; private static final String TOPIC_NAME = "test-topic"; diff --git a/apache-pulsar/src/main/java/com/baeldung/ProducerTest.java b/apache-pulsar/src/main/java/com/baeldung/ProducerUnitTest.java old mode 100755 new mode 100644 similarity index 98% rename from apache-pulsar/src/main/java/com/baeldung/ProducerTest.java rename to apache-pulsar/src/main/java/com/baeldung/ProducerUnitTest.java index 08ee0e89b9..10a4b46c4d --- a/apache-pulsar/src/main/java/com/baeldung/ProducerTest.java +++ b/apache-pulsar/src/main/java/com/baeldung/ProducerUnitTest.java @@ -11,7 +11,7 @@ import org.apache.pulsar.client.api.PulsarClientException; import java.io.IOException; import java.util.stream.IntStream; -public class ProducerTest { +public class ProducerUnitTest { private static final String SERVICE_URL = "pulsar://localhost:6650"; private static final String TOPIC_NAME = "test-topic"; diff --git a/apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionTest.java b/apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionUnitTest.java similarity index 98% rename from apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionTest.java rename to apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionUnitTest.java index efb898eaf4..79121347e7 100644 --- a/apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionTest.java +++ b/apache-pulsar/src/main/java/com/baeldung/subscriptions/ExclusiveSubscriptionUnitTest.java @@ -10,7 +10,7 @@ import org.apache.pulsar.client.api.SubscriptionType; import java.util.stream.IntStream; -public class ExclusiveSubscriptionTest { +public class ExclusiveSubscriptionUnitTest { private static final String SERVICE_URL = "pulsar://localhost:6650"; private static final String TOPIC_NAME = "test-topic"; private static final String SUBSCRIPTION_NAME = "test-subscription"; diff --git a/apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionTest.java b/apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionUnitTest.java similarity index 98% rename from apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionTest.java rename to apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionUnitTest.java index 545661e0c3..1d13b4b83a 100644 --- a/apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionTest.java +++ b/apache-pulsar/src/main/java/com/baeldung/subscriptions/FailoverSubscriptionUnitTest.java @@ -11,7 +11,7 @@ import org.apache.pulsar.client.api.SubscriptionType; import java.util.stream.IntStream; -public class FailoverSubscriptionTest { +public class FailoverSubscriptionUnitTest { private static final String SERVICE_URL = "pulsar://localhost:6650"; private static final String TOPIC_NAME = "failover-subscription-test-topic"; private static final String SUBSCRIPTION_NAME = "test-subscription"; diff --git a/core-java-modules/multimodulemavenproject/daomodule/pom.xml b/core-java-modules/multimodulemavenproject/daomodule/pom.xml index a260e15e6d..e98c48aa76 100644 --- a/core-java-modules/multimodulemavenproject/daomodule/pom.xml +++ b/core-java-modules/multimodulemavenproject/daomodule/pom.xml @@ -1,15 +1,16 @@ 4.0.0 + com.baeldung.daomodule + daomodule + 1.0 + jar + com.baeldung.multimodulemavenproject multimodulemavenproject 1.0 - com.baeldung.daomodule - daomodule - 1.0 - jar diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml index 74e6d9593b..9964bf2bb4 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -7,6 +7,12 @@ custom-pmd jar http://maven.apache.org + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml index f49a51ea4b..f9f951880e 100644 --- a/flyway-cdi-extension/pom.xml +++ b/flyway-cdi-extension/pom.xml @@ -8,6 +8,13 @@ 1.0-SNAPSHOT flyway-cdi-extension + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + javax.enterprise diff --git a/kotlin-quasar/pom.xml b/kotlin-quasar/pom.xml index a3e5a1ec25..231b02b0c7 100644 --- a/kotlin-quasar/pom.xml +++ b/kotlin-quasar/pom.xml @@ -8,6 +8,12 @@ kotlin-quasar jar + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + org.jetbrains.kotlin diff --git a/maven-polyglot/maven-polyglot-json-app/pom.json b/maven-polyglot/maven-polyglot-json-app/pom.json index abd58f3127..3e809b7b83 100644 --- a/maven-polyglot/maven-polyglot-json-app/pom.json +++ b/maven-polyglot/maven-polyglot-json-app/pom.json @@ -5,10 +5,10 @@ "version": "1.0-SNAPSHOT", "name": "Json Maven Polyglot", "parent": { - "groupId": "org.springframework.boot", - "artifactId": "spring-boot-starter-parent", - "version": "2.0.5.RELEASE", - "relativePath": null + "groupId": "com.baeldung", + "artifactId": "parent-boot-2", + "version": "0.0.1-SNAPSHOT", + "relativePath": "../../parent-boot-2" }, "properties": { "project.build.sourceEncoding": "UTF-8", diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-polyglot/maven-polyglot-json-extension/pom.xml index 5b18529ec5..1170fe7aa6 100644 --- a/maven-polyglot/maven-polyglot-json-extension/pom.xml +++ b/maven-polyglot/maven-polyglot-json-extension/pom.xml @@ -8,17 +8,24 @@ 1.0-SNAPSHOT maven-polyglot-json-extension + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../.. + + org.apache.maven maven-core - 3.5.4 + ${maven-core.version} provided com.fasterxml.jackson.core jackson-databind - 2.9.6 + ${jackson.version} @@ -42,6 +49,7 @@ 1.8 1.8 + 3.5.4 \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-yml-app/pom.yml b/maven-polyglot/maven-polyglot-yml-app/pom.yml index 445e2eec3b..393f7e9e15 100644 --- a/maven-polyglot/maven-polyglot-yml-app/pom.yml +++ b/maven-polyglot/maven-polyglot-yml-app/pom.yml @@ -4,4 +4,10 @@ artifactId: maven-polyglot-yml-app version: 1.0-SNAPSHOT name: 'YAML Demo' +parent: + groupId: "com.baeldung" + artifactId: "parent-modules" + version: "1.0.0-SNAPSHOT" + relativePath: "../.." + properties: {maven.compiler.source: 1.8, maven.compiler.target: 1.8} \ No newline at end of file diff --git a/maven/pom.xml b/maven/pom.xml index ecb031fc11..96643d76f3 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -7,6 +7,12 @@ maven pom + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + custom-rule maven-enforcer diff --git a/spring-boot-mvc-birt/pom.xml b/spring-boot-mvc-birt/pom.xml index 6feb2a7611..bf6bbbf71d 100644 --- a/spring-boot-mvc-birt/pom.xml +++ b/spring-boot-mvc-birt/pom.xml @@ -9,11 +9,12 @@ 0.0.1-SNAPSHOT jar Module For Spring Boot Integration with BIRT - + - org.springframework.boot - spring-boot-starter-parent - 2.1.1.RELEASE + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 diff --git a/testing-modules/easymock/pom.xml b/testing-modules/easymock/pom.xml index 2b16dd3a1f..ed9a077f67 100644 --- a/testing-modules/easymock/pom.xml +++ b/testing-modules/easymock/pom.xml @@ -4,23 +4,27 @@ xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 + easymock + easymock + http://maven.apache.org + com.baeldung testing-modules 1.0.0-SNAPSHOT - easymock - easymock - http://maven.apache.org - - UTF-8 - + org.easymock easymock - 4.0.2 + ${easymock.version} test + + + UTF-8 + 4.0.2 + From 3d543356556a319d8d69e0cbf0c2c9719d599707 Mon Sep 17 00:00:00 2001 From: Jon Cook Date: Wed, 10 Jul 2019 12:58:15 +0200 Subject: [PATCH 155/352] BAEL-2912 - TestWatcher API --- .../src/main/resources/logback.xml | 13 ++++ .../TestResultLoggerExtension.java | 62 +++++++++++++++++++ .../testwatcher/TestWatcherAPIUnitTest.java | 36 +++++++++++ 3 files changed, 111 insertions(+) create mode 100644 testing-modules/junit-5-advanced/src/main/resources/logback.xml create mode 100644 testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestResultLoggerExtension.java create mode 100644 testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestWatcherAPIUnitTest.java diff --git a/testing-modules/junit-5-advanced/src/main/resources/logback.xml b/testing-modules/junit-5-advanced/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/junit-5-advanced/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestResultLoggerExtension.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestResultLoggerExtension.java new file mode 100644 index 0000000000..a92c44a85b --- /dev/null +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestResultLoggerExtension.java @@ -0,0 +1,62 @@ +package com.baeldung.extensions.testwatcher; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.TestWatcher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TestResultLoggerExtension implements TestWatcher, AfterAllCallback { + + private static final Logger LOG = LoggerFactory.getLogger(TestResultLoggerExtension.class); + + private List testResultsStatus = new ArrayList<>(); + + private enum TestResultStatus { + SUCCESSFUL, ABORTED, FAILED, DISABLED; + } + + @Override + public void testDisabled(ExtensionContext context, Optional reason) { + LOG.info("Test Disabled for test {}: with reason :- {}", context.getDisplayName(), reason.orElse("No reason")); + + testResultsStatus.add(TestResultStatus.DISABLED); + } + + @Override + public void testSuccessful(ExtensionContext context) { + LOG.info("Test Successful for test {}: ", context.getDisplayName()); + + testResultsStatus.add(TestResultStatus.SUCCESSFUL); + } + + @Override + public void testAborted(ExtensionContext context, Throwable cause) { + LOG.info("Test Aborted for test {}: ", context.getDisplayName()); + + testResultsStatus.add(TestResultStatus.ABORTED); + } + + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + LOG.info("Test Aborted for test {}: ", context.getDisplayName()); + + testResultsStatus.add(TestResultStatus.FAILED); + } + + @Override + public void afterAll(ExtensionContext context) throws Exception { + Map summary = testResultsStatus.stream() + .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); + + LOG.info("Test result summary for {} {}", context.getDisplayName(), summary.toString()); + } + +} diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestWatcherAPIUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestWatcherAPIUnitTest.java new file mode 100644 index 0000000000..89666cf9b8 --- /dev/null +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/extensions/testwatcher/TestWatcherAPIUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.extensions.testwatcher; + +import static org.junit.jupiter.api.Assertions.fail; + +import org.junit.Assert; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +@ExtendWith(TestResultLoggerExtension.class) +class TestWatcherAPIUnitTest { + + @Test + void givenFalseIsTrue_whenTestAbortedThenCaptureResult() { + Assumptions.assumeTrue(false); + } + + @Disabled + @Test + void givenTrueIsTrue_whenTestDisabledThenCaptureResult() { + Assert.assertTrue(true); + } + + @Test + void givenTrueIsTrue_whenTestAbortedThenCaptureResult() { + Assumptions.assumeTrue(true); + } + + @Disabled("This test is disabled") + @Test + void givenFailure_whenTestDisabledWithReason_ThenCaptureResult() { + fail("Not yet implemented"); + } + +} From 65183f082ddc79b9b41928feabcd259eba98e982 Mon Sep 17 00:00:00 2001 From: Steven van Beelen Date: Wed, 10 Jul 2019 13:26:48 +0200 Subject: [PATCH 156/352] Update Axon dependency Update the Axon Framework version to 4.1.1. Additionally, drop the exclusion on axon-server-connector, as the page will be adjusted to use Axon Server SE. BAEL-2345 --- axon/pom.xml | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/axon/pom.xml b/axon/pom.xml index 2b9ac1fcdd..002701373f 100644 --- a/axon/pom.xml +++ b/axon/pom.xml @@ -18,12 +18,6 @@ org.axonframework axon-spring-boot-starter ${axon.version} - - - org.axonframework - axon-server-connector - - @@ -58,7 +52,7 @@ - 4.0.3 + 4.1.1 \ No newline at end of file From 97ab7130240d8995a9710ce53c611d4e51044627 Mon Sep 17 00:00:00 2001 From: Steven van Beelen Date: Wed, 10 Jul 2019 13:27:50 +0200 Subject: [PATCH 157/352] Create dedicated UnconfirmedOrderException Create a dedicated UnconfirmedOrderException and use it from the OrderAggregate instead of the IllegalStateException BAEL-2435 --- .../com/baeldung/axon/commandmodel/OrderAggregate.java | 7 ++++--- .../coreapi/exceptions/UnconfirmedOrderException.java | 8 ++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java diff --git a/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java b/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java index b37b2fdd66..4ef02e6b54 100644 --- a/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java +++ b/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java @@ -13,6 +13,7 @@ import com.baeldung.axon.coreapi.commands.ShipOrderCommand; import com.baeldung.axon.coreapi.events.OrderConfirmedEvent; import com.baeldung.axon.coreapi.events.OrderPlacedEvent; import com.baeldung.axon.coreapi.events.OrderShippedEvent; +import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException; @Aggregate public class OrderAggregate { @@ -34,7 +35,7 @@ public class OrderAggregate { @CommandHandler public void handle(ShipOrderCommand command) { if (!orderConfirmed) { - throw new IllegalStateException("Cannot ship an order which has not been confirmed yet."); + throw new UnconfirmedOrderException(); } apply(new OrderShippedEvent(orderId)); @@ -43,12 +44,12 @@ public class OrderAggregate { @EventSourcingHandler public void on(OrderPlacedEvent event) { this.orderId = event.getOrderId(); - orderConfirmed = false; + this.orderConfirmed = false; } @EventSourcingHandler public void on(OrderConfirmedEvent event) { - orderConfirmed = true; + this.orderConfirmed = true; } protected OrderAggregate() { diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java b/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java new file mode 100644 index 0000000000..1873bc6893 --- /dev/null +++ b/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java @@ -0,0 +1,8 @@ +package com.baeldung.axon.coreapi.exceptions; + +public class UnconfirmedOrderException extends IllegalStateException { + + public UnconfirmedOrderException() { + super("Cannot ship an order which has not been confirmed yet."); + } +} From 496c2b173760e6f6a8047ac0ff8627615b2cd366 Mon Sep 17 00:00:00 2001 From: Steven van Beelen Date: Wed, 10 Jul 2019 13:37:28 +0200 Subject: [PATCH 158/352] Add ProcessingGroup annotation to OrderedProductsEventHandler Add the ProcessingGroup annotation to OrderedProductsEventHandler so that this event handler is grouped in a nicely named Event Processor. If the app is started in conjunction with Axon Server, this will make the set up more evident from the dashboard BAEL-2435 --- .../baeldung/axon/querymodel/OrderedProductsEventHandler.java | 2 ++ axon/src/main/resources/application.properties | 1 + 2 files changed, 3 insertions(+) create mode 100644 axon/src/main/resources/application.properties diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java b/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java index d4cf3d999b..a37f0111ed 100644 --- a/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java +++ b/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java @@ -5,6 +5,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.axonframework.config.ProcessingGroup; import org.axonframework.eventhandling.EventHandler; import org.axonframework.queryhandling.QueryHandler; import org.springframework.stereotype.Service; @@ -16,6 +17,7 @@ import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery; import com.baeldung.axon.coreapi.queries.OrderedProduct; @Service +@ProcessingGroup("ordered-products") public class OrderedProductsEventHandler { private final Map orderedProducts = new HashMap<>(); diff --git a/axon/src/main/resources/application.properties b/axon/src/main/resources/application.properties new file mode 100644 index 0000000000..7c51eb8e1e --- /dev/null +++ b/axon/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=Order Management Service \ No newline at end of file From 7ebf52f4090015a46ac0abca49f86aac2c24493a Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Wed, 10 Jul 2019 20:22:01 +0530 Subject: [PATCH 159/352] Adding source code for tutorial tracked by BAEL-2971 (#7250) * Adding source code for tutorial tracked by BAEL-2971 * Renaming Integration Test as par standard --- morphia/README.md | 3 + morphia/pom.xml | 43 ++++++ .../com/baeldung/morphia/domain/Author.java | 31 +++++ .../com/baeldung/morphia/domain/Book.java | 116 ++++++++++++++++ .../baeldung/morphia/domain/Publisher.java | 70 ++++++++++ morphia/src/main/resources/logback.xml | 13 ++ .../morphia/MorphiaIntegrationTest.java | 130 ++++++++++++++++++ pom.xml | 2 + 8 files changed, 408 insertions(+) create mode 100644 morphia/README.md create mode 100644 morphia/pom.xml create mode 100644 morphia/src/main/java/com/baeldung/morphia/domain/Author.java create mode 100644 morphia/src/main/java/com/baeldung/morphia/domain/Book.java create mode 100644 morphia/src/main/java/com/baeldung/morphia/domain/Publisher.java create mode 100644 morphia/src/main/resources/logback.xml create mode 100644 morphia/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java diff --git a/morphia/README.md b/morphia/README.md new file mode 100644 index 0000000000..008cf76c49 --- /dev/null +++ b/morphia/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Intro to Morphia](http://www.baeldung.com/intro-to-morphia) diff --git a/morphia/pom.xml b/morphia/pom.xml new file mode 100644 index 0000000000..e4010a26a1 --- /dev/null +++ b/morphia/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + com.baeldung.morphia + morphia + morphia + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + + dev.morphia.morphia + core + ${morphia.version} + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot-maven-plugin.version} + + + + + + + 1.4.2.RELEASE + 1.5.3 + + + diff --git a/morphia/src/main/java/com/baeldung/morphia/domain/Author.java b/morphia/src/main/java/com/baeldung/morphia/domain/Author.java new file mode 100644 index 0000000000..b45aee6068 --- /dev/null +++ b/morphia/src/main/java/com/baeldung/morphia/domain/Author.java @@ -0,0 +1,31 @@ +package com.baeldung.morphia.domain; + +import java.util.List; + +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Id; + +@Entity +public class Author { + + @Id + private String name; + private List books; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + +} diff --git a/morphia/src/main/java/com/baeldung/morphia/domain/Book.java b/morphia/src/main/java/com/baeldung/morphia/domain/Book.java new file mode 100644 index 0000000000..172c916ad9 --- /dev/null +++ b/morphia/src/main/java/com/baeldung/morphia/domain/Book.java @@ -0,0 +1,116 @@ +package com.baeldung.morphia.domain; + +import java.util.HashSet; +import java.util.Set; + +import dev.morphia.annotations.Embedded; +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Field; +import dev.morphia.annotations.Id; +import dev.morphia.annotations.Index; +import dev.morphia.annotations.IndexOptions; +import dev.morphia.annotations.Indexes; +import dev.morphia.annotations.Property; +import dev.morphia.annotations.Reference; +import dev.morphia.annotations.Validation; + +@Entity("Books") +@Indexes({ @Index(fields = @Field("title"), options = @IndexOptions(name = "book_title")) }) +@Validation("{ price : { $gt : 0 } }") +public class Book { + @Id + private String isbn; + @Property + private String title; + private String author; + @Embedded + private Publisher publisher; + @Property("price") + private double cost; + @Reference + private Set companionBooks; + + public Book() { + + } + + public String getTitle() { + return title; + } + + public String getAuthor() { + return author; + } + + public double getCost() { + return cost; + } + + public void addCompanionBooks(Book book) { + if (companionBooks != null) + this.companionBooks.add(book); + } + + public Book(String isbn, String title, String author, double cost, Publisher publisher) { + this.isbn = isbn; + this.title = title; + this.author = author; + this.cost = cost; + this.publisher = publisher; + this.companionBooks = new HashSet<>(); + } + + @Override + public String toString() { + return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((author == null) ? 0 : author.hashCode()); + long temp; + temp = Double.doubleToLongBits(cost); + result = prime * result + (int) (temp ^ (temp >>> 32)); + result = prime * result + ((isbn == null) ? 0 : isbn.hashCode()); + result = prime * result + ((publisher == null) ? 0 : publisher.hashCode()); + result = prime * result + ((title == null) ? 0 : title.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Book other = (Book) obj; + if (author == null) { + if (other.author != null) + return false; + } else if (!author.equals(other.author)) + return false; + if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost)) + return false; + if (isbn == null) { + if (other.isbn != null) + return false; + } else if (!isbn.equals(other.isbn)) + return false; + if (publisher == null) { + if (other.publisher != null) + return false; + } else if (!publisher.equals(other.publisher)) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + return true; + } + +} \ No newline at end of file diff --git a/morphia/src/main/java/com/baeldung/morphia/domain/Publisher.java b/morphia/src/main/java/com/baeldung/morphia/domain/Publisher.java new file mode 100644 index 0000000000..b9e054e9ab --- /dev/null +++ b/morphia/src/main/java/com/baeldung/morphia/domain/Publisher.java @@ -0,0 +1,70 @@ +package com.baeldung.morphia.domain; + +import org.bson.types.ObjectId; + +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Id; + +@Entity +public class Publisher { + + @Id + private ObjectId id; + private String name; + + public Publisher() { + + } + + public Publisher(ObjectId id, String name) { + this.id = id; + this.name = name; + } + + public ObjectId getId() { + return id; + } + + public void setId(ObjectId id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Catalog [id=" + id + ", name=" + name + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Publisher other = (Publisher) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + +} diff --git a/morphia/src/main/resources/logback.xml b/morphia/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/morphia/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/morphia/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java b/morphia/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java new file mode 100644 index 0000000000..a2542a56ab --- /dev/null +++ b/morphia/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java @@ -0,0 +1,130 @@ +package com.baeldung.morphia; + +import static dev.morphia.aggregation.Group.grouping; +import static dev.morphia.aggregation.Group.push; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Iterator; +import java.util.List; + +import org.bson.types.ObjectId; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import com.baeldung.morphia.domain.Author; +import com.baeldung.morphia.domain.Book; +import com.baeldung.morphia.domain.Publisher; +import com.mongodb.MongoClient; + +import dev.morphia.Datastore; +import dev.morphia.Morphia; +import dev.morphia.query.Query; +import dev.morphia.query.UpdateOperations; + +@Ignore +public class MorphiaIntegrationTest { + + private static Datastore datastore; + private static ObjectId id = new ObjectId(); + + @BeforeClass + public static void setUp() { + Morphia morphia = new Morphia(); + morphia.mapPackage("com.baeldung.morphia"); + datastore = morphia.createDatastore(new MongoClient(), "library"); + datastore.ensureIndexes(); + } + + @Test + public void givenDataSource_whenCreateEntity_thenEntityCreated() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); + Book companionBook = new Book("9789332575103", "Java Performance Companion", "Tom Kirkman", 1.95, publisher); + book.addCompanionBooks(companionBook); + datastore.save(companionBook); + datastore.save(book); + + List books = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java") + .find() + .toList(); + assertEquals(books.size(), 1); + assertEquals(books.get(0), book); + } + + @Test + public void givenDocument_whenUpdated_thenUpdateReflected() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); + datastore.save(book); + Query query = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java"); + UpdateOperations updates = datastore.createUpdateOperations(Book.class) + .inc("price", 1); + datastore.update(query, updates); + List books = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java") + .find() + .toList(); + assertEquals(books.get(0) + .getCost(), 4.95); + } + + @Test + public void givenDocument_whenDeleted_thenDeleteReflected() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); + datastore.save(book); + Query query = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java"); + datastore.delete(query); + List books = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java") + .find() + .toList(); + assertEquals(books.size(), 0); + } + + @Test + public void givenDocument_whenAggregated_thenResultsCollected() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + datastore.save(new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher)); + datastore.save(new Book("9781449313142", "Learning Perl", "Mark Pence", 2.95, publisher)); + datastore.save(new Book("9787564100476", "Learning Python", "Mark Pence", 5.95, publisher)); + datastore.save(new Book("9781449368814", "Learning Scala", "Mark Pence", 6.95, publisher)); + datastore.save(new Book("9781784392338", "Learning Go", "Jonathan Sawyer", 8.95, publisher)); + + Iterator authors = datastore.createAggregation(Book.class) + .group("author", grouping("books", push("title"))) + .out(Author.class); + + assertTrue(authors.hasNext()); + + } + + @Test + public void givenDocument_whenProjected_thenOnlyProjectionReceived() { + Publisher publisher = new Publisher(id, "Awsome Publisher"); + Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); + datastore.save(book); + List books = datastore.createQuery(Book.class) + .field("title") + .contains("Learning Java") + .project("title", true) + .find() + .toList(); + assertEquals(books.size(), 1); + assertEquals("Learning Java", books.get(0) + .getTitle()); + assertEquals(null, books.get(0) + .getAuthor()); + } + +} diff --git a/pom.xml b/pom.xml index b4fed5150d..f24a307d9e 100644 --- a/pom.xml +++ b/pom.xml @@ -558,6 +558,7 @@ tensorflow-java spring-boot-flowable spring-security-kerberos + morphia @@ -791,6 +792,7 @@ tensorflow-java spring-boot-flowable spring-security-kerberos + morphia From 4518645a1f37f734fe7599b906d2759aa31fc313 Mon Sep 17 00:00:00 2001 From: enpy Date: Thu, 11 Jul 2019 08:35:55 +0200 Subject: [PATCH 160/352] BAEL-1780 (#7237) * Singleton injection examples and tests added * code and tests implemented * test refactored * kotlin + jee * kotlin - integration test fixed * fixes * arquillian-kotlin integration fixed * formatting * formatting * data class enhanced --- jee-kotlin/README.md | 1 + jee-kotlin/pom.xml | 289 ++++++++++++++++++ .../com/baeldung/jeekotlin/entity/Student.kt | 22 ++ .../jeekotlin/rest/ApplicationConfig.kt | 9 + .../jeekotlin/rest/StudentResource.kt | 42 +++ .../jeekotlin/service/StudentService.kt | 21 ++ .../main/resources/META-INF/persistence.xml | 18 ++ jee-kotlin/src/main/webapp/WEB-INF/beans.xml | 8 + .../StudentResourceIntegrationTest.java | 108 +++++++ jee-kotlin/src/test/resources/arquillian.xml | 22 ++ 10 files changed, 540 insertions(+) create mode 100644 jee-kotlin/README.md create mode 100644 jee-kotlin/pom.xml create mode 100644 jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt create mode 100644 jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt create mode 100644 jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt create mode 100644 jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt create mode 100644 jee-kotlin/src/main/resources/META-INF/persistence.xml create mode 100644 jee-kotlin/src/main/webapp/WEB-INF/beans.xml create mode 100644 jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java create mode 100644 jee-kotlin/src/test/resources/arquillian.xml diff --git a/jee-kotlin/README.md b/jee-kotlin/README.md new file mode 100644 index 0000000000..7d843af9ea --- /dev/null +++ b/jee-kotlin/README.md @@ -0,0 +1 @@ +### Relevant Articles: diff --git a/jee-kotlin/pom.xml b/jee-kotlin/pom.xml new file mode 100644 index 0000000000..963c03d0df --- /dev/null +++ b/jee-kotlin/pom.xml @@ -0,0 +1,289 @@ + + + + 4.0.0 + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + jee-kotlin + jee-kotlin + war + + + UTF-8 + false + 8.0 + + + 1.3.41 + official + true + + + 8.2.1.Final + 3.2.3 + 2.21.0 + 3.1.1 + + 1.4.1.Final + 2.0.1.Final + 1.0.0.Alpha4 + + 4.12 + 3.8.0.Final + 2.9.8 + 3.1.3 + + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-test-junit + ${kotlin.version} + test + + + junit + junit + ${junit.version} + test + + + javax + javaee-api + ${javaee-api.version} + jar + provided + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + test + + + org.jboss.arquillian.junit + arquillian-junit-container + ${arquillian_core.version} + test + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-depchain + ${shrinkwrap.version} + pom + test + + + org.jboss.arquillian.extension + arquillian-rest-client-impl-jersey + ${arquillian-rest-client.version} + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + + + src/main/kotlin + src/test/kotlin + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + ${mvn-war-plugin.version} + + webapp + kotlin + + + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + none + + + default-testCompile + none + + + compile + compile + + compile + + + + testCompile + test-compile + + testCompile + + + + + + + + + + + org.jboss.arquillian + arquillian-bom + ${arquillian_core.version} + import + pom + + + org.jboss.arquillian.extension + arquillian-drone-bom + ${arquillian-drone-bom.version} + pom + import + + + + + + + wildfly-managed-arquillian + + true + + + + org.wildfly + wildfly-arquillian-container-embedded + ${wildfly.version} + + + org.wildfly + wildfly-embedded + ${wildfly.version} + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + ${maven-dependency-plugin.version} + + + unpack + process-test-classes + + unpack + + + + + org.wildfly + wildfly-dist + ${wildfly.version} + zip + false + target + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + always + + org.jboss.logmanager.LogManager + ${project.basedir}/target/wildfly-${wildfly.version} + ${project.basedir}/target/wildfly-${wildfly.version}/modules + + false + + + + + + + wildfly-remote-arquillian + + + org.jboss.resteasy + resteasy-client + ${resteasy.version} + test + + + org.jboss.resteasy + resteasy-jaxb-provider + ${resteasy.version} + test + + + org.jboss.resteasy + resteasy-json-p-provider + ${resteasy.version} + test + + + org.wildfly.arquillian + wildfly-arquillian-container-remote + 2.2.0.Final + test + + + + + diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt new file mode 100644 index 0000000000..07f54a39d1 --- /dev/null +++ b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt @@ -0,0 +1,22 @@ +package com.baeldung.jeekotlin.entity + +import com.fasterxml.jackson.annotation.JsonProperty +import javax.persistence.* + +@Entity +data class Student constructor ( + + @SequenceGenerator(name = "student_id_seq", sequenceName = "student_id_seq", allocationSize = 1) + @GeneratedValue(generator = "student_id_seq", strategy = GenerationType.SEQUENCE) + @Id + var id: Long?, + + var firstName: String, + + var lastName: String + +) { + constructor() : this(null, "", "") + + constructor(firstName: String, lastName: String) : this(null, firstName, lastName) +} diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt new file mode 100644 index 0000000000..12511ed320 --- /dev/null +++ b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt @@ -0,0 +1,9 @@ +package com.baeldung.jeekotlin.rest + +import javax.ws.rs.ApplicationPath +import javax.ws.rs.core.Application + +@ApplicationPath("/") +class ApplicationConfig : Application() { + override fun getClasses() = setOf(StudentResource::class.java) +} diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt new file mode 100644 index 0000000000..91fa3ff62b --- /dev/null +++ b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt @@ -0,0 +1,42 @@ +package com.baeldung.jeekotlin.rest + +import com.baeldung.jeekotlin.entity.Student +import com.baeldung.jeekotlin.service.StudentService +import javax.inject.Inject +import javax.ws.rs.* +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response + +@Path("/student") +open class StudentResource { + + @Inject + private lateinit var service: StudentService + + @POST + open fun create(student: Student): Response { + service.create(student) + return Response.ok().build() + } + + @GET + @Path("/{id}") + open fun read(@PathParam("id") id: Long): Response { + val student = service.read(id) + return Response.ok(student, MediaType.APPLICATION_JSON_TYPE).build() + } + + @PUT + open fun update(student: Student): Response { + service.update(student) + return Response.ok(student, MediaType.APPLICATION_JSON_TYPE).build() + } + + @DELETE + @Path("/{id}") + open fun delete(@PathParam("id") id: Long): Response { + service.delete(id) + return Response.noContent().build() + } + +} \ No newline at end of file diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt new file mode 100644 index 0000000000..3977a45e96 --- /dev/null +++ b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt @@ -0,0 +1,21 @@ +package com.baeldung.jeekotlin.service + +import com.baeldung.jeekotlin.entity.Student +import javax.ejb.Stateless +import javax.persistence.EntityManager +import javax.persistence.PersistenceContext + +@Stateless +open class StudentService { + + @PersistenceContext + private lateinit var entityManager: EntityManager + + open fun create(student: Student) = entityManager.persist(student) + + open fun read(id: Long): Student? = entityManager.find(Student::class.java, id) + + open fun update(student: Student) = entityManager.merge(student) + + open fun delete(id: Long) = entityManager.remove(read(id)) +} \ No newline at end of file diff --git a/jee-kotlin/src/main/resources/META-INF/persistence.xml b/jee-kotlin/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..daac86868b --- /dev/null +++ b/jee-kotlin/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,18 @@ + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + + java:jboss/datasources/ExampleDS + + com.enpy.entity.Student + + + + + + + + diff --git a/jee-kotlin/src/main/webapp/WEB-INF/beans.xml b/jee-kotlin/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..ae0f4bf2ee --- /dev/null +++ b/jee-kotlin/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,8 @@ + + + \ No newline at end of file diff --git a/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java b/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java new file mode 100644 index 0000000000..b91b47cb1f --- /dev/null +++ b/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java @@ -0,0 +1,108 @@ +package com.baeldung.jeekotlin; + +import com.baeldung.jeekotlin.entity.Student; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.container.test.api.RunAsClient; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.Filters; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.resolver.api.maven.Maven; +import org.junit.Test; +import org.junit.runner.RunWith; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.net.URISyntaxException; +import java.net.URL; + +import static org.junit.Assert.assertEquals; + +@RunWith(Arquillian.class) +public class StudentResourceIntegrationTest { + + @Deployment + public static WebArchive createDeployment() { + JavaArchive[] kotlinRuntime = Maven.configureResolver() + .workOffline() + .withMavenCentralRepo(true) + .withClassPathResolution(true) + .loadPomFromFile("pom.xml") + .resolve("org.jetbrains.kotlin:kotlin-stdlib") + .withTransitivity() + .as(JavaArchive.class); + + return ShrinkWrap.create(WebArchive.class, "kotlin.war") + .addPackages(true, Filters.exclude(".*Test*"), + "com.baeldung.jeekotlin" + ) + .addAsLibraries(kotlinRuntime) + .addAsResource("META-INF/persistence.xml") + .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); + } + + @Test + @RunAsClient + public void when_post__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { + String student = new ObjectMapper().writeValueAsString(new Student("firstName", "lastName")); + WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); + + Response response = webTarget + .path("/student") + .request(MediaType.APPLICATION_JSON) + .post(Entity.json(student)); + + assertEquals(200, response.getStatus()); + } + + @Test + @RunAsClient + public void when_get__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { + WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); + + Response response = webTarget + .path("/student/1") + .request(MediaType.APPLICATION_JSON) + .get(); + + assertEquals(200, response.getStatus()); + } + + @Test + @RunAsClient + public void when_put__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { + Student student = new Student("firstName", "lastName"); + student.setId(1L); + String studentJson = new ObjectMapper().writeValueAsString(student); + WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); + + Response response = webTarget + .path("/student") + .request(MediaType.APPLICATION_JSON) + .put(Entity.json(studentJson)); + + assertEquals(200, response.getStatus()); + } + + @Test + @RunAsClient + public void when_delete__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { + WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); + + Response response = webTarget + .path("/student/1") + .request() + .delete(); + + assertEquals(204, response.getStatus()); + } + +} \ No newline at end of file diff --git a/jee-kotlin/src/test/resources/arquillian.xml b/jee-kotlin/src/test/resources/arquillian.xml new file mode 100644 index 0000000000..5e6d7c54e8 --- /dev/null +++ b/jee-kotlin/src/test/resources/arquillian.xml @@ -0,0 +1,22 @@ + + + + + target/wildfly-8.2.1.Final + standalone.xml + true + 9990 + + + + + + 127.0.0.1 + 9990 + admin + pass + true + + + + \ No newline at end of file From c1afe47b93f9200cd398a20b0ae0dc434ce2badf Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 11 Jul 2019 15:03:33 +0300 Subject: [PATCH 161/352] remove exception handling --- .../mongodb/services/PhotoService.java | 20 ++++--------- .../mongodb/services/VideoService.java | 24 ++++----------- .../baeldung/mongodb/web/PhotoController.java | 17 ++++------- .../baeldung/mongodb/web/VideoController.java | 30 +++++-------------- 4 files changed, 24 insertions(+), 67 deletions(-) diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java index 685d67c40f..d8d7541c76 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java @@ -1,7 +1,6 @@ package com.baeldung.mongodb.services; import java.io.IOException; -import java.util.Optional; import org.bson.BsonBinarySubType; import org.bson.types.Binary; @@ -19,20 +18,13 @@ public class PhotoService { private PhotoRepository photoRepo; public Photo getPhoto(String id) { - Optional result = photoRepo.findById(id); - return result.isPresent() ? result.get() : null; + return photoRepo.findById(id).get(); } - public String addPhoto(String title, MultipartFile file) { - String id = null; - try { - Photo photo = new Photo(title); - photo.setImage(new Binary(BsonBinarySubType.BINARY, file.getBytes())); - photo = photoRepo.insert(photo); - id = photo.getId(); - } catch (IOException e) { - return null; - } - return id; + public String addPhoto(String title, MultipartFile file) throws IOException { + Photo photo = new Photo(title); + photo.setImage(new Binary(BsonBinarySubType.BINARY, file.getBytes())); + photo = photoRepo.insert(photo); + return photo.getId(); } } diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java index dea6540973..ade1f7c73a 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java @@ -25,31 +25,19 @@ public class VideoService { @Autowired private GridFsOperations operations; - public Video getVideo(String id) { - Video video = null; + public Video getVideo(String id) throws IllegalStateException, IOException { GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id))); - if (file != null) { - video = new Video(); - video.setTitle(file.getMetadata().get("title").toString()); - try { - video.setStream(operations.getResource(file).getInputStream()); - } catch (IOException e) { - return null; - } - } + Video video = new Video(); + video.setTitle(file.getMetadata().get("title").toString()); + video.setStream(operations.getResource(file).getInputStream()); return video; } - public String addVideo(String title, MultipartFile file) { + public String addVideo(String title, MultipartFile file) throws IOException { DBObject metaData = new BasicDBObject(); metaData.put("type", "video"); metaData.put("title", title); - ObjectId id; - try { - id = gridFsTemplate.store(file.getInputStream(), file.getName(), file.getContentType(), metaData); - } catch (IOException e) { - return null; - } + ObjectId id = gridFsTemplate.store(file.getInputStream(), file.getName(), file.getContentType(), metaData); return id.toString(); } diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java index fffb6ec320..4d5746f0d8 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java @@ -1,5 +1,6 @@ package com.baeldung.mongodb.web; +import java.io.IOException; import java.util.Base64; import org.springframework.beans.factory.annotation.Autowired; @@ -23,13 +24,9 @@ public class PhotoController { @GetMapping("/photos/{id}") public String getPhoto(@PathVariable String id, Model model) { Photo photo = photoService.getPhoto(id); - if (photo != null) { - model.addAttribute("title", photo.getTitle()); - model.addAttribute("image", Base64.getEncoder().encodeToString(photo.getImage().getData())); - return "photos"; - } - model.addAttribute("message", "Photo not found"); - return "index"; + model.addAttribute("title", photo.getTitle()); + model.addAttribute("image", Base64.getEncoder().encodeToString(photo.getImage().getData())); + return "photos"; } @GetMapping("/photos/upload") @@ -39,12 +36,8 @@ public class PhotoController { } @PostMapping("/photos/add") - public String addPhoto(@RequestParam("title") String title, @RequestParam("image") MultipartFile image, Model model) { + public String addPhoto(@RequestParam("title") String title, @RequestParam("image") MultipartFile image, Model model) throws IOException { String id = photoService.addPhoto(title, image); - if (id == null) { - model.addAttribute("message", "Error Occurred"); - return "index"; - } return "redirect:/photos/" + id; } } diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java index e5fda0cc64..313ce9e650 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java @@ -24,29 +24,17 @@ public class VideoController { private VideoService videoService; @GetMapping("/videos/{id}") - public String getVideo(@PathVariable String id, Model model) { + public String getVideo(@PathVariable String id, Model model) throws IllegalStateException, IOException { Video video = videoService.getVideo(id); - if (video != null) { - model.addAttribute("title", video.getTitle()); - model.addAttribute("url", "/videos/stream/" + id); - return "videos"; - } - model.addAttribute("message", "Video not found"); - return "index"; + model.addAttribute("title", video.getTitle()); + model.addAttribute("url", "/videos/stream/" + id); + return "videos"; } @GetMapping("/videos/stream/{id}") - public void streamVideo(@PathVariable String id, HttpServletResponse response) { + public void streamVideo(@PathVariable String id, HttpServletResponse response) throws IllegalStateException, IOException { Video video = videoService.getVideo(id); - if (video != null) { - try { - FileCopyUtils.copy(video.getStream(), response.getOutputStream()); - } catch (IOException e) { - response.setStatus(500); - } - } else { - response.setStatus(404); - } + FileCopyUtils.copy(video.getStream(), response.getOutputStream()); } @GetMapping("/videos/upload") @@ -56,12 +44,8 @@ public class VideoController { } @PostMapping("/videos/add") - public String addVideo(@RequestParam("title") String title, @RequestParam("file") MultipartFile file, Model model) { + public String addVideo(@RequestParam("title") String title, @RequestParam("file") MultipartFile file, Model model) throws IOException { String id = videoService.addVideo(title, file); - if (id == null) { - model.addAttribute("message", "Error Occurred"); - return "index"; - } return "redirect:/videos/" + id; } } From fc260052b7ad355f1dbace3bf2b11179289d4f46 Mon Sep 17 00:00:00 2001 From: Carlos Cano Date: Thu, 11 Jul 2019 19:00:34 +0200 Subject: [PATCH 162/352] Checking if an array is sorted in java (#7273) * SortedArrayChecker * add recursivity method with custom object * change test names --- .../baeldung/array/SortedArrayChecker.java | 71 ++++++++++++++++++ .../baeldung/arraycopy/model/Employee.java | 15 ++++ .../array/SortedArrayCheckerUnitTest.java | 73 +++++++++++++++++++ 3 files changed, 159 insertions(+) create mode 100644 core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java create mode 100644 core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java new file mode 100644 index 0000000000..ec612fd53b --- /dev/null +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java @@ -0,0 +1,71 @@ +package com.baeldung.array; + +import com.baeldung.arraycopy.model.Employee; + +public class SortedArrayChecker { + boolean isSorted(int[] array, int length) { + if (array == null || length < 2) + return true; + + if (array[length - 2] > array[length - 1]) + return false; + + return isSorted(array, length - 1); + } + + boolean isSorted(int[] array) { + for (int i = 0; i < array.length - 1; i++) { + if (array[i] > array[i + 1]) + return false; + } + + return true; + } + + boolean isSorted(String[] array, int length) { + if (array == null || length < 2) + return true; + + if (array[length - 2].compareTo(array[length - 1]) > 0) + return false; + + return isSorted(array, length - 1); + } + +boolean isSorted(String[] array) { + for (int i = 0; i < array.length - 1; ++i) { + if (array[i].compareTo(array[i + 1]) > 0) + return false; + } + + return true; +} + + boolean isSortedByName(Employee[] array) { + for (int i = 0; i < array.length - 1; ++i) { + if (array[i].getName().compareTo(array[i + 1].getName()) > 0) + return false; + } + + return true; + } + +boolean isSortedByAge(Employee[] array) { + for (int i = 0; i < array.length - 1; ++i) { + if (array[i].getAge() > (array[i + 1].getAge())) + return false; + } + + return true; +} + + boolean isSortedByAge(Employee[] array, int length) { + if (array == null || length < 2) + return true; + + if (array[length - 2].getAge() > array[length - 1].getAge()) + return false; + + return isSortedByAge(array, length - 1); + } +} diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java index a7592574d9..eba39d5716 100644 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/arraycopy/model/Employee.java @@ -6,6 +6,7 @@ public class Employee implements Serializable { private static final long serialVersionUID = -2454619097207585825L; private int id; private String name; + private int age; public Employee() { } @@ -15,10 +16,24 @@ public class Employee implements Serializable { this.name = name; } + public Employee(int id, String name, int age) { + this.id = id; + this.name = name; + this.age = age; + } + + public int getAge() { + return age; + } + public int getId() { return id; } + public void setAge(int age) { + this.age = age; + } + public void setId(int id) { this.id = id; } diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java new file mode 100644 index 0000000000..29866a3c22 --- /dev/null +++ b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.array; + +import com.baeldung.arraycopy.model.Employee; +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SortedArrayCheckerUnitTest { + + private static final int[] INTEGER_SORTED = {1, 3, 5, 7, 9}; + private static final int[] INTEGER_NOT_SORTED = {1, 3, 11, 7}; + + private static final String[] STRING_SORTED = {"abc", "cde", "fgh"}; + private static final String[] STRING_NOT_SORTED = {"abc", "fgh", "cde", "ijk"}; + + private final Employee[] EMPLOYEES_SORTED_BY_NAME = { + new Employee(1, "Carlos", 26), + new Employee(2, "Daniel", 31), + new Employee(3, "Marta", 27)}; + + private final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = { + new Employee(1, "Daniel", 31), + new Employee(2, "Carlos", 26), + new Employee(3, "Marta", 27)}; + + private final Employee[] EMPLOYEES_SORTED_BY_AGE = { + new Employee(1, "Carlos", 26), + new Employee(2, "Marta", 27), + new Employee(3, "Daniel", 31)}; + + private final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = { + new Employee(1, "Marta", 27), + new Employee(2, "Carlos", 26), + new Employee(3, "Daniel", 31)}; + + private SortedArrayChecker sortedArrayChecker; + + @Before + public void setup() { + sortedArrayChecker = new SortedArrayChecker(); + } + + @Test + public void givenIntegerArray_thenReturnIfItIsSortedOrNot() { + assertThat(sortedArrayChecker.isSorted(INTEGER_SORTED)).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(INTEGER_NOT_SORTED)).isEqualTo(false); + + assertThat(sortedArrayChecker.isSorted(INTEGER_SORTED, INTEGER_SORTED.length)).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(INTEGER_NOT_SORTED, INTEGER_NOT_SORTED.length)).isEqualTo(false); + } + + @Test + public void givenStringArray_thenReturnIfItIsSortedOrNot() { + assertThat(sortedArrayChecker.isSorted(STRING_SORTED)).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(STRING_NOT_SORTED)).isEqualTo(false); + + assertThat(sortedArrayChecker.isSorted(STRING_SORTED, STRING_SORTED.length)).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(STRING_NOT_SORTED, STRING_NOT_SORTED.length)).isEqualTo(false); + } + + @Test + public void givenEmployeeArray_thenReturnIfItIsSortedOrNot() { + assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_SORTED_BY_NAME)).isEqualTo(true); + assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_NOT_SORTED_BY_NAME)).isEqualTo(false); + + assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE)).isEqualTo(true); + assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE)).isEqualTo(false); + + assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE, EMPLOYEES_SORTED_BY_AGE.length)).isEqualTo(true); + assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE, EMPLOYEES_NOT_SORTED_BY_AGE.length)).isEqualTo(false); + } +} \ No newline at end of file From 9f5986963c6fc1ebcc841ca2c8183546ce0dc5ab Mon Sep 17 00:00:00 2001 From: Rodrigo Graciano Date: Thu, 11 Jul 2019 13:01:56 -0400 Subject: [PATCH 163/352] BAEL-3018 (#7230) * BAEL-3018 * BAEL-3018 * BAEL-3018 * BAEL-3018 * Replace Postgres by H2 * Resolve MongoDB conflict * Method name incorrect * Method name incorrect * Add batch example * Remove unnecesssary code at pom.xml * Organize the code in packages * Replaced Unit with Integration tests --- spring-5-data-reactive/pom.xml | 65 +++++++-- .../com/baeldung/r2dbc/R2dbcApplication.java | 15 +++ .../configuration/R2DBCConfiguration.java | 21 +++ .../java/com/baeldung/r2dbc/model/Player.java | 16 +++ .../r2dbc/repository/PlayerRepository.java | 15 +++ .../R2dbcApplicationIntegrationTest.java | 125 ++++++++++++++++++ 6 files changed, 249 insertions(+), 8 deletions(-) create mode 100644 spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/R2dbcApplication.java create mode 100644 spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java create mode 100644 spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java create mode 100644 spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java create mode 100644 spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml index 8c16851de0..056fb37a52 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -1,9 +1,9 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-5-data-reactive - spring-5-data-reactive + spring-5-data-reactive jar @@ -49,11 +49,11 @@ ${kotlin.version} test - + io.reactivex.rxjava2 rxjava - + org.springframework spring-test @@ -68,6 +68,39 @@ de.flapdoodle.embed.mongo test + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework + spring-tx + 5.2.0.M2 + + + + org.springframework.data + spring-data-r2dbc + 1.0.0.M2 + + + io.r2dbc + r2dbc-h2 + 0.8.0.M8 + + + com.h2database + h2 + 1.4.199 + + + org.springframework.boot + spring-boot-starter-test + test + + @@ -79,7 +112,7 @@ kotlin-maven-plugin ${kotlin-maven-plugin.version} - + compile @@ -123,7 +156,7 @@ - + org.apache.maven.plugins maven-compiler-plugin @@ -131,13 +164,13 @@ ${java.version} - default-compile none - default-testCompile @@ -167,5 +200,21 @@ 1.2.40 + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/R2dbcApplication.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/R2dbcApplication.java new file mode 100644 index 0000000000..557b6ff42a --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/R2dbcApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.r2dbc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = "com.baeldung.r2dbc") +public class R2dbcApplication { + + public static void main(String[] args) { + SpringApplication.run(R2dbcApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java new file mode 100644 index 0000000000..17eac7fee2 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/configuration/R2DBCConfiguration.java @@ -0,0 +1,21 @@ +package com.baeldung.r2dbc.configuration; + +import io.r2dbc.h2.H2ConnectionConfiguration; +import io.r2dbc.h2.H2ConnectionFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration; +import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories; + +@Configuration +//@EnableR2dbcRepositories(basePackages = "com.baeldung.r2dbc.repository") +public class R2DBCConfiguration extends AbstractR2dbcConfiguration { + @Bean + public H2ConnectionFactory connectionFactory() { + return new H2ConnectionFactory( + H2ConnectionConfiguration.builder() + .url("mem:testdb;DB_CLOSE_DELAY=-1;TRACE_LEVEL_FILE=4") + .username("sa") + .build()); + } +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java new file mode 100644 index 0000000000..1926997e97 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/model/Player.java @@ -0,0 +1,16 @@ +package com.baeldung.r2dbc.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.Id; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Player { + @Id + Integer id; + String name; + Integer age; +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java new file mode 100644 index 0000000000..33b653140e --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/r2dbc/repository/PlayerRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.r2dbc.repository; + +import com.baeldung.r2dbc.model.Player; +import org.springframework.data.r2dbc.repository.query.Query; +import org.springframework.data.repository.reactive.ReactiveCrudRepository; +import reactor.core.publisher.Flux; + +public interface PlayerRepository extends ReactiveCrudRepository { + + @Query("select id, name, age from player where name = $1") + Flux findAllByName(String name); + + @Query("select * from player where age = $1") + Flux findByAge(int age); +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java new file mode 100644 index 0000000000..a31ef4458d --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/r2dbc/R2dbcApplicationIntegrationTest.java @@ -0,0 +1,125 @@ +package com.baeldung.r2dbc; + + +import com.baeldung.r2dbc.model.Player; +import com.baeldung.r2dbc.repository.PlayerRepository; +import io.r2dbc.h2.H2ConnectionFactory; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.r2dbc.core.DatabaseClient; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Hooks; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.util.Arrays; +import java.util.List; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class R2dbcApplicationIntegrationTest { + + + @Autowired + PlayerRepository playerRepository; + + @Autowired + DatabaseClient client; + + @Autowired + H2ConnectionFactory factory; + + + @Before + public void setup() { + + Hooks.onOperatorDebug(); + + List statements = Arrays.asList(// + "DROP TABLE IF EXISTS player;", + "CREATE table player (id INT AUTO_INCREMENT NOT NULL, name VARCHAR2, age INT NOT NULL);"); + + statements.forEach(it -> client.execute() // + .sql(it) // + .fetch() // + .rowsUpdated() // + .as(StepVerifier::create) // + .expectNextCount(1) // + .verifyComplete()); + + } + + @Test + public void whenDeleteAll_then0IsExpected() { + + + playerRepository.deleteAll() + .as(StepVerifier::create) + .expectNextCount(0) + .verifyComplete(); + } + + @Test + public void whenInsert6_then6AreExpected() { + + insertPlayers(); + + playerRepository.findAll() + .as(StepVerifier::create) + .expectNextCount(6) + .verifyComplete(); + } + + @Test + public void whenSearchForCR7_then1IsExpected() { + + insertPlayers(); + + playerRepository.findAllByName("CR7") + .as(StepVerifier::create) + .expectNextCount(1) + .verifyComplete(); + } + + @Test + public void whenSearchFor32YearsOld_then2AreExpected() { + insertPlayers(); + + playerRepository.findByAge(32) + .as(StepVerifier::create) + .expectNextCount(2) + .verifyComplete(); + } + + @Test + public void whenBatchHas2Operations_then2AreExpected() { + Mono.from(factory.create()) + .flatMapMany(connection -> Flux.from(connection + .createBatch() + .add("select * from player") + .add("select * from player") + .execute())) + .as(StepVerifier::create) + .expectNextCount(2) + .verifyComplete(); + + } + + private void insertPlayers() { + List players = Arrays.asList( + new Player(1, "Kaka", 37), + new Player(2, "Messi", 32), + new Player(3, "Mbappé", 20), + new Player(4, "CR7", 34), + new Player(5, "Lewandowski", 30), + new Player(6, "Cavani", 32) + ); + + playerRepository.saveAll(players).subscribe(); + } +} + From 8791269ec70c289acf55691a96a8a0efe19f3352 Mon Sep 17 00:00:00 2001 From: codehunter34 <31874661+codehunter34@users.noreply.github.com> Date: Thu, 11 Jul 2019 13:03:59 -0400 Subject: [PATCH 164/352] BAEL-2850: Difference between vs (#7291) * BAEL-2850: Difference between vs * BAEL-2850: Difference between vs --- .../components/AccountService.java | 2 +- .../components/UserService.java | 2 +- ...{beans.xml => annotationconfigvscomponentscan-beans.xml} | 6 +++--- .../com/baeldung/SpringXMLConfigurationIntegrationTest.java | 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) rename spring-5/src/main/java/com/baeldung/{ => annotationconfigvscomponentscan}/components/AccountService.java (59%) rename spring-5/src/main/java/com/baeldung/{ => annotationconfigvscomponentscan}/components/UserService.java (82%) rename spring-5/src/main/resources/{beans.xml => annotationconfigvscomponentscan-beans.xml} (68%) diff --git a/spring-5/src/main/java/com/baeldung/components/AccountService.java b/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/AccountService.java similarity index 59% rename from spring-5/src/main/java/com/baeldung/components/AccountService.java rename to spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/AccountService.java index c2f09c735e..1997163954 100644 --- a/spring-5/src/main/java/com/baeldung/components/AccountService.java +++ b/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/AccountService.java @@ -1,4 +1,4 @@ -package com.baeldung.components; +package com.baeldung.annotationconfigvscomponentscan.components; import org.springframework.stereotype.Component; diff --git a/spring-5/src/main/java/com/baeldung/components/UserService.java b/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/UserService.java similarity index 82% rename from spring-5/src/main/java/com/baeldung/components/UserService.java rename to spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/UserService.java index 80e5e0c632..8dd5ae2ef0 100644 --- a/spring-5/src/main/java/com/baeldung/components/UserService.java +++ b/spring-5/src/main/java/com/baeldung/annotationconfigvscomponentscan/components/UserService.java @@ -1,4 +1,4 @@ -package com.baeldung.components; +package com.baeldung.annotationconfigvscomponentscan.components; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-5/src/main/resources/beans.xml b/spring-5/src/main/resources/annotationconfigvscomponentscan-beans.xml similarity index 68% rename from spring-5/src/main/resources/beans.xml rename to spring-5/src/main/resources/annotationconfigvscomponentscan-beans.xml index 004745b817..ee4bbb6573 100644 --- a/spring-5/src/main/resources/beans.xml +++ b/spring-5/src/main/resources/annotationconfigvscomponentscan-beans.xml @@ -4,11 +4,11 @@ - + - + - + diff --git a/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java index 4ecad9c43e..7cd7b81def 100644 --- a/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/SpringXMLConfigurationIntegrationTest.java @@ -5,14 +5,14 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import com.baeldung.components.AccountService; -import com.baeldung.components.UserService; +import com.baeldung.annotationconfigvscomponentscan.components.AccountService; +import com.baeldung.annotationconfigvscomponentscan.components.UserService; public class SpringXMLConfigurationIntegrationTest { @Test public void givenContextAnnotationConfigOrContextComponentScan_whenDependenciesAndBeansAnnotated_thenNoXMLNeeded() { - ApplicationContext context = new ClassPathXmlApplicationContext("classpath:beans.xml"); + ApplicationContext context = new ClassPathXmlApplicationContext("classpath:annotationconfigvscomponentscan-beans.xml"); UserService userService = context.getBean(UserService.class); AccountService accountService = context.getBean(AccountService.class); Assert.assertNotNull(userService); From 7e94de61a95380f26376332bb87de1f13135a5fd Mon Sep 17 00:00:00 2001 From: Sumeet Gajbhar Date: Fri, 12 Jul 2019 02:17:11 +0530 Subject: [PATCH 165/352] BAEL-2885 Spring Cloud Stream with Kakfa (#7114) * BAEL-2927 added logging configuration for tomcat logs * BAEL-2885 coding done * BAEL-2885 formating done * BAEL-2885 scheam namespace fixed * fixed logback issue and added group name in config * updated code to use the correct header for partition key * removed the partition count * updated the code for given comments * BAEL-2885 removed the schema registry client dependency --- .../spring-cloud-stream-kafka/pom.xml | 109 ++++++++++++++++++ .../com/baeldung/AvroKafkaApplication.java | 18 +++ .../baeldung/config/SchemRegistryConfig.java | 18 +++ .../com/baeldung/consumer/AvroConsumer.java | 21 ++++ .../baeldung/controller/AvroController.java | 22 ++++ .../com/baeldung/producer/AvroProducer.java | 42 +++++++ .../src/main/resources/application.yaml | 29 +++++ .../main/resources/employee-key-schema.avsc | 14 +++ .../src/main/resources/employee-schema.avsc | 29 +++++ 9 files changed, 302 insertions(+) create mode 100644 spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml create mode 100644 spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/AvroKafkaApplication.java create mode 100644 spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/config/SchemRegistryConfig.java create mode 100644 spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/consumer/AvroConsumer.java create mode 100644 spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/controller/AvroController.java create mode 100644 spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/producer/AvroProducer.java create mode 100644 spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/application.yaml create mode 100644 spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-key-schema.avsc create mode 100644 spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-schema.avsc diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml new file mode 100644 index 0000000000..13ad18810e --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml @@ -0,0 +1,109 @@ + + 4.0.0 + + + spring-cloud-stream-kafka + spring-cloud-stream-kafka + Simple Spring Cloud Stream + jar + + + org.springframework.boot + spring-boot-starter-parent + 2.1.5.RELEASE + + + + 1.8 + Greenwich.SR1 + + + + + + org.springframework.cloud + spring-cloud-stream-binder-kafka + + + + org.springframework.cloud + spring-cloud-stream-schema + + + + org.springframework.cloud + spring-cloud-stream-test-support + test + + + + io.confluent + kafka-avro-serializer + 4.0.0 + + + + org.apache.avro + avro-compiler + 1.8.2 + + + + org.apache.avro + avro-maven-plugin + 1.8.2 + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.avro + avro-maven-plugin + 1.8.2 + + + schemas + generate-sources + + schema + protocol + idl-protocol + + + ${project.basedir}/src/main/resources/ + ${project.basedir}/src/main/java/ + + + + + + + + + + confluent + https://packages.confluent.io/maven/ + + + + diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/AvroKafkaApplication.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/AvroKafkaApplication.java new file mode 100644 index 0000000000..47c060c143 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/AvroKafkaApplication.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.stream.annotation.EnableBinding; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.cloud.stream.schema.client.EnableSchemaRegistryClient; + +@SpringBootApplication +@EnableBinding(Processor.class) +@EnableSchemaRegistryClient +public class AvroKafkaApplication { + + public static void main(String[] args) { + SpringApplication.run(AvroKafkaApplication.class, args); + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/config/SchemRegistryConfig.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/config/SchemRegistryConfig.java new file mode 100644 index 0000000000..38ac94d952 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/config/SchemRegistryConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.stream.schema.client.ConfluentSchemaRegistryClient; +import org.springframework.cloud.stream.schema.client.SchemaRegistryClient; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SchemRegistryConfig { + + @Bean + public SchemaRegistryClient schemaRegistryClient(@Value("${spring.cloud.stream.kafka.binder.producer-properties.schema.registry.url}") String endPoint) { + ConfluentSchemaRegistryClient client = new ConfluentSchemaRegistryClient(); + client.setEndpoint(endPoint); + return client; + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/consumer/AvroConsumer.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/consumer/AvroConsumer.java new file mode 100644 index 0000000000..477946dd73 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/consumer/AvroConsumer.java @@ -0,0 +1,21 @@ +package com.baeldung.consumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.stream.annotation.StreamListener; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.stereotype.Service; + +import com.baeldung.schema.Employee; + +@Service +public class AvroConsumer { + + private static final Logger LOGGER = LoggerFactory.getLogger(AvroConsumer.class); + + @StreamListener(Processor.INPUT) + public void consumeEmployeeDetails(Employee employeeDetails) { + LOGGER.info("Let's process employee details: {}", employeeDetails); + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/controller/AvroController.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/controller/AvroController.java new file mode 100644 index 0000000000..b98b27c9fe --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/controller/AvroController.java @@ -0,0 +1,22 @@ +package com.baeldung.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.producer.AvroProducer; + +@RestController +public class AvroController { + + @Autowired + private AvroProducer avroProducer; + + @PostMapping("/employees/{id}/{firstName}/{lastName}") + public String producerAvroMessage(@PathVariable int id, @PathVariable String firstName, @PathVariable String lastName) { + avroProducer.produceEmployeeDetails(id, firstName, lastName); + return "Sent employee details to consumer"; + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/producer/AvroProducer.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/producer/AvroProducer.java new file mode 100644 index 0000000000..ff7729dd8c --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/java/com/baeldung/producer/AvroProducer.java @@ -0,0 +1,42 @@ +package com.baeldung.producer; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.messaging.Message; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.stereotype.Service; + +import com.baeldung.schema.Employee; +import com.baeldung.schema.EmployeeKey; + +@Service +public class AvroProducer { + + @Autowired + private Processor processor; + + public void produceEmployeeDetails(int empId, String firstName, String lastName) { + + // creating employee details + Employee employee = new Employee(); + employee.setId(empId); + employee.setFirstName(firstName); + employee.setLastName(lastName); + employee.setDepartment("IT"); + employee.setDesignation("Engineer"); + + // creating partition key for kafka topic + EmployeeKey employeeKey = new EmployeeKey(); + employeeKey.setId(empId); + employeeKey.setDepartmentName("IT"); + + Message message = MessageBuilder.withPayload(employee) + .setHeader(KafkaHeaders.MESSAGE_KEY, employeeKey) + .build(); + + processor.output() + .send(message); + } + +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/application.yaml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/application.yaml new file mode 100644 index 0000000000..2e30c07374 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/application.yaml @@ -0,0 +1,29 @@ +spring: + cloud: + stream: + default: + producer: + useNativeEncoding: true + consumer: + useNativeEncoding: true + bindings: + input: + destination: employee-details + content-type: application/*+avro + group: group-1 + concurrency: 3 + output: + destination: employee-details + content-type: application/*+avro + kafka: + binder: + producer-properties: + key.serializer: io.confluent.kafka.serializers.KafkaAvroSerializer + value.serializer: io.confluent.kafka.serializers.KafkaAvroSerializer + schema.registry.url: http://localhost:8081 + consumer-properties: + key.deserializer: io.confluent.kafka.serializers.KafkaAvroDeserializer + value.deserializer: io.confluent.kafka.serializers.KafkaAvroDeserializer + schema.registry.url: http://localhost:8081 + specific.avro.reader: true + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-key-schema.avsc b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-key-schema.avsc new file mode 100644 index 0000000000..d18d657e99 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-key-schema.avsc @@ -0,0 +1,14 @@ +{ + "type": "record", + "name": "EmployeeKey", + "namespace": "com.baeldung.schema", + "fields": [ + { + "name": "id", + "type": "int" + }, + { + "name": "departmentName", + "type": "string" + }] +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-schema.avsc b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-schema.avsc new file mode 100644 index 0000000000..2abf57e4a2 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/src/main/resources/employee-schema.avsc @@ -0,0 +1,29 @@ +{ + "type": "record", + "name": "Employee", + "namespace": "com.baeldung.schema", + "fields": [ + { + "name": "id", + "type": "int" + }, + { + "name": "firstName", + "type": "string" + }, + { + "name": "lastName", + "type": "string" + }, + { + "name": "department", + "type": "string", + "default": "IT " + }, + { + "name": "designation", + "type": "string", + "default": "Software Engineer" + } + ] +} \ No newline at end of file From 5216d789c4fb7feac2fed9159531f0337f48f20c Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 12 Jul 2019 09:31:12 +0200 Subject: [PATCH 166/352] BAEL-2983 move easy-random under testing-modules (#7256) * BAEL-2983 java objects generation with EasyRandom * BAEL-2983 move easy random under testing-modules --- pom.xml | 1 - {easy-random => testing-modules/easy-random}/pom.xml | 1 + .../src/main/java/org/baeldung/easy/random/model/Department.java | 0 .../src/main/java/org/baeldung/easy/random/model/Employee.java | 0 .../src/main/java/org/baeldung/easy/random/model/Grade.java | 0 .../src/main/java/org/baeldung/easy/random/model/Person.java | 0 .../main/java/org/baeldung/easy/random/model/YearQuarter.java | 0 .../baeldung/easy/random/randomizer/YearQuarterRandomizer.java | 0 .../test/java/org/baeldung/easy/random/EasyRandomUnitTest.java | 0 testing-modules/pom.xml | 1 + 10 files changed, 2 insertions(+), 1 deletion(-) rename {easy-random => testing-modules/easy-random}/pom.xml (94%) rename {easy-random => testing-modules/easy-random}/src/main/java/org/baeldung/easy/random/model/Department.java (100%) rename {easy-random => testing-modules/easy-random}/src/main/java/org/baeldung/easy/random/model/Employee.java (100%) rename {easy-random => testing-modules/easy-random}/src/main/java/org/baeldung/easy/random/model/Grade.java (100%) rename {easy-random => testing-modules/easy-random}/src/main/java/org/baeldung/easy/random/model/Person.java (100%) rename {easy-random => testing-modules/easy-random}/src/main/java/org/baeldung/easy/random/model/YearQuarter.java (100%) rename {easy-random => testing-modules/easy-random}/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java (100%) rename {easy-random => testing-modules/easy-random}/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java (100%) diff --git a/pom.xml b/pom.xml index f24a307d9e..d27c4d8a3d 100644 --- a/pom.xml +++ b/pom.xml @@ -422,7 +422,6 @@ drools dubbo - easy-random ethereum feign diff --git a/easy-random/pom.xml b/testing-modules/easy-random/pom.xml similarity index 94% rename from easy-random/pom.xml rename to testing-modules/easy-random/pom.xml index 61f0ed2cd4..93c0027f8f 100644 --- a/easy-random/pom.xml +++ b/testing-modules/easy-random/pom.xml @@ -10,6 +10,7 @@ parent-modules com.baeldung 1.0.0-SNAPSHOT + ../../ diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/Department.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Department.java similarity index 100% rename from easy-random/src/main/java/org/baeldung/easy/random/model/Department.java rename to testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Department.java diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java similarity index 100% rename from easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java rename to testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Employee.java diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java similarity index 100% rename from easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java rename to testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Grade.java diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/Person.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Person.java similarity index 100% rename from easy-random/src/main/java/org/baeldung/easy/random/model/Person.java rename to testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/Person.java diff --git a/easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java similarity index 100% rename from easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java rename to testing-modules/easy-random/src/main/java/org/baeldung/easy/random/model/YearQuarter.java diff --git a/easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java b/testing-modules/easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java similarity index 100% rename from easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java rename to testing-modules/easy-random/src/main/java/org/baeldung/easy/random/randomizer/YearQuarterRandomizer.java diff --git a/easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java b/testing-modules/easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java similarity index 100% rename from easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java rename to testing-modules/easy-random/src/test/java/org/baeldung/easy/random/EasyRandomUnitTest.java diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index bc6e23a6b7..3a1c3f3bf4 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -14,6 +14,7 @@ + easy-random gatling groovy-spock junit-5 From 6c6392a797a8039db7a95f93a2ee4f87707dd898 Mon Sep 17 00:00:00 2001 From: jemgiordano Date: Fri, 12 Jul 2019 21:02:52 +1000 Subject: [PATCH 167/352] BAEL-2798 Update to 'Scheduling in Spring with Quartz' article to add JDBC examples. --- spring-quartz/pom.xml | 13 ++++- .../basics/scheduler/QrtzScheduler.java | 55 +++++++++++++------ .../basics/scheduler/SampleJob.java | 2 +- .../basics/scheduler/SpringQrtzScheduler.java | 27 +++++++-- .../basics/service/SampleJobService.java | 15 ++++- .../src/main/resources/application.properties | 11 +++- .../src/main/resources/quartz.properties | 18 +++++- .../SpringContextIntegrationTest.java | 14 +++++ 8 files changed, 125 insertions(+), 30 deletions(-) diff --git a/spring-quartz/pom.xml b/spring-quartz/pom.xml index 58e72c1d51..4c7ac6eee9 100644 --- a/spring-quartz/pom.xml +++ b/spring-quartz/pom.xml @@ -32,6 +32,16 @@ quartz ${quartz.version} + + com.mchange + c3p0 + ${c3p0.version} + + + + com.h2database + h2 + @@ -44,7 +54,8 @@ - 2.2.3 + 2.3.0 + 0.9.5.2 \ No newline at end of file diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java index 6601df6c94..73416262ce 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java @@ -1,31 +1,32 @@ package org.baeldung.springquartz.basics.scheduler; -import static org.quartz.JobBuilder.newJob; -import static org.quartz.SimpleScheduleBuilder.simpleSchedule; -import static org.quartz.TriggerBuilder.newTrigger; - -import java.io.IOException; - -import javax.annotation.PostConstruct; - import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory; import org.quartz.*; -import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.scheduling.quartz.SpringBeanJobFactory; +import javax.annotation.PostConstruct; +import java.io.IOException; +import java.util.Properties; + +import static org.quartz.JobBuilder.newJob; +import static org.quartz.SimpleScheduleBuilder.simpleSchedule; +import static org.quartz.TriggerBuilder.newTrigger; + @Configuration @ConditionalOnExpression("'${using.spring.schedulerFactory}'=='false'") public class QrtzScheduler { - Logger logger = LoggerFactory.getLogger(getClass()); + private static final Logger logger = LoggerFactory.getLogger(QrtzScheduler.class); @Autowired private ApplicationContext applicationContext; @@ -45,14 +46,9 @@ public class QrtzScheduler { } @Bean - public Scheduler scheduler(Trigger trigger, JobDetail job) throws SchedulerException, IOException { - - StdSchedulerFactory factory = new StdSchedulerFactory(); - factory.initialize(new ClassPathResource("quartz.properties").getInputStream()); - + public Scheduler scheduler(Trigger trigger, JobDetail job, SchedulerFactoryBean factory) throws SchedulerException { logger.debug("Getting a handle to the Scheduler"); Scheduler scheduler = factory.getScheduler(); - scheduler.setJobFactory(springBeanJobFactory()); scheduler.scheduleJob(job, trigger); logger.debug("Starting Scheduler threads"); @@ -60,10 +56,29 @@ public class QrtzScheduler { return scheduler; } + @Bean + public SchedulerFactoryBean schedulerFactoryBean() throws IOException { + SchedulerFactoryBean factory = new SchedulerFactoryBean(); + factory.setJobFactory(springBeanJobFactory()); + factory.setQuartzProperties(quartzProperties()); + return factory; + } + + public Properties quartzProperties() throws IOException { + PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); + propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); + propertiesFactoryBean.afterPropertiesSet(); + return propertiesFactoryBean.getObject(); + } + @Bean public JobDetail jobDetail() { - return newJob().ofType(SampleJob.class).storeDurably().withIdentity(JobKey.jobKey("Qrtz_Job_Detail")).withDescription("Invoke Sample Job service...").build(); + return newJob().ofType(SampleJob.class) + .storeDurably() + .withIdentity(JobKey.jobKey("Qrtz_Job_Detail")) + .withDescription("Invoke Sample Job service...") + .build(); } @Bean @@ -72,6 +87,10 @@ public class QrtzScheduler { int frequencyInSec = 10; logger.info("Configuring trigger to fire every {} seconds", frequencyInSec); - return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")).withDescription("Sample trigger").withSchedule(simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()).build(); + return newTrigger().forJob(job) + .withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")) + .withDescription("Sample trigger") + .withSchedule(simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()) + .build(); } } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java index 7c50f9a231..8bfd856b86 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java @@ -12,7 +12,7 @@ import org.springframework.stereotype.Component; @Component public class SampleJob implements Job { - Logger logger = LoggerFactory.getLogger(getClass()); + private static final Logger logger = LoggerFactory.getLogger(SampleJob.class); @Autowired private SampleJobService jobService; diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java index 9978f61522..40234df1c9 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java @@ -1,7 +1,5 @@ package org.baeldung.springquartz.basics.scheduler; -import javax.annotation.PostConstruct; - import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory; import org.quartz.JobDetail; import org.quartz.SimpleTrigger; @@ -9,7 +7,11 @@ import org.quartz.Trigger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.autoconfigure.quartz.QuartzDataSource; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -19,11 +21,15 @@ import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean; import org.springframework.scheduling.quartz.SpringBeanJobFactory; +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + @Configuration +@EnableAutoConfiguration @ConditionalOnExpression("'${using.spring.schedulerFactory}'=='true'") public class SpringQrtzScheduler { - Logger logger = LoggerFactory.getLogger(getClass()); + private static final Logger logger = LoggerFactory.getLogger(SpringQrtzScheduler.class); @Autowired private ApplicationContext applicationContext; @@ -43,7 +49,9 @@ public class SpringQrtzScheduler { } @Bean - public SchedulerFactoryBean scheduler(Trigger trigger, JobDetail job) { + public SchedulerFactoryBean scheduler(Trigger trigger, + JobDetail job, + DataSource quartzDataSource) { SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean(); schedulerFactory.setConfigLocation(new ClassPathResource("quartz.properties")); @@ -53,6 +61,9 @@ public class SpringQrtzScheduler { schedulerFactory.setJobDetails(job); schedulerFactory.setTriggers(trigger); + // Comment the following line to use the default Quartz job store. + schedulerFactory.setDataSource(quartzDataSource); + return schedulerFactory; } @@ -81,4 +92,12 @@ public class SpringQrtzScheduler { trigger.setName("Qrtz_Trigger"); return trigger; } + + @Bean + @QuartzDataSource + @ConfigurationProperties(prefix = "spring.datasource") + public DataSource quartzDataSource() { + return DataSourceBuilder.create().build(); + } + } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java index ddf4efc2c5..4b976d37b0 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java @@ -4,20 +4,31 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import java.util.concurrent.atomic.AtomicInteger; + @Service public class SampleJobService { - private Logger logger = LoggerFactory.getLogger(getClass()); + public static final long EXECUTION_TIME = 5000L; + + private static final Logger logger = LoggerFactory.getLogger(SampleJobService.class); + + private AtomicInteger count = new AtomicInteger(); public void executeSampleJob() { logger.info("The sample job has begun..."); try { - Thread.sleep(5000); + Thread.sleep(EXECUTION_TIME); } catch (InterruptedException e) { logger.error("Error while executing sample job", e); } finally { + count.incrementAndGet(); logger.info("Sample job has finished..."); } } + + public int getNumberOfInvocations() { + return count.get(); + } } diff --git a/spring-quartz/src/main/resources/application.properties b/spring-quartz/src/main/resources/application.properties index 7bdd647e25..557349af2e 100644 --- a/spring-quartz/src/main/resources/application.properties +++ b/spring-quartz/src/main/resources/application.properties @@ -1 +1,10 @@ -using.spring.schedulerFactory=true \ No newline at end of file +using.spring.schedulerFactory=true + +spring.quartz.job-store-type=jdbc +# Always create the Quartz database on startup +spring.quartz.jdbc.initialize-schema=always + +spring.datasource.jdbc-url=jdbc:h2:mem:spring-quartz;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= diff --git a/spring-quartz/src/main/resources/quartz.properties b/spring-quartz/src/main/resources/quartz.properties index cefaaef8e4..662bb83eb0 100644 --- a/spring-quartz/src/main/resources/quartz.properties +++ b/spring-quartz/src/main/resources/quartz.properties @@ -4,7 +4,19 @@ org.quartz.threadPool.threadCount=2 org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true # job-store -org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore +# Enable this property for RAMJobStore +#org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore -# others -org.quartz.jobStore.misfireThreshold = 60000 \ No newline at end of file +# Enable these properties for a JDBCJobStore using JobStoreTX +org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX +org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate +org.quartz.jobStore.dataSource=quartzDataSource +# Enable this property for JobStoreCMT +#org.quartz.jobStore.nonManagedTXDataSource=quartzDataSource + +# H2 database +# use an in-memory database & initialise Quartz using their standard SQL script +org.quartz.dataSource.quartzDataSource.URL=jdbc:h2:mem:spring-quartz;INIT=RUNSCRIPT FROM 'classpath:/org/quartz/impl/jdbcjobstore/tables_h2.sql' +org.quartz.dataSource.quartzDataSource.driver=org.h2.Driver +org.quartz.dataSource.quartzDataSource.user=sa +org.quartz.dataSource.quartzDataSource.password= diff --git a/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 516cc587a7..fec47f045c 100644 --- a/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-quartz/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,16 +1,30 @@ package org.baeldung; import org.baeldung.springquartz.SpringQuartzApp; +import org.baeldung.springquartz.basics.service.SampleJobService; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringQuartzApp.class) public class SpringContextIntegrationTest { + @Autowired + private SampleJobService sampleJobService; + @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { } + + @Test + public void whenSchedulerStarts_thenJobsRun() throws InterruptedException { + assertThat(sampleJobService.getNumberOfInvocations()).isEqualTo(0); + Thread.sleep(SampleJobService.EXECUTION_TIME); + assertThat(sampleJobService.getNumberOfInvocations()).isEqualTo(1); + } } From 1f4dfef8db56afd2ba9324fc30d6b62159a96dcf Mon Sep 17 00:00:00 2001 From: vatsalgosar Date: Sat, 13 Jul 2019 05:49:41 +0530 Subject: [PATCH 168/352] BAEL-2728 | vatsalgosar@gmail.com - Sprint Boot application implementation using @SpringBootConfiguration annotation --- spring-boot-configuration/.gitignore | 31 ++++++++ spring-boot-configuration/README.md | 10 +++ spring-boot-configuration/pom.xml | 72 +++++++++++++++++++ .../main/java/com/baeldung/Application.java | 20 ++++++ .../main/java/com/baeldung/SwaggerConfig.java | 22 ++++++ .../baeldung/controller/PersonController.java | 39 ++++++++++ .../main/java/com/baeldung/domain/Person.java | 38 ++++++++++ .../exception/PersonNotFoundException.java | 8 +++ .../baeldung/repository/PersonRepository.java | 9 +++ .../com/baeldung/service/PersonService.java | 34 +++++++++ .../src/main/resources/application.properties | 3 + .../src/main/resources/schema.sql | 5 ++ .../java/com/baeldung/ApplicationTests.java | 16 +++++ 13 files changed, 307 insertions(+) create mode 100644 spring-boot-configuration/.gitignore create mode 100644 spring-boot-configuration/README.md create mode 100644 spring-boot-configuration/pom.xml create mode 100644 spring-boot-configuration/src/main/java/com/baeldung/Application.java create mode 100644 spring-boot-configuration/src/main/java/com/baeldung/SwaggerConfig.java create mode 100644 spring-boot-configuration/src/main/java/com/baeldung/controller/PersonController.java create mode 100644 spring-boot-configuration/src/main/java/com/baeldung/domain/Person.java create mode 100644 spring-boot-configuration/src/main/java/com/baeldung/exception/PersonNotFoundException.java create mode 100644 spring-boot-configuration/src/main/java/com/baeldung/repository/PersonRepository.java create mode 100644 spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java create mode 100644 spring-boot-configuration/src/main/resources/application.properties create mode 100644 spring-boot-configuration/src/main/resources/schema.sql create mode 100644 spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java diff --git a/spring-boot-configuration/.gitignore b/spring-boot-configuration/.gitignore new file mode 100644 index 0000000000..a2a3040aa8 --- /dev/null +++ b/spring-boot-configuration/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/spring-boot-configuration/README.md b/spring-boot-configuration/README.md new file mode 100644 index 0000000000..35472d575a --- /dev/null +++ b/spring-boot-configuration/README.md @@ -0,0 +1,10 @@ +Article: +SprintBootConfiguration annotation + +commands: +mvn clean install +mvn spring-boot:run + +Swagger endpoints: +http://localhost:8080/v2/api-docs +http://localhost:8080/swagger-ui.html \ No newline at end of file diff --git a/spring-boot-configuration/pom.xml b/spring-boot-configuration/pom.xml new file mode 100644 index 0000000000..ede2504272 --- /dev/null +++ b/spring-boot-configuration/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + com.baeldung + spring-boot-configuration + 0.0.1-SNAPSHOT + spring-boot-configuration + Demo project for Spring Boot Configuration + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + + + com.h2database + h2 + runtime + + + + + org.hibernate + hibernate-entitymanager + + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/spring-boot-configuration/src/main/java/com/baeldung/Application.java b/spring-boot-configuration/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..019cc5b57c --- /dev/null +++ b/spring-boot-configuration/src/main/java/com/baeldung/Application.java @@ -0,0 +1,20 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Import; + +@EnableAutoConfiguration +@ComponentScan(basePackages = {"com.baeldung.*"}) +@SpringBootConfiguration +@Import({SwaggerConfig.class}) +public class Application { + + public static void main(String[] args) { + + SpringApplication.run(Application.class, args); + } +} + diff --git a/spring-boot-configuration/src/main/java/com/baeldung/SwaggerConfig.java b/spring-boot-configuration/src/main/java/com/baeldung/SwaggerConfig.java new file mode 100644 index 0000000000..c69e65bc4e --- /dev/null +++ b/spring-boot-configuration/src/main/java/com/baeldung/SwaggerConfig.java @@ -0,0 +1,22 @@ +package com.baeldung; + +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.context.annotation.Bean; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootConfiguration +@EnableSwagger2 +public class SwaggerConfig { + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); + } +} diff --git a/spring-boot-configuration/src/main/java/com/baeldung/controller/PersonController.java b/spring-boot-configuration/src/main/java/com/baeldung/controller/PersonController.java new file mode 100644 index 0000000000..10d7386132 --- /dev/null +++ b/spring-boot-configuration/src/main/java/com/baeldung/controller/PersonController.java @@ -0,0 +1,39 @@ +package com.baeldung.controller; + +import com.baeldung.domain.Person; +import com.baeldung.exception.PersonNotFoundException; +import com.baeldung.service.PersonService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/persons") +public class PersonController { + + @Autowired + PersonService personService; + + @GetMapping + public List getPersons() { + return personService.getPersons(); + } + + @PostMapping + public void addPerson(@RequestBody Person person) { + personService.add(person); + } + + @GetMapping("/{id}") + public Person getPersonById(@PathVariable(required = true) long id) throws PersonNotFoundException { + return personService.getPersonById(id); + } + + @DeleteMapping("/{id}") + public void removePerson(@PathVariable(required = true) long id) { + personService.delete(id); + } + + +} diff --git a/spring-boot-configuration/src/main/java/com/baeldung/domain/Person.java b/spring-boot-configuration/src/main/java/com/baeldung/domain/Person.java new file mode 100644 index 0000000000..e63836420c --- /dev/null +++ b/spring-boot-configuration/src/main/java/com/baeldung/domain/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + @GeneratedValue + private long id; + private String name; + + public Person() {} + + public Person(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; + } +} + diff --git a/spring-boot-configuration/src/main/java/com/baeldung/exception/PersonNotFoundException.java b/spring-boot-configuration/src/main/java/com/baeldung/exception/PersonNotFoundException.java new file mode 100644 index 0000000000..048197a072 --- /dev/null +++ b/spring-boot-configuration/src/main/java/com/baeldung/exception/PersonNotFoundException.java @@ -0,0 +1,8 @@ +package com.baeldung.exception; + +public class PersonNotFoundException extends Exception { + + public PersonNotFoundException(String message) { + super(message); + } +} diff --git a/spring-boot-configuration/src/main/java/com/baeldung/repository/PersonRepository.java b/spring-boot-configuration/src/main/java/com/baeldung/repository/PersonRepository.java new file mode 100644 index 0000000000..b542b5ea0b --- /dev/null +++ b/spring-boot-configuration/src/main/java/com/baeldung/repository/PersonRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.repository; + +import com.baeldung.domain.Person; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PersonRepository extends CrudRepository { +} diff --git a/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java b/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java new file mode 100644 index 0000000000..e5929177de --- /dev/null +++ b/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java @@ -0,0 +1,34 @@ +package com.baeldung.service; + +import com.baeldung.domain.Person; +import com.baeldung.exception.PersonNotFoundException; +import com.baeldung.repository.PersonRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class PersonService { + + @Autowired + PersonRepository personRepository; + + public void add(Person person) { + personRepository.save(person); + } + + public void delete(long id) { + personRepository.deleteById(id); + } + + public List getPersons() { + return (List) personRepository.findAll(); + } + + public Person getPersonById(long id) throws PersonNotFoundException { + Optional optionalDog = personRepository.findById(id); + return optionalDog.orElseThrow(() -> new PersonNotFoundException("Couldn't find a Person with id: " + id)); + } +} diff --git a/spring-boot-configuration/src/main/resources/application.properties b/spring-boot-configuration/src/main/resources/application.properties new file mode 100644 index 0000000000..7de28fe306 --- /dev/null +++ b/spring-boot-configuration/src/main/resources/application.properties @@ -0,0 +1,3 @@ +# H2 +spring.h2.console.enabled=true +spring.h2.console.path=/h2 diff --git a/spring-boot-configuration/src/main/resources/schema.sql b/spring-boot-configuration/src/main/resources/schema.sql new file mode 100644 index 0000000000..02a7aca232 --- /dev/null +++ b/spring-boot-configuration/src/main/resources/schema.sql @@ -0,0 +1,5 @@ +CREATE TABLE `person` ( + `id` INT(11) NOT NULL, + `name` VARCHAR(50) NULL DEFAULT NULL, + PRIMARY KEY (`id`) +); \ No newline at end of file diff --git a/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java b/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java new file mode 100644 index 0000000000..f239fc76cc --- /dev/null +++ b/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ApplicationTests { + + @Test + public void contextLoads() { + } + +} From f021581f3c78664798d390d3f9c411ca0402e7b0 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 13 Jul 2019 12:27:26 +0530 Subject: [PATCH 169/352] [BAEL-12826] - Let's break the junit-5 module --- testing-modules/junit-5-basics/README.md | 8 +++++++- .../src/main/java/com/baeldung/junit5/Greetings.java | 0 .../main/java/com/baeldung/junit5/bean/NumbersBean.java | 0 .../src/test/java/com/baeldung/ExceptionUnitTest.java | 0 .../src/test/java/com/baeldung/FirstUnitTest.java | 0 .../src/test/java/com/baeldung/GreetingsUnitTest.java | 0 .../test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java | 0 .../src/test/java/com/baeldung/LiveTest.java | 0 .../baeldung/exception/ExceptionAssertionUnitTest.java | 0 .../baeldung/junit5/bean/test/NumbersBeanUnitTest.java | 0 .../baeldung/junit5/spring/GreetingsSpringUnitTest.java | 0 .../baeldung/junit5/spring/SpringTestConfiguration.java | 0 .../migration/junit4/AnnotationTestExampleUnitTest.java | 0 .../migration/junit4/AssertionsExampleUnitTest.java | 0 .../junit4/BeforeAndAfterAnnotationsUnitTest.java | 0 .../BeforeClassAndAfterClassAnnotationsUnitTest.java | 0 .../migration/junit4/ExceptionAssertionUnitTest.java | 0 .../baeldung/migration/junit4/RuleExampleUnitTest.java | 0 .../baeldung/migration/junit4/categories/Annotations.java | 0 .../migration/junit4/categories/JUnit4UnitTest.java | 0 .../migration/junit4/rules/TraceUnitTestRule.java | 0 .../migration/junit5/AnnotationTestExampleUnitTest.java | 0 .../migration/junit5/AssertionsExampleUnitTest.java | 0 .../com/baeldung/migration/junit5/AssumptionUnitTest.java | 0 .../junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java | 0 .../junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java | 0 .../baeldung/migration/junit5/RuleExampleUnitTest.java | 0 .../migration/junit5/extensions/TraceUnitExtension.java | 0 .../resourcedirectory/ReadResourceDirectoryUnitTest.java | 6 +++--- .../src/test/java/com/baeldung/suites/AllUnitTest.java | 0 testing-modules/junit-5/README.md | 7 ------- 31 files changed, 10 insertions(+), 11 deletions(-) rename testing-modules/{junit-5 => junit-5-basics}/src/main/java/com/baeldung/junit5/Greetings.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/main/java/com/baeldung/junit5/bean/NumbersBean.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/ExceptionUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/FirstUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/GreetingsUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/LiveTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java (100%) rename testing-modules/{junit-5 => junit-5-basics}/src/test/java/com/baeldung/suites/AllUnitTest.java (100%) diff --git a/testing-modules/junit-5-basics/README.md b/testing-modules/junit-5-basics/README.md index c09c030780..2c924a15a7 100644 --- a/testing-modules/junit-5-basics/README.md +++ b/testing-modules/junit-5-basics/README.md @@ -1,5 +1,11 @@ ### Relevant Articles: - +- [The Basics of JUnit 5 – A Preview](http://www.baeldung.com/junit-5-preview) +- [A Guide to JUnit 5](http://www.baeldung.com/junit-5) +- [JUnit5 @RunWith](http://www.baeldung.com/junit-5-runwith) - [Get the Path of the /src/test/resources Directory in JUnit](https://www.baeldung.com/junit-src-test-resources-directory-path) - [Tagging and Filtering JUnit Tests](https://www.baeldung.com/junit-filtering-tests) - [JUnit 5 Temporary Directory Support](https://www.baeldung.com/junit-5-temporary-directory) +- [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) +- [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) +- [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) +- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) \ No newline at end of file diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/junit5/Greetings.java similarity index 100% rename from testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java rename to testing-modules/junit-5-basics/src/main/java/com/baeldung/junit5/Greetings.java diff --git a/testing-modules/junit-5/src/main/java/com/baeldung/junit5/bean/NumbersBean.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/junit5/bean/NumbersBean.java similarity index 100% rename from testing-modules/junit-5/src/main/java/com/baeldung/junit5/bean/NumbersBean.java rename to testing-modules/junit-5-basics/src/main/java/com/baeldung/junit5/bean/NumbersBean.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/ExceptionUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/ExceptionUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/ExceptionUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/ExceptionUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/FirstUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/FirstUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/FirstUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/FirstUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/GreetingsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/LiveTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/LiveTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/LiveTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/LiveTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/bean/test/NumbersBeanUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssumptionUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java index 20fa372abd..eb8cab2462 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/resourcedirectory/ReadResourceDirectoryUnitTest.java @@ -17,7 +17,7 @@ public class ReadResourceDirectoryUnitTest { String absolutePath = file.getAbsolutePath(); System.out.println(absolutePath); - Assert.assertTrue(absolutePath.endsWith("src/test/resources")); + Assert.assertTrue(absolutePath.endsWith("src" + File.separator + "test" + File.separator + "resources")); } @Test @@ -27,7 +27,7 @@ public class ReadResourceDirectoryUnitTest { String absolutePath = resourceDirectory.toFile().getAbsolutePath(); System.out.println(absolutePath); - Assert.assertTrue(absolutePath.endsWith("src/test/resources")); + Assert.assertTrue(absolutePath.endsWith("src" + File.separator + "test" + File.separator + "resources")); } @Test @@ -39,7 +39,7 @@ public class ReadResourceDirectoryUnitTest { String absolutePath = file.getAbsolutePath(); System.out.println(absolutePath); - Assert.assertTrue(absolutePath.endsWith("/example_resource.txt")); + Assert.assertTrue(absolutePath.endsWith(File.separator + "example_resource.txt")); } } diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java similarity index 100% rename from testing-modules/junit-5/src/test/java/com/baeldung/suites/AllUnitTest.java rename to testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 47db6587b4..d543b9b09b 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -1,16 +1,9 @@ ### Relevant Articles: -- [The Basics of JUnit 5 – A Preview](http://www.baeldung.com/junit-5-preview) -- [A Guide to JUnit 5](http://www.baeldung.com/junit-5) - [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test) - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [A Guide to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) - [Inject Parameters into JUnit Jupiter Unit Tests](http://www.baeldung.com/junit-5-parameters) - [Mockito and JUnit 5 – Using ExtendWith](http://www.baeldung.com/mockito-junit-5-extension) -- [JUnit5 @RunWith](http://www.baeldung.com/junit-5-runwith) -- [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) -- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) -- [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) -- [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) - [JUnit5 Programmatic Extension Registration with @RegisterExtension](http://www.baeldung.com/junit-5-registerextension-annotation) - [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order) - [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java) From 6b4e6a11764dd5246e5e47967dedd52e903db844 Mon Sep 17 00:00:00 2001 From: jemgiordano Date: Sat, 13 Jul 2019 17:52:10 +1000 Subject: [PATCH 170/352] BAEL-2798 Update to 'Scheduling in Spring with Quartz' article to add JDBC examples. --- .../basics/scheduler/QrtzScheduler.java | 28 ++++++++----------- .../basics/scheduler/SampleJob.java | 2 +- .../basics/scheduler/SpringQrtzScheduler.java | 12 ++++---- .../basics/service/SampleJobService.java | 2 +- 4 files changed, 18 insertions(+), 26 deletions(-) diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java index 73416262ce..ccf9fca8c1 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java @@ -1,5 +1,13 @@ package org.baeldung.springquartz.basics.scheduler; +import static org.quartz.JobBuilder.newJob; +import static org.quartz.SimpleScheduleBuilder.simpleSchedule; +import static org.quartz.TriggerBuilder.newTrigger; + +import java.io.IOException; + +import javax.annotation.PostConstruct; + import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory; import org.quartz.*; import org.slf4j.Logger; @@ -14,19 +22,13 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.scheduling.quartz.SpringBeanJobFactory; -import javax.annotation.PostConstruct; -import java.io.IOException; import java.util.Properties; -import static org.quartz.JobBuilder.newJob; -import static org.quartz.SimpleScheduleBuilder.simpleSchedule; -import static org.quartz.TriggerBuilder.newTrigger; - @Configuration @ConditionalOnExpression("'${using.spring.schedulerFactory}'=='false'") public class QrtzScheduler { - private static final Logger logger = LoggerFactory.getLogger(QrtzScheduler.class); + Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private ApplicationContext applicationContext; @@ -74,11 +76,7 @@ public class QrtzScheduler { @Bean public JobDetail jobDetail() { - return newJob().ofType(SampleJob.class) - .storeDurably() - .withIdentity(JobKey.jobKey("Qrtz_Job_Detail")) - .withDescription("Invoke Sample Job service...") - .build(); + return newJob().ofType(SampleJob.class).storeDurably().withIdentity(JobKey.jobKey("Qrtz_Job_Detail")).withDescription("Invoke Sample Job service...").build(); } @Bean @@ -87,10 +85,6 @@ public class QrtzScheduler { int frequencyInSec = 10; logger.info("Configuring trigger to fire every {} seconds", frequencyInSec); - return newTrigger().forJob(job) - .withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")) - .withDescription("Sample trigger") - .withSchedule(simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()) - .build(); + return newTrigger().forJob(job).withIdentity(TriggerKey.triggerKey("Qrtz_Trigger")).withDescription("Sample trigger").withSchedule(simpleSchedule().withIntervalInSeconds(frequencyInSec).repeatForever()).build(); } } diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java index 8bfd856b86..7c50f9a231 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SampleJob.java @@ -12,7 +12,7 @@ import org.springframework.stereotype.Component; @Component public class SampleJob implements Job { - private static final Logger logger = LoggerFactory.getLogger(SampleJob.class); + Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private SampleJobService jobService; diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java index 40234df1c9..f824765efe 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java @@ -1,5 +1,8 @@ package org.baeldung.springquartz.basics.scheduler; +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory; import org.quartz.JobDetail; import org.quartz.SimpleTrigger; @@ -21,15 +24,12 @@ import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean; import org.springframework.scheduling.quartz.SpringBeanJobFactory; -import javax.annotation.PostConstruct; -import javax.sql.DataSource; - @Configuration @EnableAutoConfiguration @ConditionalOnExpression("'${using.spring.schedulerFactory}'=='true'") public class SpringQrtzScheduler { - private static final Logger logger = LoggerFactory.getLogger(SpringQrtzScheduler.class); + Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private ApplicationContext applicationContext; @@ -49,9 +49,7 @@ public class SpringQrtzScheduler { } @Bean - public SchedulerFactoryBean scheduler(Trigger trigger, - JobDetail job, - DataSource quartzDataSource) { + public SchedulerFactoryBean scheduler(Trigger trigger, JobDetail job, DataSource quartzDataSource) { SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean(); schedulerFactory.setConfigLocation(new ClassPathResource("quartz.properties")); diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java index 4b976d37b0..6f66352616 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/service/SampleJobService.java @@ -11,7 +11,7 @@ public class SampleJobService { public static final long EXECUTION_TIME = 5000L; - private static final Logger logger = LoggerFactory.getLogger(SampleJobService.class); + private Logger logger = LoggerFactory.getLogger(getClass()); private AtomicInteger count = new AtomicInteger(); From 8a9f399c96d3c58990331728e516b57d9df91d51 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 13 Jul 2019 11:31:47 +0300 Subject: [PATCH 171/352] Update README.md --- persistence-modules/spring-boot-persistence-mongodb/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md index 40f9f40749..f277ef66ca 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/README.md +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -2,3 +2,4 @@ - [Auto-Generated Field for MongoDB using Spring Boot](https://www.baeldung.com/spring-boot-mongodb-auto-generated-field) - [Spring Boot Integration Testing with Embedded MongoDB](http://www.baeldung.com/spring-boot-embedded-mongodb) +- [Upload and Retrieve Files Using MongoDB and Spring Boot](https://www.baeldung.com/spring-boot-mongodb-upload-file) From 328a0d1e47ab12165122831a7627549b58ae4b28 Mon Sep 17 00:00:00 2001 From: Alexander Molochko Date: Sat, 13 Jul 2019 12:31:50 +0300 Subject: [PATCH 172/352] BAEL-2378 Non-blocking Spring Boot with Kotlin Coroutines (#6966) --- pom.xml | 1647 +++++++++-------- spring-boot-kotlin/README.md | 2 + spring-boot-kotlin/pom.xml | 166 ++ .../SpringApplication.kt | 11 + .../config/DatastoreConfig.kt | 32 + .../config/RouterConfiguration.kt | 19 + .../config/WebClientConfiguration.kt | 12 + .../controller/ProductController.kt | 49 + .../controller/ProductControllerCoroutines.kt | 49 + .../controller/ProductStockView.kt | 15 + .../handlers/ProductsHandler.kt | 49 + .../nonblockingcoroutines/model/Product.kt | 7 + .../repository/ProductRepository.kt | 34 + .../repository/ProductRepositoryCoroutines.kt | 40 + .../src/main/resources/application.properties | 8 + .../src/main/resources/logback.xml | 13 + .../ProductHandlerTest.kt | 58 + 17 files changed, 1388 insertions(+), 823 deletions(-) create mode 100644 spring-boot-kotlin/README.md create mode 100644 spring-boot-kotlin/pom.xml create mode 100644 spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt create mode 100644 spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt create mode 100644 spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt create mode 100644 spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt create mode 100644 spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt create mode 100644 spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt create mode 100644 spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt create mode 100644 spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt create mode 100644 spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt create mode 100644 spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt create mode 100644 spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt create mode 100644 spring-boot-kotlin/src/main/resources/application.properties create mode 100644 spring-boot-kotlin/src/main/resources/logback.xml create mode 100644 spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt diff --git a/pom.xml b/pom.xml index d27c4d8a3d..f40659bc16 100644 --- a/pom.xml +++ b/pom.xml @@ -1,18 +1,18 @@ + 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"> 4.0.0 com.baeldung parent-modules 1.0.0-SNAPSHOT - parent-modules + parent-modules pom - - quarkus - + + quarkus + @@ -57,11 +57,11 @@ test - org.junit.jupiter - junit-jupiter-api + org.junit.jupiter + junit-jupiter-api ${junit-jupiter.version} test - + org.hamcrest hamcrest-core @@ -123,22 +123,22 @@ - - org.junit.platform - junit-platform-surefire-provider - ${junit-platform.version} - - - org.junit.jupiter - junit-jupiter-engine - ${junit-jupiter.version} - - - org.junit.vintage - junit-vintage-engine - ${junit-jupiter.version} - - + + org.junit.platform + junit-platform-surefire-provider + ${junit-platform.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} + + org.apache.maven.plugins @@ -328,62 +328,62 @@ parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - - akka-streams - algorithms-genetic - algorithms-miscellaneous-1 - algorithms-miscellaneous-2 - algorithms-miscellaneous-3 - algorithms-sorting - animal-sniffer-mvn-plugin - annotations - antlr - apache-avro - apache-bval - apache-curator - apache-cxf - apache-fop - apache-geode - apache-meecrowave - apache-opennlp - apache-poi - apache-pulsar - apache-shiro - apache-solrj - apache-spark - apache-thrift - apache-tika - apache-velocity - apache-zookeeper - asciidoctor - asm - atomix - autovalue - aws - aws-lambda - axon - azure + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + akka-streams + algorithms-genetic + algorithms-miscellaneous-1 + algorithms-miscellaneous-2 + algorithms-miscellaneous-3 + algorithms-sorting + animal-sniffer-mvn-plugin + annotations + antlr + apache-avro + apache-bval + apache-curator + apache-cxf + apache-fop + apache-geode + apache-meecrowave + apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix + autovalue + aws + aws-lambda + axon + azure - blade + blade - bootique + bootique - cas - cdi - checker-plugin - core-groovy - core-groovy-2 - core-groovy-collections - - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 + cas + cdi + checker-plugin + core-groovy + core-groovy-2 + core-groovy-collections + + + + core-java-modules/core-java-8 + core-java-modules/core-java-8-2 core-java-modules/core-java-lambdas @@ -475,84 +475,84 @@ jaxb - jee-7-security - jersey - JGit - jgroups - jhipster - jhipster-5 - jib - jjwt - jmeter - jmh - jni - jooby - jsf - json - json-path - jsoup - jta + jee-7-security + jersey + JGit + jgroups + jhipster + jhipster-5 + jib + jjwt + jmeter + jmh + jni + jooby + jsf + json + json-path + jsoup + jta - - kotlin-libraries - kotlin-libraries-2 + + kotlin-libraries + kotlin-libraries-2 - - libraries - libraries-2 - libraries-data - libraries-apache-commons - libraries-primitive - libraries-security - libraries-server - libraries-http - linkrest - logging-modules - lombok - lucene + + libraries + libraries-2 + libraries-data + libraries-apache-commons + libraries-primitive + libraries-security + libraries-server + libraries-http + linkrest + logging-modules + lombok + lucene - mapstruct - maven - maven-archetype - - maven-polyglot/maven-polyglot-json-extension - - mesos-marathon - metrics - - microprofile - msf4j - - mustache - mybatis + mapstruct + maven + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + + mesos-marathon + metrics + + microprofile + msf4j + + mustache + mybatis - optaplanner - orika - osgi + optaplanner + orika + osgi - patterns - pdf - performance-tests - - protobuffer + patterns + pdf + performance-tests + + protobuffer - persistence-modules - quarkus + persistence-modules + quarkus - rabbitmq - - ratpack - reactor-core - rest-with-spark-java - resteasy - restx - - rule-engines + rabbitmq + + ratpack + reactor-core + rest-with-spark-java + resteasy + restx + + rule-engines rsocket - rxjava - rxjava-2 - software-security/sql-injection-samples + rxjava + rxjava-2 + software-security/sql-injection-samples tensorflow-java spring-boot-flowable @@ -563,239 +563,240 @@ - - default-second - - + + default-second + + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*JdbcTest.java - **/*LiveTest.java - - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*JdbcTest.java + **/*LiveTest.java + + + - - + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - saas - spark-java + saas + spark-java - spring-4 + spring-4 - spring-5 - spring-5-webflux - spring-5-data-reactive - spring-5-mvc - spring-5-reactive - spring-5-reactive-client - spring-5-reactive-oauth - spring-5-reactive-security - spring-5-security - spring-5-security-oauth - spring-5-security-cognito + spring-5 + spring-5-webflux + spring-5-data-reactive + spring-5-mvc + spring-5-reactive + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth + spring-5-security-cognito - spring-activiti - spring-akka - spring-all - spring-amqp - spring-amqp-simple - spring-aop - spring-apache-camel - spring-batch - spring-bom + spring-activiti + spring-akka + spring-all + spring-amqp + spring-amqp-simple + spring-aop + spring-apache-camel + spring-batch + spring-bom - spring-boot - spring-boot-admin - spring-boot-angular - spring-boot-angular-ecommerce - spring-boot-autoconfiguration - spring-boot-bootstrap - spring-boot-camel - - spring-boot-client + spring-boot + spring-boot-admin + spring-boot-angular + spring-boot-angular-ecommerce + spring-boot-autoconfiguration + spring-boot-bootstrap + spring-boot-camel + + spring-boot-client - spring-boot-crud - spring-boot-ctx-fluent - spring-boot-custom-starter - spring-boot-disable-console-logging - - spring-boot-jasypt - spring-boot-keycloak - spring-boot-logging-log4j2 - spring-boot-mvc - spring-boot-mvc-birt - spring-boot-ops - spring-boot-ops-2 - spring-boot-rest - spring-boot-data - spring-boot-parent - spring-boot-property-exp - spring-boot-security - spring-boot-testing - spring-boot-vue - spring-boot-libraries + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter + spring-boot-disable-console-logging + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-kotlin + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-mvc-birt + spring-boot-ops + spring-boot-ops-2 + spring-boot-rest + spring-boot-data + spring-boot-parent + spring-boot-property-exp + spring-boot-security + spring-boot-testing + spring-boot-vue + spring-boot-libraries - spring-cloud - spring-cloud-bus - - spring-cloud-data-flow + spring-cloud + spring-cloud-bus + + spring-cloud-data-flow - spring-core - spring-core-2 - spring-cucumber + spring-core + spring-core-2 + spring-cucumber - spring-data-rest - spring-data-rest-querydsl - spring-dispatcher-servlet - spring-drools + spring-data-rest + spring-data-rest-querydsl + spring-dispatcher-servlet + spring-drools - spring-ehcache - spring-ejb - spring-exceptions + spring-ehcache + spring-ejb + spring-exceptions - spring-freemarker + spring-freemarker - spring-groovy + spring-groovy - spring-integration + spring-integration - spring-jenkins-pipeline - spring-jersey - spring-jinq - spring-jms - spring-jooq + spring-jenkins-pipeline + spring-jersey + spring-jinq + spring-jms + spring-jooq - spring-kafka - spring-katharsis + spring-kafka + spring-katharsis - spring-ldap + spring-ldap - spring-mobile - spring-mockito - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-kotlin - spring-mvc-simple - spring-mvc-simple-2 - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml + spring-mobile + spring-mockito + spring-mvc-forms-jsp + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple + spring-mvc-simple-2 + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml - spring-protobuf - + spring-protobuf + - spring-quartz + spring-quartz - spring-reactive-kotlin - spring-reactor - spring-remoting - spring-rest - spring-rest-angular - spring-rest-full - spring-rest-hal-browser - spring-rest-query-language - spring-rest-shell - spring-rest-simple - spring-resttemplate - spring-roo - spring-security-acl - spring-security-angular/server - spring-security-cache-control + spring-reactive-kotlin + spring-reactor + spring-remoting + spring-rest + spring-rest-angular + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-resttemplate + spring-roo + spring-security-acl + spring-security-angular/server + spring-security-cache-control - spring-security-client + spring-security-client - spring-security-core - spring-security-mvc-boot - spring-security-mvc-custom - spring-security-mvc-digest-auth + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth spring-security-mvc-jsonview - spring-security-mvc-ldap - spring-security-mvc-login - spring-security-mvc-persisted-remember-me - spring-security-mvc-session - spring-security-mvc-socket - spring-security-openid - - spring-security-rest - spring-security-rest-basic-auth - spring-security-rest-custom - spring-security-sso - spring-security-stormpath - spring-security-thymeleaf - spring-security-x509 - spring-session - spring-sleuth - spring-soap - spring-social-login - spring-spel - spring-state-machine - spring-static-resources - spring-swagger-codegen + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-session + spring-security-mvc-socket + spring-security-openid + + spring-security-rest + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-sso + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + spring-session + spring-sleuth + spring-soap + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen - spring-thymeleaf + spring-thymeleaf - spring-userservice + spring-userservice - spring-vault - spring-vertx + spring-vault + spring-vertx - spring-webflux-amqp + spring-webflux-amqp - spring-zuul + spring-zuul - static-analysis - stripe - structurizr - struts-2 + static-analysis + stripe + structurizr + struts-2 - testing-modules + testing-modules - twilio - Twitter4J + twilio + Twitter4J - undertow + undertow - vavr - vertx - vertx-and-rxjava - video-tutorials - vraptor + vavr + vertx + vertx-and-rxjava + video-tutorials + vraptor - wicket + wicket - xml - xmlunit-2 - xstream + xml + xmlunit-2 + xstream tensorflow-java spring-boot-flowable spring-security-kerberos morphia - + - + spring-context @@ -840,7 +841,7 @@ spring-boot-camel spring-boot-client spring-boot-custom-starter - greeter-spring-boot-autoconfigure + greeter-spring-boot-autoconfigure greeter-spring-boot-sample-app persistence-modules/spring-boot-h2/spring-boot-h2-database spring-boot-jasypt @@ -943,571 +944,571 @@ - - default-heavy - - + + default-heavy + + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - 3 - true - - **/*IntegrationTest.java - **/*IntTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*JdbcTest.java - **/*LiveTest.java - - - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*IntTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/*JdbcTest.java + **/*LiveTest.java + + + - - + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - core-java-modules/core-java-concurrency-advanced - core-kotlin - core-kotlin-2 - core-kotlin-io + core-java-modules/core-java-concurrency-advanced + core-kotlin + core-kotlin-2 + core-kotlin-io - jenkins/hello-world - jws + jenkins/hello-world + jws - libraries + libraries - persistence-modules/hibernate5 - persistence-modules/hibernate-mapping - persistence-modules/java-jpa - persistence-modules/java-mongodb - persistence-modules/jnosql + persistence-modules/hibernate5 + persistence-modules/hibernate-mapping + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql - vaadin - - + vaadin + + - - integration-lite-first + + integration-lite-first - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin - - akka-streams - algorithms-genetic - algorithms-miscellaneous-1 - algorithms-miscellaneous-2 - algorithms-miscellaneous-3 - algorithms-sorting - animal-sniffer-mvn-plugin - annotations - antlr - apache-avro - apache-bval - apache-curator - apache-cxf - apache-fop - apache-geode - apache-meecrowave - apache-opennlp - apache-poi - apache-pulsar - apache-shiro - apache-solrj - apache-spark - apache-thrift - apache-tika - apache-velocity - apache-zookeeper - asciidoctor - asm - atomix - autovalue - aws - aws-lambda - axon - azure + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + akka-streams + algorithms-genetic + algorithms-miscellaneous-1 + algorithms-miscellaneous-2 + algorithms-miscellaneous-3 + algorithms-sorting + animal-sniffer-mvn-plugin + annotations + antlr + apache-avro + apache-bval + apache-curator + apache-cxf + apache-fop + apache-geode + apache-meecrowave + apache-opennlp + apache-poi + apache-pulsar + apache-shiro + apache-solrj + apache-spark + apache-thrift + apache-tika + apache-velocity + apache-zookeeper + asciidoctor + asm + atomix + autovalue + aws + aws-lambda + axon + azure - bootique + bootique - cas - cdi - checker-plugin - core-groovy - core-groovy-2 - core-groovy-collections - - - core-java-modules/core-java-8 - core-java-modules/core-java-8-2 - - - core-java-modules/core-java-arrays - core-java-modules/core-java-collections - core-java-modules/core-java-collections-list - core-java-modules/core-java-collections-list-2 - core-java-modules/core-java-collections-array-list - core-java-modules/core-java-collections-set - core-java-modules/core-java-concurrency-basic - core-java-modules/core-java-concurrency-collections - core-java-modules/core-java-io - core-java-modules/core-java-nio - core-java-modules/core-java-security - core-java-modules/core-java-lang-syntax - core-java-modules/core-java-lang - core-java-modules/core-java-lang-oop - core-java-modules/core-java-lang-oop-2 - core-java-modules - core-java-modules/core-java-networking - core-java-modules/core-java-perf - core-java-modules/core-java-sun - core-scala - couchbase - custom-pmd + cas + cdi + checker-plugin + core-groovy + core-groovy-2 + core-groovy-collections + + + core-java-modules/core-java-8 + core-java-modules/core-java-8-2 + + + core-java-modules/core-java-arrays + core-java-modules/core-java-collections + core-java-modules/core-java-collections-list + core-java-modules/core-java-collections-list-2 + core-java-modules/core-java-collections-array-list + core-java-modules/core-java-collections-set + core-java-modules/core-java-concurrency-basic + core-java-modules/core-java-concurrency-collections + core-java-modules/core-java-io + core-java-modules/core-java-nio + core-java-modules/core-java-security + core-java-modules/core-java-lang-syntax + core-java-modules/core-java-lang + core-java-modules/core-java-lang-oop + core-java-modules/core-java-lang-oop-2 + core-java-modules + core-java-modules/core-java-networking + core-java-modules/core-java-perf + core-java-modules/core-java-sun + core-scala + couchbase + custom-pmd - dagger - data-structures - ddd - deeplearning4j - disruptor - dozer - drools - dubbo + dagger + data-structures + ddd + deeplearning4j + disruptor + dozer + drools + dubbo - ethereum + ethereum - feign - flyway-cdi-extension + feign + flyway-cdi-extension - geotools - google-cloud - google-web-toolkit - - - graphql/graphql-java - grpc - gson - guava - guava-collections - guava-modules - - guice + geotools + google-cloud + google-web-toolkit + + + graphql/graphql-java + grpc + gson + guava + guava-collections + guava-modules + + guice - hazelcast - helidon - httpclient - httpclient-simple - hystrix + hazelcast + helidon + httpclient + httpclient-simple + hystrix - image-processing - immutables + image-processing + immutables - jackson - jackson-2 - jackson-simple - java-collections-conversions - java-collections-maps - java-collections-maps-2 - - java-ee-8-security-api - java-lite - java-numbers - java-rmi - java-spi - java-streams - - java-strings - java-strings-2 - java-vavr-stream - java-websocket - javafx - javax-servlets - javaxval - jaxb - + java-ee-8-security-api + java-lite + java-numbers + java-rmi + java-spi + java-streams + + java-strings + java-strings-2 + java-vavr-stream + java-websocket + javafx + javax-servlets + javaxval + jaxb + - jee-7-security - jersey - JGit - jgroups - jhipster - jhipster-5 - jib - jjwt - jmeter - jmh - jni - jooby - jsf - json - json-path - jsoup - jta + jee-7-security + jersey + JGit + jgroups + jhipster + jhipster-5 + jib + jjwt + jmeter + jmh + jni + jooby + jsf + json + json-path + jsoup + jta - - kotlin-libraries + + kotlin-libraries - - libraries - libraries-data - libraries-apache-commons - libraries-security - libraries-server - libraries-http - linkrest - logging-modules - lombok - lucene + + libraries + libraries-data + libraries-apache-commons + libraries-security + libraries-server + libraries-http + linkrest + logging-modules + lombok + lucene - mapstruct - maven - - maven-archetype - - maven-polyglot/maven-polyglot-json-extension - - mesos-marathon - metrics - - microprofile - msf4j - - mustache - mybatis + mapstruct + maven + + maven-archetype + + maven-polyglot/maven-polyglot-json-extension + + mesos-marathon + metrics + + microprofile + msf4j + + mustache + mybatis - optaplanner - orika - osgi + optaplanner + orika + osgi - patterns - pdf - performance-tests - - protobuffer + patterns + pdf + performance-tests + + protobuffer - persistence-modules + persistence-modules - rabbitmq - - ratpack - reactor-core - rest-with-spark-java - resteasy - restx - - rule-engines - rsocket - rxjava - rxjava-2 + rabbitmq + + ratpack + reactor-core + rest-with-spark-java + resteasy + restx + + rule-engines + rsocket + rxjava + rxjava-2 - + - + - - integration-lite-second + + integration-lite-second - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - saas - spark-java + saas + spark-java - spring-4 + spring-4 - spring-5 - spring-5-data-reactive - spring-5-mvc - spring-5-reactive - spring-5-reactive-client - spring-5-reactive-oauth - spring-5-reactive-security - spring-5-security - spring-5-security-oauth - spring-5-security-cognito - spring-activiti - spring-akka - spring-all - spring-amqp - spring-amqp-simple - spring-aop - spring-apache-camel - spring-batch - spring-bom + spring-5 + spring-5-data-reactive + spring-5-mvc + spring-5-reactive + spring-5-reactive-client + spring-5-reactive-oauth + spring-5-reactive-security + spring-5-security + spring-5-security-oauth + spring-5-security-cognito + spring-activiti + spring-akka + spring-all + spring-amqp + spring-amqp-simple + spring-aop + spring-apache-camel + spring-batch + spring-bom - spring-boot - spring-boot-admin - spring-boot-angular - spring-boot-angular-ecommerce - spring-boot-autoconfiguration - spring-boot-bootstrap - spring-boot-camel - - spring-boot-client - spring-boot-crud - spring-boot-ctx-fluent - spring-boot-custom-starter - spring-boot-disable-console-logging - - spring-boot-jasypt - spring-boot-keycloak - spring-boot-logging-log4j2 - spring-boot-mvc - spring-boot-mvc-birt - spring-boot-ops - spring-boot-ops-2 - spring-boot-rest - spring-boot-data - spring-boot-parent - spring-boot-property-exp - spring-boot-security - spring-boot-vue + spring-boot + spring-boot-admin + spring-boot-angular + spring-boot-angular-ecommerce + spring-boot-autoconfiguration + spring-boot-bootstrap + spring-boot-camel + + spring-boot-client + spring-boot-crud + spring-boot-ctx-fluent + spring-boot-custom-starter + spring-boot-disable-console-logging + + spring-boot-jasypt + spring-boot-keycloak + spring-boot-logging-log4j2 + spring-boot-mvc + spring-boot-mvc-birt + spring-boot-ops + spring-boot-ops-2 + spring-boot-rest + spring-boot-data + spring-boot-parent + spring-boot-property-exp + spring-boot-security + spring-boot-vue - spring-cloud - spring-cloud-bus - - spring-cloud-data-flow + spring-cloud + spring-cloud-bus + + spring-cloud-data-flow - spring-core - spring-core-2 - spring-cucumber + spring-core + spring-core-2 + spring-cucumber - spring-data-rest - spring-data-rest-querydsl - spring-dispatcher-servlet - spring-drools + spring-data-rest + spring-data-rest-querydsl + spring-dispatcher-servlet + spring-drools spring-ehcache - spring-ejb - spring-exceptions + spring-ejb + spring-exceptions - spring-freemarker + spring-freemarker - spring-groovy + spring-groovy - spring-integration + spring-integration - spring-jenkins-pipeline - spring-jersey - spring-jinq - spring-jms - spring-jooq + spring-jenkins-pipeline + spring-jersey + spring-jinq + spring-jms + spring-jooq - spring-kafka - spring-katharsis + spring-kafka + spring-katharsis - spring-ldap + spring-ldap - spring-mobile - spring-mockito - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-kotlin - spring-mvc-simple - spring-mvc-simple-2 - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml + spring-mobile + spring-mockito + spring-mvc-forms-jsp + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-kotlin + spring-mvc-simple + spring-mvc-simple-2 + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml - spring-protobuf - + spring-protobuf + - spring-quartz + spring-quartz - spring-reactive-kotlin - spring-reactor - spring-remoting - spring-rest - spring-rest-angular - spring-rest-full - spring-rest-hal-browser - spring-rest-query-language - spring-rest-shell - spring-rest-simple - spring-resttemplate - spring-roo + spring-reactive-kotlin + spring-reactor + spring-remoting + spring-rest + spring-rest-angular + spring-rest-full + spring-rest-hal-browser + spring-rest-query-language + spring-rest-shell + spring-rest-simple + spring-resttemplate + spring-roo - spring-security-acl - spring-security-angular/server - spring-security-cache-control + spring-security-acl + spring-security-angular/server + spring-security-cache-control - spring-security-client + spring-security-client - spring-security-core - spring-security-mvc-boot - spring-security-mvc-custom - spring-security-mvc-digest-auth - spring-security-mvc-ldap - spring-security-mvc-login - spring-security-mvc-persisted-remember-me - spring-security-mvc-session - spring-security-mvc-socket - spring-security-openid - - spring-security-rest - spring-security-rest-basic-auth - spring-security-rest-custom - spring-security-sso - spring-security-stormpath - spring-security-thymeleaf - spring-security-x509 - spring-session - spring-sleuth - spring-soap - spring-social-login - spring-spel - spring-state-machine - spring-static-resources - spring-swagger-codegen + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-session + spring-security-mvc-socket + spring-security-openid + + spring-security-rest + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-sso + spring-security-stormpath + spring-security-thymeleaf + spring-security-x509 + spring-session + spring-sleuth + spring-soap + spring-social-login + spring-spel + spring-state-machine + spring-static-resources + spring-swagger-codegen - spring-thymeleaf + spring-thymeleaf - spring-userservice + spring-userservice - spring-vault - spring-vertx + spring-vault + spring-vertx - spring-webflux-amqp + spring-webflux-amqp - spring-zuul + spring-zuul - static-analysis - stripe - structurizr - struts-2 + static-analysis + stripe + structurizr + struts-2 - testing-modules + testing-modules - twilio - Twitter4J + twilio + Twitter4J - undertow + undertow - vavr - vertx - vertx-and-rxjava - video-tutorials - vraptor + vavr + vertx + vertx-and-rxjava + video-tutorials + vraptor - wicket + wicket - xml - xmlunit-2 - xstream + xml + xmlunit-2 + xstream - + - + - - integration-heavy + + integration-heavy - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ManualTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*IntTest.java - - - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + **/*IntTest.java + + + + + - - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-java - parent-kotlin + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin - core-java-modules/core-java - core-java-modules/core-java-concurrency-advanced - core-kotlin - core-kotlin-2 + core-java-modules/core-java + core-java-modules/core-java-concurrency-advanced + core-kotlin + core-kotlin-2 - jenkins/hello-world - jws + jenkins/hello-world + jws - libraries + libraries - persistence-modules/hibernate5 - persistence-modules/java-jpa - persistence-modules/java-mongodb - persistence-modules/jnosql + persistence-modules/hibernate5 + persistence-modules/java-jpa + persistence-modules/java-mongodb + persistence-modules/jnosql - vaadin - + vaadin + - + @@ -1541,7 +1542,7 @@ 1.1.7 - + 2.21.0 3.7.0 1.6.0 diff --git a/spring-boot-kotlin/README.md b/spring-boot-kotlin/README.md new file mode 100644 index 0000000000..dc50c24aa0 --- /dev/null +++ b/spring-boot-kotlin/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Non-blocking Spring Boot with Kotlin Coroutines](http://www.baeldung.com/non-blocking-spring-boot-with-kotlin-coroutines) diff --git a/spring-boot-kotlin/pom.xml b/spring-boot-kotlin/pom.xml new file mode 100644 index 0000000000..25508c52b9 --- /dev/null +++ b/spring-boot-kotlin/pom.xml @@ -0,0 +1,166 @@ + + + 4.0.0 + spring-boot-kotlin + spring-boot-kotlin + jar + Demo project showing how to use non-blocking in Kotlin with Spring Boot + + + parent-kotlin + com.baeldung + 1.0.0-SNAPSHOT + ../parent-kotlin + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + + org.jetbrains.kotlin + kotlin-reflect + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + + + org.jetbrains.kotlinx + kotlinx-coroutines-core + ${kotlinx-coroutines.version} + + + org.jetbrains.kotlinx + kotlinx-coroutines-reactor + ${kotlinx-coroutines.version} + + + org.springframework.boot + spring-boot-starter-webflux + ${spring-boot.version} + + + com.fasterxml.jackson.module + jackson-module-kotlin + + + org.springframework.data + spring-data-r2dbc + ${r2dbc.version} + + + io.r2dbc + r2dbc-h2 + ${h2-r2dbc.version} + + + io.r2dbc + r2dbc-spi + ${r2dbc-spi.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + junit + junit + + + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + io.projectreactor + reactor-test + test + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + + + -Xjsr305=strict + + + spring + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + 1.3.31 + 1.0.0.M1 + 1.0.0.M7 + 1.0.0.BUILD-SNAPSHOT + 1.2.1 + 2.2.0.M2 + + + diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt new file mode 100644 index 0000000000..23af4fe90b --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt @@ -0,0 +1,11 @@ +package com.baeldung.nonblockingcoroutines + +import org.springframework.boot.SpringApplication.run +import org.springframework.boot.autoconfigure.SpringBootApplication + +@SpringBootApplication +class SpringApplication + +fun main(args: Array) { + run(SpringApplication::class.java, *args) +} diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt new file mode 100644 index 0000000000..52ef8a708b --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt @@ -0,0 +1,32 @@ +package com.baeldung.nonblockingcoroutines.config + +import io.r2dbc.h2.H2ConnectionConfiguration +import io.r2dbc.h2.H2ConnectionFactory +import io.r2dbc.spi.ConnectionFactory +import org.springframework.beans.factory.annotation.Value +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration +import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories + +@Configuration +@EnableR2dbcRepositories +class DatastoreConfig : AbstractR2dbcConfiguration() { + @Value("\${spring.datasource.username}") + private val userName: String = "" + + @Value("\${spring.datasource.password}") + private val password: String = "" + + @Value("\${spring.datasource.dbname}") + private val dbName: String = "" + + @Bean + override fun connectionFactory(): ConnectionFactory { + return H2ConnectionFactory(H2ConnectionConfiguration.builder() + .inMemory(dbName) + .username(userName) + .password(password) + .build()) + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt new file mode 100644 index 0000000000..bda1d26278 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt @@ -0,0 +1,19 @@ +package com.baeldung.nonblockingcoroutines.config + +import com.baeldung.nonblockingcoroutines.handlers.ProductsHandler +import kotlinx.coroutines.FlowPreview +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.web.reactive.function.server.coRouter + +@Configuration +class RouterConfiguration { + + @FlowPreview + @Bean + fun productRoutes(productsHandler: ProductsHandler) = coRouter { + GET("/", productsHandler::findAll) + GET("/{id}", productsHandler::findOne) + GET("/{id}/stock", productsHandler::findOneInStock) + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt new file mode 100644 index 0000000000..85938b8be2 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt @@ -0,0 +1,12 @@ +package com.baeldung.nonblockingcoroutines.config + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.web.reactive.function.client.WebClient + +@Configuration +class WebClientConfiguration { + + @Bean + fun webClient() = WebClient.builder().baseUrl("http://localhost:8080").build() +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt new file mode 100644 index 0000000000..91b091859a --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt @@ -0,0 +1,49 @@ +package com.baeldung.nonblockingcoroutines.controller + +import com.baeldung.nonblockingcoroutines.model.Product +import com.baeldung.nonblockingcoroutines.repository.ProductRepository +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.MediaType +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.reactive.function.client.WebClient +import org.springframework.web.reactive.function.client.bodyToMono +import reactor.core.publisher.Flux +import reactor.core.publisher.Mono + +class ProductController { + @Autowired + lateinit var webClient: WebClient + @Autowired + lateinit var productRepository: ProductRepository + + @GetMapping("/{id}") + fun findOne(@PathVariable id: Int): Mono { + return productRepository + .getProductById(id) + } + + @GetMapping("/{id}/stock") + fun findOneInStock(@PathVariable id: Int): Mono { + val product = productRepository.getProductById(id) + + val stockQuantity = webClient.get() + .uri("/stock-service/product/$id/quantity") + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono() + return product.zipWith(stockQuantity) { productInStock, stockQty -> + ProductStockView(productInStock, stockQty) + } + } + + @GetMapping("/stock-service/product/{id}/quantity") + fun getStockQuantity(): Mono { + return Mono.just(2) + } + + @GetMapping("/") + fun findAll(): Flux { + return productRepository.getAllProducts() + } +} diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt new file mode 100644 index 0000000000..d70d352cda --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt @@ -0,0 +1,49 @@ +package com.baeldung.nonblockingcoroutines.controller + +import com.baeldung.nonblockingcoroutines.model.Product +import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.Flow +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.MediaType.APPLICATION_JSON +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.reactive.function.client.WebClient +import org.springframework.web.reactive.function.client.awaitBody +import org.springframework.web.reactive.function.client.awaitExchange + +class ProductControllerCoroutines { + @Autowired + lateinit var webClient: WebClient + + @Autowired + lateinit var productRepository: ProductRepositoryCoroutines + + @GetMapping("/{id}") + suspend fun findOne(@PathVariable id: Int): Product? { + return productRepository.getProductById(id) + } + + @GetMapping("/{id}/stock") + suspend fun findOneInStock(@PathVariable id: Int): ProductStockView { + val product: Deferred = GlobalScope.async { + productRepository.getProductById(id) + } + val quantity: Deferred = GlobalScope.async { + webClient.get() + .uri("/stock-service/product/$id/quantity") + .accept(APPLICATION_JSON) + .awaitExchange().awaitBody() + } + return ProductStockView(product.await()!!, quantity.await()) + } + + @FlowPreview + @GetMapping("/") + fun findAll(): Flow { + return productRepository.getAllProducts() + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt new file mode 100644 index 0000000000..44611fd1de --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt @@ -0,0 +1,15 @@ +package com.baeldung.nonblockingcoroutines.controller + +import com.baeldung.nonblockingcoroutines.model.Product + +class ProductStockView(product: Product, var stockQuantity: Int) { + var id: Int = 0 + var name: String = "" + var price: Float = 0.0f + + init { + this.id = product.id + this.name = product.name + this.price = product.price + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt new file mode 100644 index 0000000000..41c4510e0d --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt @@ -0,0 +1,49 @@ +package com.baeldung.nonblockingcoroutines.handlers + +import com.baeldung.nonblockingcoroutines.controller.ProductStockView +import com.baeldung.nonblockingcoroutines.model.Product +import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.async +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.MediaType +import org.springframework.stereotype.Component +import org.springframework.web.reactive.function.client.WebClient +import org.springframework.web.reactive.function.client.awaitBody +import org.springframework.web.reactive.function.client.awaitExchange +import org.springframework.web.reactive.function.server.ServerRequest +import org.springframework.web.reactive.function.server.ServerResponse +import org.springframework.web.reactive.function.server.bodyAndAwait +import org.springframework.web.reactive.function.server.json + +@Component +class ProductsHandler( + @Autowired var webClient: WebClient, + @Autowired var productRepository: ProductRepositoryCoroutines) { + + @FlowPreview + suspend fun findAll(request: ServerRequest): ServerResponse = + ServerResponse.ok().json().bodyAndAwait(productRepository.getAllProducts()) + + suspend fun findOneInStock(request: ServerRequest): ServerResponse { + val id = request.pathVariable("id").toInt() + + val product: Deferred = GlobalScope.async { + productRepository.getProductById(id) + } + val quantity: Deferred = GlobalScope.async { + webClient.get() + .uri("/stock-service/product/$id/quantity") + .accept(MediaType.APPLICATION_JSON) + .awaitExchange().awaitBody() + } + return ServerResponse.ok().json().bodyAndAwait(ProductStockView(product.await()!!, quantity.await())) + } + + suspend fun findOne(request: ServerRequest): ServerResponse { + val id = request.pathVariable("id").toInt() + return ServerResponse.ok().json().bodyAndAwait(productRepository.getProductById(id)!!) + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt new file mode 100644 index 0000000000..c6dcbdc9c4 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt @@ -0,0 +1,7 @@ +package com.baeldung.nonblockingcoroutines.model + +data class Product( + var id: Int = 0, + var name: String = "", + var price: Float = 0.0f +) diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt new file mode 100644 index 0000000000..20c3827c26 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt @@ -0,0 +1,34 @@ +package com.baeldung.nonblockingcoroutines.repository + +import com.baeldung.nonblockingcoroutines.model.Product +import org.springframework.data.r2dbc.function.DatabaseClient +import org.springframework.stereotype.Repository +import reactor.core.publisher.Flux +import reactor.core.publisher.Mono + +@Repository +class ProductRepository(private val client: DatabaseClient) { + + fun getProductById(id: Int): Mono { + return client.execute().sql("SELECT * FROM products WHERE id = $1") + .bind(0, id) + .`as`(Product::class.java) + .fetch() + .one() + } + + fun addNewProduct(name: String, price: Float): Mono { + return client.execute() + .sql("INSERT INTO products (name, price) VALUES($1, $2)") + .bind(0, name) + .bind(1, price) + .then() + } + + fun getAllProducts(): Flux { + return client.select().from("products") + .`as`(Product::class.java) + .fetch() + .all() + } +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt new file mode 100644 index 0000000000..60a19d4d00 --- /dev/null +++ b/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt @@ -0,0 +1,40 @@ +package com.baeldung.nonblockingcoroutines.repository + + +import com.baeldung.nonblockingcoroutines.model.Product +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.reactive.awaitFirstOrNull +import kotlinx.coroutines.reactive.flow.asFlow +import org.springframework.data.r2dbc.function.DatabaseClient +import org.springframework.stereotype.Repository + +@Repository +class ProductRepositoryCoroutines(private val client: DatabaseClient) { + + suspend fun getProductById(id: Int): Product? = + client.execute().sql("SELECT * FROM products WHERE id = $1") + .bind(0, id) + .`as`(Product::class.java) + .fetch() + .one() + .awaitFirstOrNull() + + suspend fun addNewProduct(name: String, price: Float) = + client.execute() + .sql("INSERT INTO products (name, price) VALUES($1, $2)") + .bind(0, name) + .bind(1, price) + .then() + .awaitFirstOrNull() + + @FlowPreview + fun getAllProducts(): Flow = + client.select() + .from("products") + .`as`(Product::class.java) + .fetch() + .all() + .log() + .asFlow() +} \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/resources/application.properties b/spring-boot-kotlin/src/main/resources/application.properties new file mode 100644 index 0000000000..0f84ff2d75 --- /dev/null +++ b/spring-boot-kotlin/src/main/resources/application.properties @@ -0,0 +1,8 @@ +logging.level.org.springframework.data.r2dbc=DEBUG +logging.level.org.springframework.web.reactive.function.client.ExchangeFunctions=TRACE +spring.http.log-request-details=true +spring.h2.console.enabled=true +spring.datasource.username=sa +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.password= +spring.datasource.dbname=testdb \ No newline at end of file diff --git a/spring-boot-kotlin/src/main/resources/logback.xml b/spring-boot-kotlin/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-kotlin/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt b/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt new file mode 100644 index 0000000000..53b1d50f21 --- /dev/null +++ b/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt @@ -0,0 +1,58 @@ +package com.baeldung.nonblockingcoroutines + +import com.baeldung.nonblockingcoroutines.config.RouterConfiguration +import com.baeldung.nonblockingcoroutines.handlers.ProductsHandler +import com.baeldung.nonblockingcoroutines.model.Product +import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.reactive.flow.asFlow +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.BDDMockito.given +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration +import org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest +import org.springframework.boot.test.mock.mockito.MockBean +import org.springframework.test.context.junit4.SpringRunner +import org.springframework.test.web.reactive.server.WebTestClient +import org.springframework.test.web.reactive.server.expectBodyList +import org.springframework.web.reactive.function.client.WebClient +import reactor.core.publisher.Flux +import org.springframework.test.context.ContextConfiguration + +@WebFluxTest( + excludeAutoConfiguration = [ReactiveUserDetailsServiceAutoConfiguration::class, ReactiveSecurityAutoConfiguration::class] +) +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [ProductsHandler::class, RouterConfiguration::class]) +class ProductHandlerTest { + + @Autowired + private lateinit var client: WebTestClient + + @MockBean + private lateinit var webClient: WebClient + + @MockBean + private lateinit var productsRepository: ProductRepositoryCoroutines + + + @FlowPreview + @Test + public fun `get all products`() { + val productsFlow = Flux.just( + Product(1, "product1", 1000.0F), + Product(2, "product2", 2000.0F), + Product(3, "product3", 3000.0F) + ).asFlow() + given(productsRepository.getAllProducts()).willReturn(productsFlow) + client.get() + .uri("/") + .exchange() + .expectStatus() + .isOk + .expectBodyList() + } + +} From 7672e03ec14e7af0ff6455ecac6b5b39024264e0 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 13 Jul 2019 18:29:33 +0530 Subject: [PATCH 173/352] [BAEL-10895] - Fixed tests in spring-5-data-reactive module --- spring-5-data-reactive/pom.xml | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml index 056fb37a52..5372803842 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -77,29 +77,34 @@ org.springframework spring-tx - 5.2.0.M2 + ${spring-tx.version} org.springframework.data spring-data-r2dbc - 1.0.0.M2 + ${spring-data-r2dbc.version} io.r2dbc r2dbc-h2 - 0.8.0.M8 + ${r2dbc-h2.version} com.h2database h2 - 1.4.199 + ${h2.version} org.springframework.boot spring-boot-starter-test test + + org.apache.httpcomponents + httpclient + ${httpclient.version} + @@ -195,11 +200,6 @@ - - 1.2.40 - 1.2.40 - - spring-snapshots @@ -216,5 +216,15 @@ + + 1.2.40 + 1.2.40 + 5.2.0.M2 + 1.0.0.M2 + 0.8.0.M8 + 4.5.2 + 1.4.199 + + From 54aeed4bc304b07d7b1ef39f648813345b62ca22 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 13 Jul 2019 16:36:16 +0300 Subject: [PATCH 174/352] add java sources to maveb --- spring-5-mvc/pom.xml | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 5fb8f66f71..302080a8b4 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -1,5 +1,6 @@ - 4.0.0 com.baeldung @@ -51,12 +52,10 @@ org.jetbrains.kotlin kotlin-stdlib-jre8 - ${kotlin.version} org.jetbrains.kotlin kotlin-reflect - ${kotlin.version} com.fasterxml.jackson.module @@ -91,7 +90,6 @@ - ${project.basedir}/src/main/kotlin ${project.basedir}/src/test/kotlin @@ -132,11 +130,43 @@ + + org.codehaus.mojo + build-helper-maven-plugin + + + generate-sources + + add-source + + + + ${basedir}/src/main/java + ${basedir}/src/main/kotlin + + + + + test-compile + test-compile + + add-test-source + + + + ${basedir}/src/test/java + ${basedir}/src/test/kotlin + + + + + - + 2.9.0 1.1.2 + com.baeldung.Spring5Application From 550d1eac6dd018e7661f142406839a8b9a899de5 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Sat, 13 Jul 2019 22:08:49 +0300 Subject: [PATCH 175/352] BAEL-2995 - possible lossy conversion - conflicts resolved --- pom.xml | 26 +++----------------------- 1 file changed, 3 insertions(+), 23 deletions(-) diff --git a/pom.xml b/pom.xml index 2f83b92b2c..33411ca43a 100644 --- a/pom.xml +++ b/pom.xml @@ -988,29 +988,6 @@ jws libraries - jackson - jackson-2 - jackson-simple - java-collections-conversions - java-collections-maps - java-collections-maps-2 - - java-ee-8-security-api - java-lite - java-numbers - java-numbers-2 - java-rmi - java-spi - java-streams - java-streams-2 - java-strings - java-strings-2 - java-vavr-stream - java-websocket - javafx - javax-servlets - javaxval - jaxb persistence-modules/hibernate5 persistence-modules/hibernate-mapping persistence-modules/java-jpa @@ -1170,6 +1147,7 @@ java-ee-8-security-api java-lite java-numbers + java-numbers-2 java-rmi java-spi java-streams @@ -1182,6 +1160,8 @@ javax-servlets javaxval jaxb + jee-7-security jersey JGit From bc8f5ab8c485652880a8856da36daec6445cf377 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 14 Jul 2019 01:32:22 +0530 Subject: [PATCH 176/352] [BAEL-11603] - Fixed tests in spring-mvc-java module --- spring-mvc-java/pom.xml | 7 ++++++- .../src/test/java/com/baeldung/htmlunit/TestConfig.java | 8 +++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index e5dd5ad9e1..cb16e91bc4 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -144,6 +144,11 @@ spring-messaging ${spring.version} + + org.glassfish + javax.el + ${javax.el.version} + @@ -290,7 +295,7 @@ 3.16-beta1 - 3.0.1-b06 + 3.0.1-b09 diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java index 529879fada..8c8a2f5b62 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -13,6 +13,8 @@ import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; +import com.baeldung.excel.ExcelPOIHelper; + @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.web.controller" }) @@ -44,5 +46,9 @@ public class TestConfig implements WebMvcConfigurer { templateEngine.setTemplateResolver(templateResolver()); return templateEngine; } - + + @Bean + public ExcelPOIHelper excelPOIHelper() { + return new ExcelPOIHelper(); + } } From f4a0913e79d25f3c442a13358fea0993e9ee8235 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 14 Jul 2019 18:40:26 +0530 Subject: [PATCH 177/352] [BAEL-15942] - POM Properties Cleanup --- apache-olingo/olingo2/pom.xml | 1 - aws/pom.xml | 1 - core-groovy-2/pom.xml | 2 - core-java-modules/core-java-8/pom.xml | 1 - .../core-java-concurrency-advanced/pom.xml | 1 - .../core-java-concurrency-basic/pom.xml | 2 - .../core-java-concurrency-collections/pom.xml | 1 - core-java-modules/core-java-io/pom.xml | 1 - core-java-modules/core-java-jvm/pom.xml | 1 - core-java-modules/core-java-lang-oop/pom.xml | 6 -- core-java-modules/core-java-lang/pom.xml | 3 - .../core-java-networking/pom.xml | 2 - core-java-modules/core-java-optional/pom.xml | 6 +- core-java-modules/core-java-os/pom.xml | 1 - core-java-modules/core-java-perf/pom.xml | 7 --- core-java-modules/core-java-security/pom.xml | 1 - core-java-modules/core-java-sun/pom.xml | 1 - core-java-modules/core-java/pom.xml | 5 +- core-kotlin-io/pom.xml | 4 +- core-kotlin/pom.xml | 4 +- couchbase/pom.xml | 1 - disruptor/pom.xml | 1 - dozer/pom.xml | 1 - flyway-cdi-extension/pom.xml | 1 - gson/pom.xml | 1 - guava-collections/pom.xml | 1 - guava/pom.xml | 1 - httpclient-simple/pom.xml | 2 - httpclient/pom.xml | 1 - hystrix/pom.xml | 1 - jackson-simple/pom.xml | 1 - jackson/pom.xml | 1 - java-collections-conversions/pom.xml | 1 - java-collections-maps-2/pom.xml | 1 - java-collections-maps/pom.xml | 1 - java-dates/pom.xml | 2 - java-ee-8-security-api/pom.xml | 2 - java-numbers/pom.xml | 1 - java-streams/pom.xml | 1 - javax-servlets/pom.xml | 1 - jaxb/pom.xml | 2 - jee-7/pom.xml | 2 - jee-kotlin/pom.xml | 61 +++++++++---------- jersey/pom.xml | 1 - jsf/pom.xml | 3 - jws/pom.xml | 1 - kotlin-libraries/pom.xml | 3 +- libraries-apache-commons/pom.xml | 7 +-- libraries-data/pom.xml | 1 - libraries-server/pom.xml | 3 +- libraries/pom.xml | 5 +- logging-modules/log-mdc/pom.xml | 1 - maven/pom.xml | 2 - parent-spring-4/pom.xml | 3 +- parent-spring-5/pom.xml | 3 +- patterns/design-patterns-2/pom.xml | 1 - patterns/pom.xml | 1 - persistence-modules/deltaspike/pom.xml | 1 - .../spring-hibernate-3/pom.xml | 1 - .../spring-hibernate-5/pom.xml | 1 - persistence-modules/spring-hibernate4/pom.xml | 1 - persistence-modules/spring-jpa/pom.xml | 4 -- .../spring-persistence-simple/pom.xml | 1 - pom.xml | 1 + resteasy/pom.xml | 1 - spring-5-webflux/pom.xml | 1 - spring-boot-angular/pom.xml | 4 -- spring-cloud/spring-cloud-contract/pom.xml | 1 - spring-core-2/pom.xml | 5 +- spring-core/pom.xml | 1 - spring-dispatcher-servlet/pom.xml | 1 - spring-exceptions/pom.xml | 2 - spring-jersey/pom.xml | 5 +- spring-jms/pom.xml | 1 - spring-jooq/pom.xml | 4 +- spring-katharsis/pom.xml | 1 - spring-mvc-forms-jsp/pom.xml | 1 - spring-mvc-simple/pom.xml | 6 +- spring-mvc-velocity/pom.xml | 1 - spring-mvc-webflow/pom.xml | 1 - spring-mvc-xml/pom.xml | 6 +- spring-rest-angular/pom.xml | 1 - spring-rest-full/pom.xml | 1 - spring-rest-query-language/pom.xml | 1 - spring-rest-simple/pom.xml | 1 - spring-rest/pom.xml | 1 - spring-resttemplate/pom.xml | 1 - spring-security-mvc-custom/pom.xml | 2 - spring-security-mvc-digest-auth/pom.xml | 2 - spring-security-mvc-jsonview/pom.xml | 8 +-- spring-security-mvc-login/pom.xml | 1 - .../pom.xml | 7 +-- spring-security-mvc-session/pom.xml | 1 - spring-security-mvc-socket/pom.xml | 3 +- spring-security-react/pom.xml | 2 - spring-security-rest-basic-auth/pom.xml | 1 - spring-security-rest-custom/pom.xml | 1 - spring-security-rest/pom.xml | 1 - spring-soap/pom.xml | 1 - spring-social-login/pom.xml | 4 -- spring-static-resources/pom.xml | 5 +- spring-userservice/pom.xml | 4 -- spring-zuul/pom.xml | 4 -- struts-2/pom.xml | 1 - tensorflow-java/pom.xml | 5 +- testing-modules/junit-5-basics/pom.xml | 1 - .../load-testing-comparison/pom.xml | 1 - testing-modules/mockito/pom.xml | 1 - testing-modules/rest-assured/pom.xml | 2 - testing-modules/rest-testing/pom.xml | 4 -- testing-modules/spring-testing/pom.xml | 4 +- testing-modules/test-containers/pom.xml | 1 - vaadin/pom.xml | 1 - video-tutorials/jackson-annotations/pom.xml | 4 -- xml/pom.xml | 6 -- 115 files changed, 60 insertions(+), 250 deletions(-) diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml index e3647b9c57..24e7b4e0b2 100644 --- a/apache-olingo/olingo2/pom.xml +++ b/apache-olingo/olingo2/pom.xml @@ -82,7 +82,6 @@ - 1.8 2.0.11 diff --git a/aws/pom.xml b/aws/pom.xml index 560f9145f9..75d5aac1eb 100644 --- a/aws/pom.xml +++ b/aws/pom.xml @@ -112,7 +112,6 @@ - 2.5 1.3.0 1.1.0 2.8.0 diff --git a/core-groovy-2/pom.xml b/core-groovy-2/pom.xml index 53b3e6a7ec..ba3fd0802b 100644 --- a/core-groovy-2/pom.xml +++ b/core-groovy-2/pom.xml @@ -175,8 +175,6 @@ 1.0.0 2.4.0 1.1-groovy-2.4 - 3.9 - 1.8 3.8.1 1.2.3 2.5.7 diff --git a/core-java-modules/core-java-8/pom.xml b/core-java-modules/core-java-8/pom.xml index c09c970e07..28182e515b 100644 --- a/core-java-modules/core-java-8/pom.xml +++ b/core-java-modules/core-java-8/pom.xml @@ -175,7 +175,6 @@ - 3.5 3.6.1 4.1 4.01 diff --git a/core-java-modules/core-java-concurrency-advanced/pom.xml b/core-java-modules/core-java-concurrency-advanced/pom.xml index a3ac7aa88a..5d41909ed3 100644 --- a/core-java-modules/core-java-concurrency-advanced/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced/pom.xml @@ -72,7 +72,6 @@ 21.0 - 3.5 3.6.1 4.1 4.01 diff --git a/core-java-modules/core-java-concurrency-basic/pom.xml b/core-java-modules/core-java-concurrency-basic/pom.xml index aea4bef6a7..96b3ef76f7 100644 --- a/core-java-modules/core-java-concurrency-basic/pom.xml +++ b/core-java-modules/core-java-concurrency-basic/pom.xml @@ -45,8 +45,6 @@ - - 3.5 3.6.1 1.7.0 diff --git a/core-java-modules/core-java-concurrency-collections/pom.xml b/core-java-modules/core-java-concurrency-collections/pom.xml index 27aae4ea6c..ea3bbe44f3 100644 --- a/core-java-modules/core-java-concurrency-collections/pom.xml +++ b/core-java-modules/core-java-concurrency-collections/pom.xml @@ -62,7 +62,6 @@ 21.0 - 3.5 3.6.1 4.1 4.01 diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index 44c703ee68..1a133d2cbe 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -248,7 +248,6 @@ - 3.5 1.55 1.10 3.6.1 diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml index 6c700cd005..b1860322a6 100644 --- a/core-java-modules/core-java-jvm/pom.xml +++ b/core-java-modules/core-java-jvm/pom.xml @@ -35,7 +35,6 @@ - 3.5 3.6.1 diff --git a/core-java-modules/core-java-lang-oop/pom.xml b/core-java-modules/core-java-lang-oop/pom.xml index c9bb3b3e5a..46003b132b 100644 --- a/core-java-modules/core-java-lang-oop/pom.xml +++ b/core-java-modules/core-java-lang-oop/pom.xml @@ -75,13 +75,7 @@ - - - 2.8.5 2.8.2 - - - 3.5 3.10.0 3.0.3 diff --git a/core-java-modules/core-java-lang/pom.xml b/core-java-modules/core-java-lang/pom.xml index 45ccc8d0f5..8311636873 100644 --- a/core-java-modules/core-java-lang/pom.xml +++ b/core-java-modules/core-java-lang/pom.xml @@ -75,9 +75,6 @@ 2.8.2 - - - 3.5 1.5.0-b01 diff --git a/core-java-modules/core-java-networking/pom.xml b/core-java-modules/core-java-networking/pom.xml index 550ebdb4ff..e2ee7b2fcc 100644 --- a/core-java-modules/core-java-networking/pom.xml +++ b/core-java-modules/core-java-networking/pom.xml @@ -42,8 +42,6 @@ 1.5.0-b01 - 2.5 - 3.5 4.3.4.RELEASE diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml index f60e3ba03d..eb981c0907 100644 --- a/core-java-modules/core-java-optional/pom.xml +++ b/core-java-modules/core-java-optional/pom.xml @@ -19,12 +19,12 @@ com.h2database h2 - ${h2database.version} + ${h2.version} com.fasterxml.jackson.core jackson-databind - ${jackson.databind.version} + ${jackson.version} @@ -48,7 +48,5 @@ 1.8 1.8 5.4.0.Final - 1.4.197 - 2.9.8 \ No newline at end of file diff --git a/core-java-modules/core-java-os/pom.xml b/core-java-modules/core-java-os/pom.xml index 85194b176e..f6c5ef04a5 100644 --- a/core-java-modules/core-java-os/pom.xml +++ b/core-java-modules/core-java-os/pom.xml @@ -68,7 +68,6 @@ - 3.5 4.1 4.01 diff --git a/core-java-modules/core-java-perf/pom.xml b/core-java-modules/core-java-perf/pom.xml index f225a9554b..b9c9d30ac0 100644 --- a/core-java-modules/core-java-perf/pom.xml +++ b/core-java-modules/core-java-perf/pom.xml @@ -23,11 +23,4 @@ - - - - 3.8.1 - - - diff --git a/core-java-modules/core-java-security/pom.xml b/core-java-modules/core-java-security/pom.xml index ed82a5209a..d3efb26fe8 100644 --- a/core-java-modules/core-java-security/pom.xml +++ b/core-java-modules/core-java-security/pom.xml @@ -43,7 +43,6 @@ - 3.8.1 1.60 1.11 diff --git a/core-java-modules/core-java-sun/pom.xml b/core-java-modules/core-java-sun/pom.xml index da27564d96..ab5f945114 100644 --- a/core-java-modules/core-java-sun/pom.xml +++ b/core-java-modules/core-java-sun/pom.xml @@ -264,7 +264,6 @@ 23.0 - 3.5 1.55 1.10 3.6.1 diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml index 2f33212c38..2a2cb3a6af 100644 --- a/core-java-modules/core-java/pom.xml +++ b/core-java-modules/core-java/pom.xml @@ -113,7 +113,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} @@ -453,8 +453,6 @@ 2.8.2 - 3.9 - 2.5 3.6.1 1.0.3 0.4 @@ -471,7 +469,6 @@ 2.21.0 1.1 - 1.4.197 2.1.0.1 1.19 diff --git a/core-kotlin-io/pom.xml b/core-kotlin-io/pom.xml index a0b688a223..78b36626d6 100644 --- a/core-kotlin-io/pom.xml +++ b/core-kotlin-io/pom.xml @@ -22,7 +22,7 @@ org.junit.jupiter junit-jupiter - ${junit.jupiter.version} + ${junit-jupiter.version} test @@ -88,7 +88,7 @@ 1.3.30 - 5.4.2 + 5.4.2 2.27.0 1.9.12 3.10.0 diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index 5de986b49e..e4d243360a 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -39,7 +39,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} com.github.kittinunf.fuel @@ -76,11 +76,9 @@ 3.6.1 - 3.8.1 1.1.1 5.2.0 3.10.0 - 1.4.197 1.15.0 3.3.0 1.16.1 diff --git a/couchbase/pom.xml b/couchbase/pom.xml index 31e6a53388..fc40749c61 100644 --- a/couchbase/pom.xml +++ b/couchbase/pom.xml @@ -69,7 +69,6 @@ 2.5.0 4.3.5.RELEASE - 3.5 diff --git a/disruptor/pom.xml b/disruptor/pom.xml index 296704f546..e1d78e7ed6 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -115,7 +115,6 @@ - 3.5 3.3.6 6.10 diff --git a/dozer/pom.xml b/dozer/pom.xml index 5720001acf..8234eb4c79 100644 --- a/dozer/pom.xml +++ b/dozer/pom.xml @@ -26,7 +26,6 @@ - 3.5 5.5.1 diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml index f9f951880e..e8b327e35f 100644 --- a/flyway-cdi-extension/pom.xml +++ b/flyway-cdi-extension/pom.xml @@ -58,6 +58,5 @@ 5.1.4 8.5.33 1.3.2 - 1.4.197 diff --git a/gson/pom.xml b/gson/pom.xml index a21d783c39..9d2cf630d0 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -64,7 +64,6 @@ 2.8.0 - 3.5 4.1 2.9.6 diff --git a/guava-collections/pom.xml b/guava-collections/pom.xml index a717023156..ecda3c9595 100644 --- a/guava-collections/pom.xml +++ b/guava-collections/pom.xml @@ -55,7 +55,6 @@ 24.0-jre - 3.5 4.1 diff --git a/guava/pom.xml b/guava/pom.xml index 1d37a79ab6..34eb7eafa6 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -49,7 +49,6 @@ 24.0-jre - 3.5 3.6.1 diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index efcf0452e2..7dd54c8fc4 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -297,7 +297,6 @@ 19.0 - 3.5 1.10 4.1.4 @@ -305,7 +304,6 @@ 4.4.11 4.5.8 - 2.6 1.6.1 diff --git a/httpclient/pom.xml b/httpclient/pom.xml index def3a05816..8cd483cfc6 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -120,7 +120,6 @@ 19.0 - 3.5 1.10 4.1.4 diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 7bb3e98246..e08af2c40f 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -65,7 +65,6 @@ 1.5.8 0.20.7 - 2.6 2.7 1.5.8 1.5.8 diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml index 5023ad87b6..05c1ef4595 100644 --- a/jackson-simple/pom.xml +++ b/jackson-simple/pom.xml @@ -118,7 +118,6 @@ - 3.8 2.10 2.8.5 4.2 diff --git a/jackson/pom.xml b/jackson/pom.xml index 948248d255..8a083525a2 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -118,7 +118,6 @@ - 3.8 2.10 2.8.5 4.2 diff --git a/java-collections-conversions/pom.xml b/java-collections-conversions/pom.xml index ee7221b25e..24d918d105 100644 --- a/java-collections-conversions/pom.xml +++ b/java-collections-conversions/pom.xml @@ -33,7 +33,6 @@ - 3.5 4.1 3.6.1 diff --git a/java-collections-maps-2/pom.xml b/java-collections-maps-2/pom.xml index 5f27eaa2d8..e242a8655e 100644 --- a/java-collections-maps-2/pom.xml +++ b/java-collections-maps-2/pom.xml @@ -54,7 +54,6 @@ 3.0.2 8.1.0 1.2.0 - 3.8.1 3.11.1 diff --git a/java-collections-maps/pom.xml b/java-collections-maps/pom.xml index b5eba31437..83cc97a21e 100644 --- a/java-collections-maps/pom.xml +++ b/java-collections-maps/pom.xml @@ -44,7 +44,6 @@ - 3.5 4.1 4.01 1.7.0 diff --git a/java-dates/pom.xml b/java-dates/pom.xml index d4f690d894..3fddf3f0f8 100644 --- a/java-dates/pom.xml +++ b/java-dates/pom.xml @@ -74,8 +74,6 @@ - - 3.5 2.10 3.6.1 diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml index 9b8356714f..4d4e2ba3b3 100644 --- a/java-ee-8-security-api/pom.xml +++ b/java-ee-8-security-api/pom.xml @@ -72,8 +72,6 @@ 8.0 2.3 18.0.0.1 - - 3.2.2 diff --git a/java-numbers/pom.xml b/java-numbers/pom.xml index daed356f66..ac3ca2680f 100644 --- a/java-numbers/pom.xml +++ b/java-numbers/pom.xml @@ -121,7 +121,6 @@ 3.6.1 1.0.3 - 3.5 3.6.1 diff --git a/java-streams/pom.xml b/java-streams/pom.xml index b0c56ecdf9..bd0123e01d 100644 --- a/java-streams/pom.xml +++ b/java-streams/pom.xml @@ -106,7 +106,6 @@ - 3.5 0.9.0 1.15 0.6.5 diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml index e3d8a430d9..096b1bb229 100644 --- a/javax-servlets/pom.xml +++ b/javax-servlets/pom.xml @@ -88,7 +88,6 @@ 3.9.1 2.21.0 1.3.3 - 2.6 4.0.1 diff --git a/jaxb/pom.xml b/jaxb/pom.xml index 3ed6d9b21a..d575f12c7b 100644 --- a/jaxb/pom.xml +++ b/jaxb/pom.xml @@ -130,8 +130,6 @@ 2.3 3.0.2 - 2.5 - 3.5 1.0.0 1.1 diff --git a/jee-7/pom.xml b/jee-7/pom.xml index d389b57cd5..9432801fd9 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -519,11 +519,9 @@ 1.13 2.25 1.0.0.Final - 2.6 4.2.3.RELEASE 2.21.0 1.1.2 - 2.4 2.2.14 4.5 2.0.1.Final diff --git a/jee-kotlin/pom.xml b/jee-kotlin/pom.xml index 963c03d0df..17163ba23c 100644 --- a/jee-kotlin/pom.xml +++ b/jee-kotlin/pom.xml @@ -2,43 +2,16 @@ 4.0.0 + jee-kotlin + jee-kotlin + war + parent-modules com.baeldung 1.0.0-SNAPSHOT - jee-kotlin - jee-kotlin - war - - - UTF-8 - false - 8.0 - - - 1.3.41 - official - true - - - 8.2.1.Final - 3.2.3 - 2.21.0 - 3.1.1 - - 1.4.1.Final - 2.0.1.Final - 1.0.0.Alpha4 - - 4.12 - 3.8.0.Final - 2.9.8 - 3.1.3 - - - org.jetbrains.kotlin @@ -134,7 +107,7 @@ org.apache.maven.plugins maven-war-plugin - ${mvn-war-plugin.version} + ${maven-war-plugin.version} webapp kotlin @@ -286,4 +259,28 @@ + + + UTF-8 + false + 8.0 + + + 1.3.41 + official + true + + + 8.2.1.Final + 2.21.0 + 3.1.1 + + 1.4.1.Final + 2.0.1.Final + 1.0.0.Alpha4 + + 3.8.0.Final + 3.1.3 + + diff --git a/jersey/pom.xml b/jersey/pom.xml index a3adb4cf5a..708b36ce41 100644 --- a/jersey/pom.xml +++ b/jersey/pom.xml @@ -80,7 +80,6 @@ 2.26 - 3.2.0 diff --git a/jsf/pom.xml b/jsf/pom.xml index 19f1265250..31362a8809 100644 --- a/jsf/pom.xml +++ b/jsf/pom.xml @@ -99,9 +99,6 @@ 2.2.14 3.0.0 - - 2.6 - 6.2 diff --git a/jws/pom.xml b/jws/pom.xml index 6bc790e7ee..5c19c887d3 100644 --- a/jws/pom.xml +++ b/jws/pom.xml @@ -83,7 +83,6 @@ 3.0.2 - 3.0.0 1.6.0 1.6.0 diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml index b75c77f358..e252329426 100644 --- a/kotlin-libraries/pom.xml +++ b/kotlin-libraries/pom.xml @@ -94,7 +94,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} @@ -184,7 +184,6 @@ 1.1.1 5.2.0 3.10.0 - 1.4.197 0.10.4 1.9.3 diff --git a/libraries-apache-commons/pom.xml b/libraries-apache-commons/pom.xml index cb5990df22..05d11d83fe 100644 --- a/libraries-apache-commons/pom.xml +++ b/libraries-apache-commons/pom.xml @@ -25,7 +25,7 @@ org.apache.commons commons-lang3 - ${commons-lang.version} + ${commons-lang3.version} org.apache.commons @@ -35,7 +35,7 @@ commons-io commons-io - ${commons.io.version} + ${commons-io.version} commons-chain @@ -87,13 +87,12 @@ - 3.6 + 3.6 1.1 1.9.3 1.2 1.4 3.6.2 - 2.5 1.6 4.1 2.0.0.0 diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 31aaaea951..88dcceafaa 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -449,7 +449,6 @@ 2.8.2 1.1.0 1.5.0 - 2.9.7 3.0.0 3.6.2 3.8.4 diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml index 72794729a5..9bed5e211b 100644 --- a/libraries-server/pom.xml +++ b/libraries-server/pom.xml @@ -52,7 +52,7 @@ commons-io commons-io - ${commons.io.version} + ${commons-io.version} io.netty @@ -114,7 +114,6 @@ 3.6.2 4.5.3 - 2.5 9.4.8.v20171121 4.1.20.Final 4.1 diff --git a/libraries/pom.xml b/libraries/pom.xml index 8e787bdc22..e8ffde5f99 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -45,7 +45,7 @@ org.apache.commons commons-lang3 - ${commons-lang.version} + ${commons-lang3.version} commons-net @@ -818,7 +818,6 @@ 0.1.0 0.7.0 3.2.7 - 3.6 1.9.2 1.2 3.21.0-GA @@ -826,12 +825,10 @@ 1.5.0 3.1.0 4.5.3 - 1.4.196 1.0 4.5.3 - 2.9.7 2.92 1.9.26 1.41.0 diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml index ae658e034e..ce58f43e4e 100644 --- a/logging-modules/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -101,7 +101,6 @@ 2.7 3.3.6 3.3.0.Final - 2.4 diff --git a/maven/pom.xml b/maven/pom.xml index 96643d76f3..ef6e7b7d93 100644 --- a/maven/pom.xml +++ b/maven/pom.xml @@ -299,7 +299,6 @@ - 1.8 3.0.2 3.8.0 2.22.0 @@ -310,6 +309,5 @@ Baeldung 9.4.11.v20180605 2.27 - 4.12 \ No newline at end of file diff --git a/parent-spring-4/pom.xml b/parent-spring-4/pom.xml index d7eea44989..b08ead02d4 100644 --- a/parent-spring-4/pom.xml +++ b/parent-spring-4/pom.xml @@ -23,14 +23,13 @@ org.junit.jupiter junit-jupiter-engine - ${junit.jupiter.version} + ${junit-jupiter.version} test 4.3.22.RELEASE - 5.0.2 \ No newline at end of file diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 84df8cf30a..f85924b801 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -23,14 +23,13 @@ org.junit.jupiter junit-jupiter-engine - ${junit.jupiter.version} + ${junit-jupiter.version} test 5.1.4.RELEASE - 5.0.2 5.1.4.RELEASE diff --git a/patterns/design-patterns-2/pom.xml b/patterns/design-patterns-2/pom.xml index 5c3e70b046..392035ab84 100644 --- a/patterns/design-patterns-2/pom.xml +++ b/patterns/design-patterns-2/pom.xml @@ -38,6 +38,5 @@ 1.8 1.8 16.0.2 - 3.5 diff --git a/patterns/pom.xml b/patterns/pom.xml index 875af67d55..2be9d2519e 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -51,7 +51,6 @@ - 3.0.0 9.4.0.v20161208 diff --git a/persistence-modules/deltaspike/pom.xml b/persistence-modules/deltaspike/pom.xml index 4dcef07695..46e774edff 100644 --- a/persistence-modules/deltaspike/pom.xml +++ b/persistence-modules/deltaspike/pom.xml @@ -317,7 +317,6 @@ 2.6 1.1.3 1.2.5.Final-redhat-1 - 3.5 diff --git a/persistence-modules/spring-hibernate-3/pom.xml b/persistence-modules/spring-hibernate-3/pom.xml index ec35f35bb3..4349492370 100644 --- a/persistence-modules/spring-hibernate-3/pom.xml +++ b/persistence-modules/spring-hibernate-3/pom.xml @@ -93,7 +93,6 @@ 8.5.8 19.0 - 3.5 diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml index 16e55cb0c0..e27775c76f 100644 --- a/persistence-modules/spring-hibernate-5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -146,7 +146,6 @@ 21.0 - 3.5 diff --git a/persistence-modules/spring-hibernate4/pom.xml b/persistence-modules/spring-hibernate4/pom.xml index 4289c9c3d5..388e2ab27b 100644 --- a/persistence-modules/spring-hibernate4/pom.xml +++ b/persistence-modules/spring-hibernate4/pom.xml @@ -167,7 +167,6 @@ 19.0 - 3.5 4.4.1 4.5 diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 0fdffad8db..0961cabaff 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -174,11 +174,7 @@ 21.0 - 3.5 3.8.0 - - - 2.6 \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml index 1afacab164..d0b3f5fe29 100644 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -147,7 +147,6 @@ 21.0 - 3.5 3.8.0 diff --git a/pom.xml b/pom.xml index f40659bc16..bfd8adeb7a 100644 --- a/pom.xml +++ b/pom.xml @@ -1557,6 +1557,7 @@ 2.21.0 2.5 2.6 + 3.5 1.4 3.0.0 3.1.0 diff --git a/resteasy/pom.xml b/resteasy/pom.xml index ca4124abca..8aea8077f9 100644 --- a/resteasy/pom.xml +++ b/resteasy/pom.xml @@ -143,7 +143,6 @@ 3.0.19.Final - 2.5 1.6.1 diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index 6317723467..6887f01753 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -99,7 +99,6 @@ - 1.8 2.2.0.M3 diff --git a/spring-boot-angular/pom.xml b/spring-boot-angular/pom.xml index 62a2701dd0..71c46cb7f5 100644 --- a/spring-boot-angular/pom.xml +++ b/spring-boot-angular/pom.xml @@ -44,8 +44,4 @@ - - - 1.8 - diff --git a/spring-cloud/spring-cloud-contract/pom.xml b/spring-cloud/spring-cloud-contract/pom.xml index ea71891648..a7ee52e954 100644 --- a/spring-cloud/spring-cloud-contract/pom.xml +++ b/spring-cloud/spring-cloud-contract/pom.xml @@ -56,7 +56,6 @@ UTF-8 UTF-8 - 1.8 2.1.1.RELEASE 2.1.4.RELEASE diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index bb4ca9701b..20cd900e00 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -31,13 +31,13 @@ org.junit.jupiter junit-jupiter-engine - ${junit.jupiter.version} + ${junit-jupiter.version} test org.junit.jupiter junit-jupiter-api - ${junit.jupiter.version} + ${junit-jupiter.version} test @@ -54,7 +54,6 @@ 5.1.4.RELEASE - 5.0.2 \ No newline at end of file diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 75e9fd7131..7e5a9b3feb 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -87,7 +87,6 @@ 1.4.4.RELEASE 1 20.0 - 2.6 2.5 1.5.2.RELEASE 1.10.19 diff --git a/spring-dispatcher-servlet/pom.xml b/spring-dispatcher-servlet/pom.xml index eb0fdfea46..6f816986be 100644 --- a/spring-dispatcher-servlet/pom.xml +++ b/spring-dispatcher-servlet/pom.xml @@ -96,7 +96,6 @@ 3.0-r1655215 - 3.0.0 \ No newline at end of file diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index ff28ac89bb..45c80f2c9f 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -192,7 +192,6 @@ 19.0 - 3.5 4.4.5 4.5.2 @@ -200,7 +199,6 @@ 2.9.0 - 2.6 2.7 1.6.1 diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 5a12d27180..e053ee7b4b 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -38,7 +38,7 @@ javax.servlet javax.servlet-api - ${servlet-api-version} + ${javax.servlet-api.version} provided @@ -223,11 +223,10 @@ 2.27 - 3.2.0 1.6.1 4.4.9 4.5.5 - 4.0.0 + 4.0.0 1.58 3.10.0 1.5.10.RELEASE diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml index 2ed58c0c95..ea4af32216 100644 --- a/spring-jms/pom.xml +++ b/spring-jms/pom.xml @@ -64,7 +64,6 @@ 4.3.4.RELEASE 5.14.1 - 2.6 diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index 8bce500a86..8a1fa877da 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -102,7 +102,7 @@ com.h2database h2 - ${com.h2database.version} + ${h2.version} @@ -189,8 +189,6 @@ 3.11.7 - 1.4.193 - 1.0.0 1.5 1.0.0 diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 74786e7926..18bf198948 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -137,7 +137,6 @@ 3.0.2 0.9.10 1.6.1 - 3.7 diff --git a/spring-mvc-forms-jsp/pom.xml b/spring-mvc-forms-jsp/pom.xml index 20912e71e5..5ce2d19414 100644 --- a/spring-mvc-forms-jsp/pom.xml +++ b/spring-mvc-forms-jsp/pom.xml @@ -99,7 +99,6 @@ - 2.6 6.0.10.Final 1.3.3 5.2.5.Final diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index a767cf3c37..580a40e50b 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -47,7 +47,7 @@ commons-fileupload commons-fileupload - ${fileupload.version} + ${commons-fileupload.version} org.springframework @@ -162,18 +162,16 @@ 1.8 1.8 - 3.2.0 2.21.0 2.3.2-b02 4.0.0 6.0.10.Final enter-location-of-server - 1.3.2 + 1.3.2 3.0.7.RELEASE 2.4.12 2.3.27-incubating 1.2.5 - 1.0.2 1.9.0 1.4.9 5.1.0 diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index df19b67e8e..5954e48e8f 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -115,7 +115,6 @@ 2.9.0 - 2.6 2.7 1.6.1 diff --git a/spring-mvc-webflow/pom.xml b/spring-mvc-webflow/pom.xml index c8de990da0..219a2be689 100644 --- a/spring-mvc-webflow/pom.xml +++ b/spring-mvc-webflow/pom.xml @@ -94,7 +94,6 @@ 4.5.2 - 2.6 2.7 1.6.1 diff --git a/spring-mvc-xml/pom.xml b/spring-mvc-xml/pom.xml index c978bdd983..9f7a24b358 100644 --- a/spring-mvc-xml/pom.xml +++ b/spring-mvc-xml/pom.xml @@ -33,7 +33,7 @@ javax.servlet javax.servlet-api - ${javax.servlet.version} + ${javax.servlet-api.version} provided @@ -129,17 +129,13 @@ 6.0.10.Final - 1.2 - 3.1.0 3.0.1-b08 19.0 - 3.5 2.8.0 - 2.6 1.6.1 diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 5240ae24e7..69becfb4ae 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -74,7 +74,6 @@ 19.0 - 3.5 org.baeldung.web.main.Application diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index a85393b7a8..5bc3a70ed5 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -287,7 +287,6 @@ 19.0 - 3.5 3.25.0-GA diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index 70fea91f31..7ee658d8ba 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -353,7 +353,6 @@ 19.0 - 3.5 1.7.0 diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index d301957eb9..263e451c62 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -323,7 +323,6 @@ 4.0.0 1.4 3.1.0 - 3.5 1.4.9 diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 99bdd7646d..670bac9805 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -263,7 +263,6 @@ 4.0.0 1.4 3.1.0 - 3.5 20.0 diff --git a/spring-resttemplate/pom.xml b/spring-resttemplate/pom.xml index 06d4eed9fc..ae5cfed4c9 100644 --- a/spring-resttemplate/pom.xml +++ b/spring-resttemplate/pom.xml @@ -284,7 +284,6 @@ - 3.5 1.4.9 diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index 4e932f3245..3bae514bc1 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -194,10 +194,8 @@ 19.0 - 3.5 - 2.6 1.6.1 diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index cf1de1730d..0baaea15ef 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -196,13 +196,11 @@ 19.0 - 3.5 4.4.5 4.5.2 - 2.6 1.6.1 diff --git a/spring-security-mvc-jsonview/pom.xml b/spring-security-mvc-jsonview/pom.xml index 8fa7b4ffb5..a7f668ae8b 100644 --- a/spring-security-mvc-jsonview/pom.xml +++ b/spring-security-mvc-jsonview/pom.xml @@ -111,7 +111,7 @@ javax.servlet javax.servlet-api - ${javax.servlet.version} + ${javax.servlet-api.version} provided @@ -206,12 +206,6 @@ - - 3.1.0 - 1.2 - - - 2.6 1.6.1 2.4.0 diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index 02ed0e36f2..1ca11bc1ab 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -175,7 +175,6 @@ - 2.6 1.6.1 diff --git a/spring-security-mvc-persisted-remember-me/pom.xml b/spring-security-mvc-persisted-remember-me/pom.xml index 5e987dcb77..2f7989d573 100644 --- a/spring-security-mvc-persisted-remember-me/pom.xml +++ b/spring-security-mvc-persisted-remember-me/pom.xml @@ -99,7 +99,7 @@ javax.servlet javax.servlet-api - ${javax.servlet.version} + ${javax.servlet-api.version} provided @@ -200,15 +200,10 @@ 9.4.1212 - - 3.1.0 - 1.2 - 19.0 - 2.6 1.6.1 1.5.10.RELEASE diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index 276f651436..b55ce70517 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -119,7 +119,6 @@ 3.0.2 - 2.6 1.6.1 diff --git a/spring-security-mvc-socket/pom.xml b/spring-security-mvc-socket/pom.xml index f1d28355fd..f799a7fa9f 100644 --- a/spring-security-mvc-socket/pom.xml +++ b/spring-security-mvc-socket/pom.xml @@ -78,7 +78,7 @@ com.h2database h2 - ${h2database.version} + ${h2.version} @@ -186,7 +186,6 @@ 5.2.10.Final 4.2.3.RELEASE 1.11.3.RELEASE - 1.4.196 1.2.3 diff --git a/spring-security-react/pom.xml b/spring-security-react/pom.xml index c7b7c85be8..40c284af7f 100644 --- a/spring-security-react/pom.xml +++ b/spring-security-react/pom.xml @@ -169,10 +169,8 @@ 19.0 - 3.5 - 2.6 2.7 1.6 9.4.11.v20180605 diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index 8a90247386..78bab83db5 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -279,7 +279,6 @@ 19.0 - 2.6 1.6.1 diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index 2180b917e5..4bab9b9d95 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -206,7 +206,6 @@ 19.0 - 3.5 1.2 diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index af38c1ffef..a66909a68e 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -271,7 +271,6 @@ 26.0-jre - 3.5 1.3.2 diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index 16f19b681f..e155a0f6b2 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -62,7 +62,6 @@ - 1.8 2.1.2.RELEASE diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index e948c908d4..655e885568 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -94,8 +94,4 @@ - - 3.3.2 - - \ No newline at end of file diff --git a/spring-static-resources/pom.xml b/spring-static-resources/pom.xml index 84519a37c1..b8068814ba 100644 --- a/spring-static-resources/pom.xml +++ b/spring-static-resources/pom.xml @@ -145,7 +145,7 @@ commons-io commons-io - ${commons.io.version} + ${commons-io.version} @@ -215,9 +215,6 @@ 1.5.1 - - - 2.5 \ No newline at end of file diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml index e6e8553c80..cd61dfbf27 100644 --- a/spring-userservice/pom.xml +++ b/spring-userservice/pom.xml @@ -234,11 +234,7 @@ 19.0 - 3.5 1.4.01 - - - 2.6 \ No newline at end of file diff --git a/spring-zuul/pom.xml b/spring-zuul/pom.xml index fbbbdddbf7..a613f51c3f 100644 --- a/spring-zuul/pom.xml +++ b/spring-zuul/pom.xml @@ -39,10 +39,6 @@ 2.1.0.RELEASE - - 3.5 - - 2.6 \ No newline at end of file diff --git a/struts-2/pom.xml b/struts-2/pom.xml index 7de688ff2c..1f7d6876d5 100644 --- a/struts-2/pom.xml +++ b/struts-2/pom.xml @@ -70,7 +70,6 @@ 2.5.5 2.5.8 4.3.6.RELEASE - 3.0.0 \ No newline at end of file diff --git a/tensorflow-java/pom.xml b/tensorflow-java/pom.xml index f9abde737c..84d2f6cf21 100644 --- a/tensorflow-java/pom.xml +++ b/tensorflow-java/pom.xml @@ -24,13 +24,13 @@ org.junit.jupiter junit-jupiter-api - ${junit.jupiter.version} + ${junit-jupiter.version} test org.junit.jupiter junit-jupiter-engine - ${junit.jupiter.version} + ${junit-jupiter.version} test @@ -46,6 +46,5 @@ 1.12.0 - 5.4.0 \ No newline at end of file diff --git a/testing-modules/junit-5-basics/pom.xml b/testing-modules/junit-5-basics/pom.xml index f72c14ee65..68a0ceeee7 100644 --- a/testing-modules/junit-5-basics/pom.xml +++ b/testing-modules/junit-5-basics/pom.xml @@ -153,7 +153,6 @@ 5.4.2 1.2.0 5.4.2 - 1.4.196 5.0.6.RELEASE 2.21.0 diff --git a/testing-modules/load-testing-comparison/pom.xml b/testing-modules/load-testing-comparison/pom.xml index 44014e96ab..2c53657481 100644 --- a/testing-modules/load-testing-comparison/pom.xml +++ b/testing-modules/load-testing-comparison/pom.xml @@ -145,7 +145,6 @@ 5.0 3.11 2.0.5.RELEASE - 1.4.197 \ No newline at end of file diff --git a/testing-modules/mockito/pom.xml b/testing-modules/mockito/pom.xml index 19dbaa0dc1..7b6d6e7735 100644 --- a/testing-modules/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -94,7 +94,6 @@ 2.0.9.RELEASE 19.0 - 3.5 1.7.0 diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 4ed10f0641..eb85c6c8be 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -194,14 +194,12 @@ 18.0 - 2.9.7 1.8 19.0 2.5 1.4.7 9.4.0.v20161208 - 3.5 3.2.2 4.4.5 diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index 6dad3be117..a1995ce9ff 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -151,7 +151,6 @@ 19.0 - 3.5 2.9.0 @@ -163,9 +162,6 @@ 4.5.2 4.1 - - - 2.6 \ No newline at end of file diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index f4d7b5dc66..6f2700e2df 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -73,7 +73,7 @@ javax.servlet javax.servlet-api - ${servlet.api.version} + ${javax.servlet-api.version} @@ -94,7 +94,7 @@ 3.1.6 5.4.0 5.1.4.RELEASE - 4.0.1 + 4.0.1 2.1.1 diff --git a/testing-modules/test-containers/pom.xml b/testing-modules/test-containers/pom.xml index 7ee002ea8b..292af2051a 100644 --- a/testing-modules/test-containers/pom.xml +++ b/testing-modules/test-containers/pom.xml @@ -99,7 +99,6 @@ - 5.1.0 1.0.1 4.12.1 2.8.2 diff --git a/vaadin/pom.xml b/vaadin/pom.xml index 089ebe67c1..e3d882bbda 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -187,7 +187,6 @@ 1.8 local mytheme - 3.0.0 3.0.0 diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index 2492951d1a..200ca7577f 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -141,10 +141,6 @@ 2.8.0 4.1 - - 3.5 - 2.5 - 3.0.1 3.0.0 diff --git a/xml/pom.xml b/xml/pom.xml index e9b89c71fc..123875b1d9 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -249,18 +249,12 @@ 1.6.1 1.1.6 2.0.6 - 2.5 4.1 1.2.4.5 2.1 1.4.2 1.0-2 - - 3.5 - 2.4 - 1.8 - 1.3.1 From aac72242b6e6d93c21b08fc1555baa8fd32371a4 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Mon, 15 Jul 2019 09:56:25 +0300 Subject: [PATCH 178/352] Update README.md --- spring-mvc-kotlin/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-mvc-kotlin/README.md b/spring-mvc-kotlin/README.md index e5167f69fc..cc6827eb1b 100644 --- a/spring-mvc-kotlin/README.md +++ b/spring-mvc-kotlin/README.md @@ -2,3 +2,4 @@ - [Spring MVC Setup with Kotlin](http://www.baeldung.com/spring-mvc-kotlin) - [Working with Kotlin and JPA](http://www.baeldung.com/kotlin-jpa) - [Kotlin-allopen and Spring](http://www.baeldung.com/kotlin-allopen-spring) +- [MockMvc Kotlin DSL](https://www.baeldung.com/mockmvc-kotlin-dsl) From ecfb5a2b944a847432b9d53e507a088a3486aabc Mon Sep 17 00:00:00 2001 From: eelhazati Date: Mon, 15 Jul 2019 10:25:50 +0100 Subject: [PATCH 179/352] add module to the main pom, in the profiles default-first and integration-lite-first. --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 35a7b95095..f9ee6e74c2 100644 --- a/pom.xml +++ b/pom.xml @@ -559,7 +559,7 @@ spring-boot-flowable spring-security-kerberos morphia - + oauth2-framework-impl @@ -1236,6 +1236,7 @@ rsocket rxjava rxjava-2 + oauth2-framework-impl From aba05a929c0d5084d88bf192f15055ac34127825 Mon Sep 17 00:00:00 2001 From: eelhazati Date: Mon, 15 Jul 2019 10:32:04 +0100 Subject: [PATCH 180/352] Replace the 'approbation' term with 'approval'. --- .../authorization/server/api/AuthorizationEndpoint.java | 4 ++-- .../oauth2-authorization-server/src/main/webapp/authorize.jsp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java index 10e78a2dfd..ba5e1ec359 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/AuthorizationEndpoint.java @@ -121,8 +121,8 @@ public class AuthorizationEndpoint { String redirectUri = originalParams.getFirst("resolved_redirect_uri"); StringBuilder sb = new StringBuilder(redirectUri); - String approbationStatus = params.getFirst("approbation_status"); - if ("NO".equals(approbationStatus)) { + String approvalStatus = params.getFirst("approval_status"); + if ("NO".equals(approvalStatus)) { URI location = UriBuilder.fromUri(sb.toString()) .queryParam("error", "User doesn't approved the request.") .queryParam("error_description", "User doesn't approved the request.") diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp index 1004b5b8b7..41b0582c03 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/webapp/authorize.jsp @@ -41,8 +41,8 @@ - - + + From 81ae72d8a2ccf9ef6eca1f7026cf22ca3b939d83 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 15 Jul 2019 04:09:03 -0700 Subject: [PATCH 181/352] Create README.md [skip.ci] --- core-java-modules/core-java-lambdas/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java-lambdas/README.md diff --git a/core-java-modules/core-java-lambdas/README.md b/core-java-modules/core-java-lambdas/README.md new file mode 100644 index 0000000000..10b876735e --- /dev/null +++ b/core-java-modules/core-java-lambdas/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables) From 0bcdf47ee791f77da3e014a06a3e9cda32520365 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 15 Jul 2019 04:10:03 -0700 Subject: [PATCH 182/352] Update README.md [skip ci] --- quarkus/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/quarkus/README.md b/quarkus/README.md index 01009eab3e..8116d16cb7 100644 --- a/quarkus/README.md +++ b/quarkus/README.md @@ -1,3 +1,3 @@ ## Relevant articles: -- [Guide to QuarkusIO](hhttps://www.baeldung.com/quarkus-io) +- [Guide to QuarkusIO](https://www.baeldung.com/quarkus-io) From aeb237ceb9fe5492b0f0a20a778841b7a3a50f1c Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 15 Jul 2019 04:12:06 -0700 Subject: [PATCH 183/352] Create README.md [skip ci] --- core-java-modules/core-java-12/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java-12/README.md diff --git a/core-java-modules/core-java-12/README.md b/core-java-modules/core-java-12/README.md new file mode 100644 index 0000000000..4514fd1a2b --- /dev/null +++ b/core-java-modules/core-java-12/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api) From 4e93986e9bea4cb3c662390c938bac0f123b2032 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 15 Jul 2019 04:13:32 -0700 Subject: [PATCH 184/352] Update README.MD [skip ci] --- java-strings-2/README.MD | 1 + 1 file changed, 1 insertion(+) diff --git a/java-strings-2/README.MD b/java-strings-2/README.MD index 6548c48f2c..c6d4f0222a 100644 --- a/java-strings-2/README.MD +++ b/java-strings-2/README.MD @@ -4,3 +4,4 @@ - [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) - [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) - [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) +- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) From caec5d3d6ba530e2f2702655988c4e470fe01165 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 15 Jul 2019 04:16:06 -0700 Subject: [PATCH 185/352] Create README.md [skip ci] --- .../src/main/java/com/baeldung/predicate/not/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md b/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md new file mode 100644 index 0000000000..6f8f95970e --- /dev/null +++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference) From 16105dc94c5347ead953e9c454811946d2e419e6 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 15 Jul 2019 04:17:07 -0700 Subject: [PATCH 186/352] Update README.md [skip ci] --- core-java-modules/core-java-concurrency-basic/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-concurrency-basic/README.md b/core-java-modules/core-java-concurrency-basic/README.md index 6fa702fbe7..c498bed315 100644 --- a/core-java-modules/core-java-concurrency-basic/README.md +++ b/core-java-modules/core-java-concurrency-basic/README.md @@ -17,3 +17,4 @@ - [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable) - [What is Thread-Safety and How to Achieve it?](https://www.baeldung.com/java-thread-safety) - [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread) +- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) From b360c8aa5801c837e6babfd5c1ee70a5b077d994 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 15 Jul 2019 04:18:02 -0700 Subject: [PATCH 187/352] Update README.md [skip ci] --- persistence-modules/java-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 7edcd168e9..5a99217f45 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -13,3 +13,4 @@ - [Defining JPA Entities](https://www.baeldung.com/jpa-entities) - [JPA @Basic Annotation](https://www.baeldung.com/jpa-basic-annotation) - [Default Column Values in JPA](https://www.baeldung.com/jpa-default-column-values) +- [Persisting Enums in JPA](https://www.baeldung.com/jpa-persisting-enums-in-jpa) From 40657d8eec760c78a782e7d6e32ed8e6dfcdd162 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 15 Jul 2019 04:18:48 -0700 Subject: [PATCH 188/352] Update README.md [skip ci] --- persistence-modules/spring-data-jpa-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md index 3bd62cbd45..1f7de81c02 100644 --- a/persistence-modules/spring-data-jpa-2/README.md +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -12,3 +12,4 @@ - [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update) - [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) - [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) +- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) From b7e27478c58e83b586fe68b2deb7a4db3eef8d44 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 15 Jul 2019 04:21:44 -0700 Subject: [PATCH 189/352] Create README.md [skip ci] --- core-java-modules/core-java-exceptions/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java-exceptions/README.md diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md new file mode 100644 index 0000000000..5338789a2f --- /dev/null +++ b/core-java-modules/core-java-exceptions/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) From 76bc107d24e477d7b66c8219dac98a814a810047 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 15 Jul 2019 04:22:40 -0700 Subject: [PATCH 190/352] Create README.md [skip ci] --- spf4j/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 spf4j/README.md diff --git a/spf4j/README.md b/spf4j/README.md new file mode 100644 index 0000000000..a39cd01b5e --- /dev/null +++ b/spf4j/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to SPF4J](https://www.baeldung.com/spf4j) From fb162d53f3b35c4610a6c4d17b272ec67be517b9 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 15 Jul 2019 04:30:29 -0700 Subject: [PATCH 191/352] Create README.md [skip ci] --- persistence-modules/jpa-hibernate-cascade-type/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 persistence-modules/jpa-hibernate-cascade-type/README.md diff --git a/persistence-modules/jpa-hibernate-cascade-type/README.md b/persistence-modules/jpa-hibernate-cascade-type/README.md new file mode 100644 index 0000000000..d7f3d7dd7c --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Overview of JPA/Hibernate Cascade Types](https://www.baeldung.com/jpa-cascade-types) From eed39166724144e5bbd5f9795a6282c4ca6cae93 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 15 Jul 2019 04:31:10 -0700 Subject: [PATCH 192/352] Update README.md [skip ci] --- algorithms-miscellaneous-3/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index 71541cd2b3..cd3711d573 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -6,4 +6,4 @@ - [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity) - [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted) - [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle) -- [A Guide to the Folding Technique](https://www.baeldung.com/folding-hashing-technique) +- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique) From d7fb226f308b41c87271ce3257d19e2b49a842cc Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Mon, 15 Jul 2019 15:23:51 +0300 Subject: [PATCH 193/352] Update README.md --- testing-modules/junit-5-basics/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/testing-modules/junit-5-basics/README.md b/testing-modules/junit-5-basics/README.md index 2c924a15a7..dbe6803401 100644 --- a/testing-modules/junit-5-basics/README.md +++ b/testing-modules/junit-5-basics/README.md @@ -1,5 +1,4 @@ ### Relevant Articles: -- [The Basics of JUnit 5 – A Preview](http://www.baeldung.com/junit-5-preview) - [A Guide to JUnit 5](http://www.baeldung.com/junit-5) - [JUnit5 @RunWith](http://www.baeldung.com/junit-5-runwith) - [Get the Path of the /src/test/resources Directory in JUnit](https://www.baeldung.com/junit-src-test-resources-directory-path) @@ -8,4 +7,4 @@ - [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) - [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) - [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) -- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) \ No newline at end of file +- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) From fc24c7b69bbdb990089d710e8501a22905e380ac Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 15 Jul 2019 11:13:30 -0300 Subject: [PATCH 194/352] Fixed article links, previously moved to spring-boot-mvc --- spring-boot-mvc/README.md | 2 ++ spring-mvc-basics/README.md | 1 - spring-mvc-java/README.md | 1 - 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot-mvc/README.md b/spring-boot-mvc/README.md index d5a39cdc9f..e3e3dbdb74 100644 --- a/spring-boot-mvc/README.md +++ b/spring-boot-mvc/README.md @@ -12,3 +12,5 @@ - [Setting Up Swagger 2 with a Spring REST API](http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally) - [Accessing Spring MVC Model Objects in JavaScript](https://www.baeldung.com/spring-mvc-model-objects-js) +- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) +- [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index afb71ce63d..a54d2133e9 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -8,7 +8,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) - [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) -- [Using Spring ResponseEntity to Manipulate the HTTP Response](http://www.baeldung.com/spring-response-entity) - [A Guide to the ViewResolver in Spring MVC](http://www.baeldung.com/spring-mvc-view-resolver-tutorial) - [Guide to Spring Handler Mappings](http://www.baeldung.com/spring-handler-mappings) - [Spring MVC Content Negotiation](http://www.baeldung.com/spring-mvc-content-negotiation-json-xml) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index f12c904229..402e1c89a2 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -6,7 +6,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) - [Introduction to Pointcut Expressions in Spring](http://www.baeldung.com/spring-aop-pointcut-tutorial) - [Introduction to Advice Types in Spring](http://www.baeldung.com/spring-aop-advice-tutorial) - [Integration Testing in Spring](http://www.baeldung.com/integration-testing-in-spring) From 3150b6d4fdd133942fec71d220d6ffdbe7ac580b Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 15 Jul 2019 13:07:01 -0300 Subject: [PATCH 195/352] Moved MediaTypeNotAcceptableException article from spring-mvc-java to spring-mvc-basics module, and added test --- spring-mvc-basics/README.md | 3 +- ...tAcceptableExceptionExampleController.java | 8 +++-- ...bleExceptionControllerIntegrationTest.java | 30 +++++++++++++++++++ spring-mvc-java/README.md | 1 - 4 files changed, 37 insertions(+), 5 deletions(-) rename {spring-mvc-java => spring-mvc-basics}/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java (92%) create mode 100644 spring-mvc-basics/src/test/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest.java diff --git a/spring-mvc-basics/README.md b/spring-mvc-basics/README.md index a54d2133e9..b257b3587b 100644 --- a/spring-mvc-basics/README.md +++ b/spring-mvc-basics/README.md @@ -14,4 +14,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring @RequestMapping New Shortcut Annotations](http://www.baeldung.com/spring-new-requestmapping-shortcuts) - [Spring MVC Custom Validation](http://www.baeldung.com/spring-mvc-custom-validator) - [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) -- [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) \ No newline at end of file +- [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) +- [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java b/spring-mvc-basics/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java similarity index 92% rename from spring-mvc-java/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java rename to spring-mvc-basics/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java index 539a6032a6..1e3591b7aa 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java +++ b/spring-mvc-basics/src/main/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionExampleController.java @@ -1,16 +1,18 @@ package com.baeldung.exception; +import java.util.Collections; +import java.util.Map; + import org.springframework.http.MediaType; import org.springframework.web.HttpMediaTypeNotAcceptableException; +import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; -import java.util.Collections; -import java.util.Map; - @RestController +@ControllerAdvice public class HttpMediaTypeNotAcceptableExceptionExampleController { @PostMapping(value = "/test", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) diff --git a/spring-mvc-basics/src/test/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest.java b/spring-mvc-basics/src/test/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest.java new file mode 100644 index 0000000000..797e489080 --- /dev/null +++ b/spring-mvc-basics/src/test/java/com/baeldung/exception/HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.exception; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +@AutoConfigureMockMvc +public class HttpMediaTypeNotAcceptableExceptionControllerIntegrationTest { + + @Autowired + MockMvc mockMvc; + + @Test + public void whenHttpMediaTypeNotAcceptableExceptionTriggered_thenExceptionHandled() throws Exception { + mockMvc.perform(post("/test").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_PDF)) + .andExpect(content().string("acceptable MIME type:application/json")); + } +} diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 402e1c89a2..b747a6c2a3 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -16,7 +16,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) -- [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) - [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) From f43db12fcbdac8b0c47cede959066f7de53ea46d Mon Sep 17 00:00:00 2001 From: vatsalgosar Date: Tue, 16 Jul 2019 01:55:08 +0530 Subject: [PATCH 196/352] BAEL-2728 | vatsalgosar@gmail.com - Adding spring-boot-configuration project to spring-boot-bootstrap module --- .../spring-boot-configuration}/README.md | 0 .../spring-boot-configuration}/pom.xml | 14 +-------- .../main/java/com/baeldung/Application.java | 9 ++++-- .../baeldung/controller/PersonController.java | 0 .../main/java/com/baeldung/domain/Person.java | 0 .../exception/PersonNotFoundException.java | 0 .../baeldung/repository/PersonRepository.java | 0 .../com/baeldung/service/PersonService.java | 2 +- .../src/main/resources/application.properties | 0 .../src/main/resources/schema.sql | 0 .../java/com/baeldung/ApplicationTests.java | 0 spring-boot-configuration/.gitignore | 31 ------------------- .../main/java/com/baeldung/SwaggerConfig.java | 22 ------------- 13 files changed, 9 insertions(+), 69 deletions(-) rename {spring-boot-configuration => spring-boot-bootstrap/spring-boot-configuration}/README.md (100%) rename {spring-boot-configuration => spring-boot-bootstrap/spring-boot-configuration}/pom.xml (84%) rename {spring-boot-configuration => spring-boot-bootstrap/spring-boot-configuration}/src/main/java/com/baeldung/Application.java (75%) rename {spring-boot-configuration => spring-boot-bootstrap/spring-boot-configuration}/src/main/java/com/baeldung/controller/PersonController.java (100%) rename {spring-boot-configuration => spring-boot-bootstrap/spring-boot-configuration}/src/main/java/com/baeldung/domain/Person.java (100%) rename {spring-boot-configuration => spring-boot-bootstrap/spring-boot-configuration}/src/main/java/com/baeldung/exception/PersonNotFoundException.java (100%) rename {spring-boot-configuration => spring-boot-bootstrap/spring-boot-configuration}/src/main/java/com/baeldung/repository/PersonRepository.java (100%) rename {spring-boot-configuration => spring-boot-bootstrap/spring-boot-configuration}/src/main/java/com/baeldung/service/PersonService.java (98%) rename {spring-boot-configuration => spring-boot-bootstrap/spring-boot-configuration}/src/main/resources/application.properties (100%) rename {spring-boot-configuration => spring-boot-bootstrap/spring-boot-configuration}/src/main/resources/schema.sql (100%) rename {spring-boot-configuration => spring-boot-bootstrap/spring-boot-configuration}/src/test/java/com/baeldung/ApplicationTests.java (100%) delete mode 100644 spring-boot-configuration/.gitignore delete mode 100644 spring-boot-configuration/src/main/java/com/baeldung/SwaggerConfig.java diff --git a/spring-boot-configuration/README.md b/spring-boot-bootstrap/spring-boot-configuration/README.md similarity index 100% rename from spring-boot-configuration/README.md rename to spring-boot-bootstrap/spring-boot-configuration/README.md diff --git a/spring-boot-configuration/pom.xml b/spring-boot-bootstrap/spring-boot-configuration/pom.xml similarity index 84% rename from spring-boot-configuration/pom.xml rename to spring-boot-bootstrap/spring-boot-configuration/pom.xml index ede2504272..02b2e53159 100644 --- a/spring-boot-configuration/pom.xml +++ b/spring-boot-bootstrap/spring-boot-configuration/pom.xml @@ -40,19 +40,7 @@ org.hibernate hibernate-entitymanager - - - - io.springfox - springfox-swagger2 - 2.9.2 - - - io.springfox - springfox-swagger-ui - 2.9.2 - - + org.springframework.boot spring-boot-starter-test diff --git a/spring-boot-configuration/src/main/java/com/baeldung/Application.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/Application.java similarity index 75% rename from spring-boot-configuration/src/main/java/com/baeldung/Application.java rename to spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/Application.java index 019cc5b57c..7021ae62fa 100644 --- a/spring-boot-configuration/src/main/java/com/baeldung/Application.java +++ b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/Application.java @@ -1,20 +1,25 @@ package com.baeldung; +import com.baeldung.service.PersonService; import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; @EnableAutoConfiguration @ComponentScan(basePackages = {"com.baeldung.*"}) @SpringBootConfiguration -@Import({SwaggerConfig.class}) public class Application { public static void main(String[] args) { - SpringApplication.run(Application.class, args); } + + @Bean + public PersonService personService() { + return new PersonService(); + } } diff --git a/spring-boot-configuration/src/main/java/com/baeldung/controller/PersonController.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/controller/PersonController.java similarity index 100% rename from spring-boot-configuration/src/main/java/com/baeldung/controller/PersonController.java rename to spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/controller/PersonController.java diff --git a/spring-boot-configuration/src/main/java/com/baeldung/domain/Person.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/domain/Person.java similarity index 100% rename from spring-boot-configuration/src/main/java/com/baeldung/domain/Person.java rename to spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/domain/Person.java diff --git a/spring-boot-configuration/src/main/java/com/baeldung/exception/PersonNotFoundException.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/exception/PersonNotFoundException.java similarity index 100% rename from spring-boot-configuration/src/main/java/com/baeldung/exception/PersonNotFoundException.java rename to spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/exception/PersonNotFoundException.java diff --git a/spring-boot-configuration/src/main/java/com/baeldung/repository/PersonRepository.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/repository/PersonRepository.java similarity index 100% rename from spring-boot-configuration/src/main/java/com/baeldung/repository/PersonRepository.java rename to spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/repository/PersonRepository.java diff --git a/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java similarity index 98% rename from spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java rename to spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java index e5929177de..74f7cb0a70 100644 --- a/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java +++ b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java @@ -9,7 +9,7 @@ import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; -@Service +//@Service public class PersonService { @Autowired diff --git a/spring-boot-configuration/src/main/resources/application.properties b/spring-boot-bootstrap/spring-boot-configuration/src/main/resources/application.properties similarity index 100% rename from spring-boot-configuration/src/main/resources/application.properties rename to spring-boot-bootstrap/spring-boot-configuration/src/main/resources/application.properties diff --git a/spring-boot-configuration/src/main/resources/schema.sql b/spring-boot-bootstrap/spring-boot-configuration/src/main/resources/schema.sql similarity index 100% rename from spring-boot-configuration/src/main/resources/schema.sql rename to spring-boot-bootstrap/spring-boot-configuration/src/main/resources/schema.sql diff --git a/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java b/spring-boot-bootstrap/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java similarity index 100% rename from spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java rename to spring-boot-bootstrap/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java diff --git a/spring-boot-configuration/.gitignore b/spring-boot-configuration/.gitignore deleted file mode 100644 index a2a3040aa8..0000000000 --- a/spring-boot-configuration/.gitignore +++ /dev/null @@ -1,31 +0,0 @@ -HELP.md -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/** -!**/src/test/** - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ - -### VS Code ### -.vscode/ diff --git a/spring-boot-configuration/src/main/java/com/baeldung/SwaggerConfig.java b/spring-boot-configuration/src/main/java/com/baeldung/SwaggerConfig.java deleted file mode 100644 index c69e65bc4e..0000000000 --- a/spring-boot-configuration/src/main/java/com/baeldung/SwaggerConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung; - -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.context.annotation.Bean; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -@SpringBootConfiguration -@EnableSwagger2 -public class SwaggerConfig { - @Bean - public Docket api() { - return new Docket(DocumentationType.SWAGGER_2) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build(); - } -} From ff2988fc5107d04f3bf345dcc7d359fc51f05b1b Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 15 Jul 2019 20:02:12 -0300 Subject: [PATCH 197/352] Moved Circular Depenednecy article from spring-mvc-java to spring-core module --- spring-core/README.md | 1 + .../com/baeldung/circulardependency/CircularDependencyA.java | 0 .../com/baeldung/circulardependency/CircularDependencyB.java | 0 .../circulardependency/CircularDependencyIntegrationTest.java | 0 .../test/java/com/baeldung/circulardependency/TestConfig.java | 0 spring-mvc-java/README.md | 1 - 6 files changed, 1 insertion(+), 1 deletion(-) rename {spring-mvc-java => spring-core}/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java (100%) rename {spring-mvc-java => spring-core}/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java (100%) rename {spring-mvc-java => spring-core}/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java (100%) rename {spring-mvc-java => spring-core}/src/test/java/com/baeldung/circulardependency/TestConfig.java (100%) diff --git a/spring-core/README.md b/spring-core/README.md index d542fa8ed1..74f86ef49e 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -24,3 +24,4 @@ - [What is a Spring Bean?](https://www.baeldung.com/spring-bean) - [Spring PostConstruct and PreDestroy Annotations](https://www.baeldung.com/spring-postconstruct-predestroy) - [Guice vs Spring – Dependency Injection](https://www.baeldung.com/guice-spring-dependency-injection) +- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) diff --git a/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java b/spring-core/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java rename to spring-core/src/main/java/com/baeldung/circulardependency/CircularDependencyA.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java b/spring-core/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java similarity index 100% rename from spring-mvc-java/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java rename to spring-core/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java b/spring-core/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/circulardependency/CircularDependencyIntegrationTest.java diff --git a/spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig.java b/spring-core/src/test/java/com/baeldung/circulardependency/TestConfig.java similarity index 100% rename from spring-mvc-java/src/test/java/com/baeldung/circulardependency/TestConfig.java rename to spring-core/src/test/java/com/baeldung/circulardependency/TestConfig.java diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index b747a6c2a3..e67d4f30a1 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -12,7 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Quick Guide to Spring MVC Matrix Variables](http://www.baeldung.com/spring-mvc-matrix-variables) - [Intro to WebSockets with Spring](http://www.baeldung.com/websockets-spring) - [File Upload with Spring MVC](http://www.baeldung.com/spring-file-upload) -- [Circular Dependencies in Spring](http://www.baeldung.com/circular-dependencies-in-spring) - [Introduction to HtmlUnit](http://www.baeldung.com/htmlunit) - [Upload and Display Excel Files with Spring MVC](http://www.baeldung.com/spring-mvc-excel-files) - [web.xml vs Initializer with Spring](http://www.baeldung.com/spring-xml-vs-java-config) From 9566b4d5e4c6686f603f370ea676c22ee653d406 Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Tue, 16 Jul 2019 10:02:17 +0530 Subject: [PATCH 198/352] Mongodb morphia (#7316) * Adding source code for tutorial tracked by BAEL-2971 * Renaming Integration Test as par standard * Incorporated review comments on the article. * Moved the morphia module inside persistence-modules/java-mongodb * Deleted the module morphia. --- morphia/README.md | 3 - morphia/pom.xml | 43 ----------- morphia/src/main/resources/logback.xml | 13 ---- persistence-modules/java-mongodb/pom.xml | 71 +++++++++++-------- .../com/baeldung/morphia/domain/Author.java | 0 .../com/baeldung/morphia/domain/Book.java | 0 .../baeldung/morphia/domain/Publisher.java | 0 .../morphia/MorphiaIntegrationTest.java | 13 ++-- pom.xml | 2 - 9 files changed, 47 insertions(+), 98 deletions(-) delete mode 100644 morphia/README.md delete mode 100644 morphia/pom.xml delete mode 100644 morphia/src/main/resources/logback.xml rename {morphia => persistence-modules/java-mongodb}/src/main/java/com/baeldung/morphia/domain/Author.java (100%) rename {morphia => persistence-modules/java-mongodb}/src/main/java/com/baeldung/morphia/domain/Book.java (100%) rename {morphia => persistence-modules/java-mongodb}/src/main/java/com/baeldung/morphia/domain/Publisher.java (100%) rename {morphia => persistence-modules/java-mongodb}/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java (94%) diff --git a/morphia/README.md b/morphia/README.md deleted file mode 100644 index 008cf76c49..0000000000 --- a/morphia/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Intro to Morphia](http://www.baeldung.com/intro-to-morphia) diff --git a/morphia/pom.xml b/morphia/pom.xml deleted file mode 100644 index e4010a26a1..0000000000 --- a/morphia/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - com.baeldung.morphia - morphia - morphia - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - .. - - - - - dev.morphia.morphia - core - ${morphia.version} - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot-maven-plugin.version} - - - - - - - 1.4.2.RELEASE - 1.5.3 - - - diff --git a/morphia/src/main/resources/logback.xml b/morphia/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/morphia/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml index dc4503c95e..35e59e60c6 100644 --- a/persistence-modules/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -1,40 +1,49 @@ - - 4.0.0 - com.baeldung - java-mongodb - 1.0-SNAPSHOT + + 4.0.0 + com.baeldung + java-mongodb + 1.0-SNAPSHOT java-mongodb - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + - + - - de.flapdoodle.embedmongo - de.flapdoodle.embedmongo - ${flapdoodle.version} - test - - - org.mongodb - mongo-java-driver - ${mongo.version} - + + de.flapdoodle.embedmongo + de.flapdoodle.embedmongo + ${flapdoodle.version} + test + + + org.mongodb + mongo-java-driver + ${mongo.version} + - + + dev.morphia.morphia + core + ${morphia.version} + - - 1.8 - 1.8 - 3.10.1 - 1.11 - + + + + 1.8 + 1.8 + 3.10.1 + 1.11 + 1.5.3 + diff --git a/morphia/src/main/java/com/baeldung/morphia/domain/Author.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Author.java similarity index 100% rename from morphia/src/main/java/com/baeldung/morphia/domain/Author.java rename to persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Author.java diff --git a/morphia/src/main/java/com/baeldung/morphia/domain/Book.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java similarity index 100% rename from morphia/src/main/java/com/baeldung/morphia/domain/Book.java rename to persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java diff --git a/morphia/src/main/java/com/baeldung/morphia/domain/Publisher.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Publisher.java similarity index 100% rename from morphia/src/main/java/com/baeldung/morphia/domain/Publisher.java rename to persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Publisher.java diff --git a/morphia/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java similarity index 94% rename from morphia/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java rename to persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java index a2542a56ab..f508c5f525 100644 --- a/morphia/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java @@ -2,6 +2,7 @@ package com.baeldung.morphia; import static dev.morphia.aggregation.Group.grouping; import static dev.morphia.aggregation.Group.push; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -51,8 +52,8 @@ public class MorphiaIntegrationTest { .contains("Learning Java") .find() .toList(); - assertEquals(books.size(), 1); - assertEquals(books.get(0), book); + assertEquals(1, books.size()); + assertEquals(book, books.get(0)); } @Test @@ -71,8 +72,8 @@ public class MorphiaIntegrationTest { .contains("Learning Java") .find() .toList(); - assertEquals(books.get(0) - .getCost(), 4.95); + assertEquals(4.95, books.get(0) + .getCost()); } @Test @@ -89,7 +90,7 @@ public class MorphiaIntegrationTest { .contains("Learning Java") .find() .toList(); - assertEquals(books.size(), 0); + assertEquals(0, books.size()); } @Test @@ -123,7 +124,7 @@ public class MorphiaIntegrationTest { assertEquals(books.size(), 1); assertEquals("Learning Java", books.get(0) .getTitle()); - assertEquals(null, books.get(0) + assertNull(books.get(0) .getAuthor()); } diff --git a/pom.xml b/pom.xml index 35a7b95095..05c719ec7c 100644 --- a/pom.xml +++ b/pom.xml @@ -558,7 +558,6 @@ tensorflow-java spring-boot-flowable spring-security-kerberos - morphia @@ -793,7 +792,6 @@ tensorflow-java spring-boot-flowable spring-security-kerberos - morphia From 38000941b53bb538ba9aafe321465f3a70c145ff Mon Sep 17 00:00:00 2001 From: Blake Ong Date: Tue, 16 Jul 2019 19:30:55 +0800 Subject: [PATCH 199/352] Bael 2666 concatenate strings with groovy (#7307) * BAEL-2666 code for concatenate strings with groovy * BAEL-2666 add placeholder link to readme * BAEL-2666 remove article link in README, move code to core-groovy-2 --- .../com/baeldung/concatenate/Wonder.groovy | 52 ++++++++++++++ .../concatenate/WonderUnitTest.groovy | 69 +++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 core-groovy-2/src/main/groovy/com/baeldung/concatenate/Wonder.groovy create mode 100644 core-groovy-2/src/test/groovy/com/baeldung/concatenate/WonderUnitTest.groovy diff --git a/core-groovy-2/src/main/groovy/com/baeldung/concatenate/Wonder.groovy b/core-groovy-2/src/main/groovy/com/baeldung/concatenate/Wonder.groovy new file mode 100644 index 0000000000..1d7527726e --- /dev/null +++ b/core-groovy-2/src/main/groovy/com/baeldung/concatenate/Wonder.groovy @@ -0,0 +1,52 @@ +package com.baeldung.concatenate + +class Wonder { + + String numOfWonder = 'seven' + + String operator_plus() { + return 'The ' + numOfWonder + ' wonders of the world' + } + + String operator_left() { + return 'The ' << numOfWonder << ' wonders of ' << 'the world' + } + + String interpolation_one() { + return "The $numOfWonder wonders of the world" + + } + + String interpolation_two() { + return "The ${numOfWonder} wonders of the world" + } + + String multilineString() { + return """ + There are $numOfWonder wonders of the world. + Can you name them all? + 1. The Great Pyramid of Giza + 2. Hanging Gardens of Babylon + 3. Colossus of Rhode + 4. Lighthouse of Alexendra + 5. Temple of Artemis + 6. Status of Zeus at Olympia + 7. Mausoleum at Halicarnassus + """ + } + + String method_concat() { + return 'The '.concat(numOfWonder).concat(' wonders of the world') + + } + + String method_builder() { + return new StringBuilder() + .append('The ').append(numOfWonder).append(' wonders of the world') + } + + String method_buffer() { + return new StringBuffer() + .append('The ').append(numOfWonder).append(' wonders of the world') + } +} \ No newline at end of file diff --git a/core-groovy-2/src/test/groovy/com/baeldung/concatenate/WonderUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/concatenate/WonderUnitTest.groovy new file mode 100644 index 0000000000..5fc74abd69 --- /dev/null +++ b/core-groovy-2/src/test/groovy/com/baeldung/concatenate/WonderUnitTest.groovy @@ -0,0 +1,69 @@ +package com.baeldung.concatenate + +import org.junit.Before +import org.junit.Test + +import static org.junit.Assert.* + +class WonderUnitTest { + + static final String EXPECTED_SINGLE_LINE = "The seven wonders of the world" + + Wonder wonder + + @Before + void before() { + wonder = new Wonder() + } + + @Test + void whenUsingOperatorPlus_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.operator_plus()) + } + + @Test + void whenUsingOperatorLeft_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.operator_left()) + } + + @Test + void whenUsingInterpolationOne_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.interpolation_one()) + } + + @Test + void whenUsingInterpolationTwo_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.interpolation_two()) + } + + @Test + void whenUsingMultiline_thenConcatCorrectly() { + def expectedMultiline = """ + There are seven wonders of the world. + Can you name them all? + 1. The Great Pyramid of Giza + 2. Hanging Gardens of Babylon + 3. Colossus of Rhode + 4. Lighthouse of Alexendra + 5. Temple of Artemis + 6. Status of Zeus at Olympia + 7. Mausoleum at Halicarnassus + """ + assertEquals(expectedMultiline, wonder.multilineString()) + } + + @Test + void whenUsingMethodConcat_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.method_concat()) + } + + @Test + void whenUsingMethodBuilder_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.method_builder()) + } + + @Test + void whenUsingMethodBuffer_thenConcatCorrectly() { + assertEquals(EXPECTED_SINGLE_LINE, wonder.method_buffer()) + } +} From 01a447d6d390898f5994aa4d57276d972517d28c Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Wed, 17 Jul 2019 13:25:58 +0530 Subject: [PATCH 200/352] BAEL-15951 Moved vavr, JHipster to default profiles (#7306) --- pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 05c719ec7c..2e34254bf5 100644 --- a/pom.xml +++ b/pom.xml @@ -480,7 +480,6 @@ jersey JGit jgroups - jhipster jhipster-5 jib jjwt @@ -777,7 +776,6 @@ undertow - vavr vertx vertx-and-rxjava video-tutorials @@ -983,6 +981,7 @@ core-kotlin-io jenkins/hello-world + jhipster jws libraries @@ -993,6 +992,7 @@ persistence-modules/jnosql vaadin + vavr @@ -1164,7 +1164,6 @@ jersey JGit jgroups - jhipster jhipster-5 jib jjwt @@ -1443,7 +1442,6 @@ undertow - vavr vertx vertx-and-rxjava video-tutorials @@ -1495,6 +1493,7 @@ core-kotlin-2 jenkins/hello-world + jhipster jws libraries @@ -1505,6 +1504,7 @@ persistence-modules/jnosql vaadin + vavr From 0423f598485e8353c0a3014bb19585549207ec49 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 17 Jul 2019 11:08:25 +0300 Subject: [PATCH 201/352] Update README.md --- spring-core/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-core/README.md b/spring-core/README.md index 74f86ef49e..18d14b7ecf 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -8,7 +8,6 @@ - [Spring YAML Configuration](http://www.baeldung.com/spring-yaml) - [Introduction to Spring’s StreamUtils](http://www.baeldung.com/spring-stream-utils) - [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) -- [Groovy Bean Definitions](http://www.baeldung.com/spring-groovy-beans) - [XML-Based Injection in Spring](http://www.baeldung.com/spring-xml-injection) - [A Quick Guide to the Spring @Lazy Annotation](http://www.baeldung.com/spring-lazy-annotation) - [Injecting Prototype Beans into a Singleton Instance in Spring](http://www.baeldung.com/spring-inject-prototype-bean-into-singleton) From 8449e11424bcd07b08333411f2bf5fca11c54b56 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 17 Jul 2019 11:16:57 +0300 Subject: [PATCH 202/352] Update README.md --- spring-security-angular/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-security-angular/README.md b/spring-security-angular/README.md index 49cd8dd62d..80312c4bab 100644 --- a/spring-security-angular/README.md +++ b/spring-security-angular/README.md @@ -1,3 +1,2 @@ ### Relevant Articles: - [Spring Security Login Page with Angular](https://www.baeldung.com/spring-security-login-angular) -- [Fixing 401s with CORS Preflights and Spring Security](https://www.baeldung.com/spring-security-cors-preflight) From 980b18f438cf749212f0948f6e3e070d06ca4176 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 17 Jul 2019 11:30:29 +0300 Subject: [PATCH 203/352] Create README.md --- testing-modules/junit5-migration/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 testing-modules/junit5-migration/README.md diff --git a/testing-modules/junit5-migration/README.md b/testing-modules/junit5-migration/README.md new file mode 100644 index 0000000000..b97ff8255c --- /dev/null +++ b/testing-modules/junit5-migration/README.md @@ -0,0 +1,2 @@ + +This is the code for the Junit 4 - Junit 5 Migration E-book. From 6d5e2d15f7a43928228a92b9bda694c2846c7b03 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 17 Jul 2019 11:31:26 +0300 Subject: [PATCH 204/352] Update README.md --- testing-modules/README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/testing-modules/README.md b/testing-modules/README.md index d69f07215e..b269f547ec 100644 --- a/testing-modules/README.md +++ b/testing-modules/README.md @@ -13,5 +13,3 @@ - [Headers, Cookies and Parameters with REST-assured](http://www.baeldung.com/rest-assured-header-cookie-parameter) - [JSON Schema Validation with REST-assured](http://www.baeldung.com/rest-assured-json-schema) - [Testing Callbacks with Mockito](http://www.baeldung.com/mockito-callbacks) -- [Running JUnit Tests in Parallel with Maven](https://www.baeldung.com/maven-junit-parallel-tests) -- [Gatling vs JMeter vs The Grinder: Comparing Load Test Tools](https://www.baeldung.com/gatling-jmeter-grinder-comparison) From b651206a8b647670a6b9c97cbf558e87fc0369cc Mon Sep 17 00:00:00 2001 From: Loredana Date: Wed, 17 Jul 2019 11:37:17 +0300 Subject: [PATCH 205/352] remove unused module --- pom.xml | 5 - spring-userservice/.gitignore | 1 - spring-userservice/.springBeans | 15 -- spring-userservice/README.md | 1 - spring-userservice/pom.xml | 240 ------------------ .../org/baeldung/custom/config/MvcConfig.java | 42 --- .../config/PersistenceDerbyJPAConfig.java | 89 ------- .../custom/config/SecSecurityConfig.java | 75 ------ .../baeldung/persistence/model/MyUser.java | 50 ---- .../security/MyUserDetailsService.java | 35 --- .../org/baeldung/security/UserController.java | 51 ---- .../java/org/baeldung/user/dao/MyUserDAO.java | 46 ---- .../baeldung/user/service/MyUserService.java | 49 ---- .../main/java/org/baeldung/web/MyUserDto.java | 29 --- .../src/main/resources/logback.xml | 13 - .../resources/persistence-derby.properties | 12 - .../src/main/webapp/META-INF/MANIFEST.MF | 3 - .../webapp/WEB-INF/mvc-dispatcher-servlet.xml | 88 ------- .../src/main/webapp/WEB-INF/views/index.jsp | 35 --- .../src/main/webapp/WEB-INF/views/login.jsp | 29 --- .../main/webapp/WEB-INF/views/register.jsp | 23 -- .../src/main/webapp/WEB-INF/web.xml | 51 ---- .../SpringContextIntegrationTest.java | 18 -- ...stomUserDetailsServiceIntegrationTest.java | 82 ------ 24 files changed, 1082 deletions(-) delete mode 100644 spring-userservice/.gitignore delete mode 100644 spring-userservice/.springBeans delete mode 100644 spring-userservice/README.md delete mode 100644 spring-userservice/pom.xml delete mode 100644 spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java delete mode 100644 spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java delete mode 100644 spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java delete mode 100644 spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java delete mode 100644 spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java delete mode 100644 spring-userservice/src/main/java/org/baeldung/security/UserController.java delete mode 100644 spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java delete mode 100644 spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java delete mode 100644 spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java delete mode 100644 spring-userservice/src/main/resources/logback.xml delete mode 100644 spring-userservice/src/main/resources/persistence-derby.properties delete mode 100644 spring-userservice/src/main/webapp/META-INF/MANIFEST.MF delete mode 100644 spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml delete mode 100644 spring-userservice/src/main/webapp/WEB-INF/views/index.jsp delete mode 100644 spring-userservice/src/main/webapp/WEB-INF/views/login.jsp delete mode 100644 spring-userservice/src/main/webapp/WEB-INF/views/register.jsp delete mode 100644 spring-userservice/src/main/webapp/WEB-INF/web.xml delete mode 100644 spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java delete mode 100644 spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java diff --git a/pom.xml b/pom.xml index 2e34254bf5..bca2807e75 100644 --- a/pom.xml +++ b/pom.xml @@ -755,8 +755,6 @@ spring-thymeleaf - spring-userservice - spring-vault spring-vertx @@ -925,7 +923,6 @@ spring-state-machine spring-swagger-codegen/spring-swagger-codegen-app spring-thymeleaf - spring-userservice spring-vault spring-vertx spring-zuul/spring-zuul-foos-resource @@ -1421,8 +1418,6 @@ spring-thymeleaf - spring-userservice - spring-vault spring-vertx diff --git a/spring-userservice/.gitignore b/spring-userservice/.gitignore deleted file mode 100644 index afe61e7c0c..0000000000 --- a/spring-userservice/.gitignore +++ /dev/null @@ -1 +0,0 @@ -derby.log \ No newline at end of file diff --git a/spring-userservice/.springBeans b/spring-userservice/.springBeans deleted file mode 100644 index ff32b84d3b..0000000000 --- a/spring-userservice/.springBeans +++ /dev/null @@ -1,15 +0,0 @@ - - - 1 - - - - - - - - - - - - diff --git a/spring-userservice/README.md b/spring-userservice/README.md deleted file mode 100644 index 097afc5fc1..0000000000 --- a/spring-userservice/README.md +++ /dev/null @@ -1 +0,0 @@ -spring-userservice is using a in memory derby db. Right click -> run on server to run the project \ No newline at end of file diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml deleted file mode 100644 index cd61dfbf27..0000000000 --- a/spring-userservice/pom.xml +++ /dev/null @@ -1,240 +0,0 @@ - - 4.0.0 - spring-userservice - spring-userservice - 0.0.1-SNAPSHOT - war - spring-userservice - - - com.baeldung - parent-spring-4 - 0.0.1-SNAPSHOT - ../parent-spring-4 - - - - - - - - org.springframework - spring-orm - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - - - - org.hibernate - hibernate-entitymanager - ${hibernate.version} - - - org.hibernate - hibernate-ehcache - ${hibernate.version} - - - xml-apis - xml-apis - ${xml-apis.version} - - - org.javassist - javassist - ${javassist.version} - - - mysql - mysql-connector-java - ${mysql-connector-java.version} - runtime - - - org.springframework.data - spring-data-jpa - ${spring-data-jpa.version} - - - com.h2database - h2 - ${h2.version} - - - - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - - javax.el - javax.el-api - ${javax.el-api.version} - - - - - - com.google.guava - guava - ${guava.version} - - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - test - - - - org.springframework - spring-test - ${spring.version} - test - - - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - - org.springframework.security - spring-security-core - ${org.springframework.security.version} - - - org.springframework.security - spring-security-web - ${org.springframework.security.version} - - - org.springframework.security - spring-security-config - ${org.springframework.security.version} - - - - org.apache.derby - derby - ${derby.version} - - - org.apache.derby - derbyclient - ${derby.version} - - - org.apache.derby - derbynet - ${derby.version} - - - org.apache.derby - derbytools - ${derby.version} - - - taglibs - standard - ${taglibs-standard.version} - - - org.springframework.security - spring-security-taglibs - ${org.springframework.security.version} - - - javax.servlet.jsp.jstl - jstl-api - ${jstl.version} - - - org.springframework.boot - spring-boot-test - ${spring-boot.version} - - - org.springframework.boot - spring-boot - ${spring-boot.version} - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - - - spring-userservice - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - - - - - - - 4.2.6.RELEASE - 1.5.14.RELEASE - 3.21.0-GA - - - 5.2.10.Final - 5.1.40 - 1.10.5.RELEASE - 10.13.1.1 - - - 5.3.3.Final - 2.2.5 - 1.1.2 - - - 19.0 - 1.4.01 - - - \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java deleted file mode 100644 index 4a9e737a92..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.custom.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@EnableWebMvc -@Configuration -@ComponentScan(basePackages = { "org.baeldung.security" }) -public class MvcConfig extends WebMvcConfigurerAdapter { - - public MvcConfig() { - super(); - } - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - - registry.addViewController("/"); - registry.addViewController("/index"); - registry.addViewController("/login"); - registry.addViewController("/register"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - - return bean; - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java deleted file mode 100644 index 6be7053b78..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.baeldung.custom.config; - -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.baeldung.user.dao.MyUserDAO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.google.common.base.Preconditions; - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-derby.properties" }) -public class PersistenceDerbyJPAConfig { - - @Autowired - private Environment env; - - public PersistenceDerbyJPAConfig() { - super(); - } - - // beans - - @Bean - public LocalContainerEntityManagerFactoryBean myEmf() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - em.setJpaProperties(additionalProperties()); - - return em; - } - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Bean - public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(emf); - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - final Properties additionalProperties() { - final Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); - hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); - return hibernateProperties; - } - - @Bean - public MyUserDAO myUserDAO() { - final MyUserDAO myUserDAO = new MyUserDAO(); - return myUserDAO; - } -} \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java deleted file mode 100644 index 44df02980f..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.baeldung.custom.config; - -import org.baeldung.security.MyUserDetailsService; -import org.baeldung.user.service.MyUserService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -@EnableWebSecurity -@Profile("!https") -public class SecSecurityConfig extends WebSecurityConfigurerAdapter { - - public SecSecurityConfig() { - super(); - } - - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.authenticationProvider(authenticationProvider()); - // @formatter:on - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http - .csrf().disable() - .authorizeRequests() - .antMatchers("/*").permitAll() - .and() - .formLogin() - .loginPage("/login") - .loginProcessingUrl("/login") - .defaultSuccessUrl("/",true) - .failureUrl("/login?error=true") - .and() - .logout() - .logoutUrl("/logout") - .deleteCookies("JSESSIONID") - .logoutSuccessUrl("/"); - // @formatter:on - } - - @Bean - public DaoAuthenticationProvider authenticationProvider() { - final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); - authProvider.setUserDetailsService(myUserDetailsService()); - authProvider.setPasswordEncoder(encoder()); - return authProvider; - } - - @Bean - public PasswordEncoder encoder() { - return new BCryptPasswordEncoder(11); - } - - @Bean - public MyUserDetailsService myUserDetailsService() { - return new MyUserDetailsService(); - } - - @Bean - public MyUserService myUserService() { - return new MyUserService(); - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java b/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java deleted file mode 100644 index 804d391641..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.baeldung.persistence.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(schema = "spring_custom_user_service") -public class MyUser { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private int id; - - @Column(unique = true, nullable = false) - private String username; - - @Column(nullable = false) - private String password; - - public MyUser() { - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(final String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(final String password) { - this.password = password; - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java deleted file mode 100644 index fe97984af8..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.security; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; - -import org.baeldung.persistence.model.MyUser; -import org.baeldung.user.dao.MyUserDAO; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Service; - -@Service("userDetailsService") -public class MyUserDetailsService implements UserDetailsService { - - @Autowired - MyUserDAO myUserDAO; - - @Override - public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { - final MyUser user = myUserDAO.findByUsername(username); - - if (user == null) { - throw new UsernameNotFoundException("No user found with username: " + username); - } - return new User(user.getUsername(), user.getPassword(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); - - } - -} diff --git a/spring-userservice/src/main/java/org/baeldung/security/UserController.java b/spring-userservice/src/main/java/org/baeldung/security/UserController.java deleted file mode 100644 index a4c15f7942..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/security/UserController.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.baeldung.security; - -import javax.annotation.Resource; - -import org.baeldung.user.service.MyUserService; -import org.baeldung.web.MyUserDto; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@Controller -public class UserController { - - @Resource - MyUserService myUserService; - - @RequestMapping(value = "/register", method = RequestMethod.POST) - public String registerUserAccount(final MyUserDto accountDto, final Model model) { - final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - model.addAttribute("name", auth.getName()); - try { - myUserService.registerNewUserAccount(accountDto); - model.addAttribute("message", "Registration successful"); - return "index"; - } catch (final Exception exc) { - model.addAttribute("message", "Registration failed"); - - return "index"; - } - } - - @RequestMapping(value = "/", method = RequestMethod.GET) - public String getHomepage(final Model model) { - final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - model.addAttribute("name", auth.getName()); - return "index"; - } - - @RequestMapping(value = "/register", method = RequestMethod.GET) - public String getRegister() { - return "register"; - } - - @RequestMapping(value = "/login", method = RequestMethod.GET) - public String getLogin() { - return "login"; - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java deleted file mode 100644 index 834941b68b..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.baeldung.user.dao; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; - -import org.baeldung.persistence.model.MyUser; -import org.springframework.stereotype.Repository; - -@Repository -public class MyUserDAO { - - @PersistenceContext - private EntityManager entityManager; - - public MyUser findByUsername(final String username) { - final Query query = entityManager.createQuery("from MyUser where username=:username", MyUser.class); - query.setParameter("username", username); - final List result = query.getResultList(); - if (result != null && result.size() > 0) { - return result.get(0); - } else - return null; - } - - public MyUser save(final MyUser user) { - entityManager.persist(user); - return user; - } - - public void removeUserByUsername(String username) { - final Query query = entityManager.createQuery("delete from MyUser where username=:username"); - query.setParameter("username", username); - query.executeUpdate(); - } - - public EntityManager getEntityManager() { - return entityManager; - } - - public void setEntityManager(final EntityManager entityManager) { - this.entityManager = entityManager; - } -} diff --git a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java deleted file mode 100644 index 2ab44752c0..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.baeldung.user.service; - -import org.baeldung.persistence.model.MyUser; -import org.baeldung.user.dao.MyUserDAO; -import org.baeldung.web.MyUserDto; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class MyUserService { - - @Autowired - private PasswordEncoder passwordEncoder; - - @Autowired - MyUserDAO myUserDAO; - - public MyUser registerNewUserAccount(final MyUserDto accountDto) throws Exception { - if (usernameExists(accountDto.getUsername())) { - throw new Exception("There is an account with that username: " + accountDto.getUsername()); - } - final MyUser user = new MyUser(); - - user.setUsername(accountDto.getUsername()); - user.setPassword(passwordEncoder.encode(accountDto.getPassword())); - return myUserDAO.save(user); - } - - public MyUser getUserByUsername(final String username) { - final MyUser user = myUserDAO.findByUsername(username); - return user; - } - - public void removeUserByUsername(String username) { - myUserDAO.removeUserByUsername(username); - } - - private boolean usernameExists(final String username) { - final MyUser user = myUserDAO.findByUsername(username); - if (user != null) { - return true; - } - return false; - } - -} diff --git a/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java b/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java deleted file mode 100644 index 60a6848ea4..0000000000 --- a/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.web; - -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; - -public class MyUserDto { - @NotNull - @Size(min = 1) - private String username; - - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(final String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(final String password) { - this.password = password; - } - -} diff --git a/spring-userservice/src/main/resources/logback.xml b/spring-userservice/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-userservice/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-userservice/src/main/resources/persistence-derby.properties b/spring-userservice/src/main/resources/persistence-derby.properties deleted file mode 100644 index b76c5de12f..0000000000 --- a/spring-userservice/src/main/resources/persistence-derby.properties +++ /dev/null @@ -1,12 +0,0 @@ -# jdbc.X -jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver -jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true -jdbc.user=tutorialuser -jdbc.pass=tutorialpass - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.DerbyDialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=update -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF b/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF deleted file mode 100644 index 254272e1c0..0000000000 --- a/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Class-Path: - diff --git a/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml deleted file mode 100644 index 48ef8a8c43..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /WEB-INF/views/ - - - .jsp - - - - - - - - - - - - - - - ${hibernate.hbm2ddl.auto} - ${hibernate.dialect} - ${hibernate.cache.use_second_level_cache} - ${hibernate.cache.use_query_cache} - - - - - - - - - - - - - - - - - - - diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp deleted file mode 100644 index 0c89257cd2..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp +++ /dev/null @@ -1,35 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="c" - uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> - - - - - -Welcome! - - - - - - - -Register -

- -Login - -

-${message } -

- -Hello, ${name }! -
-
-Logout -
- - - \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp deleted file mode 100644 index 29431f426d..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp +++ /dev/null @@ -1,29 +0,0 @@ -<%@ taglib prefix="c" - uri="http://java.sun.com/jsp/jstl/core" %> - - - - - -

Login

- -
- - - - - - - - - - - - - -
User:
Password:
- -
- Username or password invalid! - - \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp deleted file mode 100644 index e6e9d373a0..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp +++ /dev/null @@ -1,23 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="c" - uri="http://java.sun.com/jsp/jstl/core" %> - - - - -Welcome! - - - - - -Register here:

-
-Username:
-Password:
- -
- - - \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/web.xml b/spring-userservice/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index b526774179..0000000000 --- a/spring-userservice/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - Spring MVC Application - - - - - - mvc-dispatcher - org.springframework.web.servlet.DispatcherServlet - 1 - - - mvc-dispatcher - / - - - - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - - - springSecurityFilterChain - /* - - - - index.jsp - - - \ No newline at end of file diff --git a/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index 825b89eb10..0000000000 --- a/spring-userservice/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.baeldung.custom.config.MvcConfig; -import org.baeldung.custom.config.PersistenceDerbyJPAConfig; -import org.baeldung.custom.config.SecSecurityConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) -public class SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java deleted file mode 100644 index 1cd38228b8..0000000000 --- a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceIntegrationTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.baeldung.userservice; - -import static org.junit.Assert.assertEquals; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.baeldung.custom.config.MvcConfig; -import org.baeldung.custom.config.PersistenceDerbyJPAConfig; -import org.baeldung.custom.config.SecSecurityConfig; -import org.baeldung.user.service.MyUserService; -import org.baeldung.web.MyUserDto; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) -@WebAppConfiguration -public class CustomUserDetailsServiceIntegrationTest { - - private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest"); - - public static final String USERNAME = "user"; - public static final String PASSWORD = "pass"; - public static final String USERNAME2 = "user2"; - - @Autowired - MyUserService myUserService; - - @Autowired - AuthenticationProvider authenticationProvider; - - @Test - public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { - try { - MyUserDto userDTO = new MyUserDto(); - userDTO.setUsername(USERNAME); - userDTO.setPassword(PASSWORD); - - myUserService.registerNewUserAccount(userDTO); - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); - Authentication authentication = authenticationProvider.authenticate(auth); - - assertEquals(authentication.getName(), USERNAME); - - } catch (Exception exc) { - LOG.log(Level.SEVERE, "Error creating account"); - } finally { - myUserService.removeUserByUsername(USERNAME); - } - } - - @Test(expected = BadCredentialsException.class) - public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { - try { - MyUserDto userDTO = new MyUserDto(); - userDTO.setUsername(USERNAME); - userDTO.setPassword(PASSWORD); - - try { - myUserService.registerNewUserAccount(userDTO); - } catch (Exception exc) { - LOG.log(Level.SEVERE, "Error creating account"); - } - - UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); - Authentication authentication = authenticationProvider.authenticate(auth); - } finally { - myUserService.removeUserByUsername(USERNAME); - } - } - -} From b18a1339796fccd8e0c1123999f75e70adcf0ffc Mon Sep 17 00:00:00 2001 From: Loredana Date: Wed, 17 Jul 2019 12:03:03 +0300 Subject: [PATCH 206/352] remove duplicate spark module --- pom.xml | 2 - rest-with-spark-java/README.md | 1 - rest-with-spark-java/pom.xml | 39 ----- .../src/main/java/com/baeldung/Router.java | 50 ------ .../main/java/com/baeldung/domain/Book.java | 52 ------ .../com/baeldung/service/LibraryService.java | 40 ----- .../src/main/resources/logback.xml | 13 -- .../test/java/com/baeldung/AppLiveTest.java | 148 ------------------ 8 files changed, 345 deletions(-) delete mode 100644 rest-with-spark-java/README.md delete mode 100644 rest-with-spark-java/pom.xml delete mode 100644 rest-with-spark-java/src/main/java/com/baeldung/Router.java delete mode 100644 rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java delete mode 100644 rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java delete mode 100644 rest-with-spark-java/src/main/resources/logback.xml delete mode 100644 rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java diff --git a/pom.xml b/pom.xml index bca2807e75..3fd1bcf5fb 100644 --- a/pom.xml +++ b/pom.xml @@ -544,7 +544,6 @@ ratpack reactor-core - rest-with-spark-java resteasy restx @@ -1222,7 +1221,6 @@ ratpack reactor-core - rest-with-spark-java resteasy restx diff --git a/rest-with-spark-java/README.md b/rest-with-spark-java/README.md deleted file mode 100644 index ff12555376..0000000000 --- a/rest-with-spark-java/README.md +++ /dev/null @@ -1 +0,0 @@ -## Relevant articles: diff --git a/rest-with-spark-java/pom.xml b/rest-with-spark-java/pom.xml deleted file mode 100644 index fc78ac6b86..0000000000 --- a/rest-with-spark-java/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - com.baeldung - rest-with-spark-java - 1.0-SNAPSHOT - rest-with-spark-java - http://maven.apache.org - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - com.sparkjava - spark-core - ${spark-core.version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - - 2.5.4 - - - diff --git a/rest-with-spark-java/src/main/java/com/baeldung/Router.java b/rest-with-spark-java/src/main/java/com/baeldung/Router.java deleted file mode 100644 index 3482184e1e..0000000000 --- a/rest-with-spark-java/src/main/java/com/baeldung/Router.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung; - -import static spark.Spark.after; -import static spark.Spark.before; -import static spark.Spark.delete; -import static spark.Spark.get; -import static spark.Spark.post; -import static spark.Spark.port; - -import com.baeldung.domain.Book; -import com.baeldung.service.LibraryService; - -public class Router { - - public static void main( String[] args ){ - - port(8080); - - before((request, response) -> { - - //do some filtering stuff - - }); - - after((request, response) -> { - response.type("application/json"); - }); - - get("ListOfBooks", (request, response) -> { - return LibraryService.view(); - }); - - get("SearchBook/:title", (request, response) -> { - return LibraryService.view(request.params("title")); - }); - - post("AddBook/:title/:author/:publisher", (request, response) -> { - Book book = new Book(); - book.setTitle(request.params("title")); - book.setAuthor(request.params("author")); - book.setPublisher(request.params("publisher")); - return LibraryService.add(book); - }); - - delete("DeleteBook/:title", (request, response) -> { - return LibraryService.delete(request.params("title")); - }); - - } -} diff --git a/rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java b/rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java deleted file mode 100644 index 977d5d9f89..0000000000 --- a/rest-with-spark-java/src/main/java/com/baeldung/domain/Book.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.domain; - -public class Book { - - private String title; - private String author; - private String publisher; - - public Book() {} - - public Book(String title, String author, String publisher) { - super(); - this.title = title; - this.author = author; - this.publisher = publisher; - } - - public String getTitle() { - return title; - } - public void setTitle(String title) { - this.title = title; - } - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - public String getPublisher() { - return publisher; - } - public void setPublisher(String publisher) { - this.publisher = publisher; - } - - protected boolean canEqual(Object other) { - return other instanceof Book; - } - - @Override - public boolean equals(Object o) { - if (o == this) return true; - if (!(o instanceof Book)) return false; - Book other = (Book) o; - if (!other.canEqual((Object)this)) return false; - if (this.getTitle() == null ? other.getTitle() != null : !this.getTitle().equals(other.getTitle())) return false; - return true; - } - -} diff --git a/rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java b/rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java deleted file mode 100644 index e4ca4c270c..0000000000 --- a/rest-with-spark-java/src/main/java/com/baeldung/service/LibraryService.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.service; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.baeldung.domain.Book; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; - -public class LibraryService { - - private static ObjectWriter mapper = new ObjectMapper().writer().withDefaultPrettyPrinter(); - private static Map library = new HashMap(); - - public static String view() throws JsonProcessingException { - List books = new ArrayList(); - library.forEach((key, value) -> { - books.add(value); - }); - return mapper.writeValueAsString(books); - } - - public static String view(String title) throws JsonProcessingException { - return mapper.writeValueAsString(library.get(title)); - } - - public static String add(Book book) throws JsonProcessingException { - library.put(book.getTitle(), book); - return mapper.writeValueAsString(book); - } - - public static String delete(String title) throws JsonProcessingException { - Book deletedBook = library.remove(title); - return mapper.writeValueAsString(deletedBook); - } - -} diff --git a/rest-with-spark-java/src/main/resources/logback.xml b/rest-with-spark-java/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/rest-with-spark-java/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java b/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java deleted file mode 100644 index 9e24879767..0000000000 --- a/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.baeldung; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -import com.baeldung.domain.Book; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class AppLiveTest extends TestCase { - - ObjectMapper mapper = new ObjectMapper(); - - public AppLiveTest( String testName ) { - super( testName ); - } - - public static Test suite() { - return new TestSuite( AppLiveTest.class ); - } - - public void testApp() throws IOException, ClassNotFoundException { - - URL url; - HttpURLConnection conn; - BufferedReader br; - String output; - StringBuffer resp; - Book book; - Book temp; - - url = new URL("http://localhost:8080/AddBook/Odessy/YannMartel/GreenLeaves"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - conn.getContent(); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - book = mapper.readValue(resp.toString(), Book.class); - temp = new Book("Odessy","YannMartel","GreenLeaves"); - - assertEquals(book, temp); - - url = new URL("http://localhost:8080/AddBook/Twilight/StephenieMeyer/LittleBrown"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("POST"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - book = mapper.readValue(resp.toString(), Book.class); - temp = new Book("Twilight","StephenieMeyer","LittleBrown"); - - assertEquals(book, temp); - - url = new URL("http://localhost:8080/ListOfBooks"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - List books = new ArrayList(); - - books.add(new Book("Odessy","YannMartel","GreenLeaves")); - books.add(new Book("Twilight","StephenieMeyer","LittleBrown")); - - List listOfBooks = mapper.readValue(resp.toString(), new TypeReference>(){}); - - assertEquals(books, listOfBooks); - - url = new URL("http://localhost:8080/SearchBook/Twilight"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - book = mapper.readValue(resp.toString(), Book.class); - temp = new Book("Twilight","StephenieMeyer","LittleBrown"); - - assertEquals(book, temp); - - url = new URL("http://localhost:8080/DeleteBook/Twilight"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("DELETE"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - book = mapper.readValue(resp.toString(), Book.class); - temp = new Book("Twilight","StephenieMeyer","LittleBrown"); - - assertEquals(book, temp); - - url = new URL("http://localhost:8080/ListOfBooks"); - conn = (HttpURLConnection) url.openConnection(); - conn.setRequestMethod("GET"); - br = new BufferedReader(new InputStreamReader( - (conn.getInputStream()))); - resp = new StringBuffer(); - - while ((output = br.readLine()) != null) { - resp.append(output); - } - - books = new ArrayList(); - - books.add(new Book("Odessy","YannMartel","GreenLeaves")); - listOfBooks = mapper.readValue(resp.toString(), new TypeReference>(){}); - - assertEquals(books, listOfBooks); - - conn.disconnect(); - - } - -} From e6c7109e35effeaa7e13037a5fa8fb40b64f2399 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 17 Jul 2019 12:04:51 +0300 Subject: [PATCH 207/352] Delete README.md --- jhipster/README.md | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 jhipster/README.md diff --git a/jhipster/README.md b/jhipster/README.md deleted file mode 100644 index 289bfac754..0000000000 --- a/jhipster/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Relevant articles: - -- [JHipster with a Microservice Architecture](http://www.baeldung.com/jhipster-microservices) -- [Intro to JHipster](http://www.baeldung.com/jhipster) -- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service) -- [Creating New Roles and Authorities in JHipster](https://www.baeldung.com/jhipster-new-roles) From ec1807b828d29365971d9aab95a08ed4a5fcee27 Mon Sep 17 00:00:00 2001 From: Loredana Date: Wed, 17 Jul 2019 14:01:41 +0300 Subject: [PATCH 208/352] rename org.baeldung package --- .../config => com/baeldung}/Application.java | 4 +- .../baeldung/config/WebConfig.java | 14 ++++- .../converter/KryoHttpMessageConverter.java | 4 +- .../main/java/com/baeldung/cors/Account.java | 9 +++ .../java/com/baeldung/cors/WebConfig.java | 16 ----- .../BarMappingExamplesController.java | 2 +- .../BazzNewMappingsExampleController.java | 4 +- .../web/controller/FooController.java | 6 +- .../FooMappingExamplesController.java | 2 +- .../controller/status/ExampleController.java | 2 +- .../controller/status/ForbiddenException.java | 2 +- .../{org => com}/baeldung/web/dto/Bazz.java | 2 +- .../{org => com}/baeldung/web/dto/Foo.java | 2 +- .../baeldung/web/dto/FooProtos.java | 60 +++++++++---------- .../baeldung/web/util/LinkUtil.java | 2 +- .../main/webapp/WEB-INF/spring-web-config.xml | 4 +- .../SpringContextIntegrationTest.java | 3 +- .../web/controller/mediatypes/TestConfig.java | 4 +- .../ExampleControllerIntegrationTest.java | 5 +- ...BazzNewMappingsExampleIntegrationTest.java | 5 +- .../web/test/RequestMappingLiveTest.java | 2 +- .../web/test/RestTemplateBasicLiveTest.java | 4 +- .../SpringHttpMessageConvertersLiveTest.java | 9 +-- .../test/TestRestTemplateBasicLiveTest.java | 2 +- .../baeldung/web/util/HTTPLinkHeaderUtil.java | 2 +- 25 files changed, 87 insertions(+), 84 deletions(-) rename spring-rest-simple/src/main/java/{org/baeldung/config => com/baeldung}/Application.java (90%) rename spring-rest-simple/src/main/java/{org => com}/baeldung/config/WebConfig.java (89%) rename spring-rest-simple/src/main/java/{org => com}/baeldung/config/converter/KryoHttpMessageConverter.java (95%) delete mode 100644 spring-rest-simple/src/main/java/com/baeldung/cors/WebConfig.java rename spring-rest-simple/src/main/java/{org => com}/baeldung/web/controller/BarMappingExamplesController.java (97%) rename spring-rest-simple/src/main/java/{org => com}/baeldung/web/controller/BazzNewMappingsExampleController.java (96%) rename spring-rest-simple/src/main/java/{org => com}/baeldung/web/controller/FooController.java (96%) rename spring-rest-simple/src/main/java/{org => com}/baeldung/web/controller/FooMappingExamplesController.java (98%) rename spring-rest-simple/src/main/java/{org => com}/baeldung/web/controller/status/ExampleController.java (94%) rename spring-rest-simple/src/main/java/{org => com}/baeldung/web/controller/status/ForbiddenException.java (88%) rename spring-rest-simple/src/main/java/{org => com}/baeldung/web/dto/Bazz.java (91%) rename spring-rest-simple/src/main/java/{org => com}/baeldung/web/dto/Foo.java (95%) rename spring-rest-simple/src/main/java/{org => com}/baeldung/web/dto/FooProtos.java (90%) rename spring-rest-simple/src/main/java/{org => com}/baeldung/web/util/LinkUtil.java (96%) rename spring-rest-simple/src/test/java/{org => com}/baeldung/SpringContextIntegrationTest.java (86%) rename spring-rest-simple/src/test/java/{org => com}/baeldung/web/controller/mediatypes/TestConfig.java (66%) rename spring-rest-simple/src/test/java/{org => com}/baeldung/web/controller/status/ExampleControllerIntegrationTest.java (95%) rename spring-rest-simple/src/test/java/{org => com}/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java (97%) rename spring-rest-simple/src/test/java/{org => com}/baeldung/web/test/RequestMappingLiveTest.java (99%) rename spring-rest-simple/src/test/java/{org => com}/baeldung/web/test/RestTemplateBasicLiveTest.java (99%) rename spring-rest-simple/src/test/java/{org => com}/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java (96%) rename spring-rest-simple/src/test/java/{org => com}/baeldung/web/test/TestRestTemplateBasicLiveTest.java (99%) rename spring-rest-simple/src/test/java/{org => com}/baeldung/web/util/HTTPLinkHeaderUtil.java (98%) diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/Application.java b/spring-rest-simple/src/main/java/com/baeldung/Application.java similarity index 90% rename from spring-rest-simple/src/main/java/org/baeldung/config/Application.java rename to spring-rest-simple/src/main/java/com/baeldung/Application.java index 5c9a186619..dc6bfcb970 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/config/Application.java +++ b/spring-rest-simple/src/main/java/com/baeldung/Application.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -7,8 +7,8 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration -@ComponentScan("org.baeldung") @SpringBootApplication +@ComponentScan("com.baeldung.cors") public class Application extends SpringBootServletInitializer { public static void main(final String[] args) { diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest-simple/src/main/java/com/baeldung/config/WebConfig.java similarity index 89% rename from spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java rename to spring-rest-simple/src/main/java/com/baeldung/config/WebConfig.java index 191b87a8f2..0ccb52d54a 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest-simple/src/main/java/com/baeldung/config/WebConfig.java @@ -1,6 +1,5 @@ -package org.baeldung.config; +package com.baeldung.config; -import org.baeldung.config.converter.KryoHttpMessageConverter; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; @@ -13,9 +12,12 @@ import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConve import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; import org.springframework.oxm.xstream.XStreamMarshaller; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; +import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import com.baeldung.config.converter.KryoHttpMessageConverter; + import java.text.SimpleDateFormat; import java.util.List; @@ -24,7 +26,7 @@ import java.util.List; */ @Configuration @EnableWebMvc -@ComponentScan({ "org.baeldung.web" }) +@ComponentScan({ "com.baeldung.web" }) public class WebConfig implements WebMvcConfigurer { public WebConfig() { @@ -64,4 +66,10 @@ public class WebConfig implements WebMvcConfigurer { public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.APPLICATION_JSON); } + + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**"); + } } diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java b/spring-rest-simple/src/main/java/com/baeldung/config/converter/KryoHttpMessageConverter.java similarity index 95% rename from spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java rename to spring-rest-simple/src/main/java/com/baeldung/config/converter/KryoHttpMessageConverter.java index 6af54c379a..7ab8282350 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java +++ b/spring-rest-simple/src/main/java/com/baeldung/config/converter/KryoHttpMessageConverter.java @@ -1,13 +1,13 @@ -package org.baeldung.config.converter; +package com.baeldung.config.converter; import java.io.IOException; -import org.baeldung.web.dto.Foo; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; +import com.baeldung.web.dto.Foo; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; diff --git a/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java b/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java index dc6a541a46..429b0c102e 100644 --- a/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java +++ b/spring-rest-simple/src/main/java/com/baeldung/cors/Account.java @@ -6,4 +6,13 @@ public class Account { public Account(Long id) { this.id = id; } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + } diff --git a/spring-rest-simple/src/main/java/com/baeldung/cors/WebConfig.java b/spring-rest-simple/src/main/java/com/baeldung/cors/WebConfig.java deleted file mode 100644 index dc579ce4ba..0000000000 --- a/spring-rest-simple/src/main/java/com/baeldung/cors/WebConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.cors; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -@EnableWebMvc -public class WebConfig implements WebMvcConfigurer { - - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**"); - } -} \ No newline at end of file diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/BarMappingExamplesController.java similarity index 97% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/BarMappingExamplesController.java index 1c3a1086ca..3611a4e6cc 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/BarMappingExamplesController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/BarMappingExamplesController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/BazzNewMappingsExampleController.java similarity index 96% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/BazzNewMappingsExampleController.java index 4bcafc04fc..6c7da0296f 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/BazzNewMappingsExampleController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/BazzNewMappingsExampleController.java @@ -1,9 +1,8 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import java.util.Arrays; import java.util.List; -import org.baeldung.web.dto.Bazz; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; @@ -15,6 +14,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.web.dto.Bazz; import com.fasterxml.jackson.core.JsonProcessingException; @RestController diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java similarity index 96% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java index c68d586667..bab315c027 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooController.java @@ -1,11 +1,9 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import java.util.List; -import org.baeldung.web.dto.Foo; -import org.baeldung.web.dto.FooProtos; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -16,6 +14,8 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; +import com.baeldung.web.dto.Foo; +import com.baeldung.web.dto.FooProtos; import com.google.common.collect.Lists; @Controller diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooMappingExamplesController.java similarity index 98% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/FooMappingExamplesController.java index 5fb92d6d87..ec75e4c859 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/FooMappingExamplesController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooMappingExamplesController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller; +package com.baeldung.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ExampleController.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ExampleController.java similarity index 94% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ExampleController.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ExampleController.java index ceda138768..0cc657f0f2 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ExampleController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ExampleController.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.status; +package com.baeldung.web.controller.status; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java b/spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ForbiddenException.java similarity index 88% rename from spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java rename to spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ForbiddenException.java index 458bdaf170..301a25d070 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/controller/status/ForbiddenException.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/controller/status/ForbiddenException.java @@ -1,4 +1,4 @@ -package org.baeldung.web.controller.status; +package com.baeldung.web.controller.status; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Bazz.java b/spring-rest-simple/src/main/java/com/baeldung/web/dto/Bazz.java similarity index 91% rename from spring-rest-simple/src/main/java/org/baeldung/web/dto/Bazz.java rename to spring-rest-simple/src/main/java/com/baeldung/web/dto/Bazz.java index d9a495b726..861b4009b5 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Bazz.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/dto/Bazz.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.web.dto; public class Bazz { diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java b/spring-rest-simple/src/main/java/com/baeldung/web/dto/Foo.java similarity index 95% rename from spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java rename to spring-rest-simple/src/main/java/com/baeldung/web/dto/Foo.java index 240b368b50..5a54539927 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/dto/Foo.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/dto/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.web.dto; +package com.baeldung.web.dto; import com.thoughtworks.xstream.annotations.XStreamAlias; diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/dto/FooProtos.java b/spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java similarity index 90% rename from spring-rest-simple/src/main/java/org/baeldung/web/dto/FooProtos.java rename to spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java index 8ca96c38fc..db7cb66f87 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/dto/FooProtos.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/dto/FooProtos.java @@ -1,7 +1,7 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: FooProtos.proto -package org.baeldung.web.dto; +package com.baeldung.web.dto; public final class FooProtos { private FooProtos() { @@ -115,11 +115,11 @@ public final class FooProtos { } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.web.dto.FooProtos.Foo.class, com.baeldung.web.dto.FooProtos.Foo.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @@ -255,43 +255,43 @@ public final class FooProtos { return super.writeReplace(); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } - public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } - public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } - public static org.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + public static com.baeldung.web.dto.FooProtos.Foo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } @@ -303,7 +303,7 @@ public final class FooProtos { return newBuilder(); } - public static Builder newBuilder(org.baeldung.web.dto.FooProtos.Foo prototype) { + public static Builder newBuilder(com.baeldung.web.dto.FooProtos.Foo prototype) { return newBuilder().mergeFrom(prototype); } @@ -322,13 +322,13 @@ public final class FooProtos { */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:baeldung.Foo) - org.baeldung.web.dto.FooProtos.FooOrBuilder { + com.baeldung.web.dto.FooProtos.FooOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.web.dto.FooProtos.Foo.class, com.baeldung.web.dto.FooProtos.Foo.Builder.class); } // Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder() @@ -364,23 +364,23 @@ public final class FooProtos { } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + return com.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; } - public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { - return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); + public com.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { + return com.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); } - public org.baeldung.web.dto.FooProtos.Foo build() { - org.baeldung.web.dto.FooProtos.Foo result = buildPartial(); + public com.baeldung.web.dto.FooProtos.Foo build() { + com.baeldung.web.dto.FooProtos.Foo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } - public org.baeldung.web.dto.FooProtos.Foo buildPartial() { - org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this); + public com.baeldung.web.dto.FooProtos.Foo buildPartial() { + com.baeldung.web.dto.FooProtos.Foo result = new com.baeldung.web.dto.FooProtos.Foo(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { @@ -397,16 +397,16 @@ public final class FooProtos { } public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof org.baeldung.web.dto.FooProtos.Foo) { - return mergeFrom((org.baeldung.web.dto.FooProtos.Foo) other); + if (other instanceof com.baeldung.web.dto.FooProtos.Foo) { + return mergeFrom((com.baeldung.web.dto.FooProtos.Foo) other); } else { super.mergeFrom(other); return this; } } - public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) { - if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) + public Builder mergeFrom(com.baeldung.web.dto.FooProtos.Foo other) { + if (other == com.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) return this; if (other.hasId()) { setId(other.getId()); @@ -433,11 +433,11 @@ public final class FooProtos { } public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { - org.baeldung.web.dto.FooProtos.Foo parsedMessage = null; + com.baeldung.web.dto.FooProtos.Foo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); + parsedMessage = (com.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java b/spring-rest-simple/src/main/java/com/baeldung/web/util/LinkUtil.java similarity index 96% rename from spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java rename to spring-rest-simple/src/main/java/com/baeldung/web/util/LinkUtil.java index b2137aeeff..3ebba8ae1c 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/web/util/LinkUtil.java +++ b/spring-rest-simple/src/main/java/com/baeldung/web/util/LinkUtil.java @@ -1,4 +1,4 @@ -package org.baeldung.web.util; +package com.baeldung.web.util; import javax.servlet.http.HttpServletResponse; diff --git a/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml b/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml index 07d50ae1d6..e83e13be71 100644 --- a/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml +++ b/spring-rest-simple/src/main/webapp/WEB-INF/spring-web-config.xml @@ -2,9 +2,9 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans-4.3.xsd + http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc - http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> + http://www.springframework.org/schema/mvc/spring-mvc.xsd"> diff --git a/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-simple/src/test/java/com/baeldung/SpringContextIntegrationTest.java similarity index 86% rename from spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-rest-simple/src/test/java/com/baeldung/SpringContextIntegrationTest.java index 66243ef00d..b66e642b80 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -1,6 +1,5 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.config.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java b/spring-rest-simple/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java similarity index 66% rename from spring-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java rename to spring-rest-simple/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java index 66ffe4947d..4bbfa2818e 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/controller/mediatypes/TestConfig.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java @@ -1,11 +1,11 @@ -package org.baeldung.web.controller.mediatypes; +package com.baeldung.web.controller.mediatypes; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan({ "org.baeldung.web" }) +@ComponentScan({ "com.baeldung.web" }) public class TestConfig { } diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/controller/status/ExampleControllerIntegrationTest.java similarity index 95% rename from spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/controller/status/ExampleControllerIntegrationTest.java index 7f78146b84..f22f59e208 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/controller/status/ExampleControllerIntegrationTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/controller/status/ExampleControllerIntegrationTest.java @@ -1,9 +1,8 @@ -package org.baeldung.web.controller.status; +package com.baeldung.web.controller.status; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.config.WebConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,6 +15,8 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import com.baeldung.config.WebConfig; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) @WebAppConfiguration diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java similarity index 97% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java index dfb3ff7a38..dcd12fba32 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java @@ -1,5 +1,5 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; @@ -10,7 +10,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.config.WebConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -23,6 +22,8 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import com.baeldung.config.WebConfig; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WebConfig.class) diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/RequestMappingLiveTest.java similarity index 99% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/RequestMappingLiveTest.java index 9dd6b13f18..f26f241beb 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/RequestMappingLiveTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/RequestMappingLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/RestTemplateBasicLiveTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/RestTemplateBasicLiveTest.java similarity index 99% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/RestTemplateBasicLiveTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/RestTemplateBasicLiveTest.java index e213d0255f..51e3fb097e 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/RestTemplateBasicLiveTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/RestTemplateBasicLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.apache.commons.codec.binary.Base64.encodeBase64; import static org.hamcrest.CoreMatchers.equalTo; @@ -13,7 +13,6 @@ import java.net.URI; import java.util.Arrays; import java.util.Set; -import org.baeldung.web.dto.Foo; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpEntity; @@ -31,6 +30,7 @@ import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.RestTemplate; +import com.baeldung.web.dto.Foo; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java similarity index 96% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java index 7f250653ab..c6929da818 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/SpringHttpMessageConvertersLiveTest.java @@ -1,13 +1,10 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import java.util.Arrays; -import org.baeldung.config.converter.KryoHttpMessageConverter; -import org.baeldung.web.dto.Foo; -import org.baeldung.web.dto.FooProtos; import org.junit.Assert; import org.junit.Test; import org.springframework.http.HttpEntity; @@ -18,6 +15,10 @@ import org.springframework.http.ResponseEntity; import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; import org.springframework.web.client.RestTemplate; +import com.baeldung.config.converter.KryoHttpMessageConverter; +import com.baeldung.web.dto.Foo; +import com.baeldung.web.dto.FooProtos; + /** * Integration Test class. Tests methods hits the server's rest services. */ diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/test/TestRestTemplateBasicLiveTest.java b/spring-rest-simple/src/test/java/com/baeldung/web/test/TestRestTemplateBasicLiveTest.java similarity index 99% rename from spring-rest-simple/src/test/java/org/baeldung/web/test/TestRestTemplateBasicLiveTest.java rename to spring-rest-simple/src/test/java/com/baeldung/web/test/TestRestTemplateBasicLiveTest.java index b920ed38da..49ac651da2 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/test/TestRestTemplateBasicLiveTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/test/TestRestTemplateBasicLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.web.test; +package com.baeldung.web.test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java b/spring-rest-simple/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java similarity index 98% rename from spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java rename to spring-rest-simple/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java index bb3919eacc..86b35d2b4e 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java +++ b/spring-rest-simple/src/test/java/com/baeldung/web/util/HTTPLinkHeaderUtil.java @@ -1,4 +1,4 @@ -package org.baeldung.web.util; +package com.baeldung.web.util; import java.util.List; From ee6012a4decab36c07f4e16bd2e981c559faa528 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Wed, 17 Jul 2019 16:34:38 +0200 Subject: [PATCH 209/352] BAEL-2825 --- .../main/java/com/baeldung/jpa/entity/Article.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Article.java diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Article.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Article.java new file mode 100644 index 0000000000..02082c3d92 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Article.java @@ -0,0 +1,12 @@ +package com.baeldung.jpa.entity; + +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity(name = "MyArticle") +@Table(name = Article.TABLE_NAME) +public class Article { + + public static final String TABLE_NAME = "ARTICLES"; + +} From 4e12f7b87baeab1ca8c47fc2fd3728a95d9b3a0e Mon Sep 17 00:00:00 2001 From: Loredana Date: Wed, 17 Jul 2019 20:17:26 +0300 Subject: [PATCH 210/352] update guava list to string type --- .../baeldung/java/collections/CoreJavaCollectionsUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java b/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java index ecf68e0b2c..5f7fe356c5 100644 --- a/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java +++ b/core-java-modules/core-java-collections-array-list/src/test/java/org/baeldung/java/collections/CoreJavaCollectionsUnitTest.java @@ -42,7 +42,7 @@ public class CoreJavaCollectionsUnitTest { @Test(expected = UnsupportedOperationException.class) public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() { final List list = new ArrayList(Arrays.asList("one", "two", "three")); - final ImmutableList unmodifiableList = ImmutableList.builder().addAll(list).build(); + final ImmutableList unmodifiableList = ImmutableList.builder().addAll(list).build(); unmodifiableList.add("four"); } From f28cd5c4102e5e8fae5a67b27ee4345efd4eae8c Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 17 Jul 2019 22:07:21 +0300 Subject: [PATCH 211/352] Update README.MD --- spring-boot/README.MD | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 435398904f..a7d7b397a7 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -36,5 +36,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Injecting Git Information Into Spring](https://www.baeldung.com/spring-git-information) - [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) -- [Entity To DTO Conversion for a Spring REST API](https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application) - [Guide to @EnableConfigurationProperties](https://www.baeldung.com/spring-enable-config-properties) From 0c5b3475fac7830cdb1c7b4cd5527c92211b41fc Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 17 Jul 2019 23:10:56 +0300 Subject: [PATCH 212/352] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1030cbb09c..7f78cf1515 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Running a Spring Boot module ==================== To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory -#Running Tests +###Running Tests The command `mvn clean install` will run the unit tests in a module. To run the integration tests, use the command `mvn clean install -Pintegration-lite-first` From feb5b850ff08a38eb9e6bf1eefc16cafaaa78148 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 18 Jul 2019 00:23:38 +0300 Subject: [PATCH 213/352] sftp file transfer --- core-java-modules/core-java-io/pom.xml | 24 +++- .../io/remote/SftpFileTransferLiveTest.java | 106 ++++++++++++++++++ 2 files changed, 129 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index 44c703ee68..e263512512 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -171,6 +171,24 @@ jmimemagic ${jmime-magic.version} + + + com.jcraft + jsch + ${jsch.version} + + + com.hierynomus + sshj + ${sshj.version} + + + org.apache.commons + commons-vfs2 + ${vfs.version} + + + @@ -249,7 +267,7 @@ 3.5 - 1.55 + 1.60 1.10 3.6.1 1.0.3 @@ -262,6 +280,10 @@ 0.6.5 0.9.0 4.1 + + 0.1.55 + 0.27.0 + 2.3 3.6.1 1.7.0 diff --git a/core-java-modules/core-java-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java b/core-java-modules/core-java-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java new file mode 100644 index 0000000000..192153bc90 --- /dev/null +++ b/core-java-modules/core-java-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java @@ -0,0 +1,106 @@ +package org.baeldung.java.io.remote; + +import java.io.IOException; + +import org.apache.commons.vfs2.FileObject; +import org.apache.commons.vfs2.FileSystemManager; +import org.apache.commons.vfs2.Selectors; +import org.apache.commons.vfs2.VFS; +import org.junit.Test; + +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.Session; +import com.jcraft.jsch.SftpException; + +import net.schmizz.sshj.SSHClient; +import net.schmizz.sshj.sftp.SFTPClient; +import net.schmizz.sshj.transport.verification.PromiscuousVerifier; + +public class SftpFileTransferLiveTest { + + private String remoteHost = "HOST_NAME_HERE"; + private String username = "USERNAME_HERE"; + private String password = "PASSWORD_HERE"; + private String localFile = "src/main/resources/input.txt"; + private String remoteFile = "welcome.txt"; + private String localDir = "src/main/resources/"; + private String remoteDir = "remote_sftp_test/"; + private String knownHostsFileLoc = "/Users/USERNAME/known_hosts_sample"; + + @Test + public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException { + ChannelSftp channelSftp = setupJsch(); + channelSftp.connect(); + channelSftp.put(localFile, remoteDir + "jschFile.txt"); + channelSftp.exit(); + } + + @Test + public void whenDownloadFileUsingJsch_thenSuccess() throws JSchException, SftpException { + ChannelSftp channelSftp = setupJsch(); + channelSftp.connect(); + channelSftp.get(remoteFile, localDir + "jschFile.txt"); + channelSftp.exit(); + } + + @Test + public void whenUploadFileUsingSshj_thenSuccess() throws IOException { + SSHClient sshClient = setupSshj(); + SFTPClient sftpClient = sshClient.newSFTPClient(); + sftpClient.put(localFile, remoteDir + "sshjFile.txt"); + sftpClient.close(); + sshClient.disconnect(); + } + + @Test + public void whenDownloadFileUsingSshj_thenSuccess() throws IOException { + SSHClient sshClient = setupSshj(); + SFTPClient sftpClient = sshClient.newSFTPClient(); + sftpClient.get(remoteFile, localDir + "sshjFile.txt"); + sftpClient.close(); + sshClient.disconnect(); + } + + @Test + public void whenUploadFileUsingApacheVfs_thenSuccess() throws IOException { + FileSystemManager manager = VFS.getManager(); + FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localFile); + FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFile.txt"); + remote.copyFrom(local, Selectors.SELECT_SELF); + local.close(); + remote.close(); + } + + @Test + public void whenDownloadFileUsingApacheVfs_thenSuccess() throws IOException { + FileSystemManager manager = VFS.getManager(); + FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localDir + "vfsFile.txt"); + FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteFile); + local.copyFrom(remote, Selectors.SELECT_SELF); + local.close(); + remote.close(); + } + + // ====== ssh-keyscan -H -t rsa remoteHost >> known_hosts_sample + + private ChannelSftp setupJsch() throws JSchException { + JSch jsch = new JSch(); + jsch.setKnownHosts(knownHostsFileLoc); + Session jschSession = jsch.getSession(username, remoteHost); + jschSession.setPassword(password); + //jschSession.setConfig("StrictHostKeyChecking", "no"); + jschSession.connect(); + return (ChannelSftp) jschSession.openChannel("sftp"); + } + + private SSHClient setupSshj() throws IOException { + SSHClient client = new SSHClient(); + client.addHostKeyVerifier(new PromiscuousVerifier()); + client.connect(remoteHost); + client.authPassword(username, password); + return client; + } + +} From 3353139423e251933439f2eaf384af66bba02929 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 18 Jul 2019 12:36:33 +0300 Subject: [PATCH 214/352] Update README.md --- patterns/design-patterns/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/patterns/design-patterns/README.md b/patterns/design-patterns/README.md index 605fdc0d6e..1c611f05d2 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -20,3 +20,4 @@ - [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) - [The Adapter Pattern in Java](https://www.baeldung.com/java-adapter-pattern) - [Currying in Java](https://www.baeldung.com/java-currying) +- [The Proxy Pattern in Java](https://www.baeldung.com/java-proxy-pattern) From 0d3ee78140fd630ae37ed436853af06c3d0e6d58 Mon Sep 17 00:00:00 2001 From: Denis Date: Thu, 18 Jul 2019 16:48:37 +0200 Subject: [PATCH 215/352] BAEL 3084 Improvement: Move Xml Unit Articles (#7330) * BAEL-2983 java objects generation with EasyRandom * BAEL-2983 move easy random under testing-modules * BAEL-2983 java objects generation with EasyRandom * BAEL-2983 move easy random under testing-modules * BAEL-3084 move xmlunit-2 under testing-modules --- pom.xml | 1 - testing-modules/pom.xml | 1 + {xmlunit-2 => testing-modules/xmlunit-2}/README.md | 0 {xmlunit-2 => testing-modules/xmlunit-2}/pom.xml | 3 +-- .../baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java | 0 .../xmlunit-2}/src/main/resources/logback.xml | 0 .../src/test/java/com/baeldung/xmlunit/XMLUnitTest.java | 0 .../xmlunit-2}/src/test/resources/control.xml | 0 .../xmlunit-2}/src/test/resources/students.xml | 0 .../xmlunit-2}/src/test/resources/students.xsd | 0 .../xmlunit-2}/src/test/resources/students_with_error.xml | 0 .../xmlunit-2}/src/test/resources/teachers.xml | 0 .../xmlunit-2}/src/test/resources/test.xml | 0 13 files changed, 2 insertions(+), 3 deletions(-) rename {xmlunit-2 => testing-modules/xmlunit-2}/README.md (100%) rename {xmlunit-2 => testing-modules/xmlunit-2}/pom.xml (94%) rename {xmlunit-2 => testing-modules/xmlunit-2}/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java (100%) rename {xmlunit-2 => testing-modules/xmlunit-2}/src/main/resources/logback.xml (100%) rename {xmlunit-2 => testing-modules/xmlunit-2}/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java (100%) rename {xmlunit-2 => testing-modules/xmlunit-2}/src/test/resources/control.xml (100%) rename {xmlunit-2 => testing-modules/xmlunit-2}/src/test/resources/students.xml (100%) rename {xmlunit-2 => testing-modules/xmlunit-2}/src/test/resources/students.xsd (100%) rename {xmlunit-2 => testing-modules/xmlunit-2}/src/test/resources/students_with_error.xml (100%) rename {xmlunit-2 => testing-modules/xmlunit-2}/src/test/resources/teachers.xml (100%) rename {xmlunit-2 => testing-modules/xmlunit-2}/src/test/resources/test.xml (100%) diff --git a/pom.xml b/pom.xml index 3fd1bcf5fb..64d92acfce 100644 --- a/pom.xml +++ b/pom.xml @@ -781,7 +781,6 @@ wicket xml - xmlunit-2 xstream tensorflow-java diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index 3a1c3f3bf4..8d40c668c0 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -36,5 +36,6 @@ junit-5-basics easymock junit-5-advanced + xmlunit-2 diff --git a/xmlunit-2/README.md b/testing-modules/xmlunit-2/README.md similarity index 100% rename from xmlunit-2/README.md rename to testing-modules/xmlunit-2/README.md diff --git a/xmlunit-2/pom.xml b/testing-modules/xmlunit-2/pom.xml similarity index 94% rename from xmlunit-2/pom.xml rename to testing-modules/xmlunit-2/pom.xml index 9e146ccf33..aa516bfcc5 100644 --- a/xmlunit-2/pom.xml +++ b/testing-modules/xmlunit-2/pom.xml @@ -1,15 +1,14 @@ 4.0.0 - com.baeldung xmlunit-2 - 1.0 xmlunit-2 com.baeldung parent-modules 1.0.0-SNAPSHOT + ../../ diff --git a/xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java b/testing-modules/xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java similarity index 100% rename from xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java rename to testing-modules/xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java diff --git a/xmlunit-2/src/main/resources/logback.xml b/testing-modules/xmlunit-2/src/main/resources/logback.xml similarity index 100% rename from xmlunit-2/src/main/resources/logback.xml rename to testing-modules/xmlunit-2/src/main/resources/logback.xml diff --git a/xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java b/testing-modules/xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java similarity index 100% rename from xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java rename to testing-modules/xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java diff --git a/xmlunit-2/src/test/resources/control.xml b/testing-modules/xmlunit-2/src/test/resources/control.xml similarity index 100% rename from xmlunit-2/src/test/resources/control.xml rename to testing-modules/xmlunit-2/src/test/resources/control.xml diff --git a/xmlunit-2/src/test/resources/students.xml b/testing-modules/xmlunit-2/src/test/resources/students.xml similarity index 100% rename from xmlunit-2/src/test/resources/students.xml rename to testing-modules/xmlunit-2/src/test/resources/students.xml diff --git a/xmlunit-2/src/test/resources/students.xsd b/testing-modules/xmlunit-2/src/test/resources/students.xsd similarity index 100% rename from xmlunit-2/src/test/resources/students.xsd rename to testing-modules/xmlunit-2/src/test/resources/students.xsd diff --git a/xmlunit-2/src/test/resources/students_with_error.xml b/testing-modules/xmlunit-2/src/test/resources/students_with_error.xml similarity index 100% rename from xmlunit-2/src/test/resources/students_with_error.xml rename to testing-modules/xmlunit-2/src/test/resources/students_with_error.xml diff --git a/xmlunit-2/src/test/resources/teachers.xml b/testing-modules/xmlunit-2/src/test/resources/teachers.xml similarity index 100% rename from xmlunit-2/src/test/resources/teachers.xml rename to testing-modules/xmlunit-2/src/test/resources/teachers.xml diff --git a/xmlunit-2/src/test/resources/test.xml b/testing-modules/xmlunit-2/src/test/resources/test.xml similarity index 100% rename from xmlunit-2/src/test/resources/test.xml rename to testing-modules/xmlunit-2/src/test/resources/test.xml From 82f1efaabe55577d9f1df64851213a16e346df9d Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 18 Jul 2019 18:50:31 +0300 Subject: [PATCH 216/352] Update pom.xml --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index e04d9f7bba..9be2971be4 100644 --- a/pom.xml +++ b/pom.xml @@ -556,7 +556,6 @@ tensorflow-java spring-boot-flowable spring-security-kerberos - morphia oauth2-framework-impl From cd88156b5c9a50cf0e93f80384239bbea3347533 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 18 Jul 2019 20:17:01 +0300 Subject: [PATCH 217/352] create module libraries-io --- core-java-modules/core-java-io/pom.xml | 26 +----------- libraries-io/README.md | 4 ++ libraries-io/pom.xml | 40 +++++++++++++++++++ libraries-io/src/main/resources/input.txt | 1 + .../io/remote/SftpFileTransferLiveTest.java | 0 pom.xml | 1 + 6 files changed, 48 insertions(+), 24 deletions(-) create mode 100644 libraries-io/README.md create mode 100644 libraries-io/pom.xml create mode 100644 libraries-io/src/main/resources/input.txt rename {core-java-modules/core-java-io => libraries-io}/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java (100%) diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index d12b10d34e..75e820c95b 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -170,25 +170,7 @@ net.sf.jmimemagic jmimemagic ${jmime-magic.version} - - - - com.jcraft - jsch - ${jsch.version} - - - com.hierynomus - sshj - ${sshj.version} - - - org.apache.commons - commons-vfs2 - ${vfs.version} - - - + @@ -278,11 +260,7 @@ 1.13 0.6.5 0.9.0 - 4.1 - - 0.1.55 - 0.27.0 - 2.4 + 4.1 3.6.1 1.7.0 diff --git a/libraries-io/README.md b/libraries-io/README.md new file mode 100644 index 0000000000..f8ea2f1be8 --- /dev/null +++ b/libraries-io/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + + diff --git a/libraries-io/pom.xml b/libraries-io/pom.xml new file mode 100644 index 0000000000..5b78ae9442 --- /dev/null +++ b/libraries-io/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + libraries-io + libraries-io + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + com.jcraft + jsch + ${jsch.version} + + + com.hierynomus + sshj + ${sshj.version} + + + org.apache.commons + commons-vfs2 + ${vfs.version} + + + + + + 0.1.55 + 0.27.0 + 2.4 + + diff --git a/libraries-io/src/main/resources/input.txt b/libraries-io/src/main/resources/input.txt new file mode 100644 index 0000000000..a10db923e5 --- /dev/null +++ b/libraries-io/src/main/resources/input.txt @@ -0,0 +1 @@ +This is a sample text content \ No newline at end of file diff --git a/core-java-modules/core-java-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java b/libraries-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java similarity index 100% rename from core-java-modules/core-java-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java rename to libraries-io/src/test/java/org/baeldung/java/io/remote/SftpFileTransferLiveTest.java diff --git a/pom.xml b/pom.xml index 3fd1bcf5fb..e522689890 100644 --- a/pom.xml +++ b/pom.xml @@ -506,6 +506,7 @@ libraries-security libraries-server libraries-http + libraries-io linkrest logging-modules lombok From 631817cc3e60032cb75db55fd5ddd39e45fe67e8 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 18 Jul 2019 20:22:53 +0300 Subject: [PATCH 218/352] minor cleanup --- core-java-modules/core-java-io/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index 75e820c95b..1a133d2cbe 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -170,7 +170,7 @@ net.sf.jmimemagic jmimemagic ${jmime-magic.version} - + @@ -260,7 +260,7 @@ 1.13 0.6.5 0.9.0 - 4.1 + 4.1 3.6.1 1.7.0 From 04e9fdafa45f92d172f0423c17fe7148fcd176f3 Mon Sep 17 00:00:00 2001 From: drazen Date: Thu, 18 Jul 2019 20:23:15 +0200 Subject: [PATCH 219/352] BAEL-3007: WebClient vs RestTemplate example. --- pom.xml | 3 + spring-5-reactive-2/.gitignore | 12 ++++ spring-5-reactive-2/README.md | 1 + spring-5-reactive-2/pom.xml | 50 ++++++++++++++++ .../java/com/baeldung/webclient/Tweet.java | 13 ++++ .../TweetsSlowServiceController.java | 20 +++++++ .../webclient/WebClientApplication.java | 11 ++++ .../com/baeldung/webclient/WebController.java | 60 +++++++++++++++++++ .../WebControllerIntegrationTest.java | 51 ++++++++++++++++ 9 files changed, 221 insertions(+) create mode 100644 spring-5-reactive-2/.gitignore create mode 100644 spring-5-reactive-2/README.md create mode 100644 spring-5-reactive-2/pom.xml create mode 100644 spring-5-reactive-2/src/main/java/com/baeldung/webclient/Tweet.java create mode 100644 spring-5-reactive-2/src/main/java/com/baeldung/webclient/TweetsSlowServiceController.java create mode 100644 spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebClientApplication.java create mode 100644 spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebController.java create mode 100644 spring-5-reactive-2/src/test/java/com/baeldung/webclient/WebControllerIntegrationTest.java diff --git a/pom.xml b/pom.xml index 2e34254bf5..179f7844ee 100644 --- a/pom.xml +++ b/pom.xml @@ -606,6 +606,7 @@ spring-5-data-reactive spring-5-mvc spring-5-reactive + spring-5-reactive-2 spring-5-reactive-client spring-5-reactive-oauth spring-5-reactive-security @@ -820,6 +821,7 @@ spring-5 spring-5-data-reactive spring-5-reactive + spring-5-reactive-2 spring-5-reactive-client spring-5-reactive-security spring-5-security @@ -1277,6 +1279,7 @@ spring-5-data-reactive spring-5-mvc spring-5-reactive + spring-5-reactive-2 spring-5-reactive-client spring-5-reactive-oauth spring-5-reactive-security diff --git a/spring-5-reactive-2/.gitignore b/spring-5-reactive-2/.gitignore new file mode 100644 index 0000000000..dec013dfa4 --- /dev/null +++ b/spring-5-reactive-2/.gitignore @@ -0,0 +1,12 @@ +#folders# +.idea +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-5-reactive-2/README.md b/spring-5-reactive-2/README.md new file mode 100644 index 0000000000..bbb45e9f8c --- /dev/null +++ b/spring-5-reactive-2/README.md @@ -0,0 +1 @@ +## Spring 5 Reactive Project diff --git a/spring-5-reactive-2/pom.xml b/spring-5-reactive-2/pom.xml new file mode 100644 index 0000000000..668e0e5cf9 --- /dev/null +++ b/spring-5-reactive-2/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + com.baeldung + spring-5-reactive-2 + 0.0.1-SNAPSHOT + spring-5-reactive-2 + jar + spring 5 sample project about new features + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.webclient.WebClientApplication + JAR + + + + + + diff --git a/spring-5-reactive-2/src/main/java/com/baeldung/webclient/Tweet.java b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/Tweet.java new file mode 100644 index 0000000000..8d294955f3 --- /dev/null +++ b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/Tweet.java @@ -0,0 +1,13 @@ +package com.baeldung.webclient; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Tweet { + private String text; + private String username; +} diff --git a/spring-5-reactive-2/src/main/java/com/baeldung/webclient/TweetsSlowServiceController.java b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/TweetsSlowServiceController.java new file mode 100644 index 0000000000..fecaca25ef --- /dev/null +++ b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/TweetsSlowServiceController.java @@ -0,0 +1,20 @@ +package com.baeldung.webclient; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Arrays; +import java.util.List; + +@RestController +public class TweetsSlowServiceController { + + @GetMapping("/slow-service-tweets") + private List getAllTweets() throws Exception { + Thread.sleep(2000L); // delay + return Arrays.asList( + new Tweet("RestTemplate rules", "@user1"), + new Tweet("WebClient is better", "@user2"), + new Tweet("OK, both are useful", "@user1")); + } +} diff --git a/spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebClientApplication.java b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebClientApplication.java new file mode 100644 index 0000000000..751e3a9487 --- /dev/null +++ b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebClientApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.webclient; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class WebClientApplication { + public static void main(String[] args) { + SpringApplication.run(WebClientApplication.class, args); + } +} diff --git a/spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebController.java b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebController.java new file mode 100644 index 0000000000..73f5724819 --- /dev/null +++ b/spring-5-reactive-2/src/main/java/com/baeldung/webclient/WebController.java @@ -0,0 +1,60 @@ +package com.baeldung.webclient; + +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Flux; + +import java.util.List; + +@Slf4j +@RestController +public class WebController { + + private static final int DEFAULT_PORT = 8080; + + @Setter + private int serverPort = DEFAULT_PORT; + + @GetMapping("/tweets-blocking") + public List getTweetsBlocking() { + log.info("Starting BLOCKING Controller!"); + final String uri = getSlowServiceUri(); + + RestTemplate restTemplate = new RestTemplate(); + ResponseEntity> response = restTemplate.exchange( + uri, HttpMethod.GET, null, + new ParameterizedTypeReference>(){}); + + List result = response.getBody(); + result.forEach(tweet -> log.info(tweet.toString())); + log.info("Exiting BLOCKING Controller!"); + return result; + } + + @GetMapping(value = "/tweets-non-blocking", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux getTweetsNonBlocking() { + log.info("Starting NON-BLOCKING Controller!"); + Flux tweetFlux = WebClient.create() + .get() + .uri(getSlowServiceUri()) + .retrieve() + .bodyToFlux(Tweet.class); + + tweetFlux.subscribe(tweet -> log.info(tweet.toString())); + log.info("Exiting NON-BLOCKING Controller!"); + return tweetFlux; + } + + private String getSlowServiceUri() { + return "http://localhost:" + serverPort + "/slow-service-tweets"; + } + +} diff --git a/spring-5-reactive-2/src/test/java/com/baeldung/webclient/WebControllerIntegrationTest.java b/spring-5-reactive-2/src/test/java/com/baeldung/webclient/WebControllerIntegrationTest.java new file mode 100644 index 0000000000..09c3a5fb84 --- /dev/null +++ b/spring-5-reactive-2/src/test/java/com/baeldung/webclient/WebControllerIntegrationTest.java @@ -0,0 +1,51 @@ +package com.baeldung.webclient; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebClientApplication.class) +public class WebControllerIntegrationTest { + + @LocalServerPort + int randomServerPort; + + @Autowired + private WebTestClient testClient; + + @Autowired + private WebController webController; + + @Before + public void setup() { + webController.setServerPort(randomServerPort); + } + + @Test + public void whenEndpointWithBlockingClientIsCalled_thenThreeTweetsAreReceived() { + testClient.get() + .uri("/tweets-blocking") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Tweet.class) + .hasSize(3); + } + + @Test + public void whenEndpointWithNonBlockingClientIsCalled_thenThreeTweetsAreReceived() { + testClient.get() + .uri("/tweets-non-blocking") + .exchange() + .expectStatus() + .isOk() + .expectBodyList(Tweet.class) + .hasSize(3); + } +} \ No newline at end of file From e12749abcd76f7e66b93393b2a3f84a5222b0e5e Mon Sep 17 00:00:00 2001 From: Thabo Ntsoko Date: Thu, 18 Jul 2019 20:23:31 +0200 Subject: [PATCH 220/352] Demo code for looping diagonally through a square 2D array --- .../array/looping/LoopDiagonally.java | 45 +++++++++++++++++++ .../array/looping/LoopDiagonallyTest.java | 20 +++++++++ 2 files changed, 65 insertions(+) create mode 100644 core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java create mode 100644 core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java diff --git a/core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java b/core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java new file mode 100644 index 0000000000..71e2840f45 --- /dev/null +++ b/core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java @@ -0,0 +1,45 @@ +package com.baeldung.array.looping; + +public class LoopDiagonally { + + + public String loopDiagonally(String[][] twoDArray) { + + int length = twoDArray.length; + int diagonalLines = (length + length) - 1; + int itemsInDiagonal = 0; + int midPoint = (diagonalLines / 2) + 1; + StringBuilder output = new StringBuilder(); + + for (int i = 1; i <= diagonalLines; i++) { + + StringBuilder items = new StringBuilder(); + int rowIndex; + int columnIndex; + + if (i <= midPoint) { + itemsInDiagonal++; + for (int j = 0; j < itemsInDiagonal; j++) { + rowIndex = (i - j) - 1; + columnIndex = j; + items.append(twoDArray[rowIndex][columnIndex]); + } + } else { + itemsInDiagonal--; + for (int j = 0; j < itemsInDiagonal; j++) { + rowIndex = (length - 1) - j; + columnIndex = (i - length) + j; + items.append(twoDArray[rowIndex][columnIndex]); + } + } + + if (i != diagonalLines) { + output.append(items).append(" "); + } else { + output.append(items); + } + } + + return output.toString(); + } +} diff --git a/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java b/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java new file mode 100644 index 0000000000..df6079270b --- /dev/null +++ b/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java @@ -0,0 +1,20 @@ +package com.baeldung.array.looping; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class LoopDiagonallyTest { + + @Test + public void twoArrayIsLoopedDiagonallyAsExpected() { + + LoopDiagonally loopDiagonally = new LoopDiagonally(); + String[][] twoDArray = {{"a", "b", "c"}, + {"d", "e", "f"}, + {"g", "h", "i"}}; + + String output = loopDiagonally.loopDiagonally(twoDArray); + assertEquals("a db gec hf i", output); + } +} \ No newline at end of file From da86b78fa5a54f850c5c24bac02cc830a99ca820 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Fri, 19 Jul 2019 00:10:31 +0530 Subject: [PATCH 221/352] [BAEL-11603] - Moved MessageController to a child package and removed ExcelPOIHelper bean definition from TestConfig --- .../web/controller/{ => message}/MessageController.java | 2 +- .../src/test/java/com/baeldung/htmlunit/TestConfig.java | 9 +-------- 2 files changed, 2 insertions(+), 9 deletions(-) rename spring-mvc-java/src/main/java/com/baeldung/web/controller/{ => message}/MessageController.java (94%) diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/message/MessageController.java similarity index 94% rename from spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java rename to spring-mvc-java/src/main/java/com/baeldung/web/controller/message/MessageController.java index 111bf023f7..fdb0d75530 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/message/MessageController.java @@ -1,4 +1,4 @@ -package com.baeldung.web.controller; +package com.baeldung.web.controller.message; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java index 8c8a2f5b62..75efd57ae4 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -13,11 +13,9 @@ import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; -import com.baeldung.excel.ExcelPOIHelper; - @Configuration @EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.web.controller" }) +@ComponentScan(basePackages = { "com.baeldung.web.controller.message" }) public class TestConfig implements WebMvcConfigurer { @Autowired @@ -46,9 +44,4 @@ public class TestConfig implements WebMvcConfigurer { templateEngine.setTemplateResolver(templateResolver()); return templateEngine; } - - @Bean - public ExcelPOIHelper excelPOIHelper() { - return new ExcelPOIHelper(); - } } From 999c5ea5e1623135bdf16871e4c9c10445c38778 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 19 Jul 2019 08:25:59 +0300 Subject: [PATCH 222/352] Create README.md --- testing-modules/junit-5-advanced/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 testing-modules/junit-5-advanced/README.md diff --git a/testing-modules/junit-5-advanced/README.md b/testing-modules/junit-5-advanced/README.md new file mode 100644 index 0000000000..7282a4efad --- /dev/null +++ b/testing-modules/junit-5-advanced/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [JUnit 5 TestWatcher API](https://www.baeldung.com/junit-testwatcher) From c9599313c809abbbb96204b3c785fc9284d1f769 Mon Sep 17 00:00:00 2001 From: "sreekanth.nair" Date: Fri, 19 Jul 2019 11:46:05 +0530 Subject: [PATCH 223/352] Get Current Directory Using Java --- .../core/pwd/CurrentDirectoryFetcher.java | 40 +++++++++++++++++++ .../core/pwd/CurrentDirectoryFetcherTest.java | 34 ++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 core-java-modules/core-java-os/src/main/java/com/baeldung/core/pwd/CurrentDirectoryFetcher.java create mode 100644 core-java-modules/core-java-os/src/test/java/com/baeldung/core/pwd/CurrentDirectoryFetcherTest.java diff --git a/core-java-modules/core-java-os/src/main/java/com/baeldung/core/pwd/CurrentDirectoryFetcher.java b/core-java-modules/core-java-os/src/main/java/com/baeldung/core/pwd/CurrentDirectoryFetcher.java new file mode 100644 index 0000000000..8f022d2cc7 --- /dev/null +++ b/core-java-modules/core-java-os/src/main/java/com/baeldung/core/pwd/CurrentDirectoryFetcher.java @@ -0,0 +1,40 @@ +package com.baeldung.core.pwd; + +import java.io.File; +import java.nio.file.FileSystems; +import java.nio.file.Paths; + +public final class CurrentDirectoryFetcher { + + public static void main(String[] args) { + System.out.printf("Current Directory Using Java System API: %s%n", currentDirectoryUsingSystemProperties()); + + System.out.printf("Current Directory Using Java IO File API: %s%n", currentDirectoryUsingFile()); + + System.out.printf("Current Directory Using Java NIO FileSystems API: %s%n", currentDirectoryUsingFileSystems()); + + System.out.printf("Current Directory Using Java NIO Paths API: %s%n", currentDirectoryUsingPaths()); + } + + public static String currentDirectoryUsingSystemProperties() { + return System.getProperty("user.dir"); + } + + public static String currentDirectoryUsingPaths() { + return Paths.get("") + .toAbsolutePath() + .toString(); + } + + public static String currentDirectoryUsingFileSystems() { + return FileSystems.getDefault() + .getPath("") + .toAbsolutePath() + .toString(); + } + + public static String currentDirectoryUsingFile() { + return new File("").getAbsolutePath(); + } + +} diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/core/pwd/CurrentDirectoryFetcherTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/core/pwd/CurrentDirectoryFetcherTest.java new file mode 100644 index 0000000000..dbaad211d9 --- /dev/null +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/core/pwd/CurrentDirectoryFetcherTest.java @@ -0,0 +1,34 @@ +package com.baeldung.core.pwd; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class CurrentDirectoryFetcherTest { + + private static final String CURRENT_DIR = "core-java-os"; + + @Test + public void whenUsingSystemProperties_thenReturnCurrentDirectory() { + assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingSystemProperties() + .endsWith(CURRENT_DIR)); + } + + @Test + public void whenUsingJavaNioPaths_thenReturnCurrentDirectory() { + assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingPaths() + .endsWith(CURRENT_DIR)); + } + + @Test + public void whenUsingJavaNioFileSystems_thenReturnCurrentDirectory() { + assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFileSystems() + .endsWith(CURRENT_DIR)); + } + + @Test + public void whenUsingJavaIoFile_thenReturnCurrentDirectory() { + assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFile() + .endsWith(CURRENT_DIR)); + } +} \ No newline at end of file From 595786a32a497ddbd519e1e793bd8bb82603aa48 Mon Sep 17 00:00:00 2001 From: Loredana Date: Fri, 19 Jul 2019 11:56:12 +0300 Subject: [PATCH 224/352] update link --- spring-boot-di/README.MD | 6 ++++++ spring-boot/README.MD | 1 - 2 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 spring-boot-di/README.MD diff --git a/spring-boot-di/README.MD b/spring-boot-di/README.MD new file mode 100644 index 0000000000..78cd163668 --- /dev/null +++ b/spring-boot-di/README.MD @@ -0,0 +1,6 @@ +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index a7d7b397a7..b2064be896 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -30,7 +30,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Shutdown Callbacks](http://www.baeldung.com/spring-shutdown-callbacks) - [Container Configuration in Spring Boot 2](http://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) - [Introduction to Chaos Monkey](https://www.baeldung.com/spring-boot-chaos-monkey) -- [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) - [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) - [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report) - [Injecting Git Information Into Spring](https://www.baeldung.com/spring-git-information) From ca4b885face88244775d86732898edc50372088c Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 19 Jul 2019 12:28:48 +0300 Subject: [PATCH 225/352] Update README.MD --- spring-boot/README.MD | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index a7d7b397a7..a2c6157699 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -5,7 +5,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring) - [The @ServletComponentScan Annotation in Spring Boot](http://www.baeldung.com/spring-servletcomponentscan) -- [Intro to Building an Application with Spring Boot](http://www.baeldung.com/intro-to-spring-boot) - [How to Register a Servlet in Java](http://www.baeldung.com/register-servlet) - [Guide to Spring WebUtils and ServletRequestUtils](http://www.baeldung.com/spring-webutils-servletrequestutils) - [Using Custom Banners in Spring Boot](http://www.baeldung.com/spring-boot-custom-banners) From 8226e6982f530f95fd37d159cd4d10c4e582347d Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 19 Jul 2019 12:54:52 +0300 Subject: [PATCH 226/352] Update README.md --- core-java-modules/core-java/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md index b32b5d5cd9..436a481803 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -37,7 +37,6 @@ - [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions) - [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) - [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) -- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) - [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources) - [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class) - [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding) From 9a0d24b26f3293d9e45a18a99c71704f572244f1 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 19 Jul 2019 13:06:29 +0300 Subject: [PATCH 227/352] Update README.md --- core-java-modules/core-java-lang/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-modules/core-java-lang/README.md b/core-java-modules/core-java-lang/README.md index e9169a5820..74936eac21 100644 --- a/core-java-modules/core-java-lang/README.md +++ b/core-java-modules/core-java-lang/README.md @@ -18,7 +18,6 @@ - [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces) - [Recursion In Java](http://www.baeldung.com/java-recursion) - [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize) -- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums) - [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) - [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system) - [Using Java Assertions](http://www.baeldung.com/java-assert) From 85eba5fdb80f85e3742e99579c5c96813a699eaf Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 19 Jul 2019 13:57:21 +0300 Subject: [PATCH 228/352] Update README.md --- libraries/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries/README.md b/libraries/README.md index f6f2cf4e07..c7b40e3c94 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -42,7 +42,6 @@ - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [Introduction to Smooks](http://www.baeldung.com/smooks) - [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan) -- [Introduction to OpenCSV](http://www.baeldung.com/opencsv) - [A Guide to Unirest](http://www.baeldung.com/unirest) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy) From 62d1391db542de03cedb5cc427c933a657336429 Mon Sep 17 00:00:00 2001 From: Steven van Beelen Date: Fri, 19 Jul 2019 16:05:12 +0200 Subject: [PATCH 229/352] Update Axon version Update Axon version to 4.1.2 BAEL-3099 --- axon/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/axon/pom.xml b/axon/pom.xml index 002701373f..3d30cceb83 100644 --- a/axon/pom.xml +++ b/axon/pom.xml @@ -52,7 +52,7 @@ - 4.1.1 + 4.1.2 \ No newline at end of file From ce364f6b2ebfb4ae3c443382497f2ee4b7d024ae Mon Sep 17 00:00:00 2001 From: Steven van Beelen Date: Fri, 19 Jul 2019 16:05:39 +0200 Subject: [PATCH 230/352] Adjust expected exception Adjust expected exception from IllegalArgumentException to UnconfirmedOrderException BAEL-3099 --- .../baeldung/axon/commandmodel/OrderAggregateUnitTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java b/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java index 9beedbaa19..aaefe49fb1 100644 --- a/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java +++ b/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java @@ -2,6 +2,7 @@ package com.baeldung.axon.commandmodel; import java.util.UUID; +import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException; import org.axonframework.test.aggregate.AggregateTestFixture; import org.axonframework.test.aggregate.FixtureConfiguration; import org.junit.*; @@ -41,12 +42,12 @@ public class OrderAggregateUnitTest { } @Test - public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowIllegalStateException() { + public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowUnconfirmedOrderException() { String orderId = UUID.randomUUID().toString(); String product = "Deluxe Chair"; fixture.given(new OrderPlacedEvent(orderId, product)) .when(new ShipOrderCommand(orderId)) - .expectException(IllegalStateException.class); + .expectException(UnconfirmedOrderException.class); } @Test From 50dd0ff2825e41314b0761adf2188b32ca90ede0 Mon Sep 17 00:00:00 2001 From: Pazis Date: Sat, 20 Jul 2019 07:29:26 +0430 Subject: [PATCH 231/352] BAEL-2962 Java Multi-line String FIX (#7348) * added readme * hexagonal architecture implemented * Java Multiline String * BAEL-2856 Difference between getRequestURI and getPathInfo in HttpServletRequest * MyHttpServlet * package fix * remove latest change * undo * remove multiline * add * add --- .../string/{ => multiline}/MultiLineStringUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename java-strings-2/src/test/java/com/baeldung/string/{ => multiline}/MultiLineStringUnitTest.java (93%) diff --git a/java-strings-2/src/test/java/com/baeldung/string/MultiLineStringUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java similarity index 93% rename from java-strings-2/src/test/java/com/baeldung/string/MultiLineStringUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java index b458fae79b..3ebee9b5d1 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/MultiLineStringUnitTest.java +++ b/java-strings-2/src/test/java/com/baeldung/string/multiline/MultiLineStringUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.string.multiline; import org.junit.Test; import static org.junit.Assert.assertEquals; From 815d5829ec19e592c0384e1fadff0a9335bcade1 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 20 Jul 2019 11:13:58 +0530 Subject: [PATCH 232/352] [BAEL-15976] - Configured Cargo for parent-spring-4 --- parent-spring-4/pom.xml | 23 +++++++++++++++++++ persistence-modules/spring-hibernate4/pom.xml | 7 +++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/parent-spring-4/pom.xml b/parent-spring-4/pom.xml index b08ead02d4..ab66cf19bf 100644 --- a/parent-spring-4/pom.xml +++ b/parent-spring-4/pom.xml @@ -28,8 +28,31 @@ + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + 8082 + + + + + + + 4.3.22.RELEASE + 1.6.1 \ No newline at end of file diff --git a/persistence-modules/spring-hibernate4/pom.xml b/persistence-modules/spring-hibernate4/pom.xml index 388e2ab27b..c22342a34a 100644 --- a/persistence-modules/spring-hibernate4/pom.xml +++ b/persistence-modules/spring-hibernate4/pom.xml @@ -7,10 +7,10 @@ spring-hibernate4 + parent-spring-4 com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + 0.0.1-SNAPSHOT + ../../parent-spring-4 @@ -175,7 +175,6 @@ 2.7 - 1.6.1 From 2a5576618e3c999688d917812744b4a9d6ca447a Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 20 Jul 2019 10:29:33 +0300 Subject: [PATCH 233/352] update test containers --- testing-modules/test-containers/pom.xml | 27 ++++++++++++------- .../WebDriverContainerLiveTest.java | 13 ++++----- 2 files changed, 23 insertions(+), 17 deletions(-) diff --git a/testing-modules/test-containers/pom.xml b/testing-modules/test-containers/pom.xml index 292af2051a..480b7c8277 100644 --- a/testing-modules/test-containers/pom.xml +++ b/testing-modules/test-containers/pom.xml @@ -23,6 +23,12 @@ ${junit.platform.version} test + + org.junit.platform + junit-platform-commons + ${junit.platform.version} + test + org.junit.vintage junit-vintage-engine @@ -59,6 +65,11 @@ selenium-remote-driver ${selenium-remote-driver.version} + + org.seleniumhq.selenium + selenium-chrome-driver + ${selenium-remote-driver.version} + @@ -99,15 +110,13 @@ - 1.0.1 - 4.12.1 - 2.8.2 - 2.21.0 - 5.0.1.RELEASE - 1.7.2 - 42.2.2 - 3.12.0 - 2.21.0 + 1.5.0 + 5.5.0 + 2.12.0 + 1.11.4 + 42.2.6 + 3.141.59 + 2.22.2 diff --git a/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java index 0e52c4e9f7..0fdf0ede79 100644 --- a/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java +++ b/testing-modules/test-containers/src/test/java/com/baeldung/testconainers/WebDriverContainerLiveTest.java @@ -2,29 +2,26 @@ package com.baeldung.testconainers; import static org.junit.Assert.assertEquals; -import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.openqa.selenium.By; -import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.RemoteWebDriver; -import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.BrowserWebDriverContainer; -import org.testcontainers.containers.GenericContainer; public class WebDriverContainerLiveTest { @Rule public BrowserWebDriverContainer chrome = new BrowserWebDriverContainer() - .withDesiredCapabilities(DesiredCapabilities.chrome()); + .withCapabilities(new ChromeOptions()); @Test public void whenNavigatedToPage_thenHeadingIsInThePage() { RemoteWebDriver driver = chrome.getWebDriver(); - driver.get("https://saucelabs.com/test/guinea-pig"); - String heading = driver.findElement(By.xpath("/html/body/h1")) + driver.get("http://example.com"); + String heading = driver.findElement(By.xpath("/html/body/div/h1")) .getText(); - assertEquals("This page is a Selenium sandbox", heading); + assertEquals("Example Domain", heading); } } From 9978d337fcededcc0fa6e51ba4819dcccde25e8f Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 20 Jul 2019 12:09:38 +0300 Subject: [PATCH 234/352] fix envers test --- .../src/main/java/com/baeldung/spring/PersistenceConfig.java | 2 +- .../persistence/audit/EnversFooBarAuditIntegrationTest.java | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java index 35e80b81a5..b7cf0fadf2 100644 --- a/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java +++ b/persistence-modules/spring-hibernate4/src/main/java/com/baeldung/spring/PersistenceConfig.java @@ -47,7 +47,7 @@ import com.google.common.base.Preconditions; @EnableTransactionManagement @EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager") @EnableJpaAuditing -@PropertySource({ "classpath:persistence-mysql.properties" }) +@PropertySource({ "classpath:persistence-h2.properties" }) @ComponentScan({ "com.baeldung.persistence" }) public class PersistenceConfig { diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java index 2f23a9a532..0530c2a70f 100644 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java +++ b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java @@ -2,6 +2,7 @@ package com.baeldung.persistence.audit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.List; @@ -17,6 +18,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @@ -29,6 +31,7 @@ import com.baeldung.spring.config.PersistenceTestConfig; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class EnversFooBarAuditIntegrationTest { private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class); @@ -118,7 +121,7 @@ public class EnversFooBarAuditIntegrationTest { barRevisionList = barService.getRevisions(); assertNotNull(barRevisionList); - assertEquals(4, barRevisionList.size()); + assertTrue(barRevisionList.size()>=4); assertEquals("BAR", barRevisionList.get(0).getName()); assertEquals("BAR", barRevisionList.get(1).getName()); From 98c537f20f49a720909ca44ea055a64cc44e9050 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 20 Jul 2019 12:11:16 +0300 Subject: [PATCH 235/352] update links --- persistence-modules/spring-data-jpa/README.md | 1 - persistence-modules/spring-hibernate4/README.md | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-data-jpa/README.md b/persistence-modules/spring-data-jpa/README.md index e85d8a8487..4b4a590e10 100644 --- a/persistence-modules/spring-data-jpa/README.md +++ b/persistence-modules/spring-data-jpa/README.md @@ -10,7 +10,6 @@ - [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) - [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) - [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) -- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) - [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) - [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) - [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md index 426944c149..020e867c82 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -10,6 +10,7 @@ - [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) - [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading) - [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) +- [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) ### Quick Start From c10619ea207c50d8ac638622a7ad50cedc20873f Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 20 Jul 2019 12:13:01 +0300 Subject: [PATCH 236/352] update test --- .../persistence/audit/EnversFooBarAuditIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java index 0530c2a70f..444324dafc 100644 --- a/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java +++ b/persistence-modules/spring-hibernate4/src/test/java/com/baeldung/persistence/audit/EnversFooBarAuditIntegrationTest.java @@ -121,7 +121,7 @@ public class EnversFooBarAuditIntegrationTest { barRevisionList = barService.getRevisions(); assertNotNull(barRevisionList); - assertTrue(barRevisionList.size()>=4); + assertEquals(4, barRevisionList.size()); assertEquals("BAR", barRevisionList.get(0).getName()); assertEquals("BAR", barRevisionList.get(1).getName()); From 55d250318a5473fa9c2a24c8b4367352d5077569 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 20 Jul 2019 15:25:56 +0530 Subject: [PATCH 237/352] [BAEL-15974] - Fixed issue in Command Pattern article --- .../AuthenticationProcessor.java | 2 +- .../AuthenticationProvider.java | 2 +- .../OAuthAuthenticationProcessor.java | 2 +- .../OAuthTokenProvider.java | 2 +- .../SamlAuthenticationProvider.java | 2 +- ...ernamePasswordAuthenticationProcessor.java | 2 +- .../UsernamePasswordProvider.java | 2 +- .../command/client/TextFileApplication.java | 12 ++++----- .../command/OpenTextFileOperation.java | 4 +-- .../command/SaveTextFileOperation.java | 4 +-- .../command/command/TextFileOperation.java | 2 +- .../invoker/TextFileOperationExecutor.java | 4 +-- .../baeldung/command/receiver/TextFile.java | 2 +- .../application/Application.java | 12 ++++----- .../templatemethod/model/Computer.java | 2 +- .../templatemethod/model/ComputerBuilder.java | 3 +-- .../templatemethod/model/HighEndComputer.java | 3 +-- .../model/HighEndComputerBuilder.java | 2 +- .../model/StandardComputer.java | 3 +-- .../model/StandardComputerBuilder.java | 2 +- .../ChainOfResponsibilityIntegrationTest.java | 9 ++----- .../test/OpenTextFileOperationUnitTest.java | 12 +++++---- .../test/SaveTextFileOperationUnitTest.java | 12 +++++---- .../TextFileOperationExecutorUnitTest.java | 26 +++++++++++++------ .../command/test/TextFileUnitTest.java | 10 ++++--- .../TemplateMethodPatternIntegrationTest.java | 14 +++++----- 26 files changed, 80 insertions(+), 72 deletions(-) diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProcessor.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProcessor.java index 374de31ba9..986c1d9660 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProcessor.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public abstract class AuthenticationProcessor { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProvider.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProvider.java index 7b8771ca41..4d5e3bde24 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProvider.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/AuthenticationProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public interface AuthenticationProvider { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthAuthenticationProcessor.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthAuthenticationProcessor.java index 3bf20cfc85..5f994bad89 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthAuthenticationProcessor.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthAuthenticationProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class OAuthAuthenticationProcessor extends AuthenticationProcessor { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthTokenProvider.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthTokenProvider.java index 92d5f94245..37f419b6e2 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthTokenProvider.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/OAuthTokenProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class OAuthTokenProvider implements AuthenticationProvider { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/SamlAuthenticationProvider.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/SamlAuthenticationProvider.java index cd927932ad..3a0c35a9b9 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/SamlAuthenticationProvider.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/SamlAuthenticationProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class SamlAuthenticationProvider implements AuthenticationProvider { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java index 3885b2b79b..39038b1374 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordAuthenticationProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class UsernamePasswordAuthenticationProcessor extends AuthenticationProcessor { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordProvider.java b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordProvider.java index 9877039446..14dc93b8fc 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordProvider.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/chainofresponsibility/UsernamePasswordProvider.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; public class UsernamePasswordProvider implements AuthenticationProvider { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/client/TextFileApplication.java b/patterns/design-patterns/src/main/java/com/baeldung/command/client/TextFileApplication.java index 30dcf08e89..878b67e0cf 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/client/TextFileApplication.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/client/TextFileApplication.java @@ -1,10 +1,10 @@ -package com.baeldung.pattern.command.client; +package com.baeldung.command.client; -import com.baeldung.pattern.command.command.OpenTextFileOperation; -import com.baeldung.pattern.command.command.SaveTextFileOperation; -import com.baeldung.pattern.command.command.TextFileOperation; -import com.baeldung.pattern.command.invoker.TextFileOperationExecutor; -import com.baeldung.pattern.command.receiver.TextFile; +import com.baeldung.command.command.OpenTextFileOperation; +import com.baeldung.command.command.SaveTextFileOperation; +import com.baeldung.command.command.TextFileOperation; +import com.baeldung.command.invoker.TextFileOperationExecutor; +import com.baeldung.command.receiver.TextFile; public class TextFileApplication { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/command/OpenTextFileOperation.java b/patterns/design-patterns/src/main/java/com/baeldung/command/command/OpenTextFileOperation.java index c90a162b88..74adce0116 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/command/OpenTextFileOperation.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/command/OpenTextFileOperation.java @@ -1,6 +1,6 @@ -package com.baeldung.pattern.command.command; +package com.baeldung.command.command; -import com.baeldung.pattern.command.receiver.TextFile; +import com.baeldung.command.receiver.TextFile; public class OpenTextFileOperation implements TextFileOperation { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/command/SaveTextFileOperation.java b/patterns/design-patterns/src/main/java/com/baeldung/command/command/SaveTextFileOperation.java index b908e2c44c..f0462622e3 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/command/SaveTextFileOperation.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/command/SaveTextFileOperation.java @@ -1,6 +1,6 @@ -package com.baeldung.pattern.command.command; +package com.baeldung.command.command; -import com.baeldung.pattern.command.receiver.TextFile; +import com.baeldung.command.receiver.TextFile; public class SaveTextFileOperation implements TextFileOperation { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/command/TextFileOperation.java b/patterns/design-patterns/src/main/java/com/baeldung/command/command/TextFileOperation.java index 506bb23d99..2d0267d315 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/command/TextFileOperation.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/command/TextFileOperation.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.command.command; +package com.baeldung.command.command; @FunctionalInterface public interface TextFileOperation { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/invoker/TextFileOperationExecutor.java b/patterns/design-patterns/src/main/java/com/baeldung/command/invoker/TextFileOperationExecutor.java index bd2213706e..67c6dedd89 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/invoker/TextFileOperationExecutor.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/invoker/TextFileOperationExecutor.java @@ -1,6 +1,6 @@ -package com.baeldung.pattern.command.invoker; +package com.baeldung.command.invoker; -import com.baeldung.pattern.command.command.TextFileOperation; +import com.baeldung.command.command.TextFileOperation; import java.util.ArrayList; import java.util.List; diff --git a/patterns/design-patterns/src/main/java/com/baeldung/command/receiver/TextFile.java b/patterns/design-patterns/src/main/java/com/baeldung/command/receiver/TextFile.java index c0b2d3c41e..0163102256 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/command/receiver/TextFile.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/command/receiver/TextFile.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.command.receiver; +package com.baeldung.command.receiver; public class TextFile { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/application/Application.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/application/Application.java index 9ab34c3cd8..353a369837 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/application/Application.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/application/Application.java @@ -1,11 +1,9 @@ -package com.baeldung.pattern.templatemethod.application; +package com.baeldung.templatemethod.application; -import com.baeldung.pattern.templatemethod.model.Computer; -import com.baeldung.pattern.templatemethod.model.StandardComputer; -import com.baeldung.pattern.templatemethod.model.HighEndComputer; -import com.baeldung.pattern.templatemethod.model.ComputerBuilder; -import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder; -import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder; +import com.baeldung.templatemethod.model.Computer; +import com.baeldung.templatemethod.model.ComputerBuilder; +import com.baeldung.templatemethod.model.HighEndComputerBuilder; +import com.baeldung.templatemethod.model.StandardComputerBuilder; public class Application { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/Computer.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/Computer.java index 1419398f62..129a8d4c65 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/Computer.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/Computer.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; import java.util.HashMap; import java.util.Map; diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/ComputerBuilder.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/ComputerBuilder.java index 515a6940f5..b5c7ee3987 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/ComputerBuilder.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/ComputerBuilder.java @@ -1,6 +1,5 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; -import com.baeldung.pattern.templatemethod.model.Computer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputer.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputer.java index 0684b1b233..55394d1df6 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputer.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputer.java @@ -1,6 +1,5 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; -import com.baeldung.pattern.templatemethod.model.Computer; import java.util.Map; public class HighEndComputer extends Computer { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java index c992aa2bff..2ee6f93f9b 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; public class HighEndComputerBuilder extends ComputerBuilder { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputer.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputer.java index 4e1d857016..3abe240316 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputer.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputer.java @@ -1,6 +1,5 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; -import com.baeldung.pattern.templatemethod.model.Computer; import java.util.Map; public class StandardComputer extends Computer { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java index cc81dddc1b..da2c2e9b2d 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.templatemethod.model; +package com.baeldung.templatemethod.model; public class StandardComputerBuilder extends ComputerBuilder { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java index 824b104f81..4556232815 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java @@ -1,14 +1,9 @@ package com.baeldung.chainofresponsibility; -import org.junit.Test; -import com.baeldung.pattern.chainofresponsibility.AuthenticationProcessor; -import com.baeldung.pattern.chainofresponsibility.OAuthAuthenticationProcessor; -import com.baeldung.pattern.chainofresponsibility.OAuthTokenProvider; -import com.baeldung.pattern.chainofresponsibility.UsernamePasswordProvider; -import com.baeldung.pattern.chainofresponsibility.SamlAuthenticationProvider; -import com.baeldung.pattern.chainofresponsibility.UsernamePasswordAuthenticationProcessor; import static org.junit.Assert.assertTrue; +import org.junit.Test; + public class ChainOfResponsibilityIntegrationTest { private static AuthenticationProcessor getChainOfAuthProcessor() { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/command/test/OpenTextFileOperationUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/command/test/OpenTextFileOperationUnitTest.java index 1c72bfdd2f..eac62313f7 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/command/test/OpenTextFileOperationUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/command/test/OpenTextFileOperationUnitTest.java @@ -1,10 +1,12 @@ -package com.baeldung.pattern.command.test; +package com.baeldung.command.test; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.pattern.command.command.OpenTextFileOperation; -import com.baeldung.pattern.command.command.TextFileOperation; -import com.baeldung.pattern.command.receiver.TextFile; import org.junit.Test; -import static org.assertj.core.api.Assertions.*; + +import com.baeldung.command.command.OpenTextFileOperation; +import com.baeldung.command.command.TextFileOperation; +import com.baeldung.command.receiver.TextFile; public class OpenTextFileOperationUnitTest { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/command/test/SaveTextFileOperationUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/command/test/SaveTextFileOperationUnitTest.java index a7bc1f3025..3e47f10366 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/command/test/SaveTextFileOperationUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/command/test/SaveTextFileOperationUnitTest.java @@ -1,10 +1,12 @@ -package com.baeldung.pattern.command.test; +package com.baeldung.command.test; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.pattern.command.command.SaveTextFileOperation; -import com.baeldung.pattern.command.command.TextFileOperation; -import com.baeldung.pattern.command.receiver.TextFile; import org.junit.Test; -import static org.assertj.core.api.Assertions.*; + +import com.baeldung.command.command.SaveTextFileOperation; +import com.baeldung.command.command.TextFileOperation; +import com.baeldung.command.receiver.TextFile; public class SaveTextFileOperationUnitTest { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileOperationExecutorUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileOperationExecutorUnitTest.java index efafa0d8a2..3861b1109e 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileOperationExecutorUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileOperationExecutorUnitTest.java @@ -1,14 +1,17 @@ -package com.baeldung.pattern.command.test; +package com.baeldung.command.test; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.pattern.command.command.OpenTextFileOperation; -import com.baeldung.pattern.command.command.SaveTextFileOperation; -import com.baeldung.pattern.command.command.TextFileOperation; -import com.baeldung.pattern.command.invoker.TextFileOperationExecutor; -import com.baeldung.pattern.command.receiver.TextFile; import java.util.function.Function; -import org.junit.Test; -import static org.assertj.core.api.Assertions.*; + import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.command.command.OpenTextFileOperation; +import com.baeldung.command.command.SaveTextFileOperation; +import com.baeldung.command.command.TextFileOperation; +import com.baeldung.command.invoker.TextFileOperationExecutor; +import com.baeldung.command.receiver.TextFile; public class TextFileOperationExecutorUnitTest { @@ -65,4 +68,11 @@ public class TextFileOperationExecutorUnitTest { Function executeMethodReference = SaveTextFileOperation::execute; assertThat(executeMethodReference.apply(new SaveTextFileOperation(new TextFile("file1.txt")))).isEqualTo("Saving file file1.txt"); } + + @Test + public void givenOpenAndSaveTextFileOperationExecutorInstance_whenCalledExecuteOperationWithLambdaExpression_thenBothAssertion() { + TextFileOperationExecutor textFileOperationExecutor = new TextFileOperationExecutor(); + assertThat(textFileOperationExecutor.executeOperation(() -> "Opening file file1.txt")).isEqualTo("Opening file file1.txt"); + assertThat(textFileOperationExecutor.executeOperation(() -> "Saving file file1.txt")).isEqualTo("Saving file file1.txt"); + } } diff --git a/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileUnitTest.java index 32b83897c9..e35c785f3e 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/command/test/TextFileUnitTest.java @@ -1,9 +1,11 @@ -package com.baeldung.pattern.command.test; +package com.baeldung.command.test; + +import static org.assertj.core.api.Assertions.assertThat; -import com.baeldung.pattern.command.receiver.TextFile; -import org.junit.Test; -import static org.assertj.core.api.Assertions.*; import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.command.receiver.TextFile; public class TextFileUnitTest { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java index 4ad4debb27..2c721be5da 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java @@ -1,14 +1,16 @@ package com.baeldung.templatemethod.test; -import com.baeldung.pattern.templatemethod.model.Computer; -import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder; -import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder; -import org.junit.Assert; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertThat; + +import com.baeldung.templatemethod.model.Computer; +import com.baeldung.templatemethod.model.HighEndComputerBuilder; +import com.baeldung.templatemethod.model.StandardComputerBuilder; public class TemplateMethodPatternIntegrationTest { From 7755f11bb5ededc3b0c0afbd311189c49d96b237 Mon Sep 17 00:00:00 2001 From: Dhrubajyoti Bhattacharjee Date: Sat, 20 Jul 2019 16:50:19 +0530 Subject: [PATCH 238/352] BAEL-3004 spring boot application as a dependency (#7325) * BAEL-3004 spring boot application as a dependency * BAEL-3004 spring boot application as dependency --- spring-boot-crud/pom.xml | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/spring-boot-crud/pom.xml b/spring-boot-crud/pom.xml index 15ff6c5d11..1d956bdba6 100644 --- a/spring-boot-crud/pom.xml +++ b/spring-boot-crud/pom.xml @@ -54,7 +54,28 @@ org.springframework.boot spring-boot-maven-plugin + + exec + + + org.apache.maven.plugins + maven-assembly-plugin + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + @@ -62,4 +83,4 @@ UTF-8 - \ No newline at end of file + From b6ae9ec3b48f8bd5d5dbb308796cf364f55119a6 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 20 Jul 2019 17:03:56 +0530 Subject: [PATCH 239/352] Story/bael 14304 (#7311) * BAEL-15951 Moved vavr, JHipster to default profiles * BAEL-14304 Include the SpringContextIntegrationTest in the default build - Added SpringContextTest.java in all the modules where SpringContextIntegrationTest already exists * BAEL-14304 Changes in pmd rule and pom.xml to run UnitTest and SpringContextTest additionally in default profiles * BAEL-14304 Minor changes --- custom-pmd-0.0.1.jar | Bin 4357 -> 3725 bytes .../pmd/UnitTestNamingConventionRule.java | 4 ++ .../java/com/baeldung/SpringContextTest.java | 19 +++++ .../java/org/baeldung/SpringContextTest.java | 67 ++++++++++++++++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 19 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/com/baeldung/SpringContextTest.java | 21 ++++++ pom.xml | 13 +++- .../java/org/baeldung/SpringContextTest.java | 20 ++++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/com/baeldung/SpringContextTest.java | 19 +++++ .../java/org/baeldung/SpringContextTest.java | 15 ++++ .../java/org/baeldung/SpringContextTest.java | 13 ++++ .../java/org/baeldung/SpringContextTest.java | 12 ++++ .../java/org/baeldung/SpringContextTest.java | 13 ++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/com/baeldung/SpringContextTest.java | 15 ++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 13 ++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../SpringContextTest.java | 15 ++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/com/baeldung/SpringContextTest.java | 16 +++++ .../com/baeldung/boot/SpringContextTest.java | 15 ++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../additionalsources/SpringContextTest.java | 15 ++++ .../archaius/basic/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../archaius/jdbconfig/SpringContextTest.java | 15 ++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../bootstrap/gateway/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../config/server/SpringContextTest.java | 16 +++++ .../connectors/heroku/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../eureka/client/SpringContextTest.java | 16 +++++ .../cloud/feign/client/SpringContextTest.java | 16 +++++ .../eureka/server/SpringContextTest.java | 16 +++++ .../cloudfunction/aws/SpringContextTest.java | 15 ++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../rest/consumer/SpringContextTest.java | 18 +++++ .../rest/consumer/SpringContextTest.java | 18 +++++ .../rest/producer/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/com/baeldung/SpringContextTest.java | 17 +++++ .../java/com/baeldung/SpringContextTest.java | 17 +++++ .../travelagency/SpringContextTest.java | 16 +++++ .../cloud/openfeign/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 15 ++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../aggregate/SpringContextTest.java | 15 ++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../cloud/vaultsample/SpringContextTest.java | 15 ++++ .../src/test/baeldung/SpringContextTest.java | 17 +++++ .../cloud/helloworld/SpringContextTest.java | 16 +++++ .../eureka/client/SpringContextTest.java | 16 +++++ .../eureka/server/SpringContextTest.java | 16 +++++ .../cloud/zuul/config/SpringContextTest.java | 16 +++++ .../controller/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 19 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 20 ++++++ .../java/org/baeldung/SpringContextTest.java | 21 ++++++ .../java/org/baeldung/SpringContextTest.java | 19 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 15 ++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 19 +++++ .../listbindingexample/SpringContextTest.java | 17 +++++ .../sessionattrs/SpringContextTest.java | 17 +++++ .../java/com/baeldung/SpringContextTest.java | 21 ++++++ .../java/com/baeldung/SpringContextTest.java | 21 ++++++ .../java/org/baeldung/SpringContextTest.java | 20 ++++++ .../java/org/baeldung/SpringContextTest.java | 19 +++++ .../java/org/baeldung/SpringContextTest.java | 19 +++++ .../java/org/baeldung/SpringContextTest.java | 19 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/com/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/com/baeldung/SpringContextTest.java | 24 +++++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 19 +++++ .../java/org/baeldung/SpringContextTest.java | 20 ++++++ .../java/com/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 15 ++++ .../java/com/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 20 ++++++ .../java/org/baeldung/SpringContextTest.java | 19 +++++ .../java/org/baeldung/SpringContextTest.java | 24 +++++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 15 ++++ .../java/org/baeldung/SpringContextTest.java | 20 ++++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 15 ++++ .../java/org/baeldung/SpringContextTest.java | 23 ++++++ .../java/com/baeldung/SpringContextTest.java | 20 ++++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 22 ++++++ .../java/org/baeldung/SpringContextTest.java | 18 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 17 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ .../java/org/baeldung/SpringContextTest.java | 16 +++++ 182 files changed, 3128 insertions(+), 1 deletion(-) create mode 100644 persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-4/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-5-security/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-5/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-activiti/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-aop/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-batch/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-bom/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-ops-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java create mode 100644 spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-boot-rest/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java create mode 100644 spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-connectors-heroku/src/test/java/com/baeldung/spring/cloud/connectors/heroku/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/test/java/com/baeldung/spring/cloud/feign/client/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-hystrix/rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-hystrix/rest-producer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/producer/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-kubernetes/client-service/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-kubernetes/travel-agency-service/src/test/java/com/baeldung/spring/cloud/kubernetes/travelagency/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/com/baeldung/twitterhdfs/aggregate/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-zookeeper/HelloWorld/src/test/java/com/baeldung/spring/cloud/helloworld/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/test/java/com/baeldung/spring/cloud/zuul/config/SpringContextTest.java create mode 100644 spring-cloud/spring-cloud-zuul/src/test/java/com/baeldung/spring/cloud/zuulratelimitdemo/controller/SpringContextTest.java create mode 100644 spring-cucumber/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-data-rest/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-drools/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-freemarker/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-integration/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-jersey/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-jinq/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-jms/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-katharsis/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-ldap/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-mobile/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-mockito/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java create mode 100644 spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java create mode 100644 spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-mvc-simple/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-quartz/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-reactor/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-rest-full/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-rest-query-language/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-rest/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-core/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-mvc-jsonview/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-openid/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-react/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-social-login/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-spel/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-userservice/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-vault/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-vertx/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-webflux-amqp/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextTest.java create mode 100644 spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextTest.java diff --git a/custom-pmd-0.0.1.jar b/custom-pmd-0.0.1.jar index e19bce6e52a4b43fc383cbb5f176c57b6c99bd95..3ae5e8e41af612675c00d36abf3a14c02b46f20b 100644 GIT binary patch literal 3725 zcmb7H2Ut^A8xE^N0A&O;1q5WT2t-yRQ$bcJ$P!r+mW&Wg0s{+lABV*kJW^5mZTB;WgnY0YmD&Lq6^>Hj;yN zvm41tcRqgl`)Tmq}neX!kRUmVL6J9xU z?w2-E-rVIOBmp{isC{y5GApypF2t50n63Q1NrIQZE+~5m`I;=08Duk<+`6_zvUrKM z{leq&C{isf#BjiG`bW0mJYDUgPabuJERrJ5kdt%IZpA+i_yX(QXRaX>ybKG9JkWeX zF(K&eLaQ(D`wJ50O~aF9wGu11m%BnmQBmBYAr*Gh`(+q!4%oC?-&7ke7rb1&SZ&Rg|#RLj*)sW^Qbm%VVi@>$^9Hy_m$9h~P)yRK+R+#$_i?Q<7&LFMJSX)y$cE=ygMJ?{GXk9JKT!siMD=Hx32_?m7V zYRw!^%Biro9ZX4RpRg7cbyp{5?K8aJ(NU^*?Q=)TY=W*#pg7Jd9Yc5>ryw<}EZl9B z<47%zL0Azicf-kGHaSv20zOY%=;`}?DrPV&5^0Ln-1?^Le^`W z1&j-X#|&3!O;g*JN}40iQEpshT2)D>U~p6?4OS7})y1<#K3H?eI|A}@Z*2OL+CZIX zSA|9$WL!JdE9y>5=7MHdw_TIe33;4XqLK(_;R;uZ6m=#=*!g7F{PW!U-y|pjVlkzo z_E~A=C8Km!E+s`DczIYN^{DXzjG_FxrsYw7TpC&Cl%(=Gxmvj~1kbCneNfG!4=g8T z5MzNyI5fOqShLlVb3(D6ypvksLfJmcGeXb!q&;sJ-z_(Q?F;-55BOejYtpY2(RP=s z?$>oE@27JgO<^kb^e+&rd4izY&yH6P+$O-Gw$l8^L?P?cOUb@p#xp+S^>5sXNTdW0|GpCn4eFspRKiL;p1QhQoLzh0n26*^u_M!1kpHMwDJ7>xT-MtnoVEy zoLY9okShI~w*n%y^sb&Vt#|$0YN`t^-9RTxd+@gW=-6H=Xxr$+kk)PSmP3xkd8qmR ziaG4!C!qv5AGYhHckJv=bm!+eKh+ve4dSpdP`tsts&+3E7L5`3GocKO7!|mfKCl4C=iwZ{oUM zJ9dN~1d7-P0xAAGB3}%eRW`EZ9dS5LU3XLD4bkwFvL-ogUiep z^>;y_IY%3C&Ip?l$kE7uussQsb)CW@?=U<4<90D{3o?do$K+>jqFL3d!z#Gb3SQqLn^0o!qUA6;Xp% zLpHiED7321^n@o)aIQIs-!Zd$1c?^Bd2B`BTeX00GVpqm-+MXa-NS(>)4Y4_`j!O> zXpx-u6w1XIzLNo^v9cl^vyC|ci|iR!`xMkKe_@mnmOMu%c+#WcOe#@!0M0{A`&qEe zGSN7llPW$PV6Vi~6ySZkkx7J{2h)n5W*!`=cryt7iTjF!ipi-L3peH~9TyIF_E3Gq z59FDK>uWFa;~N|Z8}qr1`t)qw6;}NIl7emi%0)HCA}}6f$^9+0A0xd(9oF~XQ&s;B zS3kcT?0>FI>Cyo#>)S>1?1PQ<#iX{#LPDLuaV>_CC+hER^$9pRdKiA`qPzI&?QyF> zI%(_x+@DPrij*Kg(;ghLi?+|{eWYP4!f1p=p!pK-C%#frUc7u2-@GWF{ti!YejpJO zb82d`nW!>o%sS)qelF?7)Cmf>t8WqYseu(map-ezbbWr@JpORL0X^ za^Z9~>hoU*_i7nKS((x`7h8yDiaoia2;Rd#E>?C{W;Zme*8O4I@9Afz(ce<1)TdgC zGQq~={;ZY(^4Hkz7m291sQ57_>q z?OVj(SNARIyzriXNBmXmcjl1!&o{zv&+-nx9&k>+nZrHPuxsEn{+*L;YQ*#djfxHU NcrpN6miCqe`Y%N0ksSa4 literal 4357 zcmeHKdpuNWAD<$`=oQwkOD*M+$;`TqvLWL#E;Ft(ZZ%}mU^0v~hN)?jQbI0~%ch95 zR=I`@BDr59lw60bTw1w|#UkD_tMIDzzPLtYBT&uSG=P#qrbUsJ4ah#V}FrWM{YR-qVs--cue z2j}t$qJR$}mO>~?OqovDj-WcxG~Uu6LfRSL>a*2nV+8o+iyY)TC66e~fM4_ThtdjZ zg`kh_fk0E6qWITF_uTP51dp{?J{6YyRG94L0y~K(kWNuOTwtE=r?${O_&;bnQ7PVJ zcj(qYoB$ADcMDVeA0$3{wuR{K&7vD^^Zc1Fv^9Jp9}r^!QyrLV|N3gaK1sobAUw(L zFi$VCC&9~`NTAqWun_ZAM{kQSXdFG-b zC%XPjg@!W=kx&T<^(?A*>QGnFAN_Nq^Q@<{zi&aKl%*XhES58|P8Xw#p}P0xL&3}% zi7|USoYBd?ndmgMy-1WNZ^f%z^qW&e(WpeUZOublab?7O;H~qW(Pv|mr;FY*$2&F6 zX2`Fkyv!@b8_3|77J5sReWxvBI$@%v_tQttJu+nl+AOWDoz+|@`jLdEwt+x7Tp*D0 zm*;}!PRhsHle;B_e{9aWnp`3lNj>(UcE~+SHoq$+!|H^5=?`@z?F+ZjRx67u@A^hsG~A;ZbPP!hx;_NSCIt4Z z1kXDYmYiJ@)w<!S zjg|S^)QqJP)#NkjO+Ed7#Ao`Zv)I)6CGql$F)a_?`3pSoMmS>)r{oztkHNxM!JLDR zh6fi#mwmbDi+tI&wZ>@ojHQC@N1V{J43f8I_yzDy`m;iEi~1B?OXNv zgqJhAToaOgmqA)Kk4I( zso2o7>pCVKs1b#@D?@sh^(ItBTHOZSu_OPUq2rwrSok%Bgh59rU`k`uY|fEu4qL?dZqWZ?^H+_KIE-ReKi>|*4n7FP_QsTXb*$h* z+#s!)L1pHX3icY-Mjx^b8BNOGQ$pfSmX>mRMU4$=85X=UYacG>5?Dy>70|-pkgb(g z@hE;27ZCvwj+OClriqBo#k$AZlp{kIQR#0Yq)*JE-zcas!=Ab03v3I5f*fX-iX5DJ za&&aaY6|a_{9#ktSlde)O*D^?;_}%ZgQSW&w;}@fqlj#W1I4%z|F0KhPwW@od%Q;4 zsYpR!;YN~%rNfhd${v7y~jJQd0%B~CPTzcyhr%nYsBs!sDrgXGyA0QcIfN_ za)I-8H?PZAHO)ctD6pgsfyN%3W7FXvEPZD^V>GYfj+jzDx6cjc)4^66y!_?l-oDr= z!%O}$qTz4_r_0mgqC3P&b)sJ(x%nsh?L{AmCG@+AGF|6Im=;1N^aP%O=9_%Dbh>p* z;?p_x>}Azfbu7Hyu|8YXGoAR0({1!@jo!H6P+CHYoR=&@*61PT>o{>`IrRf9>n0Mp z!6&4k;0Qjl7wM$gRhJDXIbzC3{KlX=4~1oAnHeu&p}d{KENP?kcctz&=E79i8?kg# z*HqrB3W#4aYhRR4QbF4=D>Z4H6+CRMQ*+%jZSo3#hGz$_H3=c3Zhv?rlVRLXHvpCR z1jpxI37{MS4>stD*|l1BVP03-3))MR21L=5LoUmFwM%UA>TeMzLb>#Dy>A1jda9hD z-c1L7TF^~A{-{n*^&nSRzmZwf@3_*k03-Qt6ePlha$4dD(C&mb*sBcP+P#{4l0|-L z;gQ#OQtp_74=s{H9!BC3k%J+Zcr4OVm5->2N`>9h4W3m+j?xpP zzt0fN7#%nvRdUrz>ke5~9J((h_6qUg)6qJEnhDyBHn)dFf_A%1eIcqWc79% zu3Tui`v=%P!D+;$HtSA{>jRJd#nU&nr+78(X<@%j@`#?^e{{DV#D^XuaVah}sMt8Y zIpWl{!%QjP-O&S;_VLDf#aB^EB}O=;e{Jdy;`*(q0bZlrkp(^{Wn`jG{7DQ8`;#El(M4GYQ_c%?k{r71mpZ z1go%EB>oxj4ERi8YsfT;PXj|@g|z-2DTtw18naq|=k>zS3I#)qmD>cPP!}TW?p4YB zQCQ@N2b#WZ+l4v)n)m?m07C#Yj$l968sc@e&l4fGFngr<%K`T_wGFgr9pO{@!R9Kf zgKfAPcwIyI$XwRF-b{2PKd7#H&2Hs4DSy(&Z{-S`%d8HzD@s5^{NKX2cTKDqv zG-KV&c8)K~HQNk8IyU07iTvg+bRA!J$N$xnZZz<@qhsB`1km_?!D9J~05(^ab$mte b7vrxpRCCl0fY^aR{J=F2WO@z&1A+bxcvh*6 diff --git a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java index 3b73f9c21c..2cbab782ee 100644 --- a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java +++ b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java @@ -22,6 +22,10 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule { String className = node.getImage(); Objects.requireNonNull(className); + if (className.endsWith("SpringContextTest")) { + return data; + } + if (className.endsWith("Tests") || (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) { addViolation(data, node); diff --git a/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..90787681cf --- /dev/null +++ b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..89e729da86 --- /dev/null +++ b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,67 @@ +package org.baeldung; + +import java.io.IOException; +import java.util.HashMap; + +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.thrift.transport.TTransportException; +import org.baeldung.spring.data.cassandra.config.CassandraConfig; +import org.baeldung.spring.data.cassandra.model.Book; +import org.cassandraunit.utils.EmbeddedCassandraServerHelper; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cassandra.core.cql.CqlIdentifier; +import org.springframework.data.cassandra.core.CassandraAdminOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.Session; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = CassandraConfig.class) +public class SpringContextTest { + + public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; + + public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;"; + + public static final String DATA_TABLE_NAME = "book"; + + @Autowired + private CassandraAdminOperations adminTemplate; + + @BeforeClass + public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { + EmbeddedCassandraServerHelper.startEmbeddedCassandra(); + final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); + final Session session = cluster.connect(); + session.execute(KEYSPACE_CREATION_QUERY); + session.execute(KEYSPACE_ACTIVATE_QUERY); + Thread.sleep(5000); + } + + @Before + public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException { + adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap()); + } + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + + @After + public void dropTable() { + adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); + } + + @AfterClass + public static void stopCassandraEmbedded() { + EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); + } +} diff --git a/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/persistence-modules/spring-data-dynamodb/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4c69245f65 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.eclipselink.springdata.EclipselinkSpringDataApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = EclipselinkSpringDataApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3772e22137 --- /dev/null +++ b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.spring.data.gemfire.function.GemfireConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes=GemfireConfiguration.class, loader=AnnotationConfigContextLoader.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..db7b156415 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e6cc5c15af --- /dev/null +++ b/persistence-modules/spring-data-keyvalue/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.data.keyvalue.SpringDataKeyValueApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataKeyValueApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5bf54fc0bd --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.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() { + } +} diff --git a/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..6652345595 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.redis.config.RedisConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RedisConfig.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..09bf0255a0 --- /dev/null +++ b/persistence-modules/spring-data-solr/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.solr.config.SolrConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = SolrConfig.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..956d5279a3 --- /dev/null +++ b/persistence-modules/spring-hibernate-3/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.PersistenceConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..6815ebf304 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.spring.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.java b/persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..6815ebf304 --- /dev/null +++ b/persistence-modules/spring-hibernate4/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.spring.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..291e49d0c4 --- /dev/null +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.baeldung.config.PersistenceJPAConfigL2Cache; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +@DirtiesContext +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/pom.xml b/pom.xml index 92350ab892..b888994a43 100644 --- a/pom.xml +++ b/pom.xml @@ -312,6 +312,10 @@ 3 true + + SpringContextTest + **/*UnitTest + **/*IntegrationTest.java **/*IntTest.java @@ -574,6 +578,10 @@ 3 true + + SpringContextTest + **/*UnitTest + **/*IntegrationTest.java **/*IntTest.java @@ -950,6 +958,10 @@ 3 true + + SpringContextTest + **/*UnitTest + **/*IntegrationTest.java **/*IntTest.java @@ -1446,7 +1458,6 @@ xml xmlunit-2 xstream - diff --git a/spring-4/src/test/java/org/baeldung/SpringContextTest.java b/spring-4/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..cccdaff0cd --- /dev/null +++ b/spring-4/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.flips.ApplicationConfig; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ApplicationConfig.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c3ea1d8435 --- /dev/null +++ b/spring-5-data-reactive/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.Spring5ReactiveApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..678d04897b --- /dev/null +++ b/spring-5-reactive-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.Spring5ReactiveTestApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveTestApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..479c35d986 --- /dev/null +++ b/spring-5-reactive-security/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.security.SpringSecurity5Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSecurity5Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c3ea1d8435 --- /dev/null +++ b/spring-5-reactive/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.Spring5ReactiveApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java b/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..729790bd14 --- /dev/null +++ b/spring-5-security/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.dsl.CustomConfigurerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CustomConfigurerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-5/src/test/java/org/baeldung/SpringContextTest.java b/spring-5/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..56e8697f5c --- /dev/null +++ b/spring-5/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Spring5Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-activiti/src/test/java/com/baeldung/SpringContextTest.java b/spring-activiti/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..14df617b1f --- /dev/null +++ b/spring-activiti/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.activitiwithspring.ActivitiWithSpringApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ActivitiWithSpringApplication.class) +@AutoConfigureTestDatabase +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-aop/src/test/java/org/baeldung/SpringContextTest.java b/spring-aop/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4d3ed953c4 --- /dev/null +++ b/spring-aop/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1c098a56ab --- /dev/null +++ b/spring-apache-camel/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.camel.main.App; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + App.main(null); + } +} diff --git a/spring-batch/src/test/java/org/baeldung/SpringContextTest.java b/spring-batch/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0de9a07b0a --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,12 @@ +package org.baeldung; + +import org.baeldung.batch.App; +import org.junit.Test; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + App.main(null); + } +} diff --git a/spring-bom/src/test/java/org/baeldung/SpringContextTest.java b/spring-bom/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..783567cdfa --- /dev/null +++ b/spring-bom/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.spring.bom.HelloWorldApp; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + HelloWorldApp.main(null); + } +} diff --git a/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..834f26dacf --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootadminclient.SpringBootAdminClientApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootAdminClientApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c185456019 --- /dev/null +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootadminserver.SpringBootAdminServerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootAdminServerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..961d756a68 --- /dev/null +++ b/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.ecommerce.EcommerceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = EcommerceApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4340e27fb4 --- /dev/null +++ b/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8324fabfca --- /dev/null +++ b/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.camel.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9c3b83ea79 --- /dev/null +++ b/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.boot.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ff3e795778 --- /dev/null +++ b/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,13 @@ +package org.baeldung; + +import org.junit.Test; + +import com.baeldung.parent.App; + +public class SpringContextTest { + + @Test + public final void testMain() throws Exception { + App.main(new String[] {}); + } +} diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e6ce83fab5 --- /dev/null +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.greeter.autoconfigure.GreeterAutoConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = GreeterAutoConfiguration.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b82b67df68 --- /dev/null +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.greeter.sample.GreeterSampleApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GreeterSampleApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ab6e4557d5 --- /dev/null +++ b/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.jasypt.Main; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Main.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4effccc083 --- /dev/null +++ b/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.keycloak.SpringBoot; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBoot.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9817522e68 --- /dev/null +++ b/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootlogging.SpringBootLoggingApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootLoggingApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..16e0708fc9 --- /dev/null +++ b/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootmvc.SpringBootMvcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootMvcApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-ops-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java b/spring-boot-ops-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java new file mode 100644 index 0000000000..11bbad8bb2 --- /dev/null +++ b/spring-boot-ops-2/src/test/java/com/baeldung/springbootconfiguration/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.springbootconfiguration; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..874c4f582f --- /dev/null +++ b/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootPropertyExpansionApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..874c4f582f --- /dev/null +++ b/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootPropertyExpansionApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-rest/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-rest/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9cba7f8fc1 --- /dev/null +++ b/spring-boot-rest/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SpringBootRestApplication.class}) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java b/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java new file mode 100644 index 0000000000..f3c8b9a954 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.boot; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..16e0708fc9 --- /dev/null +++ b/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootmvc.SpringBootMvcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootMvcApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a5ab1342a1 --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringCloudConfigClientApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudConfigClientApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..19ca53c4a7 --- /dev/null +++ b/spring-cloud-bus/spring-cloud-config-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringCloudConfigServerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudConfigServerApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3ac11452d3 --- /dev/null +++ b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.JobConfiguration; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +@ContextConfiguration(classes = JobConfiguration.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..83cb8067cf --- /dev/null +++ b/spring-cloud-data-flow/data-flow-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.DataFlowServerApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = DataFlowServerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..c456f69979 --- /dev/null +++ b/spring-cloud-data-flow/data-flow-shell/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.DataFlowShellApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = DataFlowShellApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..42903189d3 --- /dev/null +++ b/spring-cloud-data-flow/log-sink/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.LogSinkApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = LogSinkApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..d090e626d2 --- /dev/null +++ b/spring-cloud-data-flow/time-processor/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.TimeProcessorApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TimeProcessorApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e19b88de90 --- /dev/null +++ b/spring-cloud-data-flow/time-source/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.cloud.TimeSourceApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TimeSourceApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java new file mode 100644 index 0000000000..7e38329f88 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.archaius.additionalsources; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AdditionalSourcesSimpleApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java new file mode 100644 index 0000000000..e88ec436c6 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.archaius.basic; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7674713ff8 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/basic-config/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.archaius.basic.BasicArchaiusApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BasicArchaiusApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a03bd8c23b --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/extra-configs/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.archaius.extraconfigs.ExtraConfigsApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ExtraConfigsApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java b/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java new file mode 100644 index 0000000000..5d3bc8e741 --- /dev/null +++ b/spring-cloud/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.archaius.jdbconfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = JdbcSourcesApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..98ae3e4895 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/config/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.bootstrap.config.ConfigApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConfigApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextTest.java new file mode 100644 index 0000000000..a2d1cd1087 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.bootstrap.gateway; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..76b7539b6b --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/zipkin/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.bootstrap.zipkin.ZipkinApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ZipkinApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java b/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java new file mode 100644 index 0000000000..d879737553 --- /dev/null +++ b/spring-cloud/spring-cloud-config/server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.config.server; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = ConfigServer.class) +@WebAppConfiguration +public class SpringContextTest { + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-connectors-heroku/src/test/java/com/baeldung/spring/cloud/connectors/heroku/SpringContextTest.java b/spring-cloud/spring-cloud-connectors-heroku/src/test/java/com/baeldung/spring/cloud/connectors/heroku/SpringContextTest.java new file mode 100644 index 0000000000..c6066027f5 --- /dev/null +++ b/spring-cloud/spring-cloud-connectors-heroku/src/test/java/com/baeldung/spring/cloud/connectors/heroku/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.cloud.connectors.heroku; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.connectors.heroku.ConnectorsHerokuApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ConnectorsHerokuApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e9098b1467 --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.springcloudcontractconsumer.SpringCloudContractConsumerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudContractConsumerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7d77cbbd7a --- /dev/null +++ b/spring-cloud/spring-cloud-contract/spring-cloud-contract-producer/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.springcloudcontractproducer.SpringCloudContractProducerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudContractProducerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java new file mode 100644 index 0000000000..a3ed012abb --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.client; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/test/java/com/baeldung/spring/cloud/feign/client/SpringContextTest.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/test/java/com/baeldung/spring/cloud/feign/client/SpringContextTest.java new file mode 100644 index 0000000000..ac8150defa --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-feign-client/src/test/java/com/baeldung/spring/cloud/feign/client/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.feign.client; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java new file mode 100644 index 0000000000..e7996bd316 --- /dev/null +++ b/spring-cloud/spring-cloud-eureka/spring-cloud-eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.server; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/SpringContextTest.java b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/SpringContextTest.java new file mode 100644 index 0000000000..67411ebd4a --- /dev/null +++ b/spring-cloud/spring-cloud-functions/src/test/java/com/baeldung/spring/cloudfunction/aws/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloudfunction.aws; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CloudFunctionAwsApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b7e2acf7a8 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.GatewayApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GatewayApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java new file mode 100644 index 0000000000..d5f8180f20 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/feign-rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RestConsumerFeignApplication.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java new file mode 100644 index 0000000000..d3260a4517 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-consumer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/consumer/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.cloud.hystrix.rest.consumer; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RestConsumerApplication.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-hystrix/rest-producer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/producer/SpringContextTest.java b/spring-cloud/spring-cloud-hystrix/rest-producer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/producer/SpringContextTest.java new file mode 100644 index 0000000000..bd871fc1da --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/rest-producer/src/test/java/com/baeldung/spring/cloud/hystrix/rest/producer/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.hystrix.rest.producer; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/client-service/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/client-service/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..af59614f7c --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/client-service/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.kubernetes.client.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..af393cb697 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.kubernetes.backend.KubernetesBackendApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KubernetesBackendApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..17cb5a5f39 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.kubernetes.frontend.KubernetesFrontendApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = KubernetesFrontendApplication.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7c605567d8 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.liveness.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..59802d220a --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.readiness.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/travel-agency-service/src/test/java/com/baeldung/spring/cloud/kubernetes/travelagency/SpringContextTest.java b/spring-cloud/spring-cloud-kubernetes/travel-agency-service/src/test/java/com/baeldung/spring/cloud/kubernetes/travelagency/SpringContextTest.java new file mode 100644 index 0000000000..6e7f99fb0d --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/travel-agency-service/src/test/java/com/baeldung/spring/cloud/kubernetes/travelagency/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.kubernetes.travelagency; + + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java new file mode 100644 index 0000000000..4bf35f74f4 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.cloud.openfeign; + + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ExampleApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1b4083e7a6 --- /dev/null +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudRestConfigApplication.class) +public class SpringContextTest { + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..23dbcf8ff6 --- /dev/null +++ b/spring-cloud/spring-cloud-ribbon-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.ribbon.client.ServerLocationApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ServerLocationApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..02c429acf5 --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.CloudSite; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CloudSite.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a061928bf5 --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-resource/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..aec56a574c --- /dev/null +++ b/spring-cloud/spring-cloud-security/auth-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.AuthServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AuthServer.class) +public class SpringContextTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/com/baeldung/twitterhdfs/aggregate/SpringContextTest.java b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/com/baeldung/twitterhdfs/aggregate/SpringContextTest.java new file mode 100644 index 0000000000..d78a18d557 --- /dev/null +++ b/spring-cloud/spring-cloud-stream-starters/twitterhdfs/src/test/java/com/baeldung/twitterhdfs/aggregate/SpringContextTest.java @@ -0,0 +1,15 @@ +package com.baeldung.twitterhdfs.aggregate; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AggregateApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0f3b8de901 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.stream.rabbit.MultipleOutputsServiceApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MultipleOutputsServiceApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..51f0926429 --- /dev/null +++ b/spring-cloud/spring-cloud-task/springcloudtasksink/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringCloudTaskFinal.SpringCloudTaskSinkApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringCloudTaskSinkApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextTest.java b/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextTest.java new file mode 100644 index 0000000000..73fcbe55f0 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/test/java/org/baeldung/spring/cloud/vaultsample/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung.spring.cloud.vaultsample; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = VaultSampleApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.java b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b45e7b9889 --- /dev/null +++ b/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.ribbon.client.ServerLocationApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = GreetingApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-zookeeper/HelloWorld/src/test/java/com/baeldung/spring/cloud/helloworld/SpringContextTest.java b/spring-cloud/spring-cloud-zookeeper/HelloWorld/src/test/java/com/baeldung/spring/cloud/helloworld/SpringContextTest.java new file mode 100644 index 0000000000..df7335dfa6 --- /dev/null +++ b/spring-cloud/spring-cloud-zookeeper/HelloWorld/src/test/java/com/baeldung/spring/cloud/helloworld/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.helloworld; + + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = HelloWorldApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java new file mode 100644 index 0000000000..9e3680b244 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-client/src/test/java/com/baeldung/spring/cloud/eureka/client/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.client; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java new file mode 100644 index 0000000000..e7996bd316 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/eureka-server/src/test/java/com/baeldung/spring/cloud/eureka/server/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.eureka.server; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/test/java/com/baeldung/spring/cloud/zuul/config/SpringContextTest.java b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/test/java/com/baeldung/spring/cloud/zuul/config/SpringContextTest.java new file mode 100644 index 0000000000..a5350655fb --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/zuul-server/src/test/java/com/baeldung/spring/cloud/zuul/config/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.zuul.config; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/spring-cloud/spring-cloud-zuul/src/test/java/com/baeldung/spring/cloud/zuulratelimitdemo/controller/SpringContextTest.java b/spring-cloud/spring-cloud-zuul/src/test/java/com/baeldung/spring/cloud/zuulratelimitdemo/controller/SpringContextTest.java new file mode 100644 index 0000000000..b5ddf6f65c --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/src/test/java/com/baeldung/spring/cloud/zuulratelimitdemo/controller/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.cloud.zuulratelimitdemo.controller; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.cloud.zuulratelimitdemo.ZuulRatelimitDemoApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ZuulRatelimitDemoApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cucumber/src/test/java/org/baeldung/SpringContextTest.java b/spring-cucumber/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7b8fa74fc9 --- /dev/null +++ b/spring-cucumber/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringDemoApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDemoApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextTest.java b/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/spring-data-rest-querydsl/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-data-rest/src/test/java/org/baeldung/SpringContextTest.java b/spring-data-rest/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7e7fccadef --- /dev/null +++ b/spring-data-rest/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.books.SpringDataRestApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringDataRestApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.java b/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..d1de77b1e6 --- /dev/null +++ b/spring-dispatcher-servlet/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.springdispatcherservlet.configuration.AppConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-drools/src/test/java/org/baeldung/SpringContextTest.java b/spring-drools/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9a36a521f1 --- /dev/null +++ b/spring-drools/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.drools.service.TaxiFareConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = TaxiFareConfiguration.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3e9af8a336 --- /dev/null +++ b/spring-ejb/spring-ejb-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springejbclient.SpringEjbClientApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringEjbClientApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-freemarker/src/test/java/org/baeldung/SpringContextTest.java b/spring-freemarker/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..49b8fe94d1 --- /dev/null +++ b/spring-freemarker/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.freemarker.config.SpringWebConfig; +import com.baeldung.freemarker.config.WebConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SpringWebConfig.class, WebConfiguration.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-integration/src/test/java/org/baeldung/SpringContextTest.java b/spring-integration/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e45997b71e --- /dev/null +++ b/spring-integration/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.si.security.MessageConsumer; +import com.baeldung.si.security.SecuredDirectChannel; +import com.baeldung.si.security.SecurityConfig; +import com.baeldung.si.security.SecurityPubSubChannel; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SecurityConfig.class, SecuredDirectChannel.class, SecurityPubSubChannel.class, + MessageConsumer.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.java b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..79ab2f48b8 --- /dev/null +++ b/spring-jenkins-pipeline/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.SpringJenkinsPipelineApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringJenkinsPipelineApplication.class) +@DirtiesContext +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jersey/src/test/java/org/baeldung/SpringContextTest.java b/spring-jersey/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..f480e597b3 --- /dev/null +++ b/spring-jersey/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.server.config.RestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RestConfig.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jinq/src/test/java/org/baeldung/SpringContextTest.java b/spring-jinq/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e0da75c7af --- /dev/null +++ b/spring-jinq/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.jinq.JinqApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = JinqApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-jms/src/test/java/org/baeldung/SpringContextTest.java b/spring-jms/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e89faeebb7 --- /dev/null +++ b/spring-jms/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:EmbeddedActiveMQ.xml"}) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-katharsis/src/test/java/org/baeldung/SpringContextTest.java b/spring-katharsis/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..769a436778 --- /dev/null +++ b/spring-katharsis/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-ldap/src/test/java/org/baeldung/SpringContextTest.java b/spring-ldap/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8f0c3d4612 --- /dev/null +++ b/spring-ldap/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.ldap.javaconfig.AppConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mobile/src/test/java/org/baeldung/SpringContextTest.java b/spring-mobile/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/spring-mobile/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mockito/src/test/java/org/baeldung/SpringContextTest.java b/spring-mockito/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b6a4e8e389 --- /dev/null +++ b/spring-mockito/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.MocksApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MocksApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e35fc8c86c --- /dev/null +++ b/spring-mvc-forms-jsp/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import com.baeldung.springmvcforms.configuration.ApplicationConfiguration; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ApplicationConfiguration.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java new file mode 100644 index 0000000000..751df882f9 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/listbindingexample/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung.listbindingexample; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.listbindingexample.ListBindingApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {ListBindingApplication.class}) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java new file mode 100644 index 0000000000..0b308319b1 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/test/java/org/baeldung/sessionattrs/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung.sessionattrs; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.sessionattrs.SessionAttrsApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {SessionAttrsApplication.class}) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9777addb61 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.config.AppInitializer; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppInitializer.class }, loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + + } +} diff --git a/spring-mvc-simple/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-simple/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ab0b23c4a5 --- /dev/null +++ b/spring-mvc-simple/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,21 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.spring.configuration.ApplicationConfiguration; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes={ApplicationConfiguration.class}) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} + diff --git a/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..22a4486aa7 --- /dev/null +++ b/spring-mvc-velocity/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.mvc.velocity.spring.config.WebConfig; +import com.baeldung.mvc.velocity.test.config.TestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { TestConfig.class, WebConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..122dc18bad --- /dev/null +++ b/spring-mvc-webflow/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.baeldung.spring.WebFlowConfig; +import org.baeldung.spring.WebMvcConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {WebFlowConfig.class, WebMvcConfig.class}) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java b/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..27dcb83bd4 --- /dev/null +++ b/spring-mvc-xml/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.spring.ClientWebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ClientWebConfig.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java b/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4f655277b7 --- /dev/null +++ b/spring-protobuf/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.protobuf.Application; + +@DirtiesContext +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-quartz/src/test/java/org/baeldung/SpringContextTest.java b/spring-quartz/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..a210e847c8 --- /dev/null +++ b/spring-quartz/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.springquartz.SpringQuartzApp; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringQuartzApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-reactor/src/test/java/org/baeldung/SpringContextTest.java b/spring-reactor/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5e68a8e64f --- /dev/null +++ b/spring-reactor/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..fe20382ab4 --- /dev/null +++ b/spring-remoting/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.client.AmqpClient; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AmqpClient.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4325b0ddef --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.client.BurlapClient; +import com.baeldung.client.HessianClient; + +@SpringBootTest(classes = {BurlapClient.class, HessianClient.class}) +@RunWith(SpringRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e676bb0ff2 --- /dev/null +++ b/spring-remoting/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.server.Server; + +@SpringBootTest(classes = Server.class) +@RunWith(SpringRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e676bb0ff2 --- /dev/null +++ b/spring-remoting/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.server.Server; + +@SpringBootTest(classes = Server.class) +@RunWith(SpringRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..95721b6eaa --- /dev/null +++ b/spring-remoting/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.client.JmsClient; + +@SpringBootTest(classes = JmsClient.class) +@RunWith(SpringRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..6cae1b66fc --- /dev/null +++ b/spring-remoting/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.server.RmiServer; + +@SpringBootTest(classes = RmiServer.class) +@RunWith(SpringRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9136ce43eb --- /dev/null +++ b/spring-rest-angular/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.web.main.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-full/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-full/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8debddc40a --- /dev/null +++ b/spring-rest-full/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-query-language/src/test/java/com/baeldung/SpringContextTest.java b/spring-rest-query-language/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..57886a232a --- /dev/null +++ b/spring-rest-query-language/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-rest/src/test/java/com/baeldung/SpringContextTest.java b/spring-rest/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4b2024e207 --- /dev/null +++ b/spring-rest/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,24 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.custom.CustomApplication; +import com.baeldung.produceimage.ImageApplication; +import com.baeldung.propertyeditor.PropertyEditorApplication; +import com.baeldung.responseheaders.ResponseHeadersApplication; +import com.baeldung.sampleapp.config.MainApplication; +import com.baeldung.web.log.app.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { CustomApplication.class, ImageApplication.class, PropertyEditorApplication.class, + ResponseHeadersApplication.class, Application.class, com.baeldung.web.upload.app.UploadApplication.class, + MainApplication.class}) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java b/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e52d249f0b --- /dev/null +++ b/spring-resttemplate/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.resttemplate.RestTemplateConfigurationApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = RestTemplateConfigurationApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..74f26e2e5a --- /dev/null +++ b/spring-security-acl/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.acl.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e61d512bca --- /dev/null +++ b/spring-security-angular/server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootsecurityrest.basicauth.SpringBootSecurityApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootSecurityApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8fbaa7169b --- /dev/null +++ b/spring-security-cache-control/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.cachecontrol.AppRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AppRunner.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-jsp-authentication/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-jsp-authorize/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-jsp-config/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-mvc/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0afb3899db --- /dev/null +++ b/spring-security-client/spring-security-thymeleaf-config/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-core/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-core/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1707c706ae --- /dev/null +++ b/spring-security-core/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.app.App; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = App.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..2041249b71 --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.custom.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5ee80d856a --- /dev/null +++ b/spring-security-mvc-custom/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..cd2b796308 --- /dev/null +++ b/spring-security-mvc-digest-auth/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.ClientConfig; +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { ClientConfig.class, MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-jsonview/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-mvc-jsonview/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b1a3de714e --- /dev/null +++ b/spring-security-mvc-jsonview/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.spring.AppConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AppConfig.class) +@WebAppConfiguration +public class SpringContextTest { + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..30ba7671d8 --- /dev/null +++ b/spring-security-mvc-ldap/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SampleLDAPApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4cf3b736ea --- /dev/null +++ b/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@WebAppConfiguration +public class SpringContextTest { + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..8113ed0fbe --- /dev/null +++ b/spring-security-mvc-persisted-remember-me/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.PersistenceConfig; +import org.baeldung.spring.SecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, PersistenceConfig.class, SecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5ee80d856a --- /dev/null +++ b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,19 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..7b9c738904 --- /dev/null +++ b/spring-security-mvc-socket/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,24 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.springsecuredsockets.config.AppConfig; +import com.baeldung.springsecuredsockets.config.DataStoreConfig; +import com.baeldung.springsecuredsockets.config.SecurityConfig; +import com.baeldung.springsecuredsockets.config.SocketBrokerConfig; +import com.baeldung.springsecuredsockets.config.SocketSecurityConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppConfig.class, DataStoreConfig.class, SecurityConfig.class, + SocketBrokerConfig.class, SocketSecurityConfig.class }) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-openid/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-openid/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..fa346b2b31 --- /dev/null +++ b/spring-security-openid/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.SpringOpenidApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringOpenidApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-react/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-react/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..9cc52b4726 --- /dev/null +++ b/spring-security-react/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.baeldung.spring.MvcConfig; +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..f54cbf3b7b --- /dev/null +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration({ "/webSecurityConfig.xml" }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..d984cf5c35 --- /dev/null +++ b/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package org.baeldung; + +import org.baeldung.spring.ClientWebConfig; +import org.baeldung.spring.SecurityJavaConfig; +import org.baeldung.spring.WebConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..f677f683b2 --- /dev/null +++ b/spring-security-sso/spring-security-sso-auth-server/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.config.AuthorizationServerApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AuthorizationServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..61a2a022ed --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui-2/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.config.UiApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..61a2a022ed --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.config.UiApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5c65dd3e8a --- /dev/null +++ b/spring-security-x509/spring-security-x509-basic-auth/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.security.x509.X509AuthenticationServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = X509AuthenticationServer.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..5c65dd3e8a --- /dev/null +++ b/spring-security-x509/spring-security-x509-client-auth/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.security.x509.X509AuthenticationServer; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = X509AuthenticationServer.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..b69855ba38 --- /dev/null +++ b/spring-session/spring-session-jdbc/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springsessionjdbc.SpringSessionJdbcApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSessionJdbcApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..307d31a809 --- /dev/null +++ b/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import com.baeldung.springsessionmongodb.SpringSessionMongoDBApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringSessionMongoDBApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextTest.java b/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..994f93c24f --- /dev/null +++ b/spring-session/spring-session-redis/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.session.SessionWebApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SessionWebApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java b/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..ff22398ca4 --- /dev/null +++ b/spring-sleuth/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.session.SleuthWebApp; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SleuthWebApp.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java b/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..cfd8759c52 --- /dev/null +++ b/spring-social-login/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.config.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringContextTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } +} diff --git a/spring-spel/src/test/java/org/baeldung/SpringContextTest.java b/spring-spel/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..e25c1bf8e4 --- /dev/null +++ b/spring-spel/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"classpath:applicationContext.xml"}) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java b/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1e847c0d65 --- /dev/null +++ b/spring-state-machine/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,23 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.statemachine.config.ForkJoinStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.HierarchicalStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.JunctionStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.SimpleEnumStateMachineConfiguration; +import com.baeldung.spring.statemachine.config.SimpleStateMachineConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SimpleStateMachineConfiguration.class, SimpleEnumStateMachineConfiguration.class, + JunctionStateMachineConfiguration.class, HierarchicalStateMachineConfiguration.class, + ForkJoinStateMachineConfiguration.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java b/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..0dcbba3221 --- /dev/null +++ b/spring-static-resources/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,20 @@ +package com.baeldung; + +import org.baeldung.spring.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { SecSecurityConfig.class }, loader = AnnotationConfigContextLoader.class) +@WebAppConfiguration +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + + } +} diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..79b2b7fa88 --- /dev/null +++ b/spring-swagger-codegen/spring-swagger-codegen-app/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.petstore.app.PetStoreApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PetStoreApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.java b/spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..1ff1c52c68 --- /dev/null +++ b/spring-thymeleaf/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,22 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.thymeleaf.config.InitSecurity; +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import com.baeldung.thymeleaf.config.WebMVCSecurity; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-userservice/src/test/java/org/baeldung/SpringContextTest.java b/spring-userservice/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..2853a955fa --- /dev/null +++ b/spring-userservice/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package org.baeldung; + +import org.baeldung.custom.config.MvcConfig; +import org.baeldung.custom.config.PersistenceDerbyJPAConfig; +import org.baeldung.custom.config.SecSecurityConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-vault/src/test/java/org/baeldung/SpringContextTest.java b/spring-vault/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..95abe622fa --- /dev/null +++ b/spring-vault/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.springvault.SpringVaultApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringVaultApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java b/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..4ce94ec16a --- /dev/null +++ b/spring-vertx/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.vertxspring.VertxSpringApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = VertxSpringApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextTest.java b/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..88d29d5ac0 --- /dev/null +++ b/spring-webflux-amqp/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.spring.amqp.SpringWebfluxAmqpApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringWebfluxAmqpApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextTest.java b/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..2a57d7aa07 --- /dev/null +++ b/spring-zuul/spring-zuul-foos-resource/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.ResourceServerApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ResourceServerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextTest.java b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..fd35ec0841 --- /dev/null +++ b/spring-zuul/spring-zuul-ui/src/test/java/org/baeldung/SpringContextTest.java @@ -0,0 +1,16 @@ +package org.baeldung; + +import org.baeldung.config.UiApplication; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = UiApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} From ca5eb17e0024e474c1fea289144306e2b6d78f97 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 20 Jul 2019 17:53:02 +0300 Subject: [PATCH 240/352] minor fix --- testing-modules/test-containers/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/testing-modules/test-containers/pom.xml b/testing-modules/test-containers/pom.xml index 480b7c8277..bd87cb5b22 100644 --- a/testing-modules/test-containers/pom.xml +++ b/testing-modules/test-containers/pom.xml @@ -87,7 +87,7 @@ org.junit.platform junit-platform-surefire-provider - ${junit.platform.version} + ${junit-platform-surefire-provider.version} @@ -117,6 +117,7 @@ 42.2.6 3.141.59 2.22.2 + 1.3.2 From e81753727d534f8121de19a9008d1c11cebeb90d Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 21 Jul 2019 00:57:41 +0530 Subject: [PATCH 241/352] [BAEL-15959] - Moved article to spring-security-core --- spring-5-mvc/README.md | 1 - .../java/com/baeldung/Spring5Application.java | 32 ------------------- spring-5-mvc/src/main/webapp/WEB-INF/web.xml | 9 ------ spring-security-core/README.md | 1 + .../src/main/java/org/baeldung/app/App.java | 32 +++++++++++++++++++ .../org/baeldung}/filter/CustomFilter.java | 2 +- .../src/main/webapp/WEB-INF/web.xml | 17 ++++++++++ 7 files changed, 51 insertions(+), 43 deletions(-) rename {spring-5-mvc/src/main/java/com/baeldung/spring => spring-security-core/src/main/java/org/baeldung}/filter/CustomFilter.java (96%) create mode 100644 spring-security-core/src/main/webapp/WEB-INF/web.xml diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index 7e83077f54..063945281f 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -1,4 +1,3 @@ ### Relevant Articles: - [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin) - [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) -- [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) diff --git a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java index 74a348dea6..38b2d943f8 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java +++ b/spring-5-mvc/src/main/java/com/baeldung/Spring5Application.java @@ -1,12 +1,8 @@ package com.baeldung; -import javax.servlet.Filter; - import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.web.filter.DelegatingFilterProxy; -import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @SpringBootApplication( exclude = SecurityAutoConfiguration.class) public class Spring5Application { @@ -14,32 +10,4 @@ public class Spring5Application { public static void main(String[] args) { SpringApplication.run(Spring5Application.class, args); } - - public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { - - @Override - protected Class[] getRootConfigClasses() { - return null; - } - - @Override - protected Class[] getServletConfigClasses() { - // TODO Auto-generated method stub - return null; - } - - @Override - protected String[] getServletMappings() { - // TODO Auto-generated method stub - return null; - } - - @Override - protected javax.servlet.Filter[] getServletFilters() { - DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy(); - delegateFilterProxy.setTargetBeanName("loggingFilter"); - return new Filter[] { delegateFilterProxy }; - } - } - } diff --git a/spring-5-mvc/src/main/webapp/WEB-INF/web.xml b/spring-5-mvc/src/main/webapp/WEB-INF/web.xml index 43c7143e5b..ab4d38ce1c 100644 --- a/spring-5-mvc/src/main/webapp/WEB-INF/web.xml +++ b/spring-5-mvc/src/main/webapp/WEB-INF/web.xml @@ -16,14 +16,5 @@ functional / - - loggingFilter - org.springframework.web.filter.DelegatingFilterProxy - - - - loggingFilter - /* - \ No newline at end of file diff --git a/spring-security-core/README.md b/spring-security-core/README.md index b38dc061b4..bc9a8afed7 100644 --- a/spring-security-core/README.md +++ b/spring-security-core/README.md @@ -10,3 +10,4 @@ mvn clean install - [Spring Security – @PreFilter and @PostFilter](http://www.baeldung.com/spring-security-prefilter-postfilter) - [Spring Boot Authentication Auditing Support](http://www.baeldung.com/spring-boot-authentication-audit) - [Introduction to Spring Method Security](http://www.baeldung.com/spring-security-method-security) +- [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) \ No newline at end of file diff --git a/spring-security-core/src/main/java/org/baeldung/app/App.java b/spring-security-core/src/main/java/org/baeldung/app/App.java index 37d8c34c5a..db0c9135c4 100644 --- a/spring-security-core/src/main/java/org/baeldung/app/App.java +++ b/spring-security-core/src/main/java/org/baeldung/app/App.java @@ -1,11 +1,15 @@ package org.baeldung.app; +import javax.servlet.Filter; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.web.filter.DelegatingFilterProxy; +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @SpringBootApplication @EnableJpaRepositories("org.baeldung.repository") @@ -15,4 +19,32 @@ public class App extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(App.class, args); } + + public static class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected javax.servlet.Filter[] getServletFilters() { + DelegatingFilterProxy delegateFilterProxy = new DelegatingFilterProxy(); + delegateFilterProxy.setTargetBeanName("loggingFilter"); + return new Filter[] { delegateFilterProxy }; + } + + @Override + protected Class[] getRootConfigClasses() { + // TODO Auto-generated method stub + return null; + } + + @Override + protected Class[] getServletConfigClasses() { + // TODO Auto-generated method stub + return null; + } + + @Override + protected String[] getServletMappings() { + // TODO Auto-generated method stub + return null; + } + } } diff --git a/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java b/spring-security-core/src/main/java/org/baeldung/filter/CustomFilter.java similarity index 96% rename from spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java rename to spring-security-core/src/main/java/org/baeldung/filter/CustomFilter.java index 4aa33cd749..35596eae16 100644 --- a/spring-5-mvc/src/main/java/com/baeldung/spring/filter/CustomFilter.java +++ b/spring-security-core/src/main/java/org/baeldung/filter/CustomFilter.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.filter; +package org.baeldung.filter; import java.io.IOException; diff --git a/spring-security-core/src/main/webapp/WEB-INF/web.xml b/spring-security-core/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..e4954338a9 --- /dev/null +++ b/spring-security-core/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,17 @@ + + + + + loggingFilter + org.springframework.web.filter.DelegatingFilterProxy + + + + loggingFilter + /* + + + \ No newline at end of file From 7eaa85d524a1e435e8550ff333e8955b319546f4 Mon Sep 17 00:00:00 2001 From: Carlos Cano Date: Sun, 21 Jul 2019 05:20:19 +0200 Subject: [PATCH 242/352] add constructor chaining example (#7125) --- .../baeldung/constructors/BankAccount.java | 12 ++++++ .../constructors/ConstructorUnitTest.java | 38 ++++++++++++------- 2 files changed, 36 insertions(+), 14 deletions(-) diff --git a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java index 3d50e85245..b78b5937e1 100644 --- a/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java +++ b/core-java-modules/core-java-lang-oop/src/main/java/com/baeldung/constructors/BankAccount.java @@ -54,3 +54,15 @@ class BankAccountCopyConstructor extends BankAccount { this.balance = 0.0f; } } + +class BankAccountChainedConstructors extends BankAccount { + public BankAccountChainedConstructors(String name, LocalDateTime opened, double balance) { + this.name = name; + this.opened = opened; + this.balance = balance; + } + + public BankAccountChainedConstructors(String name) { + this(name, LocalDateTime.now(), 0.0f); + } +} diff --git a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java b/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java index 2cd8832fbf..66c8520e34 100644 --- a/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java +++ b/core-java-modules/core-java-lang-oop/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java @@ -1,15 +1,14 @@ package com.baeldung.constructors; -import com.baeldung.constructors.*; +import com.google.common.collect.Comparators; +import org.junit.Test; -import java.util.logging.Logger; import java.time.LocalDateTime; import java.time.Month; +import java.util.ArrayList; +import java.util.logging.Logger; -import org.junit.Test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.*; public class ConstructorUnitTest { final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName()); @@ -17,26 +16,28 @@ public class ConstructorUnitTest { @Test public void givenNoExplicitContructor_whenUsed_thenFails() { BankAccount account = new BankAccount(); - assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class); + assertThatThrownBy(() -> { + account.toString(); + }).isInstanceOf(Exception.class); } @Test public void givenNoArgumentConstructor_whenUsed_thenSucceeds() { BankAccountEmptyConstructor account = new BankAccountEmptyConstructor(); assertThatCode(() -> { - account.toString(); - }).doesNotThrowAnyException(); + account.toString(); + }).doesNotThrowAnyException(); } @Test public void givenParameterisedConstructor_whenUsed_thenSucceeds() { LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00); BankAccountParameterizedConstructor account = - new BankAccountParameterizedConstructor("Tom", opened, 1000.0f); - + new BankAccountParameterizedConstructor("Tom", opened, 1000.0f); + assertThatCode(() -> { - account.toString(); - }).doesNotThrowAnyException(); + account.toString(); + }).doesNotThrowAnyException(); } @Test @@ -47,7 +48,16 @@ public class ConstructorUnitTest { assertThat(account.getName()).isEqualTo(newAccount.getName()); assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened()); - + assertThat(newAccount.getBalance()).isEqualTo(0.0f); } + + @Test + public void givenChainedConstructor_whenUsed_thenMaintainsLogic() { + BankAccountChainedConstructors account = new BankAccountChainedConstructors("Tim"); + BankAccountChainedConstructors newAccount = new BankAccountChainedConstructors("Tim", LocalDateTime.now(), 0.0f); + + assertThat(account.getName()).isEqualTo(newAccount.getName()); + assertThat(account.getBalance()).isEqualTo(newAccount.getBalance()); + } } From a057974b11505b6552d4a6e7d77e28d462eea0ea Mon Sep 17 00:00:00 2001 From: nikunjgandhi1987 <51273165+nikunjgandhi1987@users.noreply.github.com> Date: Sat, 20 Jul 2019 23:26:37 -0400 Subject: [PATCH 243/352] Lombok related code changes (#7326) --- spring-boot-logging-log4j2/pom.xml | 6 ++++ .../LombokLoggingController.java | 28 +++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java diff --git a/spring-boot-logging-log4j2/pom.xml b/spring-boot-logging-log4j2/pom.xml index 6cc60da52c..64696969ca 100644 --- a/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-logging-log4j2/pom.xml @@ -34,6 +34,12 @@ org.springframework.boot spring-boot-starter-log4j2 + + org.projectlombok + lombok + 1.18.4 + provided + diff --git a/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java b/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java new file mode 100644 index 0000000000..5f75dbd5a1 --- /dev/null +++ b/spring-boot-logging-log4j2/src/main/java/com/baeldung/springbootlogging/LombokLoggingController.java @@ -0,0 +1,28 @@ +package com.baeldung.springbootlogging; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import lombok.extern.slf4j.Slf4j; + +//import lombok.extern.log4j.Log4j2; +//import lombok.extern.apachecommons.CommonsLog; + +@RestController("LombokLoggingController") +@Slf4j +// @CommonsLog (Comment any other Lombok logging annotation and uncomment this +// to work with Apache Commons Logging) +// @Log4j2 (Comment any other Lombok logging annotation and uncomment this to +// work directly with Log4j2) +public class LombokLoggingController { + + @GetMapping("/lombok") + public String index() { + log.trace("A TRACE Message"); + log.debug("A DEBUG Message"); + log.info("An INFO Message"); + log.warn("A WARN Message"); + log.error("An ERROR Message"); + return "Howdy! Check out the Logs to see the output..."; + } +} From abccede29148cbe7a56ed1c4bfbc41fc2684c828 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 21 Jul 2019 09:39:21 +0300 Subject: [PATCH 244/352] Update README.md --- libraries-io/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries-io/README.md b/libraries-io/README.md index f8ea2f1be8..90095a2f23 100644 --- a/libraries-io/README.md +++ b/libraries-io/README.md @@ -1,4 +1,5 @@ ### Relevant Articles: +- [Transferring a File Through SFTP in Java](https://www.baeldung.com/java-file-sftp) From f0c877bf0c999e7f980356c87697a0545a13ea45 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 21 Jul 2019 10:03:58 +0300 Subject: [PATCH 245/352] compilation fix --- .../src/test/java/org/baeldung/SpringContextTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java index 0afb3899db..5e68a8e64f 100644 --- a/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-rest-simple/src/test/java/org/baeldung/SpringContextTest.java @@ -1,11 +1,12 @@ package org.baeldung; -import org.baeldung.config.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.Application; + @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class SpringContextTest { From 9fe7b80348854fe6011bb8cffa4c323689d5520e Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 15:54:32 +0800 Subject: [PATCH 246/352] Update README.md --- spring-5-reactive-client/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spring-5-reactive-client/README.md b/spring-5-reactive-client/README.md index f94bd0b0c1..f03ed7237d 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -4,3 +4,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles + +- [Spring Security 5 for Reactive Applications](https://www.baeldung.com/spring-security-5-reactive) From e4f1ddd488a420dc16d6b9f2a844cabd67509822 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 15:56:00 +0800 Subject: [PATCH 247/352] Update README.md --- spring-groovy/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spring-groovy/README.md b/spring-groovy/README.md index ff12555376..2aab1b2e18 100644 --- a/spring-groovy/README.md +++ b/spring-groovy/README.md @@ -1 +1,3 @@ ## Relevant articles: + +- [Groovy Bean Definitions](https://www.baeldung.com/spring-groovy-beans) From 01b8b344116403d4b1c9370d32b22afca6612177 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 15:57:07 +0800 Subject: [PATCH 248/352] Delete README.md --- resteasy/bin/README.md | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 resteasy/bin/README.md diff --git a/resteasy/bin/README.md b/resteasy/bin/README.md deleted file mode 100644 index f4dba1493a..0000000000 --- a/resteasy/bin/README.md +++ /dev/null @@ -1,6 +0,0 @@ -========= - -## A Guide to RESTEasy - - -### Relevant Articles: From 1d4c353cf646b7fcb8bd86187c6f6cb8d5094f5d Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:00:24 +0800 Subject: [PATCH 249/352] Create README.md --- core-java-modules/multimodulemavenproject/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/multimodulemavenproject/README.md diff --git a/core-java-modules/multimodulemavenproject/README.md b/core-java-modules/multimodulemavenproject/README.md new file mode 100644 index 0000000000..fc4ca60b6b --- /dev/null +++ b/core-java-modules/multimodulemavenproject/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms) From 6780457b188610101a609386a4142d3539fd3b74 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:01:53 +0800 Subject: [PATCH 250/352] Create README.md --- spring-security-cors/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 spring-security-cors/README.md diff --git a/spring-security-cors/README.md b/spring-security-cors/README.md new file mode 100644 index 0000000000..2ab5e33ee3 --- /dev/null +++ b/spring-security-cors/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Fixing 401s with CORS Preflights and Spring Security](https://www.baeldung.com/spring-security-cors-preflight) From 2f04bde63ec5cb901fbe655145f2937ce34e0312 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:03:46 +0800 Subject: [PATCH 251/352] Create README.md --- testing-modules/load-testing-comparison/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 testing-modules/load-testing-comparison/README.md diff --git a/testing-modules/load-testing-comparison/README.md b/testing-modules/load-testing-comparison/README.md new file mode 100644 index 0000000000..bad22e7a49 --- /dev/null +++ b/testing-modules/load-testing-comparison/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +-[Gatling vs JMeter vs The Grinder: Comparing Load Test Tools](https://www.baeldung.com/gatling-jmeter-grinder-comparison) From f76d67c2489b4db663fce54012c3ca03bcba1714 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:04:00 +0800 Subject: [PATCH 252/352] Update README.md --- testing-modules/load-testing-comparison/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/load-testing-comparison/README.md b/testing-modules/load-testing-comparison/README.md index bad22e7a49..9823be5369 100644 --- a/testing-modules/load-testing-comparison/README.md +++ b/testing-modules/load-testing-comparison/README.md @@ -1,3 +1,3 @@ ## Relevant Articles --[Gatling vs JMeter vs The Grinder: Comparing Load Test Tools](https://www.baeldung.com/gatling-jmeter-grinder-comparison) +- [Gatling vs JMeter vs The Grinder: Comparing Load Test Tools](https://www.baeldung.com/gatling-jmeter-grinder-comparison) From f574a14badd7cd577a3775e6125a080b6871be36 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:05:12 +0800 Subject: [PATCH 253/352] Create README.md --- testing-modules/parallel-tests-junit/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 testing-modules/parallel-tests-junit/README.md diff --git a/testing-modules/parallel-tests-junit/README.md b/testing-modules/parallel-tests-junit/README.md new file mode 100644 index 0000000000..0b7834c5e7 --- /dev/null +++ b/testing-modules/parallel-tests-junit/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Running JUnit Tests in Parallel with Maven](https://www.baeldung.com/maven-junit-parallel-tests) From 8b39d2ab37aa6318992a9cff0758529c2a212a10 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:09:53 +0800 Subject: [PATCH 254/352] Create README.md --- jhipster/jhipster-uaa/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 jhipster/jhipster-uaa/README.md diff --git a/jhipster/jhipster-uaa/README.md b/jhipster/jhipster-uaa/README.md new file mode 100644 index 0000000000..3971e3c8c6 --- /dev/null +++ b/jhipster/jhipster-uaa/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service) From 196289923e97200f10974d5c0b8ab31f219207b0 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:11:32 +0800 Subject: [PATCH 255/352] Update README.md --- jhipster/jhipster-monolithic/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jhipster/jhipster-monolithic/README.md b/jhipster/jhipster-monolithic/README.md index a2c267b74d..3a44f3f120 100644 --- a/jhipster/jhipster-monolithic/README.md +++ b/jhipster/jhipster-monolithic/README.md @@ -1,5 +1,7 @@ ### Relevant articles +- [Intro to JHipster](https://www.baeldung.com/jhipster) + # baeldung This application was generated using JHipster 4.0.8, you can find documentation and help at [https://jhipster.github.io/documentation-archive/v4.0.8](https://jhipster.github.io/documentation-archive/v4.0.8). From db63ca45ca61c89fe097c98ac4f9cebd1d5a1428 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:11:46 +0800 Subject: [PATCH 256/352] Update README.md --- jhipster/jhipster-monolithic/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jhipster/jhipster-monolithic/README.md b/jhipster/jhipster-monolithic/README.md index 3a44f3f120..15c55118ee 100644 --- a/jhipster/jhipster-monolithic/README.md +++ b/jhipster/jhipster-monolithic/README.md @@ -1,4 +1,4 @@ -### Relevant articles +### Relevant Articles - [Intro to JHipster](https://www.baeldung.com/jhipster) From 51cd7667a59760cdfb5bc144d585a5f552bc63df Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:12:02 +0800 Subject: [PATCH 257/352] Update README.md --- jhipster/jhipster-monolithic/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jhipster/jhipster-monolithic/README.md b/jhipster/jhipster-monolithic/README.md index 15c55118ee..65cc51ad88 100644 --- a/jhipster/jhipster-monolithic/README.md +++ b/jhipster/jhipster-monolithic/README.md @@ -1,4 +1,4 @@ -### Relevant Articles +## Relevant Articles - [Intro to JHipster](https://www.baeldung.com/jhipster) From f9b26474ce4f84cacba083e0ed77136b26e75ea4 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:13:15 +0800 Subject: [PATCH 258/352] Create README.md --- jhipster/jhipster-microservice/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 jhipster/jhipster-microservice/README.md diff --git a/jhipster/jhipster-microservice/README.md b/jhipster/jhipster-microservice/README.md new file mode 100644 index 0000000000..7abe3204c4 --- /dev/null +++ b/jhipster/jhipster-microservice/README.md @@ -0,0 +1,3 @@ +## Relevant Articles + +- [JHipster with a Microservice Architecture](https://www.baeldung.com/jhipster-microservices) From c8ea0b65a90b5f30b4e8d78627d263150574a5e3 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:17:57 +0800 Subject: [PATCH 259/352] Update README.md --- quarkus/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/quarkus/README.md b/quarkus/README.md index 8116d16cb7..3ff08c6f9e 100644 --- a/quarkus/README.md +++ b/quarkus/README.md @@ -1,3 +1,3 @@ -## Relevant articles: +## Relevant Articles: - [Guide to QuarkusIO](https://www.baeldung.com/quarkus-io) From dc65ed87f68de3614a087b4aaa92cebd2835517c Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:20:20 +0800 Subject: [PATCH 260/352] Update README.md --- spring-groovy/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-groovy/README.md b/spring-groovy/README.md index 2aab1b2e18..36404230a9 100644 --- a/spring-groovy/README.md +++ b/spring-groovy/README.md @@ -1,3 +1,3 @@ -## Relevant articles: +## Relevant Articles: - [Groovy Bean Definitions](https://www.baeldung.com/spring-groovy-beans) From 0fa09cf5ae0ff47d566f6aee6172149311d3419f Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:22:09 +0800 Subject: [PATCH 261/352] Update README.md --- core-java-modules/core-java-exceptions/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md index 5338789a2f..79e5bad23a 100644 --- a/core-java-modules/core-java-exceptions/README.md +++ b/core-java-modules/core-java-exceptions/README.md @@ -1,3 +1,3 @@ -## Relevant articles: +## Relevant Articles: - [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) From 9bdd157a48c3565f59e1dce0e75ef83fdea499ed Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:22:48 +0800 Subject: [PATCH 262/352] Update README.md --- core-java-modules/core-java-exceptions/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md index 79e5bad23a..4fda36bb44 100644 --- a/core-java-modules/core-java-exceptions/README.md +++ b/core-java-modules/core-java-exceptions/README.md @@ -1,3 +1,3 @@ ## Relevant Articles: -- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) + From f66288d9b53e4b33f195652ee48073d6aef1339e Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:23:10 +0800 Subject: [PATCH 263/352] Update README.md --- core-java-modules/core-java-12/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-12/README.md b/core-java-modules/core-java-12/README.md index 4514fd1a2b..4fda36bb44 100644 --- a/core-java-modules/core-java-12/README.md +++ b/core-java-modules/core-java-12/README.md @@ -1,3 +1,3 @@ -## Relevant articles: +## Relevant Articles: + -- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api) From 340f9656659cea31151b439aba7267b2d5f65c14 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:24:41 +0800 Subject: [PATCH 264/352] Update README.md --- parent-java/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-java/README.md b/parent-java/README.md index ff12555376..729105e3fd 100644 --- a/parent-java/README.md +++ b/parent-java/README.md @@ -1 +1 @@ -## Relevant articles: +## Relevant Articles: From a672639976e1dc5ff815fad63f2cd227216c175a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:26:13 +0800 Subject: [PATCH 265/352] Update README.md --- video-tutorials/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/video-tutorials/README.md b/video-tutorials/README.md index ff12555376..729105e3fd 100644 --- a/video-tutorials/README.md +++ b/video-tutorials/README.md @@ -1 +1 @@ -## Relevant articles: +## Relevant Articles: From 21c12dcef58a0eb21339af283218d046825feda1 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:26:37 +0800 Subject: [PATCH 266/352] Update README.md --- parent-spring-4/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-spring-4/README.md b/parent-spring-4/README.md index ff12555376..729105e3fd 100644 --- a/parent-spring-4/README.md +++ b/parent-spring-4/README.md @@ -1 +1 @@ -## Relevant articles: +## Relevant Articles: From 474aa7a5eef9d696037443ca152512e8677931cb Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sun, 21 Jul 2019 16:26:53 +0800 Subject: [PATCH 267/352] Update README.md --- parent-spring-5/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-spring-5/README.md b/parent-spring-5/README.md index ff12555376..729105e3fd 100644 --- a/parent-spring-5/README.md +++ b/parent-spring-5/README.md @@ -1 +1 @@ -## Relevant articles: +## Relevant Articles: From ca10190f5b3174a22ff2dec43a21225c9fa85ce9 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 21 Jul 2019 11:46:51 +0300 Subject: [PATCH 268/352] Update README.md --- core-java-modules/core-java-12/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-12/README.md b/core-java-modules/core-java-12/README.md index 4fda36bb44..6c603e4dea 100644 --- a/core-java-modules/core-java-12/README.md +++ b/core-java-modules/core-java-12/README.md @@ -1,3 +1,4 @@ ## Relevant Articles: +- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api) From 006bb85ca23661a5ef718be368bc8bc7b925b0a8 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 21 Jul 2019 11:47:08 +0300 Subject: [PATCH 269/352] Update README.md --- core-java-modules/core-java-exceptions/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md index 4fda36bb44..79e5bad23a 100644 --- a/core-java-modules/core-java-exceptions/README.md +++ b/core-java-modules/core-java-exceptions/README.md @@ -1,3 +1,3 @@ ## Relevant Articles: - +- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch) From 11836c0626b6a795e790aad88666523b4c8c15dd Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 21 Jul 2019 11:47:24 +0300 Subject: [PATCH 270/352] Update README.md --- spring-5-reactive-client/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-5-reactive-client/README.md b/spring-5-reactive-client/README.md index f03ed7237d..0df2bdd339 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -5,4 +5,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles -- [Spring Security 5 for Reactive Applications](https://www.baeldung.com/spring-security-5-reactive) From 85d3960cf8612c54435f8e441f5f78f8ddb6633f Mon Sep 17 00:00:00 2001 From: Lukasz Rys Date: Sun, 21 Jul 2019 14:52:37 +0200 Subject: [PATCH 271/352] [BAEL-3079]: Embedded Redis Server Article (#7368) --- spring-boot-testing/pom.xml | 11 +++++++ .../configuration/RedisConfiguration.java | 24 ++++++++++++++ .../configuration/RedisProperties.java | 23 ++++++++++++++ .../boot/embeddedRedis/domain/User.java | 25 +++++++++++++++ .../domain/repository/UserRepository.java | 10 ++++++ .../src/main/resources/application.properties | 3 ++ .../embeddedRedis/TestRedisConfiguration.java | 28 +++++++++++++++++ .../UserRepositoryIntegrationTest.java | 31 +++++++++++++++++++ .../src/test/resources/application.properties | 3 ++ 9 files changed, 158 insertions(+) create mode 100644 spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java create mode 100644 spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java create mode 100644 spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java create mode 100644 spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java create mode 100644 spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java create mode 100644 spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java diff --git a/spring-boot-testing/pom.xml b/spring-boot-testing/pom.xml index 84107070bd..12fb14b366 100644 --- a/spring-boot-testing/pom.xml +++ b/spring-boot-testing/pom.xml @@ -15,6 +15,10 @@ + + org.springframework.boot + spring-boot-starter-data-redis + org.springframework.boot spring-boot-starter-web @@ -33,6 +37,13 @@ test + + + it.ozimov + embedded-redis + 0.7.2 + test + org.spockframework diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java new file mode 100644 index 0000000000..6b5b20892f --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java @@ -0,0 +1,24 @@ +package com.baeldung.boot.embeddedRedis.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; + +@Configuration +@EnableRedisRepositories +public class RedisConfiguration { + + @Bean + public LettuceConnectionFactory redisConnectionFactory(final RedisProperties redisProperties) { + return new LettuceConnectionFactory(redisProperties.getRedisHost(), redisProperties.getRedisPort()); + } + + @Bean + public RedisTemplate redisTemplate(final LettuceConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(connectionFactory); + return template; + } +} diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java new file mode 100644 index 0000000000..76f2e1bbfe --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java @@ -0,0 +1,23 @@ +package com.baeldung.boot.embeddedRedis.configuration; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class RedisProperties { + private final int redisPort; + private final String redisHost; + + public RedisProperties(@Value("${spring.redis.port}") final int redisPort, @Value("${spring.redis.host}") final String redisHost) { + this.redisPort = redisPort; + this.redisHost = redisHost; + } + + public int getRedisPort() { + return redisPort; + } + + public String getRedisHost() { + return redisHost; + } +} diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java new file mode 100644 index 0000000000..41657aaa66 --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java @@ -0,0 +1,25 @@ +package com.baeldung.boot.embeddedRedis.domain; + +import org.springframework.data.annotation.Id; +import org.springframework.data.redis.core.RedisHash; + +import java.util.UUID; + +@RedisHash("user") +public class User { + @Id private UUID id; + private String name; + + public User(UUID id, String name) { + this.id = id; + this.name = name; + } + + public UUID getId() { + return id; + } + + public String getName() { + return name; + } +} diff --git a/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java new file mode 100644 index 0000000000..0558bb8482 --- /dev/null +++ b/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.boot.embeddedRedis.domain.repository; + +import com.baeldung.boot.embeddedRedis.domain.User; +import org.springframework.data.repository.CrudRepository; + +import java.util.UUID; + +public interface UserRepository extends CrudRepository { + +} diff --git a/spring-boot-testing/src/main/resources/application.properties b/spring-boot-testing/src/main/resources/application.properties index e378aacdd5..8dc7f6e3c3 100644 --- a/spring-boot-testing/src/main/resources/application.properties +++ b/spring-boot-testing/src/main/resources/application.properties @@ -1,3 +1,6 @@ +# embedded redis +spring.redis.host= localhost +spring.redis.port= 6379 # security spring.security.user.name=john diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java b/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java new file mode 100644 index 0000000000..b4748bcd38 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java @@ -0,0 +1,28 @@ +package com.baeldung.boot.embeddedRedis; + +import com.baeldung.boot.embeddedRedis.configuration.RedisProperties; +import org.springframework.boot.test.context.TestConfiguration; +import redis.embedded.RedisServer; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +@TestConfiguration +public class TestRedisConfiguration { + + private final RedisServer redisServer; + + public TestRedisConfiguration(final RedisProperties redisProperties) { + this.redisServer = new RedisServer(redisProperties.getRedisPort()); + } + + @PostConstruct + public void postConstruct() { + redisServer.start(); + } + + @PreDestroy + public void preDestroy() { + redisServer.stop(); + } +} diff --git a/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java b/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9577ccf0e8 --- /dev/null +++ b/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.boot.embeddedRedis.domain.repository; + +import com.baeldung.boot.embeddedRedis.TestRedisConfiguration; +import com.baeldung.boot.embeddedRedis.domain.User; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.UUID; + +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestRedisConfiguration.class) +public class UserRepositoryIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Test + public void shouldSaveUser_toRedis() { + final UUID id = UUID.randomUUID(); + final User user = new User(id, "name"); + + final User saved = userRepository.save(user); + + assertNotNull(saved); + } +} \ No newline at end of file diff --git a/spring-boot-testing/src/test/resources/application.properties b/spring-boot-testing/src/test/resources/application.properties index 9a8b496a8b..0c5b0e13e6 100644 --- a/spring-boot-testing/src/test/resources/application.properties +++ b/spring-boot-testing/src/test/resources/application.properties @@ -1,3 +1,6 @@ +#embedded redis +spring.redis.host= localhost +spring.redis.port= 6370 # security spring.security.user.name=john spring.security.user.password=123 \ No newline at end of file From 968710433aebdead914b595f4194b7aa2e8e3c82 Mon Sep 17 00:00:00 2001 From: Denis Date: Sun, 21 Jul 2019 18:56:35 +0200 Subject: [PATCH 272/352] BAEL-3084 remove xmlunit-2 ref from 'integration-lite-second' profile (#7372) --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index b888994a43..21a42f89d6 100644 --- a/pom.xml +++ b/pom.xml @@ -1456,7 +1456,6 @@ wicket xml - xmlunit-2 xstream From f5142320bf4809d6dabe6c03fc3108286fd7228e Mon Sep 17 00:00:00 2001 From: priyank-sriv Date: Mon, 22 Jul 2019 00:54:49 +0530 Subject: [PATCH 273/352] first commit - basic test --- patterns/backoff-jitter/pom.xml | 61 ++++++++++++++ .../backoff/jitter/BackoffWithJitterTest.java | 81 +++++++++++++++++++ patterns/pom.xml | 3 +- 3 files changed, 144 insertions(+), 1 deletion(-) create mode 100644 patterns/backoff-jitter/pom.xml create mode 100644 patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java diff --git a/patterns/backoff-jitter/pom.xml b/patterns/backoff-jitter/pom.xml new file mode 100644 index 0000000000..0a48a18abb --- /dev/null +++ b/patterns/backoff-jitter/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + com.baeldung + backoff-jitter + 1.0.0-SNAPSHOT + pom + + + + + + + + + + + junit + junit + ${junit.version} + test + + + org.mockito + mockito-core + ${mockito-core.version} + test + + + io.github.resilience4j + resilience4j-retry + ${resilience4j.version} + test + + + org.slf4j + slf4j-api + ${slf4j.version} + test + + + org.slf4j + slf4j-simple + ${slf4j.version} + test + + + + + UTF-8 + 1.8 + 1.8 + 4.12 + 2.27.0 + 1.7.26 + 0.16.0 + + + \ No newline at end of file diff --git a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java new file mode 100644 index 0000000000..aef9f7fab7 --- /dev/null +++ b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java @@ -0,0 +1,81 @@ +package com.baeldung.backoff.jitter; + +import io.github.resilience4j.retry.IntervalFunction; +import io.github.resilience4j.retry.Retry; +import io.github.resilience4j.retry.RetryConfig; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.function.Function; + +import static com.baeldung.backoff.jitter.BackoffWithJitterTest.RetryProperties.*; +import static io.github.resilience4j.retry.IntervalFunction.ofExponentialBackoff; +import static io.github.resilience4j.retry.IntervalFunction.ofExponentialRandomBackoff; +import static java.util.Collections.nCopies; +import static java.util.concurrent.Executors.newFixedThreadPool; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +public class BackoffWithJitterTest { + + static Logger log = LoggerFactory.getLogger(BackoffWithJitterTest.class); + + interface PingPongService { + + String call(String ping) throws PingPongServiceException; + } + + class PingPongServiceException extends RuntimeException { + + public PingPongServiceException(String reason) { + super(reason); + } + } + + private PingPongService service; + private static final int NUM_TASKS = 8; + + @Before + public void setUp() { + service = mock(PingPongService.class); + } + + @Test + public void whenRetryExponentialBackoff_thenRetriedConfiguredNoOfTimes() { + IntervalFunction intervalFn = ofExponentialBackoff(INITIAL_INTERVAL, MULTIPLIER); + Function pingPongFn = getRetryablePingPongFn(intervalFn); + + when(service.call(anyString())).thenThrow(PingPongServiceException.class); + try { + pingPongFn.apply("Hello"); + } catch (PingPongServiceException e) { + verify(service, times(MAX_TRIES)).call(anyString()); + } + } + + private Function getRetryablePingPongFn(IntervalFunction intervalFn) { + RetryConfig retryConfig = RetryConfig.custom() + .maxAttempts(MAX_TRIES) + .intervalFunction(intervalFn) + .retryExceptions(PingPongServiceException.class) + .build(); + Retry retry = Retry.of("pingpong", retryConfig); + return Retry.decorateFunction(retry, ping -> { + log.info("Invoked at {}", LocalDateTime.now()); + return service.call(ping); + }); + } + + static class RetryProperties { + static final Long INITIAL_INTERVAL = 1000L; + static final Double MULTIPLIER = 2.0D; + static final Double RANDOMIZATION_FACTOR = 0.6D; + static final Integer MAX_TRIES = 4; + } +} diff --git a/patterns/pom.xml b/patterns/pom.xml index 2be9d2519e..7f7368ca07 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -19,7 +19,8 @@ design-patterns design-patterns-2 solid - dip + dip + backoff-jitter From 412e8b7634df712ad966d4ddce22f3ecc76d488b Mon Sep 17 00:00:00 2001 From: priyank-sriv Date: Mon, 22 Jul 2019 00:55:25 +0530 Subject: [PATCH 274/352] simple exponential backoff --- .../backoff/jitter/BackoffWithJitterTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java index aef9f7fab7..966207f430 100644 --- a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java +++ b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java @@ -59,6 +59,22 @@ public class BackoffWithJitterTest { } } + @Test + public void whenRetryExponentialBackoffWithoutJitter_thenThunderingHerdProblemOccurs() throws InterruptedException { + IntervalFunction intervalFn = ofExponentialBackoff(INITIAL_INTERVAL, MULTIPLIER); + test(intervalFn); + } + + private void test(IntervalFunction intervalFn) throws InterruptedException { + Function pingPongFn = getRetryablePingPongFn(intervalFn); + ExecutorService executors = newFixedThreadPool(NUM_TASKS); + List> tasks = nCopies(NUM_TASKS, () -> pingPongFn.apply("Hello")); + + when(service.call(anyString())).thenThrow(PingPongServiceException.class); + + executors.invokeAll(tasks); + } + private Function getRetryablePingPongFn(IntervalFunction intervalFn) { RetryConfig retryConfig = RetryConfig.custom() .maxAttempts(MAX_TRIES) From ae1807fca2a9170abd547f6caf22017974aa3ac7 Mon Sep 17 00:00:00 2001 From: priyank-sriv Date: Mon, 22 Jul 2019 00:55:41 +0530 Subject: [PATCH 275/352] backoff with jitter --- .../com/baeldung/backoff/jitter/BackoffWithJitterTest.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java index 966207f430..0f0e652596 100644 --- a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java +++ b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java @@ -65,6 +65,12 @@ public class BackoffWithJitterTest { test(intervalFn); } + @Test + public void whenRetryExponentialBackoffWithJitter_thenRetriesAreSpread() throws InterruptedException { + IntervalFunction intervalFn = ofExponentialRandomBackoff(INITIAL_INTERVAL, MULTIPLIER, RANDOMIZATION_FACTOR); + test(intervalFn); + } + private void test(IntervalFunction intervalFn) throws InterruptedException { Function pingPongFn = getRetryablePingPongFn(intervalFn); ExecutorService executors = newFixedThreadPool(NUM_TASKS); From 8b2b894bbd37b10e504a1131bd4d40f09c5cbdf9 Mon Sep 17 00:00:00 2001 From: Paul Latzelsperger <43503240+beardyinc@users.noreply.github.com> Date: Mon, 22 Jul 2019 08:18:49 +0200 Subject: [PATCH 276/352] added example code for BAEL-3082 (#7374) --- .../failure_vs_error/SimpleCalculator.java | 15 +++++++++ .../SimpleCalculatorUnitTest.java | 32 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 testing-modules/junit-5-advanced/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java create mode 100644 testing-modules/junit-5-advanced/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java diff --git a/testing-modules/junit-5-advanced/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java b/testing-modules/junit-5-advanced/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java new file mode 100644 index 0000000000..d018aa939f --- /dev/null +++ b/testing-modules/junit-5-advanced/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java @@ -0,0 +1,15 @@ +package com.baeldung.failure_vs_error; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +public class SimpleCalculator { + + public static double divideNumbers(double dividend, double divisor) { + if (divisor == 0) { + throw new ArithmeticException("Division by zero!"); + } + return dividend / divisor; + } +} diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java new file mode 100644 index 0000000000..9b1777258c --- /dev/null +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.failure_vs_error; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +class SimpleCalculatorUnitTest { + + @Test + void divideNumbers() { + double result = SimpleCalculator.divideNumbers(6, 3); + assertEquals(2, result); + } + + @Test + @Disabled("test is expected to fail, disabled so that CI build still goes through") + void divideNumbers_failure() { + double result = SimpleCalculator.divideNumbers(6, 3); + assertEquals(15, result); + } + + @Test + @Disabled("test is expected to raise an error, disabled so that CI build still goes through") + void divideNumbers_error() { + SimpleCalculator.divideNumbers(10, 0); + } +} From da152e53a1794e7d6f51a665c8cf827d1293717f Mon Sep 17 00:00:00 2001 From: dionisPrifti Date: Mon, 22 Jul 2019 19:53:15 +0200 Subject: [PATCH 277/352] Bael 2997 spring boot configuration processor (#7376) * BAEL-2997: Adding spring boot configuration processor dependency. * BAEL-2997: Added examples for spring boot configuration processor, simple and nested properties. * BAEL-2997: Fixed the identation * BAEL-2997: Formatted the added dependencies * BAEL-2997: Added version for configuration-processor dependency. --- spring-boot-autoconfiguration/pom.xml | 15 +++- .../AnnotationProcessorApplication.java | 15 ++++ .../DatabaseProperties.java | 73 +++++++++++++++++++ .../DatabasePropertiesIntegrationTest.java | 31 ++++++++ .../databaseproperties-test.properties | 7 ++ 5 files changed, 139 insertions(+), 2 deletions(-) create mode 100644 spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/AnnotationProcessorApplication.java create mode 100644 spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/DatabaseProperties.java create mode 100644 spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/annotationprocessor/DatabasePropertiesIntegrationTest.java create mode 100644 spring-boot-autoconfiguration/src/test/resources/databaseproperties-test.properties diff --git a/spring-boot-autoconfiguration/pom.xml b/spring-boot-autoconfiguration/pom.xml index 91692ebfff..5b3b0eb86c 100644 --- a/spring-boot-autoconfiguration/pom.xml +++ b/spring-boot-autoconfiguration/pom.xml @@ -38,6 +38,19 @@ mysql mysql-connector-java + + + org.springframework.boot + spring-boot-configuration-processor + 2.1.6.RELEASE + true + + + + org.hsqldb + hsqldb + runtime + @@ -50,12 +63,10 @@ - org.apache.maven.plugins maven-war-plugin - diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/AnnotationProcessorApplication.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/AnnotationProcessorApplication.java new file mode 100644 index 0000000000..91ea94e43e --- /dev/null +++ b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/AnnotationProcessorApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.autoconfiguration.annotationprocessor; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.annotation.ComponentScan; + +import com.baeldung.autoconfiguration.MySQLAutoconfiguration; + +@EnableAutoConfiguration(exclude = { MySQLAutoconfiguration.class}) +@ComponentScan(basePackageClasses = {DatabaseProperties.class}) +public class AnnotationProcessorApplication { + public static void main(String[] args) { + new SpringApplicationBuilder(AnnotationProcessorApplication.class).run(); + } +} diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/DatabaseProperties.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/DatabaseProperties.java new file mode 100644 index 0000000000..4fb5b408a2 --- /dev/null +++ b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/annotationprocessor/DatabaseProperties.java @@ -0,0 +1,73 @@ +package com.baeldung.autoconfiguration.annotationprocessor; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "database") +public class DatabaseProperties { + + public static class Server { + + /** + * The IP of the database server + */ + private String ip; + + /** + * The Port of the database server. + * The Default value is 443. + * The allowed values are in the range 400-4000. + */ + @Min(400) + @Max(800) + private int port = 443; + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + } + + private String username; + private String password; + private Server server; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Server getServer() { + return server; + } + + public void setServer(Server server) { + this.server = server; + } +} \ No newline at end of file diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/annotationprocessor/DatabasePropertiesIntegrationTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/annotationprocessor/DatabasePropertiesIntegrationTest.java new file mode 100644 index 0000000000..350e65b465 --- /dev/null +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/annotationprocessor/DatabasePropertiesIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.autoconfiguration.annotationprocessor; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AnnotationProcessorApplication.class) +@TestPropertySource("classpath:databaseproperties-test.properties") +public class DatabasePropertiesIntegrationTest { + + @Autowired + private DatabaseProperties databaseProperties; + + @Test + public void whenSimplePropertyQueriedThenReturnsPropertyValue() throws Exception { + Assert.assertEquals("Incorrectly bound Username property", "baeldung", databaseProperties.getUsername()); + Assert.assertEquals("Incorrectly bound Password property", "password", databaseProperties.getPassword()); + } + + @Test + public void whenNestedPropertyQueriedThenReturnsPropertyValue() throws Exception { + Assert.assertEquals("Incorrectly bound Server IP nested property", "127.0.0.1", databaseProperties.getServer().getIp()); + Assert.assertEquals("Incorrectly bound Server Port nested property", 3306, databaseProperties.getServer().getPort()); + } + +} diff --git a/spring-boot-autoconfiguration/src/test/resources/databaseproperties-test.properties b/spring-boot-autoconfiguration/src/test/resources/databaseproperties-test.properties new file mode 100644 index 0000000000..c0d1d1f158 --- /dev/null +++ b/spring-boot-autoconfiguration/src/test/resources/databaseproperties-test.properties @@ -0,0 +1,7 @@ +#Simple Properties +database.username=baeldung +database.password=password + +#Nested Properties +database.server.ip=127.0.0.1 +database.server.port=3306 \ No newline at end of file From cb686cf9c4f1587d729e66668ec9387631b4a1f9 Mon Sep 17 00:00:00 2001 From: priyank-sriv Date: Tue, 23 Jul 2019 01:52:22 +0530 Subject: [PATCH 278/352] minor modifications --- patterns/backoff-jitter/README.md | 2 ++ patterns/backoff-jitter/pom.xml | 7 ------- .../backoff/jitter/BackoffWithJitterTest.java | 12 ++++++------ 3 files changed, 8 insertions(+), 13 deletions(-) create mode 100644 patterns/backoff-jitter/README.md diff --git a/patterns/backoff-jitter/README.md b/patterns/backoff-jitter/README.md new file mode 100644 index 0000000000..6459e4c8e0 --- /dev/null +++ b/patterns/backoff-jitter/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Better Retries with Exponential Backoff and Jitter](https://baeldung.com/retries-with-exponential-backoff-and-jitter) diff --git a/patterns/backoff-jitter/pom.xml b/patterns/backoff-jitter/pom.xml index 0a48a18abb..6b0d016609 100644 --- a/patterns/backoff-jitter/pom.xml +++ b/patterns/backoff-jitter/pom.xml @@ -8,13 +8,6 @@ 1.0.0-SNAPSHOT pom - - - - - - - junit diff --git a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java index 0f0e652596..f6b3ebbe45 100644 --- a/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java +++ b/patterns/backoff-jitter/src/test/java/com/baeldung/backoff/jitter/BackoffWithJitterTest.java @@ -39,7 +39,7 @@ public class BackoffWithJitterTest { } private PingPongService service; - private static final int NUM_TASKS = 8; + private static final int NUM_CONCURRENT_CLIENTS = 8; @Before public void setUp() { @@ -55,7 +55,7 @@ public class BackoffWithJitterTest { try { pingPongFn.apply("Hello"); } catch (PingPongServiceException e) { - verify(service, times(MAX_TRIES)).call(anyString()); + verify(service, times(MAX_RETRIES)).call(anyString()); } } @@ -73,8 +73,8 @@ public class BackoffWithJitterTest { private void test(IntervalFunction intervalFn) throws InterruptedException { Function pingPongFn = getRetryablePingPongFn(intervalFn); - ExecutorService executors = newFixedThreadPool(NUM_TASKS); - List> tasks = nCopies(NUM_TASKS, () -> pingPongFn.apply("Hello")); + ExecutorService executors = newFixedThreadPool(NUM_CONCURRENT_CLIENTS); + List> tasks = nCopies(NUM_CONCURRENT_CLIENTS, () -> pingPongFn.apply("Hello")); when(service.call(anyString())).thenThrow(PingPongServiceException.class); @@ -83,7 +83,7 @@ public class BackoffWithJitterTest { private Function getRetryablePingPongFn(IntervalFunction intervalFn) { RetryConfig retryConfig = RetryConfig.custom() - .maxAttempts(MAX_TRIES) + .maxAttempts(MAX_RETRIES) .intervalFunction(intervalFn) .retryExceptions(PingPongServiceException.class) .build(); @@ -98,6 +98,6 @@ public class BackoffWithJitterTest { static final Long INITIAL_INTERVAL = 1000L; static final Double MULTIPLIER = 2.0D; static final Double RANDOMIZATION_FACTOR = 0.6D; - static final Integer MAX_TRIES = 4; + static final Integer MAX_RETRIES = 4; } } From 4bf6b77067b91fa8a53be84b0a2973e4a61165e6 Mon Sep 17 00:00:00 2001 From: Juan Moreno Date: Tue, 23 Jul 2019 00:16:48 -0300 Subject: [PATCH 279/352] Sample code for BAEL-2539 (#7238) * UPDATE Added junit5 & assertJ configuration in order to run tests * FEAT Added JaxpTransformer basic implementation * UPDATE Added JAXP polish version * UPDATE Polish jaxp implementation * FEAT Added complete JAXP Sample * FIX typo * Added additional samples and JMH benchmark * FIX indent in Joox sample --- xml/pom.xml | 100 +++++++++++++++--- .../xml/attribute/Dom4jTransformer.java | 45 ++++++++ .../xml/attribute/JaxpTransformer.java | 63 +++++++++++ .../xml/attribute/JooxTransformer.java | 38 +++++++ .../xml/attribute/jmh/AttributeBenchMark.java | 72 +++++++++++++ xml/src/main/resources/xml/attribute.xml | 5 + .../main/resources/xml/attribute_expected.xml | 5 + .../xml/attribute/Dom4jProcessorUnitTest.java | 55 ++++++++++ .../xml/attribute/JaxpProcessorUnitTest.java | 34 ++++++ .../xml/attribute/JooxProcessorUnitTest.java | 54 ++++++++++ xml/src/test/resources/xml/attribute.xml | 5 + .../test/resources/xml/attribute_expected.xml | 5 + 12 files changed, 469 insertions(+), 12 deletions(-) create mode 100644 xml/src/main/java/com/baeldung/xml/attribute/Dom4jTransformer.java create mode 100644 xml/src/main/java/com/baeldung/xml/attribute/JaxpTransformer.java create mode 100644 xml/src/main/java/com/baeldung/xml/attribute/JooxTransformer.java create mode 100644 xml/src/main/java/com/baeldung/xml/attribute/jmh/AttributeBenchMark.java create mode 100644 xml/src/main/resources/xml/attribute.xml create mode 100644 xml/src/main/resources/xml/attribute_expected.xml create mode 100644 xml/src/test/java/com/baeldung/xml/attribute/Dom4jProcessorUnitTest.java create mode 100644 xml/src/test/java/com/baeldung/xml/attribute/JaxpProcessorUnitTest.java create mode 100644 xml/src/test/java/com/baeldung/xml/attribute/JooxProcessorUnitTest.java create mode 100644 xml/src/test/resources/xml/attribute.xml create mode 100644 xml/src/test/resources/xml/attribute_expected.xml diff --git a/xml/pom.xml b/xml/pom.xml index 123875b1d9..540b1fc03b 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -1,4 +1,5 @@ - 4.0.0 xml @@ -14,7 +15,7 @@ - dom4j + org.dom4j dom4j ${dom4j.version} @@ -23,18 +24,31 @@ jaxen ${jaxen.version} - + + org.jooq + joox-java-6 + ${joox.version} + org.jdom jdom2 ${jdom2.version} - - javax.xml + javax.xml.bind jaxb-api ${jaxb-api.version} + + com.sun.xml.bind + jaxb-impl + ${jaxb-impl.version} + + + com.sun.xml.bind + jaxb-core + ${jaxb-core.version} + javax.xml jaxp-api @@ -45,7 +59,17 @@ stax-api ${stax-api.version} - + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + commons-io @@ -76,6 +100,31 @@ commons-lang ${commons-lang.version} + + + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} + test + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + org.xmlunit + xmlunit-assertj + ${xmlunit-assertj.version} + test + @@ -86,6 +135,16 @@ true + + + maven-compiler-plugin + ${maven-compiler-plugin.version} + + + maven-surefire-plugin + ${maven-surefire-plugin.version} + + @@ -213,7 +272,8 @@ - + maven-assembly-plugin ${project.basedir} @@ -232,8 +292,10 @@ - make-assembly - package + make-assembly + package attached @@ -246,17 +308,31 @@ - 1.6.1 - 1.1.6 + 2.1.1 + 1.2.0 2.0.6 + 1.6.2 + 2.5 4.1 1.2.4.5 - 2.1 + 2.3.1 1.4.2 + 2.3.0.1 + 2.3.2 1.0-2 + 3.12.2 + 2.6.3 + 5.5.0 + 1.21 + + 3.5 + 2.4 + 1.8 1.3.1 + 3.8.0 + 2.22.2 diff --git a/xml/src/main/java/com/baeldung/xml/attribute/Dom4jTransformer.java b/xml/src/main/java/com/baeldung/xml/attribute/Dom4jTransformer.java new file mode 100644 index 0000000000..a1922ad224 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/attribute/Dom4jTransformer.java @@ -0,0 +1,45 @@ +package com.baeldung.xml.attribute; + +import org.dom4j.*; +import org.dom4j.io.DocumentSource; +import org.dom4j.io.SAXReader; + +import javax.xml.XMLConstants; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import java.io.StringWriter; +import java.io.Writer; +import java.util.List; + +public class Dom4jTransformer { + private final Document input; + + public Dom4jTransformer(String resourcePath) throws DocumentException { + // 1- Build the doc from the XML file + SAXReader xmlReader = new SAXReader(); + this.input = xmlReader.read(resourcePath); + } + + public String modifyAttribute(String attribute, String oldValue, String newValue) throws TransformerException { + // 2- Locate the node(s) with xpath, we can use index and iterator too. + String expr = String.format("//*[contains(@%s, '%s')]", attribute, oldValue); + XPath xpath = DocumentHelper.createXPath(expr); + List nodes = xpath.selectNodes(input); + // 3- Make the change on the selected nodes + for (int i = 0; i < nodes.size(); i++) { + Element element = (Element) nodes.get(i); + element.addAttribute(attribute, newValue); + } + // 4- Save the result to a new XML doc + TransformerFactory factory = TransformerFactory.newInstance(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + Transformer xformer = factory.newTransformer(); + xformer.setOutputProperty(OutputKeys.INDENT, "yes"); + Writer output = new StringWriter(); + xformer.transform(new DocumentSource(input), new StreamResult(output)); + return output.toString(); + } +} diff --git a/xml/src/main/java/com/baeldung/xml/attribute/JaxpTransformer.java b/xml/src/main/java/com/baeldung/xml/attribute/JaxpTransformer.java new file mode 100644 index 0000000000..a2266a2b44 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/attribute/JaxpTransformer.java @@ -0,0 +1,63 @@ +package com.baeldung.xml.attribute; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +public class JaxpTransformer { + + private Document input; + + public JaxpTransformer(String resourcePath) throws SAXException, IOException, ParserConfigurationException { + // 1- Build the doc from the XML file + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + input = factory.newDocumentBuilder() + .parse(resourcePath); + } + + public String modifyAttribute(String attribute, String oldValue, String newValue) throws XPathExpressionException, TransformerFactoryConfigurationError, TransformerException { + // 2- Locate the node(s) with xpath + XPath xpath = XPathFactory.newInstance() + .newXPath(); + NodeList nodes = (NodeList) xpath.evaluate(String.format("//*[contains(@%s, '%s')]", attribute, oldValue), input, XPathConstants.NODESET); + // 3- Make the change on the selected nodes + for (int i = 0; i < nodes.getLength(); i++) { + Element value = (Element) nodes.item(i); + value.setAttribute(attribute, newValue); + } + //Stream api syntax + // IntStream + // .range(0, nodes.getLength()) + // .mapToObj(i -> (Element) nodes.item(i)) + // .forEach(value -> value.setAttribute(attribute, newValue)); + // 4- Save the result to a new XML doc + TransformerFactory factory = TransformerFactory.newInstance(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + Transformer xformer = factory.newTransformer(); + xformer.setOutputProperty(OutputKeys.INDENT, "yes"); + Writer output = new StringWriter(); + xformer.transform(new DOMSource(input), new StreamResult(output)); + return output.toString(); + } +} diff --git a/xml/src/main/java/com/baeldung/xml/attribute/JooxTransformer.java b/xml/src/main/java/com/baeldung/xml/attribute/JooxTransformer.java new file mode 100644 index 0000000000..d36d60ec59 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/attribute/JooxTransformer.java @@ -0,0 +1,38 @@ +package com.baeldung.xml.attribute; + +import org.joox.JOOX; +import org.joox.Match; +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.transform.TransformerFactoryConfigurationError; +import java.io.IOException; + +import static org.joox.JOOX.$; + +public class JooxTransformer { + + private final Document input; + + public JooxTransformer(String resourcePath) throws SAXException, IOException { + // 1- Build the doc from the XML file + DocumentBuilder builder = JOOX.builder(); + input = builder.parse(resourcePath); + } + + public String modifyAttribute(String attribute, String oldValue, String newValue) throws TransformerFactoryConfigurationError { + // 2- Select the document + Match $ = $(input); + // 3 - Find node to modify + String expr = String.format("//*[contains(@%s, '%s')]", attribute, oldValue); + $ + // .find("to") or with xpath + .xpath(expr) + .get() + .stream() + .forEach(e -> e.setAttribute(attribute, newValue)); + // 4- Return result as String + return $.toString(); + } +} diff --git a/xml/src/main/java/com/baeldung/xml/attribute/jmh/AttributeBenchMark.java b/xml/src/main/java/com/baeldung/xml/attribute/jmh/AttributeBenchMark.java new file mode 100644 index 0000000000..064e181713 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/attribute/jmh/AttributeBenchMark.java @@ -0,0 +1,72 @@ +package com.baeldung.xml.attribute.jmh; + +import org.dom4j.DocumentException; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; +import org.xml.sax.SAXException; + +import com.baeldung.xml.attribute.Dom4jTransformer; +import com.baeldung.xml.attribute.JaxpTransformer; +import com.baeldung.xml.attribute.JooxTransformer; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.xpath.XPathExpressionException; +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@State(Scope.Benchmark) +public class AttributeBenchMark { + + public static void main(String[] args) throws RunnerException { + Options opt = new OptionsBuilder() + .include(AttributeBenchMark.class.getSimpleName()) + .forks(1) + .build(); + new Runner(opt).run(); + } + + @Benchmark + public String dom4jBenchmark() throws DocumentException, TransformerException { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + Dom4jTransformer transformer = new Dom4jTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + + return transformer.modifyAttribute(attribute, oldValue, newValue); + } + + @Benchmark + public String jooxBenchmark() throws IOException, SAXException { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + JooxTransformer transformer = new JooxTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + + return transformer.modifyAttribute(attribute, oldValue, newValue); + } + + @Benchmark + public String jaxpBenchmark() throws TransformerException, ParserConfigurationException, SAXException, IOException, XPathExpressionException { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + JaxpTransformer transformer = new JaxpTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + + return transformer.modifyAttribute(attribute, oldValue, newValue); + } +} diff --git a/xml/src/main/resources/xml/attribute.xml b/xml/src/main/resources/xml/attribute.xml new file mode 100644 index 0000000000..c8fa3f1071 --- /dev/null +++ b/xml/src/main/resources/xml/attribute.xml @@ -0,0 +1,5 @@ + + + john@email.com + mary@email.com + \ No newline at end of file diff --git a/xml/src/main/resources/xml/attribute_expected.xml b/xml/src/main/resources/xml/attribute_expected.xml new file mode 100644 index 0000000000..1d5d7b0cea --- /dev/null +++ b/xml/src/main/resources/xml/attribute_expected.xml @@ -0,0 +1,5 @@ + + + john@email.com + mary@email.com + \ No newline at end of file diff --git a/xml/src/test/java/com/baeldung/xml/attribute/Dom4jProcessorUnitTest.java b/xml/src/test/java/com/baeldung/xml/attribute/Dom4jProcessorUnitTest.java new file mode 100644 index 0000000000..485744f9a5 --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/attribute/Dom4jProcessorUnitTest.java @@ -0,0 +1,55 @@ +package com.baeldung.xml.attribute; + +import org.dom4j.DocumentException; +import org.junit.jupiter.api.Test; + +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactoryConfigurationError; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import static org.xmlunit.assertj.XmlAssert.assertThat; + +/** + * Unit test for {@link Dom4jTransformer}. + */ +public class Dom4jProcessorUnitTest { + + @Test + public void givenXmlWithAttributes_whenModifyAttribute_thenGetXmlUpdated() throws TransformerFactoryConfigurationError, TransformerException, DocumentException { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + Dom4jTransformer transformer = new Dom4jTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + + String result = transformer.modifyAttribute(attribute, oldValue, newValue); + + assertThat(result).hasXPath("//*[contains(@customer, 'false')]"); + } + + @Test + public void givenTwoXml_whenModifyAttribute_thenGetSimilarXml() throws IOException, TransformerFactoryConfigurationError, TransformerException, URISyntaxException, DocumentException { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + Dom4jTransformer transformer = new Dom4jTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + String expectedXml = new String(Files.readAllBytes((Paths.get(getClass() + .getResource("/xml/attribute_expected.xml") + .toURI())))); + + String result = transformer.modifyAttribute(attribute, oldValue, newValue); + + assertThat(result) + .and(expectedXml) + .areSimilar(); + } + +} diff --git a/xml/src/test/java/com/baeldung/xml/attribute/JaxpProcessorUnitTest.java b/xml/src/test/java/com/baeldung/xml/attribute/JaxpProcessorUnitTest.java new file mode 100644 index 0000000000..8394016dbd --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/attribute/JaxpProcessorUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.xml.attribute; + +import static org.xmlunit.assertj.XmlAssert.assertThat; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.xpath.XPathExpressionException; + +import org.junit.jupiter.api.Test; +import org.xml.sax.SAXException; + +/** + * Unit test for {@link JaxpTransformer}. + */ +public class JaxpProcessorUnitTest { + + @Test + public void givenXmlWithAttributes_whenModifyAttribute_thenGetXmlUpdated() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException { + String path = getClass().getResource("/xml/attribute.xml") + .toString(); + JaxpTransformer transformer = new JaxpTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + + String result = transformer.modifyAttribute(attribute, oldValue, newValue); + + assertThat(result).hasXPath("//*[contains(@customer, 'false')]"); + } + +} diff --git a/xml/src/test/java/com/baeldung/xml/attribute/JooxProcessorUnitTest.java b/xml/src/test/java/com/baeldung/xml/attribute/JooxProcessorUnitTest.java new file mode 100644 index 0000000000..38c7c59789 --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/attribute/JooxProcessorUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.xml.attribute; + +import org.junit.jupiter.api.Test; +import org.xml.sax.SAXException; + +import javax.xml.transform.TransformerFactoryConfigurationError; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import static org.xmlunit.assertj.XmlAssert.assertThat; + +/** + * Unit test for {@link JooxTransformer}. + */ +public class JooxProcessorUnitTest { + + @Test + public void givenXmlWithAttributes_whenModifyAttribute_thenGetXmlUpdated() throws IOException, SAXException, TransformerFactoryConfigurationError { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + JooxTransformer transformer = new JooxTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + + String result = transformer.modifyAttribute(attribute, oldValue, newValue); + + assertThat(result).hasXPath("//*[contains(@customer, 'false')]"); + } + + @Test + public void givenTwoXml_whenModifyAttribute_thenGetSimilarXml() throws IOException, TransformerFactoryConfigurationError, URISyntaxException, SAXException { + String path = getClass() + .getResource("/xml/attribute.xml") + .toString(); + JooxTransformer transformer = new JooxTransformer(path); + String attribute = "customer"; + String oldValue = "true"; + String newValue = "false"; + String expectedXml = new String(Files.readAllBytes((Paths.get(getClass() + .getResource("/xml/attribute_expected.xml") + .toURI())))); + + String result = transformer.modifyAttribute(attribute, oldValue, newValue); + + assertThat(result) + .and(expectedXml) + .areSimilar(); + } + +} diff --git a/xml/src/test/resources/xml/attribute.xml b/xml/src/test/resources/xml/attribute.xml new file mode 100644 index 0000000000..c8fa3f1071 --- /dev/null +++ b/xml/src/test/resources/xml/attribute.xml @@ -0,0 +1,5 @@ + + + john@email.com + mary@email.com + \ No newline at end of file diff --git a/xml/src/test/resources/xml/attribute_expected.xml b/xml/src/test/resources/xml/attribute_expected.xml new file mode 100644 index 0000000000..1d5d7b0cea --- /dev/null +++ b/xml/src/test/resources/xml/attribute_expected.xml @@ -0,0 +1,5 @@ + + + john@email.com + mary@email.com + \ No newline at end of file From dd0003a478ab37c80e1e5ea7f706fe9a92e5338f Mon Sep 17 00:00:00 2001 From: cdjole Date: Tue, 23 Jul 2019 07:36:04 +0200 Subject: [PATCH 280/352] Shell sort (#7391) * Shell sort * Add new line at the end --- .../algorithms/shellsort/ShellSort.java | 20 +++++++++++++++++++ .../shellsort/ShellSortUnitTest.java | 17 ++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 algorithms-sorting/src/main/java/com/baeldung/algorithms/shellsort/ShellSort.java create mode 100644 algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/shellsort/ShellSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/shellsort/ShellSort.java new file mode 100644 index 0000000000..c130e2d866 --- /dev/null +++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/shellsort/ShellSort.java @@ -0,0 +1,20 @@ +package com.baeldung.algorithms.shellsort; + +public class ShellSort { + + public static void sort(int arrayToSort[]) { + int n = arrayToSort.length; + + for (int gap = n / 2; gap > 0; gap /= 2) { + for (int i = gap; i < n; i++) { + int key = arrayToSort[i]; + int j = i; + while (j >= gap && arrayToSort[j - gap] > key) { + arrayToSort[j] = arrayToSort[j - gap]; + j -= gap; + } + arrayToSort[j] = key; + } + } + } +} diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java new file mode 100644 index 0000000000..91a27c41d0 --- /dev/null +++ b/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.algorithms.shellsort; + +import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; + +import org.junit.Test; + +public class ShellSortUnitTest { + + @Test + public void givenUnsortedArray_whenShellSort_thenSortedAsc() { + int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8}; + ShellSort.sort(input); + int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82}; + assertArrayEquals("the two arrays are not equal", expected, input); + } +} From b6de1db857aec5368fe74cae9396fa0cb452bb77 Mon Sep 17 00:00:00 2001 From: eelhazati Date: Tue, 23 Jul 2019 09:09:56 +0100 Subject: [PATCH 281/352] add refresh token feature. --- .../server/api/TokenEndpoint.java | 4 +- .../handler/AbstractGrantTypeHandler.java | 87 +++++++++++++++++++ .../AuthorizationCodeGrantTypeHandler.java | 53 +---------- .../handler/RefreshTokenGrantTypeHandler.java | 64 ++++++++++++++ .../oauth2/client/AbstractServlet.java | 23 +++++ .../oauth2/client/CallbackServlet.java | 3 + .../oauth2/client/RefreshTokenServlet.java | 52 +++++++++++ .../oauth2-client/src/main/webapp/index.jsp | 16 +++- 8 files changed, 250 insertions(+), 52 deletions(-) create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java create mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java create mode 100644 oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java create mode 100644 oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java index f39bb2ea2d..df4011ddc1 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java @@ -15,15 +15,15 @@ import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; +import java.util.Arrays; import java.util.Base64; -import java.util.Collections; import java.util.List; import java.util.Objects; @Path("token") public class TokenEndpoint { - List supportedGrantTypes = Collections.singletonList("authorization_code"); + List supportedGrantTypes = Arrays.asList("authorization_code", "refresh_token"); @Inject private AppDataRepository appDataRepository; diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java new file mode 100644 index 0000000000..324bacb33f --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AbstractGrantTypeHandler.java @@ -0,0 +1,87 @@ +package com.baeldung.oauth2.authorization.server.handler; + +import com.baeldung.oauth2.authorization.server.PEMKeyUtils; +import com.nimbusds.jose.*; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jose.crypto.RSASSAVerifier; +import com.nimbusds.jose.jwk.JWK; +import com.nimbusds.jose.jwk.RSAKey; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Date; +import java.util.UUID; + +public abstract class AbstractGrantTypeHandler implements AuthorizationGrantTypeHandler { + + //Always RSA 256, but could be parametrized + protected JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); + + @Inject + protected Config config; + + //30 min + protected Long expiresInMin = 30L; + + protected JWSVerifier getJWSVerifier() throws Exception { + String verificationkey = config.getValue("verificationkey", String.class); + String pemEncodedRSAPublicKey = PEMKeyUtils.readKeyAsString(verificationkey); + RSAKey rsaPublicKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPublicKey); + return new RSASSAVerifier(rsaPublicKey); + } + + protected JWSSigner getJwsSigner() throws Exception { + String signingkey = config.getValue("signingkey", String.class); + String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey); + RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey); + return new RSASSASigner(rsaKey.toRSAPrivateKey()); + } + + protected String getAccessToken(String clientId, String subject, String approvedScope) throws Exception { + //4. Signing + JWSSigner jwsSigner = getJwsSigner(); + + Instant now = Instant.now(); + //Long expiresInMin = 30L; + Date expirationTime = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES)); + + //3. JWT Payload or claims + JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder() + .issuer("http://localhost:9080") + .subject(subject) + .claim("upn", subject) + .claim("client_id", clientId) + .audience("http://localhost:9280") + .claim("scope", approvedScope) + .claim("groups", Arrays.asList(approvedScope.split(" "))) + .expirationTime(expirationTime) // expires in 30 minutes + .notBeforeTime(Date.from(now)) + .issueTime(Date.from(now)) + .jwtID(UUID.randomUUID().toString()) + .build(); + SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims); + signedJWT.sign(jwsSigner); + return signedJWT.serialize(); + } + + protected String getRefreshToken(String clientId, String subject, String approvedScope) throws Exception { + JWSSigner jwsSigner = getJwsSigner(); + Instant now = Instant.now(); + //6.Build refresh token + JWTClaimsSet refreshTokenClaims = new JWTClaimsSet.Builder() + .subject(subject) + .claim("client_id", clientId) + .claim("scope", approvedScope) + //refresh token for 1 day. + .expirationTime(Date.from(now.plus(1, ChronoUnit.DAYS))) + .build(); + SignedJWT signedRefreshToken = new SignedJWT(jwsHeader, refreshTokenClaims); + signedRefreshToken.sign(jwsSigner); + return signedRefreshToken.serialize(); + } +} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java index 889c7fcea2..78128aead6 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/AuthorizationCodeGrantTypeHandler.java @@ -1,18 +1,7 @@ package com.baeldung.oauth2.authorization.server.handler; -import com.baeldung.oauth2.authorization.server.PEMKeyUtils; import com.baeldung.oauth2.authorization.server.model.AuthorizationCode; -import com.nimbusds.jose.JOSEObjectType; -import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jose.JWSHeader; -import com.nimbusds.jose.crypto.RSASSASigner; -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.jwk.RSAKey; -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.jwt.SignedJWT; -import org.eclipse.microprofile.config.Config; -import javax.inject.Inject; import javax.inject.Named; import javax.json.Json; import javax.json.JsonObject; @@ -20,22 +9,14 @@ import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; -import java.time.Instant; import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.util.Arrays; -import java.util.Date; -import java.util.UUID; @Named("authorization_code") -public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantTypeHandler { +public class AuthorizationCodeGrantTypeHandler extends AbstractGrantTypeHandler { @PersistenceContext private EntityManager entityManager; - @Inject - private Config config; - @Override public JsonObject createAccessToken(String clientId, MultivaluedMap params) throws Exception { //1. code is required @@ -58,42 +39,16 @@ public class AuthorizationCodeGrantTypeHandler implements AuthorizationGrantType throw new WebApplicationException("invalid_grant"); } - //JWT Header - JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build(); - - Instant now = Instant.now(); - Long expiresInMin = 30L; - Date expiresIn = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES)); - //3. JWT Payload or claims - JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder() - .issuer("http://localhost:9080") - .subject(authorizationCode.getUserId()) - .claim("upn", authorizationCode.getUserId()) - .audience("http://localhost:9280") - .claim("scope", authorizationCode.getApprovedScopes()) - .claim("groups", Arrays.asList(authorizationCode.getApprovedScopes().split(" "))) - .expirationTime(expiresIn) // expires in 30 minutes - .notBeforeTime(Date.from(now)) - .issueTime(Date.from(now)) - .jwtID(UUID.randomUUID().toString()) - .build(); - SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims); - - //4. Signing - String signingkey = config.getValue("signingkey", String.class); - String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey); - RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey); - signedJWT.sign(new RSASSASigner(rsaKey.toRSAPrivateKey())); - - //5. Finally the JWT access token - String accessToken = signedJWT.serialize(); + String accessToken = getAccessToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes()); + String refreshToken = getRefreshToken(clientId, authorizationCode.getUserId(), authorizationCode.getApprovedScopes()); return Json.createObjectBuilder() .add("token_type", "Bearer") .add("access_token", accessToken) .add("expires_in", expiresInMin * 60) .add("scope", authorizationCode.getApprovedScopes()) + .add("refresh_token", refreshToken) .build(); } } diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java new file mode 100644 index 0000000000..27c0ed4427 --- /dev/null +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java @@ -0,0 +1,64 @@ +package com.baeldung.oauth2.authorization.server.handler; + +import com.nimbusds.jose.JWSVerifier; +import com.nimbusds.jwt.SignedJWT; + +import javax.inject.Named; +import javax.json.Json; +import javax.json.JsonObject; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MultivaluedMap; +import java.util.*; + +@Named("refresh_token") +public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler { + + @Override + public JsonObject createAccessToken(String clientId, MultivaluedMap params) throws Exception { + String refreshToken = params.getFirst("refresh_token"); + if (refreshToken == null || "".equals(refreshToken)) { + throw new WebApplicationException("invalid_grant"); + } + + //Decode refresh token + SignedJWT signedRefreshToken = SignedJWT.parse(refreshToken); + JWSVerifier verifier = getJWSVerifier(); + + if (!signedRefreshToken.verify(verifier)) { + throw new WebApplicationException("Invalid refresh token."); + } + if (!(new Date().before(signedRefreshToken.getJWTClaimsSet().getExpirationTime()))) { + throw new WebApplicationException("Refresh token expired."); + } + String refreshTokenClientId = signedRefreshToken.getJWTClaimsSet().getStringClaim("client_id"); + if (!clientId.equals(refreshTokenClientId)) { + throw new WebApplicationException("Invalid client_id."); + } + + //At this point, the refresh token is valid and not yet expired + //So create a new access token from it. + String subject = signedRefreshToken.getJWTClaimsSet().getSubject(); + String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope"); + + String finalScope = approvedScopes; + String requestedScopes = params.getFirst("scope"); + if (requestedScopes != null && !requestedScopes.isEmpty()) { + Set allowedScopes = new LinkedHashSet<>(); + Set rScopes = new HashSet(Arrays.asList(requestedScopes.split(" "))); + Set aScopes = new HashSet(Arrays.asList(approvedScopes.split(" "))); + for (String scope : rScopes) { + if (aScopes.contains(scope)) allowedScopes.add(scope); + } + finalScope = String.join(" ", allowedScopes); + } + + String accessToken = getAccessToken(clientId, subject, finalScope); + return Json.createObjectBuilder() + .add("token_type", "Bearer") + .add("access_token", accessToken) + .add("expires_in", expiresInMin * 60) + .add("scope", finalScope) + .add("refresh_token", refreshToken) + .build(); + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java new file mode 100644 index 0000000000..7059c4f7e1 --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java @@ -0,0 +1,23 @@ +package com.baeldung.oauth2.client; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Base64; + +public abstract class AbstractServlet extends HttpServlet { + + protected void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + RequestDispatcher requestDispatcher = request.getRequestDispatcher(location); + requestDispatcher.forward(request, response); + } + + protected String getAuthorizationHeaderValue(String clientId, String clientSecret) { + String token = clientId + ":" + clientSecret; + String encodedString = Base64.getEncoder().encodeToString(token.getBytes()); + return "Basic " + encodedString; + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java index 87aa8bc668..a172d20235 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java @@ -29,6 +29,9 @@ public class CallbackServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String clientId = config.getValue("client.clientId", String.class); + String clientSecret = config.getValue("client.clientSecret", String.class); + //Error: String error = request.getParameter("error"); if (error != null) { diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java new file mode 100644 index 0000000000..2cfadc700f --- /dev/null +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java @@ -0,0 +1,52 @@ +package com.baeldung.oauth2.client; + +import org.eclipse.microprofile.config.Config; + +import javax.inject.Inject; +import javax.json.JsonObject; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import java.io.IOException; + +@WebServlet(urlPatterns = "/refreshtoken") +public class RefreshTokenServlet extends AbstractServlet { + + @Inject + private Config config; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + String clientId = config.getValue("client.clientId", String.class); + String clientSecret = config.getValue("client.clientSecret", String.class); + + JsonObject actualTokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse"); + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(config.getValue("provider.tokenUri", String.class)); + + Form form = new Form(); + form.param("grant_type", "refresh_token"); + form.param("refresh_token", actualTokenResponse.getString("refresh_token")); + + String scope = request.getParameter("scope"); + if (scope != null && !scope.isEmpty()) { + form.param("scope", scope); + } + + JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) + .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) + .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); + + request.getSession().setAttribute("tokenResponse", tokenResponse); + dispatch("/", request, response); + } +} diff --git a/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp index 23fec70f33..ccb74df228 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp +++ b/oauth2-framework-impl/oauth2-client/src/main/webapp/index.jsp @@ -10,6 +10,7 @@ body { margin: 0px; } + input[type=text], input[type=password] { width: 75%; padding: 4px 0px; @@ -17,6 +18,7 @@ border: 1px solid #502bcc; box-sizing: border-box; } + .container-error { padding: 16px; border: 1px solid #cc102a; @@ -25,6 +27,7 @@ margin-left: 25px; margin-bottom: 25px; } + .container { padding: 16px; border: 1px solid #130ecc; @@ -81,8 +84,20 @@
  • access_token: ${tokenResponse.getString("access_token")}
  • scope: ${tokenResponse.getString("scope")}
  • Expires in (s): ${tokenResponse.getInt("expires_in")}
  • +
  • refresh_token: ${tokenResponse.getString("refresh_token")}
  • + + +

    OAuth2 Resource Server Call


    @@ -90,7 +105,6 @@
  • Read Protected Resource
  • Write Protected Resource
  • -
    From 7486f1a305855f3c27c3dacae97365a9dc3efc8b Mon Sep 17 00:00:00 2001 From: eelhazati Date: Tue, 23 Jul 2019 09:24:25 +0100 Subject: [PATCH 282/352] scope in refresh token request should be a subset of those authorized by the resource owner. --- .../handler/RefreshTokenGrantTypeHandler.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java index 27c0ed4427..513bcc2cf0 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java @@ -8,7 +8,10 @@ import javax.json.Json; import javax.json.JsonObject; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; -import java.util.*; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; @Named("refresh_token") public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler { @@ -40,24 +43,23 @@ public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler { String subject = signedRefreshToken.getJWTClaimsSet().getSubject(); String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope"); - String finalScope = approvedScopes; String requestedScopes = params.getFirst("scope"); if (requestedScopes != null && !requestedScopes.isEmpty()) { - Set allowedScopes = new LinkedHashSet<>(); Set rScopes = new HashSet(Arrays.asList(requestedScopes.split(" "))); Set aScopes = new HashSet(Arrays.asList(approvedScopes.split(" "))); - for (String scope : rScopes) { - if (aScopes.contains(scope)) allowedScopes.add(scope); + if (!aScopes.containsAll(rScopes)) { + throw new WebApplicationException("Requested scopes should be a subset of those authorized by the resource owner."); } - finalScope = String.join(" ", allowedScopes); + } else { + requestedScopes = approvedScopes; } - String accessToken = getAccessToken(clientId, subject, finalScope); + String accessToken = getAccessToken(clientId, subject, requestedScopes); return Json.createObjectBuilder() .add("token_type", "Bearer") .add("access_token", accessToken) .add("expires_in", expiresInMin * 60) - .add("scope", finalScope) + .add("scope", requestedScopes) .add("refresh_token", refreshToken) .build(); } From e314cddbe66eb1c063369f1b460792b19682547d Mon Sep 17 00:00:00 2001 From: eelhazati Date: Tue, 23 Jul 2019 10:03:17 +0100 Subject: [PATCH 283/352] scope in refresh token request should be a subset of those authorized by the resource owner. --- .../oauth2/client/CallbackServlet.java | 32 ++++++------------- .../oauth2/client/RefreshTokenServlet.java | 7 +++- 2 files changed, 16 insertions(+), 23 deletions(-) diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java index a172d20235..e72877076c 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java @@ -4,10 +4,8 @@ import org.eclipse.microprofile.config.Config; import javax.inject.Inject; import javax.json.JsonObject; -import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.client.Client; @@ -18,10 +16,9 @@ import javax.ws.rs.core.Form; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import java.io.IOException; -import java.util.Base64; @WebServlet(urlPatterns = "/callback") -public class CallbackServlet extends HttpServlet { +public class CallbackServlet extends AbstractServlet { @Inject private Config config; @@ -56,24 +53,15 @@ public class CallbackServlet extends HttpServlet { form.param("code", code); form.param("redirect_uri", config.getValue("client.redirectUri", String.class)); - JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) - .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue()) - .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); - - request.getSession().setAttribute("tokenResponse", tokenResponse); + try { + JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) + .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) + .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); + request.getSession().setAttribute("tokenResponse", tokenResponse); + } catch (Exception ex) { + System.out.println(ex.getMessage()); + request.setAttribute("error", ex.getMessage()); + } dispatch("/", request, response); } - - private void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - RequestDispatcher requestDispatcher = request.getRequestDispatcher(location); - requestDispatcher.forward(request, response); - } - - private String getAuthorizationHeaderValue() { - String clientId = config.getValue("client.clientId", String.class); - String clientSecret = config.getValue("client.clientSecret", String.class); - String token = clientId + ":" + clientSecret; - String encodedString = Base64.getEncoder().encodeToString(token.getBytes()); - return "Basic " + encodedString; - } } diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java index 2cfadc700f..b9fd7a4a21 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java @@ -46,7 +46,12 @@ public class RefreshTokenServlet extends AbstractServlet { .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); - request.getSession().setAttribute("tokenResponse", tokenResponse); + String error = tokenResponse.getString("error"); + if (error != null) { + request.setAttribute("error", error); + } else { + request.getSession().setAttribute("tokenResponse", tokenResponse); + } dispatch("/", request, response); } } From 5903f4b60f3b7d0b1a2f46774051c6d0377bfaaf Mon Sep 17 00:00:00 2001 From: Carlos Cano Date: Tue, 23 Jul 2019 13:48:24 +0200 Subject: [PATCH 284/352] [BAEL-3041] Spring boot mysql timezone (#7154) * testing with user CRUD * update project * rename location * delete maven files --- .../spring-boot-mysql/.gitignore | 5 ++ persistence-modules/spring-boot-mysql/pom.xml | 59 +++++++++++++++++++ .../java/com/baeldung/boot/Application.java | 20 +++++++ .../java/com/baeldung/boot/Controller.java | 27 +++++++++ .../src/main/java/com/baeldung/boot/User.java | 40 +++++++++++++ .../com/baeldung/boot/UserRepository.java | 10 ++++ .../src/main/resources/application.yml | 14 +++++ 7 files changed, 175 insertions(+) create mode 100644 persistence-modules/spring-boot-mysql/.gitignore create mode 100644 persistence-modules/spring-boot-mysql/pom.xml create mode 100644 persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Application.java create mode 100644 persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Controller.java create mode 100644 persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/User.java create mode 100644 persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/UserRepository.java create mode 100644 persistence-modules/spring-boot-mysql/src/main/resources/application.yml diff --git a/persistence-modules/spring-boot-mysql/.gitignore b/persistence-modules/spring-boot-mysql/.gitignore new file mode 100644 index 0000000000..96136ab255 --- /dev/null +++ b/persistence-modules/spring-boot-mysql/.gitignore @@ -0,0 +1,5 @@ +/target/ +.settings/ +.classpath +.project +.mvn/ \ No newline at end of file diff --git a/persistence-modules/spring-boot-mysql/pom.xml b/persistence-modules/spring-boot-mysql/pom.xml new file mode 100644 index 0000000000..6be58332aa --- /dev/null +++ b/persistence-modules/spring-boot-mysql/pom.xml @@ -0,0 +1,59 @@ + + + 4.0.0 + spring-boot-mysql + 0.1.0 + spring-boot-mysql + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + 2.1.5.RELEASE + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-test + + + org.springframework.boot + spring-boot-devtools + true + + + mysql + mysql-connector-java + + + + + spring-boot-mysql-timezone + + + src/main/resources + true + + + + + + + + + UTF-8 + 8.0.12 + + + diff --git a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Application.java b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Application.java new file mode 100644 index 0000000000..d69f66fc7a --- /dev/null +++ b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Application.java @@ -0,0 +1,20 @@ +package com.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import javax.annotation.PostConstruct; +import java.util.TimeZone; + +@SpringBootApplication +public class Application { + + @PostConstruct + void started() { + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Controller.java b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Controller.java new file mode 100644 index 0000000000..48864269fe --- /dev/null +++ b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Controller.java @@ -0,0 +1,27 @@ +package com.baeldung.boot; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +public class Controller { + + @Autowired + UserRepository userRepository; + + @GetMapping + public User get() { + User user = new User(); + userRepository.save(user); + return user; + } + + @GetMapping("/find") + public List find() { + List users = userRepository.findAll(); + return users; + } +} diff --git a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/User.java b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/User.java new file mode 100644 index 0000000000..55cb97dec2 --- /dev/null +++ b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/User.java @@ -0,0 +1,40 @@ +package com.baeldung.boot; + + +import org.springframework.data.annotation.CreatedDate; + +import javax.persistence.*; +import java.util.Date; + +@Entity +public class User { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Integer id; + + @Column + private String name; + + @CreatedDate + private Date createdDate = new Date(); + + public Date getCreatedDate() { + return createdDate; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/UserRepository.java b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/UserRepository.java new file mode 100644 index 0000000000..3c50c30cce --- /dev/null +++ b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/UserRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.boot; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.io.Serializable; + +@Repository +public interface UserRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-boot-mysql/src/main/resources/application.yml b/persistence-modules/spring-boot-mysql/src/main/resources/application.yml new file mode 100644 index 0000000000..5404555d49 --- /dev/null +++ b/persistence-modules/spring-boot-mysql/src/main/resources/application.yml @@ -0,0 +1,14 @@ +spring: + datasource: + url: jdbc:mysql://localhost:3306/test?useLegacyDatetimeCode=false + username: root + password: + + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + jdbc: + time_zone: UTC \ No newline at end of file From b6b90f556af9099e0e0db47a151fa5f0ca4dcb4c Mon Sep 17 00:00:00 2001 From: "EZZEDDINE.ELHAZATI" Date: Tue, 23 Jul 2019 13:26:23 +0100 Subject: [PATCH 285/352] refactoring. --- .../server/api/TokenEndpoint.java | 42 +++++++++++-------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java index df4011ddc1..4716c1bb26 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java @@ -18,7 +18,6 @@ import javax.ws.rs.core.Response; import java.util.Arrays; import java.util.Base64; import java.util.List; -import java.util.Objects; @Path("token") public class TokenEndpoint { @@ -39,28 +38,26 @@ public class TokenEndpoint { //Check grant_type params String grantType = params.getFirst("grant_type"); - Objects.requireNonNull(grantType, "grant_type params is required"); - if (!supportedGrantTypes.contains(grantType)) { - JsonObject error = Json.createObjectBuilder() - .add("error", "unsupported_grant_type") - .add("error_description", "grant type should be one of :" + supportedGrantTypes) - .build(); - return Response.status(Response.Status.BAD_REQUEST) - .entity(error).build(); + if (grantType == null || grantType.isEmpty()) + return responseError("Invalid_request", "grant_type is required", Response.Status.BAD_REQUEST); + if (!supportedGrantTypes.contains(grantType)) { + return responseError("unsupported_grant_type", "grant_type should be one of :" + supportedGrantTypes, Response.Status.BAD_REQUEST); } //Client Authentication String[] clientCredentials = extract(authHeader); + if (clientCredentials.length != 2) { + return responseError("Invalid_request", "Bad Credentials client_id/client_secret", Response.Status.BAD_REQUEST); + } String clientId = clientCredentials[0]; - String clientSecret = clientCredentials[1]; Client client = appDataRepository.getClient(clientId); - if (client == null || clientSecret == null || !clientSecret.equals(client.getClientSecret())) { - JsonObject error = Json.createObjectBuilder() - .add("error", "invalid_client") - .build(); - return Response.status(Response.Status.UNAUTHORIZED) - .entity(error).build(); + if (client == null) { + return responseError("Invalid_request", "Invalid client_id", Response.Status.BAD_REQUEST); + } + String clientSecret = clientCredentials[1]; + if (!clientSecret.equals(client.getClientSecret())) { + return responseError("Invalid_request", "Invalid client_secret", Response.Status.UNAUTHORIZED); } AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get(); @@ -68,7 +65,7 @@ public class TokenEndpoint { try { tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params); } catch (Exception e) { - e.printStackTrace(); + return responseError("Invalid_request", "Can't get token", Response.Status.INTERNAL_SERVER_ERROR); } return Response.ok(tokenResponse) @@ -81,6 +78,15 @@ public class TokenEndpoint { if (authHeader != null && authHeader.startsWith("Basic ")) { return new String(Base64.getDecoder().decode(authHeader.substring(6))).split(":"); } - return null; + return new String[]{}; + } + + private Response responseError(String error, String errorDescription, Response.Status status) { + JsonObject errorResponse = Json.createObjectBuilder() + .add("error", error) + .add("error_description", errorDescription) + .build(); + return Response.status(status) + .entity(errorResponse).build(); } } From 4c6182d45f4edabf0b54e7c88e108db6b634ba28 Mon Sep 17 00:00:00 2001 From: "EZZEDDINE.ELHAZATI" Date: Tue, 23 Jul 2019 16:04:35 +0100 Subject: [PATCH 286/352] refactoring. --- .../authorization/server/api/TokenEndpoint.java | 2 ++ .../handler/RefreshTokenGrantTypeHandler.java | 8 +++++++- .../oauth2/client/RefreshTokenServlet.java | 14 ++++++-------- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java index 4716c1bb26..0ea12da16e 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/api/TokenEndpoint.java @@ -64,6 +64,8 @@ public class TokenEndpoint { JsonObject tokenResponse = null; try { tokenResponse = authorizationGrantTypeHandler.createAccessToken(clientId, params); + } catch (WebApplicationException e) { + return e.getResponse(); } catch (Exception e) { return responseError("Invalid_request", "Can't get token", Response.Status.INTERNAL_SERVER_ERROR); } diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java index 513bcc2cf0..63e3552353 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java +++ b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/handler/RefreshTokenGrantTypeHandler.java @@ -8,6 +8,7 @@ import javax.json.Json; import javax.json.JsonObject; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; import java.util.Arrays; import java.util.Date; import java.util.HashSet; @@ -48,7 +49,12 @@ public class RefreshTokenGrantTypeHandler extends AbstractGrantTypeHandler { Set rScopes = new HashSet(Arrays.asList(requestedScopes.split(" "))); Set aScopes = new HashSet(Arrays.asList(approvedScopes.split(" "))); if (!aScopes.containsAll(rScopes)) { - throw new WebApplicationException("Requested scopes should be a subset of those authorized by the resource owner."); + JsonObject error = Json.createObjectBuilder() + .add("error", "Invalid_request") + .add("error_description", "Requested scopes should be a subset of the original scopes.") + .build(); + Response response = Response.status(Response.Status.BAD_REQUEST).entity(error).build(); + throw new WebApplicationException(response); } } else { requestedScopes = approvedScopes; diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java index b9fd7a4a21..766a4e3f1f 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java @@ -15,6 +15,7 @@ import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import java.io.IOException; @WebServlet(urlPatterns = "/refreshtoken") @@ -42,16 +43,13 @@ public class RefreshTokenServlet extends AbstractServlet { form.param("scope", scope); } - JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE) + Response jaxrsResponse = target.request(MediaType.APPLICATION_JSON_TYPE) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) - .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class); + .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class); + JsonObject tokenResponse = jaxrsResponse.readEntity(JsonObject.class); + System.out.println(tokenResponse); - String error = tokenResponse.getString("error"); - if (error != null) { - request.setAttribute("error", error); - } else { - request.getSession().setAttribute("tokenResponse", tokenResponse); - } + request.getSession().setAttribute("tokenResponse", tokenResponse); dispatch("/", request, response); } } From 4998ed9be4dcaaa58ee729f3b1f79b73fd8fda89 Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Tue, 23 Jul 2019 10:59:02 -0400 Subject: [PATCH 287/352] BAEL-3153: Added test cases for String toLowerCase and toUpperCase The toLowerCase and toUpperCase methods are simple enough that no new classes are needed under the main/ directory. The included tests exercise the changing of case for an English string using the default locale, a foreign string using the default locale, and a foreign string using a provided locale. --- java-strings-2/README.MD | 14 ++++----- .../changecase/ToLowerCaseUnitTest.java | 29 +++++++++++++++++++ .../changecase/ToUpperCaseUnitTest.java | 29 +++++++++++++++++++ 3 files changed, 65 insertions(+), 7 deletions(-) create mode 100644 java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java create mode 100644 java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java diff --git a/java-strings-2/README.MD b/java-strings-2/README.MD index c6d4f0222a..4db93f64e0 100644 --- a/java-strings-2/README.MD +++ b/java-strings-2/README.MD @@ -1,7 +1,7 @@ -## Relevant Articles - -- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) -- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) -- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) -- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) -- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) +## Relevant Articles + +- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) +- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) +- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) +- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) +- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java new file mode 100644 index 0000000000..14102be993 --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.string.changecase; + +import static org.junit.Assert.assertEquals; + +import java.util.Locale; + +import org.junit.Test; + +public class ToLowerCaseUnitTest { + + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignUppercase = "\u0049"; + + @Test + public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() { + assertEquals("john doe", name.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() { + assertEquals("\u0069", foreignUppercase.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() { + assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH)); + } +} diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java new file mode 100644 index 0000000000..90b80714a7 --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.string.changecase; + +import static org.junit.Assert.assertEquals; + +import java.util.Locale; + +import org.junit.Test; + +public class ToUpperCaseUnitTest { + + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignUppercase = "\u0069"; + + @Test + public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { + assertEquals("JOHN DOE", name.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { + assertEquals("\u0049", foreignUppercase.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { + assertEquals("\u0130", foreignUppercase.toUpperCase(TURKISH)); + } +} From ce9e9561993eaf36255cb516aea372cf363fac6b Mon Sep 17 00:00:00 2001 From: "EZZEDDINE.ELHAZATI" Date: Tue, 23 Jul 2019 16:13:48 +0100 Subject: [PATCH 288/352] refactoring. --- .../com/baeldung/oauth2/client/RefreshTokenServlet.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java index 766a4e3f1f..a519a53070 100644 --- a/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java +++ b/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/RefreshTokenServlet.java @@ -47,9 +47,11 @@ public class RefreshTokenServlet extends AbstractServlet { .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class); JsonObject tokenResponse = jaxrsResponse.readEntity(JsonObject.class); - System.out.println(tokenResponse); - - request.getSession().setAttribute("tokenResponse", tokenResponse); + if (jaxrsResponse.getStatus() == 200) { + request.getSession().setAttribute("tokenResponse", tokenResponse); + } else { + request.setAttribute("error", tokenResponse.getString("error_description", "error!")); + } dispatch("/", request, response); } } From 7000dfe094d88cff47166f12584995de2c915eba Mon Sep 17 00:00:00 2001 From: rahul Date: Tue, 23 Jul 2019 21:49:03 +0530 Subject: [PATCH 289/352] Checking if a URL Exists in Java --- .../core-java-networking-2/.gitignore | 25 ++++++++++++ .../core-java-networking-2/README.md | 7 ++++ .../core-java-networking-2/pom.xml | 22 +++++++++++ .../java/com/baeldung/url/UrlChecker.java | 25 ++++++++++++ .../com/baeldung/url/UrlCheckerUnitTest.java | 39 +++++++++++++++++++ 5 files changed, 118 insertions(+) create mode 100644 core-java-modules/core-java-networking-2/.gitignore create mode 100644 core-java-modules/core-java-networking-2/README.md create mode 100644 core-java-modules/core-java-networking-2/pom.xml create mode 100644 core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/UrlChecker.java create mode 100644 core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/UrlCheckerUnitTest.java diff --git a/core-java-modules/core-java-networking-2/.gitignore b/core-java-modules/core-java-networking-2/.gitignore new file mode 100644 index 0000000000..374c8bf907 --- /dev/null +++ b/core-java-modules/core-java-networking-2/.gitignore @@ -0,0 +1,25 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-modules/core-java-networking-2/README.md b/core-java-modules/core-java-networking-2/README.md new file mode 100644 index 0000000000..15cccf4a60 --- /dev/null +++ b/core-java-modules/core-java-networking-2/README.md @@ -0,0 +1,7 @@ +========= + +## Core Java Networking - 2 + +### Relevant Articles + +- [Checking if a URL Exists in Java](https://www.baeldung.com/checking-if-a-url-exists-with-java) diff --git a/core-java-modules/core-java-networking-2/pom.xml b/core-java-modules/core-java-networking-2/pom.xml new file mode 100644 index 0000000000..88e038d4c9 --- /dev/null +++ b/core-java-modules/core-java-networking-2/pom.xml @@ -0,0 +1,22 @@ + + 4.0.0 + core-java-networking-2 + 0.1.0-SNAPSHOT + core-java-networking-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + + + core-java-networking-2 + + diff --git a/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/UrlChecker.java b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/UrlChecker.java new file mode 100644 index 0000000000..b99e74f8bf --- /dev/null +++ b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/UrlChecker.java @@ -0,0 +1,25 @@ +package com.baeldung.url; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +public class UrlChecker { + + public int getResponseCodeForURL(String address) throws IOException { + return getResponseCodeForURLUsing(address, "GET"); + } + + public int getResponseCodeForURLUsingHead(String address) throws IOException { + return getResponseCodeForURLUsing(address, "HEAD"); + } + + private int getResponseCodeForURLUsing(String address, String method) throws IOException { + HttpURLConnection.setFollowRedirects(false); // Set follow redirects to false + final URL url = new URL(address); + HttpURLConnection huc = (HttpURLConnection) url.openConnection(); + huc.setRequestMethod(method); + return huc.getResponseCode(); + } + +} diff --git a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/UrlCheckerUnitTest.java b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/UrlCheckerUnitTest.java new file mode 100644 index 0000000000..5e295e65a0 --- /dev/null +++ b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/UrlCheckerUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.url; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; + +import org.junit.Test; + +public class UrlCheckerUnitTest { + + @Test + public void givenValidUrl_WhenUsingHEAD_ThenReturn200() throws IOException { + UrlChecker tester = new UrlChecker(); + int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com"); + assertEquals(200, responseCode); + } + + @Test + public void givenInvalidIUrl_WhenUsingHEAD_ThenReturn404() throws IOException { + UrlChecker tester = new UrlChecker(); + int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com/unkownurl"); + assertEquals(404, responseCode); + } + + @Test + public void givenValidUrl_WhenUsingGET_ThenReturn200() throws IOException { + UrlChecker tester = new UrlChecker(); + int responseCode = tester.getResponseCodeForURL("http://www.example.com"); + assertEquals(200, responseCode); + } + + @Test + public void givenInvalidIUrl_WhenUsingGET_ThenReturn404() throws IOException { + UrlChecker tester = new UrlChecker(); + int responseCode = tester.getResponseCodeForURL("http://www.example.com/unkownurl"); + assertEquals(404, responseCode); + } + +} From eaa0c63620d0ac7807a6ea65d95defcd8202d879 Mon Sep 17 00:00:00 2001 From: vatsalgosar Date: Wed, 24 Jul 2019 00:18:45 +0530 Subject: [PATCH 290/352] BAEL-2728 - Removed unnecessary code --- .../spring-boot-configuration/README.md | 4 - .../spring-boot-configuration/pom.xml | 88 ++++++++----------- .../main/java/com/baeldung/Application.java | 24 +++-- .../ServiceImpl/PersonServiceImpl.java | 6 ++ .../baeldung/controller/PersonController.java | 39 -------- .../main/java/com/baeldung/domain/Person.java | 38 -------- .../exception/PersonNotFoundException.java | 8 -- .../baeldung/repository/PersonRepository.java | 9 -- .../com/baeldung/service/PersonService.java | 32 +------ .../src/main/resources/application.properties | 3 - .../src/main/resources/schema.sql | 5 -- .../java/com/baeldung/ApplicationTests.java | 6 +- 12 files changed, 56 insertions(+), 206 deletions(-) create mode 100644 spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/ServiceImpl/PersonServiceImpl.java delete mode 100644 spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/controller/PersonController.java delete mode 100644 spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/domain/Person.java delete mode 100644 spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/exception/PersonNotFoundException.java delete mode 100644 spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/repository/PersonRepository.java delete mode 100644 spring-boot-bootstrap/spring-boot-configuration/src/main/resources/application.properties delete mode 100644 spring-boot-bootstrap/spring-boot-configuration/src/main/resources/schema.sql diff --git a/spring-boot-bootstrap/spring-boot-configuration/README.md b/spring-boot-bootstrap/spring-boot-configuration/README.md index 35472d575a..d5ec5f63da 100644 --- a/spring-boot-bootstrap/spring-boot-configuration/README.md +++ b/spring-boot-bootstrap/spring-boot-configuration/README.md @@ -4,7 +4,3 @@ SprintBootConfiguration annotation commands: mvn clean install mvn spring-boot:run - -Swagger endpoints: -http://localhost:8080/v2/api-docs -http://localhost:8080/swagger-ui.html \ No newline at end of file diff --git a/spring-boot-bootstrap/spring-boot-configuration/pom.xml b/spring-boot-bootstrap/spring-boot-configuration/pom.xml index 02b2e53159..d7b4122c20 100644 --- a/spring-boot-bootstrap/spring-boot-configuration/pom.xml +++ b/spring-boot-bootstrap/spring-boot-configuration/pom.xml @@ -1,60 +1,42 @@ - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.1.6.RELEASE - - - com.baeldung - spring-boot-configuration - 0.0.1-SNAPSHOT - spring-boot-configuration - Demo project for Spring Boot Configuration + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + com.baeldung + spring-boot-configuration + 0.0.1-SNAPSHOT + spring-boot-configuration + Demo project for Spring Boot Configuration - - 1.8 - + + 1.8 + - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-web - + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-test + test + + - - - com.h2database - h2 - runtime - - - - - org.hibernate - hibernate-entitymanager - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/Application.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/Application.java index 7021ae62fa..15adb4bb3e 100644 --- a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/Application.java +++ b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/Application.java @@ -1,25 +1,23 @@ package com.baeldung; -import com.baeldung.service.PersonService; import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Import; -@EnableAutoConfiguration -@ComponentScan(basePackages = {"com.baeldung.*"}) +import com.baeldung.ServiceImpl.PersonServiceImpl; +import com.baeldung.service.PersonService; + +@ComponentScan(basePackages = { "com.baeldung.*" }) @SpringBootConfiguration public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } - @Bean - public PersonService personService() { - return new PersonService(); - } + @Bean + public PersonService personService() { + return new PersonServiceImpl(); + } } - diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/ServiceImpl/PersonServiceImpl.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/ServiceImpl/PersonServiceImpl.java new file mode 100644 index 0000000000..f08fbaa7f2 --- /dev/null +++ b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/ServiceImpl/PersonServiceImpl.java @@ -0,0 +1,6 @@ +package com.baeldung.ServiceImpl; + +import com.baeldung.service.PersonService; + +public class PersonServiceImpl implements PersonService { +} diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/controller/PersonController.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/controller/PersonController.java deleted file mode 100644 index 10d7386132..0000000000 --- a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/controller/PersonController.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.controller; - -import com.baeldung.domain.Person; -import com.baeldung.exception.PersonNotFoundException; -import com.baeldung.service.PersonService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@RestController -@RequestMapping("/persons") -public class PersonController { - - @Autowired - PersonService personService; - - @GetMapping - public List getPersons() { - return personService.getPersons(); - } - - @PostMapping - public void addPerson(@RequestBody Person person) { - personService.add(person); - } - - @GetMapping("/{id}") - public Person getPersonById(@PathVariable(required = true) long id) throws PersonNotFoundException { - return personService.getPersonById(id); - } - - @DeleteMapping("/{id}") - public void removePerson(@PathVariable(required = true) long id) { - personService.delete(id); - } - - -} diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/domain/Person.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/domain/Person.java deleted file mode 100644 index e63836420c..0000000000 --- a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/domain/Person.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.domain; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -@Entity -public class Person { - - @Id - @GeneratedValue - private long id; - private String name; - - public Person() {} - - public Person(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; - } -} - diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/exception/PersonNotFoundException.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/exception/PersonNotFoundException.java deleted file mode 100644 index 048197a072..0000000000 --- a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/exception/PersonNotFoundException.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.exception; - -public class PersonNotFoundException extends Exception { - - public PersonNotFoundException(String message) { - super(message); - } -} diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/repository/PersonRepository.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/repository/PersonRepository.java deleted file mode 100644 index b542b5ea0b..0000000000 --- a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/repository/PersonRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.domain.Person; -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface PersonRepository extends CrudRepository { -} diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java index 74f7cb0a70..e959e3b835 100644 --- a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java +++ b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java @@ -1,34 +1,4 @@ package com.baeldung.service; -import com.baeldung.domain.Person; -import com.baeldung.exception.PersonNotFoundException; -import com.baeldung.repository.PersonRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Optional; - -//@Service -public class PersonService { - - @Autowired - PersonRepository personRepository; - - public void add(Person person) { - personRepository.save(person); - } - - public void delete(long id) { - personRepository.deleteById(id); - } - - public List getPersons() { - return (List) personRepository.findAll(); - } - - public Person getPersonById(long id) throws PersonNotFoundException { - Optional optionalDog = personRepository.findById(id); - return optionalDog.orElseThrow(() -> new PersonNotFoundException("Couldn't find a Person with id: " + id)); - } +public interface PersonService { } diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/main/resources/application.properties b/spring-boot-bootstrap/spring-boot-configuration/src/main/resources/application.properties deleted file mode 100644 index 7de28fe306..0000000000 --- a/spring-boot-bootstrap/spring-boot-configuration/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -# H2 -spring.h2.console.enabled=true -spring.h2.console.path=/h2 diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/main/resources/schema.sql b/spring-boot-bootstrap/spring-boot-configuration/src/main/resources/schema.sql deleted file mode 100644 index 02a7aca232..0000000000 --- a/spring-boot-bootstrap/spring-boot-configuration/src/main/resources/schema.sql +++ /dev/null @@ -1,5 +0,0 @@ -CREATE TABLE `person` ( - `id` INT(11) NOT NULL, - `name` VARCHAR(50) NULL DEFAULT NULL, - PRIMARY KEY (`id`) -); \ No newline at end of file diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java b/spring-boot-bootstrap/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java index f239fc76cc..3bd3cc2ec6 100644 --- a/spring-boot-bootstrap/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java +++ b/spring-boot-bootstrap/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java @@ -9,8 +9,8 @@ import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest public class ApplicationTests { - @Test - public void contextLoads() { - } + @Test + public void contextLoads() { + } } From 22d6a3efb2b95944c0b12e3382f4dc8692013447 Mon Sep 17 00:00:00 2001 From: Loredana Date: Tue, 23 Jul 2019 22:18:39 +0300 Subject: [PATCH 291/352] exclude modules with failing tests --- pom.xml | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/pom.xml b/pom.xml index 21a42f89d6..aa4e497844 100644 --- a/pom.xml +++ b/pom.xml @@ -663,22 +663,23 @@ spring-boot-vue spring-boot-libraries - spring-cloud - spring-cloud-bus + + + - spring-cloud-data-flow + spring-core spring-core-2 spring-cucumber spring-data-rest - spring-data-rest-querydsl + spring-dispatcher-servlet spring-drools spring-ehcache - spring-ejb + spring-exceptions spring-freemarker @@ -752,7 +753,7 @@ spring-security-stormpath spring-security-thymeleaf spring-security-x509 - spring-session + spring-sleuth spring-soap spring-social-login @@ -763,10 +764,10 @@ spring-thymeleaf - spring-vault + spring-vertx - spring-webflux-amqp + spring-zuul From b355af4d01472a32d823685a3ff35f1d3736cc9a Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Tue, 23 Jul 2019 16:22:20 -0300 Subject: [PATCH 292/352] fixed migration to spring boot 2, plus now added properties in articles --- spring-security-mvc-session/pom.xml | 87 +++++-------------- .../baeldung/SpringSessionApplication.java | 2 +- .../monitoring/MetricRegistrySingleton.java | 2 +- ...SimpleUrlAuthenticationSuccessHandler.java | 2 +- .../baeldung/security/SessionFilter.java | 2 +- .../java/com/baeldung/spring/MvcConfig.java | 33 +++++++ .../baeldung/spring/SecSecurityConfig.java | 11 ++- .../web/SessionListenerWithMetrics.java | 5 +- .../java/org/baeldung/spring/MvcConfig.java | 44 ---------- .../src/main/resources/application.properties | 8 ++ .../SpringContextIntegrationTest.java | 15 ++++ .../SpringContextIntegrationTest.java | 19 ---- .../java/org/baeldung/SpringContextTest.java | 19 ---- 13 files changed, 90 insertions(+), 159 deletions(-) rename spring-security-mvc-session/src/main/java/{org => com}/baeldung/SpringSessionApplication.java (93%) rename spring-security-mvc-session/src/main/java/{org => com}/baeldung/monitoring/MetricRegistrySingleton.java (95%) rename spring-security-mvc-session/src/main/java/{org => com}/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java (99%) rename spring-security-mvc-session/src/main/java/{org => com}/baeldung/security/SessionFilter.java (97%) create mode 100644 spring-security-mvc-session/src/main/java/com/baeldung/spring/MvcConfig.java rename spring-security-mvc-session/src/main/java/{org => com}/baeldung/spring/SecSecurityConfig.java (91%) rename spring-security-mvc-session/src/main/java/{org => com}/baeldung/web/SessionListenerWithMetrics.java (92%) delete mode 100644 spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java create mode 100644 spring-security-mvc-session/src/main/resources/application.properties create mode 100644 spring-security-mvc-session/src/test/java/com/baeldung/SpringContextIntegrationTest.java delete mode 100644 spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java delete mode 100644 spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index b55ce70517..5ed7fbecd3 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -1,18 +1,19 @@ - + 4.0.0 com.baeldung spring-security-mvc-session 0.1-SNAPSHOT spring-security-mvc-session - war + jar - parent-boot-2 com.baeldung + parent-boot-2 0.0.1-SNAPSHOT ../parent-boot-2 - + @@ -35,20 +36,13 @@ org.apache.tomcat.embed tomcat-embed-jasper + provided org.springframework.boot spring-boot-starter-tomcat - - - - javax.servlet - javax.servlet-api - provided - - javax.servlet jstl @@ -56,70 +50,35 @@ - - com.codahale.metrics + io.dropwizard.metrics metrics-core - ${codahale.metrics.version} - + - org.springframework.boot - spring-boot-starter-test - test - - + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + - spring-security-mvc-session - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} + org.springframework.boot + spring-boot-maven-plugin - true - - jetty8x - embedded - - - - - - - 8082 - - + com.baeldung.SpringSessionApplication + JAR - - - - - 3.0.2 - - - 1.6.1 - - - \ No newline at end of file + diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java b/spring-security-mvc-session/src/main/java/com/baeldung/SpringSessionApplication.java similarity index 93% rename from spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java rename to spring-security-mvc-session/src/main/java/com/baeldung/SpringSessionApplication.java index 9e52f0430a..c2a4b35df0 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/SpringSessionApplication.java +++ b/spring-security-mvc-session/src/main/java/com/baeldung/SpringSessionApplication.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/monitoring/MetricRegistrySingleton.java b/spring-security-mvc-session/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java similarity index 95% rename from spring-security-mvc-session/src/main/java/org/baeldung/monitoring/MetricRegistrySingleton.java rename to spring-security-mvc-session/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java index ed253305ed..e2224996c2 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/monitoring/MetricRegistrySingleton.java +++ b/spring-security-mvc-session/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java @@ -1,4 +1,4 @@ -package org.baeldung.monitoring; +package com.baeldung.monitoring; import java.util.concurrent.TimeUnit; diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-mvc-session/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java similarity index 99% rename from spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java rename to spring-security-mvc-session/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 19f49ea59d..9d4fc19098 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-mvc-session/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import java.io.IOException; import java.util.Collection; diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/security/SessionFilter.java b/spring-security-mvc-session/src/main/java/com/baeldung/security/SessionFilter.java similarity index 97% rename from spring-security-mvc-session/src/main/java/org/baeldung/security/SessionFilter.java rename to spring-security-mvc-session/src/main/java/com/baeldung/security/SessionFilter.java index d37d46e478..f4f876af9c 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/security/SessionFilter.java +++ b/spring-security-mvc-session/src/main/java/com/baeldung/security/SessionFilter.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package com.baeldung.security; import java.io.IOException; import java.util.Arrays; diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/spring/MvcConfig.java b/spring-security-mvc-session/src/main/java/com/baeldung/spring/MvcConfig.java new file mode 100644 index 0000000000..38a4f3f81b --- /dev/null +++ b/spring-security-mvc-session/src/main/java/com/baeldung/spring/MvcConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class MvcConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/anonymous.html"); + + registry.addViewController("/login.html"); + registry.addViewController("/homepage.html"); + registry.addViewController("/sessionExpired.html"); + registry.addViewController("/invalidSession.html"); + registry.addViewController("/console.html"); + } + + + /* + * Spring Boot supports configuring a ViewResolver with properties + */ +// @Bean +// public ViewResolver viewResolver() { +// final InternalResourceViewResolver bean = new InternalResourceViewResolver(); +// +// bean.setViewClass(JstlView.class); +// bean.setPrefix("/WEB-INF/view/"); +// bean.setSuffix(".jsp"); +// } +} diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-session/src/main/java/com/baeldung/spring/SecSecurityConfig.java similarity index 91% rename from spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java rename to spring-security-mvc-session/src/main/java/com/baeldung/spring/SecSecurityConfig.java index b7996ebf18..a922ba6f7f 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-session/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -1,11 +1,9 @@ -package org.baeldung.spring; +package com.baeldung.spring; -import org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @@ -13,9 +11,10 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.session.HttpSessionEventPublisher; +import com.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; + @Configuration // @ImportResource({ "classpath:webSecurityConfig.xml" }) -@EnableWebSecurity public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public SecSecurityConfig() { @@ -39,7 +38,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { .csrf().disable() .authorizeRequests() .antMatchers("/anonymous*").anonymous() - .antMatchers("/login*").permitAll() + .antMatchers("/login*","/invalidSession*", "/sessionExpired*").permitAll() .anyRequest().authenticated() .and() .formLogin() @@ -70,7 +69,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter { public HttpSessionEventPublisher httpSessionEventPublisher() { return new HttpSessionEventPublisher(); } - + @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/web/SessionListenerWithMetrics.java b/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java similarity index 92% rename from spring-security-mvc-session/src/main/java/org/baeldung/web/SessionListenerWithMetrics.java rename to spring-security-mvc-session/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java index 46bf2708f7..fb1a81744e 100644 --- a/spring-security-mvc-session/src/main/java/org/baeldung/web/SessionListenerWithMetrics.java +++ b/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java @@ -1,12 +1,11 @@ -package org.baeldung.web; +package com.baeldung.web; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; -import org.baeldung.monitoring.MetricRegistrySingleton; - +import com.baeldung.monitoring.MetricRegistrySingleton; import com.codahale.metrics.Counter; public class SessionListenerWithMetrics implements HttpSessionListener { diff --git a/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java deleted file mode 100644 index b9f50ded73..0000000000 --- a/spring-security-mvc-session/src/main/java/org/baeldung/spring/MvcConfig.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@EnableWebMvc -@Configuration -public class MvcConfig implements WebMvcConfigurer { - - public MvcConfig() { - super(); - } - - // API - - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - - registry.addViewController("/anonymous.html"); - - registry.addViewController("/login.html"); - registry.addViewController("/homepage.html"); - registry.addViewController("/sessionExpired.html"); - registry.addViewController("/invalidExpired.html"); - registry.addViewController("/console.html"); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - - return bean; - } -} \ No newline at end of file diff --git a/spring-security-mvc-session/src/main/resources/application.properties b/spring-security-mvc-session/src/main/resources/application.properties new file mode 100644 index 0000000000..39ec0a0b27 --- /dev/null +++ b/spring-security-mvc-session/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.servlet.session.timeout=60s + +spring.mvc.view.prefix=/WEB-INF/view/ +spring.mvc.view.suffix=.jsp + +## Secure Session Cookie configurations +#server.servlet.session.cookie.http-only=true +#server.servlet.session.cookie.secure=true \ No newline at end of file diff --git a/spring-security-mvc-session/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-session/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..8e53a6371a --- /dev/null +++ b/spring-security-mvc-session/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index 9e74e83a53..0000000000 --- a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.MvcConfig; -import org.baeldung.spring.SecSecurityConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) -@WebAppConfiguration -public class SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 5ee80d856a..0000000000 --- a/spring-security-mvc-session/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.MvcConfig; -import org.baeldung.spring.SecSecurityConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class }) -@WebAppConfiguration -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} From d3ed9d75fd959cbba33c09d6d4f4d391fb8693cb Mon Sep 17 00:00:00 2001 From: Alessio Stalla Date: Wed, 24 Jul 2019 23:32:58 +0200 Subject: [PATCH 293/352] Tests for BAEL-2991 --- persistence-modules/java-sql2o/README.md | 3 + persistence-modules/java-sql2o/pom.xml | 55 +++ .../jdbi/Sql2oIntegrationTest.java | 343 ++++++++++++++++++ persistence-modules/pom.xml | 1 + 4 files changed, 402 insertions(+) create mode 100644 persistence-modules/java-sql2o/README.md create mode 100644 persistence-modules/java-sql2o/pom.xml create mode 100644 persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java diff --git a/persistence-modules/java-sql2o/README.md b/persistence-modules/java-sql2o/README.md new file mode 100644 index 0000000000..4c1ff931ce --- /dev/null +++ b/persistence-modules/java-sql2o/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [A Guide to Jdbi](http://www.baeldung.com/jdbi) diff --git a/persistence-modules/java-sql2o/pom.xml b/persistence-modules/java-sql2o/pom.xml new file mode 100644 index 0000000000..54838c32cb --- /dev/null +++ b/persistence-modules/java-sql2o/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + com.baeldung + java-sql2o + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 8 + 8 + + + + + java-sql2o + + + + + + org.sql2o + sql2o + ${sql2o.version} + + + org.hsqldb + hsqldb + ${hsqldb.version} + test + + + junit + junit + ${junit.version} + test + + + + + 2.4.0 + 4.12 + 1.6.0 + + + diff --git a/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java b/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java new file mode 100644 index 0000000000..56f2e3a62e --- /dev/null +++ b/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java @@ -0,0 +1,343 @@ +package com.baeldung.persistence.jdbi; + +import org.junit.Test; +import org.sql2o.Connection; +import org.sql2o.Query; +import org.sql2o.ResultSetIterable; +import org.sql2o.Sql2o; +import org.sql2o.data.Row; +import org.sql2o.data.Table; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static org.junit.Assert.*; + +public class Sql2oIntegrationTest { + + @Test + public void whenSql2oCreated_thenSuccess() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + java.sql.Connection jdbcConnection = connection.getJdbcConnection(); + assertFalse(jdbcConnection.isClosed()); + } catch (SQLException e) { + fail(e.getMessage()); + } + } + + @Test + public void whenTableCreated_thenInsertIsPossible() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_1 (id integer identity, name varchar(50), url varchar(100))").executeUpdate(); + assertEquals(0, connection.getResult()); + connection.createQuery("INSERT INTO PROJECT_1 VALUES (1, 'tutorials', 'github.com/eugenp/tutorials')").executeUpdate(); + assertEquals(1, connection.getResult()); + connection.createQuery("drop table PROJECT_1").executeUpdate(); + } + } + + @Test + public void whenIdentityColumn_thenInsertReturnsNewId() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + Query query = connection.createQuery( + "INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')", + true); + assertEquals(0, query.executeUpdate().getKey()); + query = connection.createQuery("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')", + true); + assertEquals(1, query.executeUpdate().getKeys()[0]); + connection.createQuery("drop table PROJECT_2").executeUpdate(); + } + } + + @Test + public void whenSelect_thenResultsAreObjects() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')").executeUpdate(); + Query query = connection.createQuery("select * from PROJECT_3 order by id"); + List list = query.executeAndFetch(Project.class); + + assertEquals("tutorials", list.get(0).getName()); + assertEquals("REST with Spring", list.get(1).getName()); + + connection.createQuery("drop table PROJECT_3").executeUpdate(); + } + } + + @Test + public void whenSelectAlias_thenResultsAreObjects() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_4 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_4 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate(); + Query query = connection.createQuery("select NAME, URL, creation_date as creationDate from PROJECT_4 order by id"); + List list = query.executeAndFetch(Project.class); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + assertEquals("2019-01-01", sdf.format(list.get(0).getCreationDate())); + assertEquals("2019-02-01", sdf.format(list.get(1).getCreationDate())); + + connection.createQuery("drop table PROJECT_4").executeUpdate(); + } + } + + @Test + public void whenSelectMapping_thenResultsAreObjects() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate(); + Query query = connection.createQuery("select * from PROJECT_5 order by id") + .addColumnMapping("CrEaTiOn_date", "creationDate"); + List list = query.executeAndFetch(Project.class); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + assertEquals("2019-01-01", sdf.format(list.get(0).getCreationDate())); + assertEquals("2019-02-01", sdf.format(list.get(1).getCreationDate())); + + connection.createQuery("drop table PROJECT_5").executeUpdate(); + } + } + + @Test + public void whenSelectCount_thenResultIsScalar() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_6 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_6 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate(); + Query query = connection.createQuery("select count(*) from PROJECT_6"); + assertEquals(2.0, query.executeScalar(Double.TYPE), 0.001); + connection.createQuery("drop table PROJECT_6").executeUpdate(); + } + } + + @Test + public void whenFetchTable_thenResultsAreMaps() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate(); + Query query = connection.createQuery("select * from PROJECT_5 order by id"); + Table table = query.executeAndFetchTable(); + List> list = table.asList(); + + assertEquals("tutorials", list.get(0).get("name")); + assertEquals("REST with Spring", list.get(1).get("name")); + + connection.createQuery("drop table PROJECT_5").executeUpdate(); + } + } + + @Test + public void whenFetchTable_thenResultsAreRows() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100), creation_date date)").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('tutorials', 'github.com/eugenp/tutorials', '2019-01-01')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_5 (NAME, URL, creation_date) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring', '2019-02-01')").executeUpdate(); + Query query = connection.createQuery("select * from PROJECT_5 order by id"); + Table table = query.executeAndFetchTable(); + List rows = table.rows(); + + assertEquals("tutorials", rows.get(0).getString("name")); + assertEquals("REST with Spring", rows.get(1).getString("name")); + + connection.createQuery("drop table PROJECT_5").executeUpdate(); + } + } + + @Test + public void whenParameters_thenReplacement() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + Query query = connection.createQuery("INSERT INTO PROJECT_10 (NAME, URL) VALUES (:name, :url)") + .addParameter("name", "REST with Spring") + .addParameter("url", "github.com/eugenp/REST-With-Spring"); + assertEquals(1, query.executeUpdate().getResult()); + + List list = connection.createQuery("SELECT * FROM PROJECT_10 WHERE NAME = 'REST with Spring'").executeAndFetch(Project.class); + assertEquals(1, list.size()); + + connection.createQuery("drop table PROJECT_10").executeUpdate(); + } + } + + @Test + public void whenPOJOParameters_thenReplacement() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + + Project project = new Project(); + project.setName("REST with Spring"); + project.setUrl("github.com/eugenp/REST-With-Spring"); + connection.createQuery("INSERT INTO PROJECT_11 (NAME, URL) VALUES (:name, :url)") + .bind(project).executeUpdate(); + assertEquals(1, connection.getResult()); + + List list = connection.createQuery("SELECT * FROM PROJECT_11 WHERE NAME = 'REST with Spring'").executeAndFetch(Project.class); + assertEquals(1, list.size()); + + connection.createQuery("drop table PROJECT_11").executeUpdate(); + } + } + + @Test + public void whenTransactionRollback_thenNoDataInserted() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.beginTransaction()) { + connection.createQuery("create table PROJECT_12 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_12 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate(); + connection.rollback(); + List> list = connection.createQuery("SELECT * FROM PROJECT_12").executeAndFetchTable().asList(); + assertEquals(0, list.size()); + } + } + + @Test + public void whenTransactionEnds_thenSubsequentStatementsNotRolledBack() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.beginTransaction()) { + connection.createQuery("create table PROJECT_13 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate(); + List> list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList(); + assertEquals(1, list.size()); + connection.rollback(); + list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList(); + assertEquals(0, list.size()); + connection.createQuery("INSERT INTO PROJECT_13 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate(); + list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList(); + assertEquals(1, list.size()); + //No implicit rollback + } + try(Connection connection = sql2o.beginTransaction()) { + List> list = connection.createQuery("SELECT * FROM PROJECT_13").executeAndFetchTable().asList(); + assertEquals(1, list.size()); + } + } + + @Test + public void whenTransactionRollbackThenCommit_thenOnlyLastInserted() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.beginTransaction()) { + connection.createQuery("create table PROJECT_14 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate(); + List> list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList(); + assertEquals(1, list.size()); + connection.rollback(false); + list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList(); + assertEquals(0, list.size()); + connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate(); + list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList(); + assertEquals(1, list.size()); + //Implicit rollback + } + try(Connection connection = sql2o.beginTransaction()) { + List> list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList(); + assertEquals(0, list.size()); + connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_14 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')").executeUpdate(); + connection.commit(); + list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList(); + assertEquals(2, list.size()); + } + try(Connection connection = sql2o.beginTransaction()) { + List> list = connection.createQuery("SELECT * FROM PROJECT_14").executeAndFetchTable().asList(); + assertEquals(2, list.size()); + } + } + + @Test + public void whenBatch_thenMultipleInserts() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.beginTransaction()) { + connection.createQuery("create table PROJECT_15 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + Query query = connection.createQuery("INSERT INTO PROJECT_15 (NAME, URL) VALUES (:name, :url)"); + for(int i = 0; i < 1000; i++) { + query.addParameter("name", "tutorials" + i); + query.addParameter("url", "https://github.com/eugenp/tutorials" + i); + query.addToBatch(); + } + query.executeBatch(); + connection.commit(); + } + try(Connection connection = sql2o.beginTransaction()) { + assertEquals(1000L, connection.createQuery("SELECT count(*) FROM PROJECT_15").executeScalar()); + } + } + + @Test + public void whenLazyFetch_thenResultsAreObjects() { + Sql2o sql2o = new Sql2o("jdbc:hsqldb:mem:testDB", "sa", ""); + try(Connection connection = sql2o.open()) { + connection.createQuery("create table PROJECT_16 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_16 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')").executeUpdate(); + connection.createQuery("INSERT INTO PROJECT_16 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')").executeUpdate(); + Query query = connection.createQuery("select * from PROJECT_16 order by id"); + try(ResultSetIterable projects = query.executeAndFetchLazy(Project.class)) { + for(Project p : projects) { + assertNotNull(p.getName()); + assertNotNull(p.getUrl()); + assertNull(p.getCreationDate()); + } + } + connection.createQuery("drop table PROJECT_16").executeUpdate(); + } + } + + static class Project { + private long id; + private String name; + private String url; + private Date creationDate; + + 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 String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public Date getCreationDate() { + return creationDate; + } + + public void setCreationDate(Date creationDate) { + this.creationDate = creationDate; + } + } + + +} diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 390bcc9d51..5df91b5a8d 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -30,6 +30,7 @@ java-jdbi java-jpa java-mongodb + java-sql2o jnosql liquibase orientdb From 155d3ea52f328f3bb6cfaa98d18fc4671e5a63e2 Mon Sep 17 00:00:00 2001 From: Alessio Stalla Date: Wed, 24 Jul 2019 23:35:22 +0200 Subject: [PATCH 294/352] Fix readme --- persistence-modules/java-sql2o/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/java-sql2o/README.md b/persistence-modules/java-sql2o/README.md index 4c1ff931ce..a86e45f1c8 100644 --- a/persistence-modules/java-sql2o/README.md +++ b/persistence-modules/java-sql2o/README.md @@ -1,3 +1,3 @@ ### Relevant Articles: -- [A Guide to Jdbi](http://www.baeldung.com/jdbi) +- [A Guide to Sql2o](http://www.baeldung.com/sql2o) From 2b5e275716fb5d032c65dba07a4ef846b76cb20c Mon Sep 17 00:00:00 2001 From: Alessio Stalla Date: Wed, 24 Jul 2019 23:35:54 +0200 Subject: [PATCH 295/352] Fix package name --- .../persistence/{jdbi => sql2o}/Sql2oIntegrationTest.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) rename persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/{jdbi => sql2o}/Sql2oIntegrationTest.java (99%) diff --git a/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java b/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/sql2o/Sql2oIntegrationTest.java similarity index 99% rename from persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java rename to persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/sql2o/Sql2oIntegrationTest.java index 56f2e3a62e..4429b1578c 100644 --- a/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/jdbi/Sql2oIntegrationTest.java +++ b/persistence-modules/java-sql2o/src/test/java/com/baeldung/persistence/sql2o/Sql2oIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.persistence.jdbi; +package com.baeldung.persistence.sql2o; import org.junit.Test; import org.sql2o.Connection; @@ -8,12 +8,9 @@ import org.sql2o.Sql2o; import org.sql2o.data.Row; import org.sql2o.data.Table; -import java.sql.PreparedStatement; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.*; -import java.util.function.Supplier; -import java.util.stream.Stream; import static org.junit.Assert.*; From 45f85e2c7d010d8cedeece71e270a7f81b8428d5 Mon Sep 17 00:00:00 2001 From: rahul Date: Thu, 25 Jul 2019 07:49:53 +0530 Subject: [PATCH 296/352] Changing the parent pom for core-java-networking-2 --- core-java-modules/core-java-networking-2/README.md | 7 ------- core-java-modules/core-java-networking-2/pom.xml | 8 +++----- core-java-modules/pom.xml | 1 + 3 files changed, 4 insertions(+), 12 deletions(-) delete mode 100644 core-java-modules/core-java-networking-2/README.md diff --git a/core-java-modules/core-java-networking-2/README.md b/core-java-modules/core-java-networking-2/README.md deleted file mode 100644 index 15cccf4a60..0000000000 --- a/core-java-modules/core-java-networking-2/README.md +++ /dev/null @@ -1,7 +0,0 @@ -========= - -## Core Java Networking - 2 - -### Relevant Articles - -- [Checking if a URL Exists in Java](https://www.baeldung.com/checking-if-a-url-exists-with-java) diff --git a/core-java-modules/core-java-networking-2/pom.xml b/core-java-modules/core-java-networking-2/pom.xml index 88e038d4c9..8a26f6ab9f 100644 --- a/core-java-modules/core-java-networking-2/pom.xml +++ b/core-java-modules/core-java-networking-2/pom.xml @@ -2,15 +2,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-networking-2 - 0.1.0-SNAPSHOT core-java-networking-2 jar - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + com.baeldung.core-java-modules + core-java-modules + 1.0.0-SNAPSHOT diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 11a1003460..2dca62005d 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -17,6 +17,7 @@ pre-jpms core-java-exceptions core-java-optional + core-java-networking-2 From 2c53cdd44e9fdc4d8ef1386e99dd370990fb13da Mon Sep 17 00:00:00 2001 From: Amy DeGregorio Date: Thu, 25 Jul 2019 01:22:28 -0400 Subject: [PATCH 297/352] BAEL-3010 (#7408) * BAEL-3010 changing template dir * BAEL-3010 Add ThymeleafConfig --- .../baeldung/thymeleaf/ThymeleafConfig.java | 23 +++++++++++++++++++ .../templatedir/HelloController.java | 13 +++++++++++ .../src/main/resources/application.properties | 1 + .../src/main/resources/templates-2/hello.html | 10 ++++++++ 4 files changed, 47 insertions(+) create mode 100644 spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java create mode 100644 spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java create mode 100644 spring-thymeleaf-2/src/main/resources/application.properties create mode 100644 spring-thymeleaf-2/src/main/resources/templates-2/hello.html diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java new file mode 100644 index 0000000000..2fd11628ad --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/ThymeleafConfig.java @@ -0,0 +1,23 @@ +package com.baeldung.thymeleaf; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; + +@Configuration +public class ThymeleafConfig { + + @Bean + public ClassLoaderTemplateResolver secondaryTemplateResolver() { + ClassLoaderTemplateResolver secondaryTemplateResolver = new ClassLoaderTemplateResolver(); + secondaryTemplateResolver.setPrefix("templates-2/"); + secondaryTemplateResolver.setSuffix(".html"); + secondaryTemplateResolver.setTemplateMode(TemplateMode.HTML); + secondaryTemplateResolver.setCharacterEncoding("UTF-8"); + secondaryTemplateResolver.setOrder(1); + secondaryTemplateResolver.setCheckExistence(true); + + return secondaryTemplateResolver; + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java new file mode 100644 index 0000000000..b404418106 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/templatedir/HelloController.java @@ -0,0 +1,13 @@ +package com.baeldung.thymeleaf.templatedir; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class HelloController { + + @GetMapping("/hello") + public String sayHello() { + return "hello"; + } +} diff --git a/spring-thymeleaf-2/src/main/resources/application.properties b/spring-thymeleaf-2/src/main/resources/application.properties new file mode 100644 index 0000000000..b09232bb1b --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/application.properties @@ -0,0 +1 @@ +#spring.thymeleaf.prefix=classpath:/templates-2/ \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates-2/hello.html b/spring-thymeleaf-2/src/main/resources/templates-2/hello.html new file mode 100644 index 0000000000..035904c8ba --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates-2/hello.html @@ -0,0 +1,10 @@ + + + + +Enums in Thymeleaf + + +

    Hello from 'templates/templates-2'

    + + \ No newline at end of file From ffada1e2a749cf5903d28921e4697760f2b9569f Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Thu, 25 Jul 2019 07:52:18 -0400 Subject: [PATCH 298/352] BAEL-3153: Updated code format to match standard Baeldung format Converted tabs into spaces --- .../changecase/ToLowerCaseUnitTest.java | 36 +++++++++---------- .../changecase/ToUpperCaseUnitTest.java | 34 +++++++++--------- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java index 14102be993..c395b61068 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java +++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToLowerCaseUnitTest.java @@ -7,23 +7,23 @@ import java.util.Locale; import org.junit.Test; public class ToLowerCaseUnitTest { - - private static final Locale TURKISH = new Locale("tr"); - private String name = "John Doe"; - private String foreignUppercase = "\u0049"; - @Test - public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() { - assertEquals("john doe", name.toLowerCase()); - } - - @Test - public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() { - assertEquals("\u0069", foreignUppercase.toLowerCase()); - } - - @Test - public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() { - assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH)); - } + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignUppercase = "\u0049"; + + @Test + public void givenMixedCaseString_WhenToLowerCase_ThenResultIsLowerCase() { + assertEquals("john doe", name.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithoutLocale_ThenResultIsLowerCase() { + assertEquals("\u0069", foreignUppercase.toLowerCase()); + } + + @Test + public void givenForeignString_WhenToLowerCaseWithLocale_ThenResultIsLowerCase() { + assertEquals("\u0131", foreignUppercase.toLowerCase(TURKISH)); + } } diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java index 90b80714a7..365b5ae52f 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java +++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java @@ -8,22 +8,22 @@ import org.junit.Test; public class ToUpperCaseUnitTest { - private static final Locale TURKISH = new Locale("tr"); - private String name = "John Doe"; - private String foreignUppercase = "\u0069"; + private static final Locale TURKISH = new Locale("tr"); + private String name = "John Doe"; + private String foreignUppercase = "\u0069"; - @Test - public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { - assertEquals("JOHN DOE", name.toUpperCase()); - } - - @Test - public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { - assertEquals("\u0049", foreignUppercase.toUpperCase()); - } - - @Test - public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { - assertEquals("\u0130", foreignUppercase.toUpperCase(TURKISH)); - } + @Test + public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { + assertEquals("JOHN DOE", name.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { + assertEquals("\u0049", foreignUppercase.toUpperCase()); + } + + @Test + public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { + assertEquals("\u0130", foreignUppercase.toUpperCase(TURKISH)); + } } From b981da41c825aeb1bb821c4268cc78b0f8ec9d47 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Thu, 25 Jul 2019 11:40:21 -0300 Subject: [PATCH 299/352] added live tests for session timeout properties --- .../baeldung/web/SessionRestController.java | 17 ++++ .../src/main/resources/application.properties | 2 +- .../SessionConfigurationIntegrationTest.java | 92 +++++++++++++++++++ 3 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 spring-security-mvc-session/src/main/java/com/baeldung/web/SessionRestController.java create mode 100644 spring-security-mvc-session/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionRestController.java b/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionRestController.java new file mode 100644 index 0000000000..1353ee25d0 --- /dev/null +++ b/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionRestController.java @@ -0,0 +1,17 @@ +package com.baeldung.web; + +import javax.servlet.http.HttpSession; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SessionRestController { + + @GetMapping("/session-max-interval") + @ResponseBody + public String retrieveMaxSessionIncativeInterval(HttpSession session) { + return "Max Inactive Interval before Session expires: " + session.getMaxInactiveInterval(); + } +} diff --git a/spring-security-mvc-session/src/main/resources/application.properties b/spring-security-mvc-session/src/main/resources/application.properties index 39ec0a0b27..56b2b7b123 100644 --- a/spring-security-mvc-session/src/main/resources/application.properties +++ b/spring-security-mvc-session/src/main/resources/application.properties @@ -1,4 +1,4 @@ -server.servlet.session.timeout=60s +server.servlet.session.timeout=65s spring.mvc.view.prefix=/WEB-INF/view/ spring.mvc.view.suffix=.jsp diff --git a/spring-security-mvc-session/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java b/spring-security-mvc-session/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java new file mode 100644 index 0000000000..5a9bf72077 --- /dev/null +++ b/spring-security-mvc-session/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java @@ -0,0 +1,92 @@ +package com.baeldung.session; + +import static io.restassured.RestAssured.given; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Optional; + +import org.junit.Test; +import org.springframework.http.HttpStatus; + +import io.restassured.filter.session.SessionFilter; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; + +/** + * This Live Test requires the service to be up and running. + */ +public class SessionConfigurationIntegrationTest { + + private static final String USER = "user1"; + private static final String PASSWORD = "user1Pass"; + private static final String SESSION_SVC_URL = "http://localhost:8080/session-max-interval"; + + @Test + public void givenValidUser_whenRequestResourceAfterSessionExpiration_thenRedirectedToInvalidSessionUri() throws Exception { + SessionFilter sessionFilter = new SessionFilter(); + simpleSvcRequestLoggingIn(sessionFilter); + Response resp2 = simpleResponseRequestUsingSessionNotFollowingRedirects(sessionFilter); + assertThat(resp2.getStatusCode()).isEqualTo(HttpStatus.OK.value()); + assertThat(resp2.getBody() + .asString()).isEqualTo("Max Inactive Interval before Session expires: 60"); + + // session will be expired in 60 seconds... + Thread.sleep(62000); + Response resp3 = simpleResponseRequestUsingSessionNotFollowingRedirects(sessionFilter); + + assertThat(resp3.getStatusCode()).isEqualTo(HttpStatus.FOUND.value()); + assertThat(resp3.getHeader("Location")).isEqualTo("http://localhost:8080/invalidSession.html"); + } + + @Test + public void givenValidUser_whenLoginMoreThanMaxValidSession_thenRedirectedToExpiredSessionUri() throws Exception { + SessionFilter sessionFilter = new SessionFilter(); + simpleSvcRequestLoggingIn(sessionFilter); + simpleSvcRequestLoggingIn(); + + // this login will expire the first session + simpleSvcRequestLoggingIn(); + + // now try to access a resource using expired session + Response resp4 = given().filter(sessionFilter) + .and() + .redirects() + .follow(false) + .when() + .get(SESSION_SVC_URL); + + assertThat(resp4.getStatusCode()).isEqualTo(HttpStatus.FOUND.value()); + assertThat(resp4.getHeader("Location")).isEqualTo("http://localhost:8080/sessionExpired.html"); + } + + private static void simpleSvcRequestLoggingIn() { + simpleSvcRequestLoggingIn(null); + } + + private static void simpleSvcRequestLoggingIn(SessionFilter sessionFilter) { + Response response = simpleResponseSvcRequestLoggingIn(Optional.ofNullable(sessionFilter)); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK.value()); + assertThat(response.getBody() + .asString()).isEqualTo("Max Inactive Interval before Session expires: 60"); + } + + private static Response simpleResponseSvcRequestLoggingIn(Optional sessionFilter) { + RequestSpecification spec = given().auth() + .form(USER, PASSWORD); + sessionFilter.ifPresent(filter -> spec.and() + .filter(filter)); + return spec.when() + .get(SESSION_SVC_URL); + } + + private static Response simpleResponseRequestUsingSessionNotFollowingRedirects(SessionFilter sessionFilter) { + return given().filter(sessionFilter) + .and() + .redirects() + .follow(false) + .when() + .get(SESSION_SVC_URL); + } + +} From 30f4da3dd5b6d29dd64778fa68ab4e51167025c3 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Thu, 25 Jul 2019 12:08:47 -0300 Subject: [PATCH 300/352] renamed spring-security-mvc-session to simply spring-security-mvc --- pom.xml | 6 +++--- .../.gitignore | 0 .../README.md | 0 .../pom.xml | 4 ++-- .../main/java/com/baeldung/SpringSessionApplication.java | 0 .../com/baeldung/monitoring/MetricRegistrySingleton.java | 0 .../security/MySimpleUrlAuthenticationSuccessHandler.java | 0 .../src/main/java/com/baeldung/security/SessionFilter.java | 0 .../src/main/java/com/baeldung/spring/MvcConfig.java | 0 .../main/java/com/baeldung/spring/SecSecurityConfig.java | 0 .../java/com/baeldung/web/SessionListenerWithMetrics.java | 0 .../main/java/com/baeldung/web/SessionRestController.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/logback.xml | 0 .../src/main/resources/webSecurityConfig.xml | 0 .../src/main/webapp/WEB-INF/mvc-servlet.xml | 0 .../src/main/webapp/WEB-INF/view/anonymous.jsp | 0 .../src/main/webapp/WEB-INF/view/console.jsp | 0 .../src/main/webapp/WEB-INF/view/homepage.jsp | 0 .../src/main/webapp/WEB-INF/view/invalidSession.jsp | 0 .../src/main/webapp/WEB-INF/view/login.jsp | 0 .../src/main/webapp/WEB-INF/view/sessionExpired.jsp | 0 .../src/main/webapp/WEB-INF/web.xml | 0 .../java/com/baeldung/SpringContextIntegrationTest.java | 0 .../session/SessionConfigurationIntegrationTest.java | 0 .../src/test/resources/.gitignore | 0 26 files changed, 5 insertions(+), 5 deletions(-) rename {spring-security-mvc-session => spring-security-mvc}/.gitignore (100%) rename {spring-security-mvc-session => spring-security-mvc}/README.md (100%) rename {spring-security-mvc-session => spring-security-mvc}/pom.xml (96%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/SpringSessionApplication.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/security/SessionFilter.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/spring/MvcConfig.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/spring/SecSecurityConfig.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/java/com/baeldung/web/SessionRestController.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/resources/application.properties (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/resources/logback.xml (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/resources/webSecurityConfig.xml (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/mvc-servlet.xml (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/view/anonymous.jsp (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/view/console.jsp (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/view/homepage.jsp (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/view/invalidSession.jsp (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/view/login.jsp (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/view/sessionExpired.jsp (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/main/webapp/WEB-INF/web.xml (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/test/java/com/baeldung/SpringContextIntegrationTest.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java (100%) rename {spring-security-mvc-session => spring-security-mvc}/src/test/resources/.gitignore (100%) diff --git a/pom.xml b/pom.xml index 21a42f89d6..81baa611d8 100644 --- a/pom.xml +++ b/pom.xml @@ -741,7 +741,7 @@ spring-security-mvc-ldap spring-security-mvc-login spring-security-mvc-persisted-remember-me - spring-security-mvc-session + spring-security-mvc spring-security-mvc-socket spring-security-openid @@ -916,7 +916,7 @@ spring-security-mvc-digest-auth spring-security-mvc-ldap spring-security-mvc-persisted-remember-me - spring-security-mvc-session + spring-security-mvc spring-security-mvc-socket spring-security-rest spring-security-sso @@ -1407,7 +1407,7 @@ spring-security-mvc-ldap spring-security-mvc-login spring-security-mvc-persisted-remember-me - spring-security-mvc-session + spring-security-mvc spring-security-mvc-socket spring-security-openid diff --git a/spring-security-mvc-session/.gitignore b/spring-security-mvc/.gitignore similarity index 100% rename from spring-security-mvc-session/.gitignore rename to spring-security-mvc/.gitignore diff --git a/spring-security-mvc-session/README.md b/spring-security-mvc/README.md similarity index 100% rename from spring-security-mvc-session/README.md rename to spring-security-mvc/README.md diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc/pom.xml similarity index 96% rename from spring-security-mvc-session/pom.xml rename to spring-security-mvc/pom.xml index 5ed7fbecd3..98ad3daa46 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc/pom.xml @@ -3,9 +3,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - spring-security-mvc-session + spring-security-mvc 0.1-SNAPSHOT - spring-security-mvc-session + spring-security-mvc jar diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/SpringSessionApplication.java b/spring-security-mvc/src/main/java/com/baeldung/SpringSessionApplication.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/SpringSessionApplication.java rename to spring-security-mvc/src/main/java/com/baeldung/SpringSessionApplication.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java b/spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java rename to spring-security-mvc/src/main/java/com/baeldung/monitoring/MetricRegistrySingleton.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-mvc/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java rename to spring-security-mvc/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/security/SessionFilter.java b/spring-security-mvc/src/main/java/com/baeldung/security/SessionFilter.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/security/SessionFilter.java rename to spring-security-mvc/src/main/java/com/baeldung/security/SessionFilter.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/spring/MvcConfig.java b/spring-security-mvc/src/main/java/com/baeldung/spring/MvcConfig.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/spring/MvcConfig.java rename to spring-security-mvc/src/main/java/com/baeldung/spring/MvcConfig.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc/src/main/java/com/baeldung/spring/SecSecurityConfig.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/spring/SecSecurityConfig.java rename to spring-security-mvc/src/main/java/com/baeldung/spring/SecSecurityConfig.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java b/spring-security-mvc/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java rename to spring-security-mvc/src/main/java/com/baeldung/web/SessionListenerWithMetrics.java diff --git a/spring-security-mvc-session/src/main/java/com/baeldung/web/SessionRestController.java b/spring-security-mvc/src/main/java/com/baeldung/web/SessionRestController.java similarity index 100% rename from spring-security-mvc-session/src/main/java/com/baeldung/web/SessionRestController.java rename to spring-security-mvc/src/main/java/com/baeldung/web/SessionRestController.java diff --git a/spring-security-mvc-session/src/main/resources/application.properties b/spring-security-mvc/src/main/resources/application.properties similarity index 100% rename from spring-security-mvc-session/src/main/resources/application.properties rename to spring-security-mvc/src/main/resources/application.properties diff --git a/spring-security-mvc-session/src/main/resources/logback.xml b/spring-security-mvc/src/main/resources/logback.xml similarity index 100% rename from spring-security-mvc-session/src/main/resources/logback.xml rename to spring-security-mvc/src/main/resources/logback.xml diff --git a/spring-security-mvc-session/src/main/resources/webSecurityConfig.xml b/spring-security-mvc/src/main/resources/webSecurityConfig.xml similarity index 100% rename from spring-security-mvc-session/src/main/resources/webSecurityConfig.xml rename to spring-security-mvc/src/main/resources/webSecurityConfig.xml diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-security-mvc/src/main/webapp/WEB-INF/mvc-servlet.xml similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/mvc-servlet.xml rename to spring-security-mvc/src/main/webapp/WEB-INF/mvc-servlet.xml diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/anonymous.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/anonymous.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/anonymous.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/anonymous.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/console.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/console.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/console.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/homepage.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/homepage.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/homepage.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/invalidSession.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/invalidSession.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/invalidSession.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/invalidSession.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/login.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/login.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/login.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/view/sessionExpired.jsp b/spring-security-mvc/src/main/webapp/WEB-INF/view/sessionExpired.jsp similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/view/sessionExpired.jsp rename to spring-security-mvc/src/main/webapp/WEB-INF/view/sessionExpired.jsp diff --git a/spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml b/spring-security-mvc/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-security-mvc-session/src/main/webapp/WEB-INF/web.xml rename to spring-security-mvc/src/main/webapp/WEB-INF/web.xml diff --git a/spring-security-mvc-session/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc/src/test/java/com/baeldung/SpringContextIntegrationTest.java similarity index 100% rename from spring-security-mvc-session/src/test/java/com/baeldung/SpringContextIntegrationTest.java rename to spring-security-mvc/src/test/java/com/baeldung/SpringContextIntegrationTest.java diff --git a/spring-security-mvc-session/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java b/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java similarity index 100% rename from spring-security-mvc-session/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java rename to spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java diff --git a/spring-security-mvc-session/src/test/resources/.gitignore b/spring-security-mvc/src/test/resources/.gitignore similarity index 100% rename from spring-security-mvc-session/src/test/resources/.gitignore rename to spring-security-mvc/src/test/resources/.gitignore From 29e2806ade867f6189db6ba76aa1dbac73bdcf52 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Fri, 26 Jul 2019 00:26:13 +0530 Subject: [PATCH 301/352] [BAEL-10984-1] - Added new URL for MyUIServlet and updated Grid creation logic --- .../java/com/baeldung/introduction/Row.java | 45 +++++++++++++++++++ .../com/baeldung/introduction/VaadinUI.java | 14 +++--- 2 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 vaadin/src/main/java/com/baeldung/introduction/Row.java diff --git a/vaadin/src/main/java/com/baeldung/introduction/Row.java b/vaadin/src/main/java/com/baeldung/introduction/Row.java new file mode 100644 index 0000000000..412a286376 --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/introduction/Row.java @@ -0,0 +1,45 @@ +package com.baeldung.introduction; + +public class Row { + + private String column1; + + private String column2; + + private String column3; + + public Row() { + + } + + public Row(String column1, String column2, String column3) { + super(); + this.column1 = column1; + this.column2 = column2; + this.column3 = column3; + } + + public String getColumn1() { + return column1; + } + + public void setColumn1(String column1) { + this.column1 = column1; + } + + public String getColumn2() { + return column2; + } + + public void setColumn2(String column2) { + this.column2 = column2; + } + + public String getColumn3() { + return column3; + } + + public void setColumn3(String column3) { + this.column3 = column3; + } +} \ No newline at end of file diff --git a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java index 68be53b1b3..22ce19f5e0 100644 --- a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java +++ b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java @@ -201,10 +201,14 @@ public class VaadinUI extends UI { TwinColSelect twinColSelect = new TwinColSelect("TwinColSelect"); twinColSelect.setItems(numbers); - Grid grid = new Grid("Grid"); - grid.setColumns("Column1", "Column2", "Column3"); - grid.setItems("Item1", "Item2", "Item3"); - grid.setItems("Item4", "Item5", "Item6"); + Grid grid = new Grid(Row.class); + grid.setColumns("column1", "column2", "column3"); + Row row1 = new Row("Item1", "Item2", "Item3"); + Row row2 = new Row("Item4", "Item5", "Item6"); + List rows = new ArrayList(); + rows.add(row1); + rows.add(row2); + grid.setItems(rows); Panel panel = new Panel("Panel"); panel.setContent(grid); @@ -271,7 +275,7 @@ public class VaadinUI extends UI { setContent(verticalLayout); } - @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true) + @WebServlet(urlPatterns = "/VAADIN/*", name = "MyUIServlet", asyncSupported = true) @VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false) public static class MyUIServlet extends VaadinServlet { } From 0d7a1747cc3c421174b42016cda053141350a686 Mon Sep 17 00:00:00 2001 From: Carlos Cano Date: Thu, 25 Jul 2019 21:09:02 +0200 Subject: [PATCH 302/352] Checking if an array is sorted in java (#7385) * SortedArrayChecker * add recursivity method with custom object * change test names * add new case with comparator * update methods with comparable param * format * fix test * change sign by comparable * change employee by object. Rename method --- .../baeldung/array/SortedArrayChecker.java | 38 ++++++++----------- .../array/SortedArrayCheckerUnitTest.java | 30 +++++++++------ 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java index ec612fd53b..78a9a8f4d1 100644 --- a/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java +++ b/core-java-modules/core-java-arrays/src/main/java/com/baeldung/array/SortedArrayChecker.java @@ -2,7 +2,10 @@ package com.baeldung.array; import com.baeldung.arraycopy.model.Employee; +import java.util.Comparator; + public class SortedArrayChecker { + boolean isSorted(int[] array, int length) { if (array == null || length < 2) return true; @@ -22,7 +25,7 @@ public class SortedArrayChecker { return true; } - boolean isSorted(String[] array, int length) { + boolean isSorted(Comparable[] array, int length) { if (array == null || length < 2) return true; @@ -32,40 +35,31 @@ public class SortedArrayChecker { return isSorted(array, length - 1); } -boolean isSorted(String[] array) { - for (int i = 0; i < array.length - 1; ++i) { - if (array[i].compareTo(array[i + 1]) > 0) - return false; - } - - return true; -} - - boolean isSortedByName(Employee[] array) { + boolean isSorted(Comparable[] array) { for (int i = 0; i < array.length - 1; ++i) { - if (array[i].getName().compareTo(array[i + 1].getName()) > 0) + if (array[i].compareTo(array[i + 1]) > 0) return false; } return true; } -boolean isSortedByAge(Employee[] array) { - for (int i = 0; i < array.length - 1; ++i) { - if (array[i].getAge() > (array[i + 1].getAge())) - return false; + boolean isSorted(Object[] array, Comparator comparator) { + for (int i = 0; i < array.length - 1; ++i) { + if (comparator.compare(array[i], (array[i + 1])) > 0) + return false; + } + + return true; } - return true; -} - - boolean isSortedByAge(Employee[] array, int length) { + boolean isSorted(Object[] array, Comparator comparator, int length) { if (array == null || length < 2) return true; - if (array[length - 2].getAge() > array[length - 1].getAge()) + if (comparator.compare(array[length - 2], array[length - 1]) > 0) return false; - return isSortedByAge(array, length - 1); + return isSorted(array, comparator, length - 1); } } diff --git a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java index 29866a3c22..7971e0eab7 100644 --- a/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java +++ b/core-java-modules/core-java-arrays/src/test/java/com/baeldung/array/SortedArrayCheckerUnitTest.java @@ -4,32 +4,33 @@ import com.baeldung.arraycopy.model.Employee; import org.junit.Before; import org.junit.Test; +import java.util.Comparator; + import static org.assertj.core.api.Assertions.assertThat; -class SortedArrayCheckerUnitTest { - +public class SortedArrayCheckerUnitTest { private static final int[] INTEGER_SORTED = {1, 3, 5, 7, 9}; private static final int[] INTEGER_NOT_SORTED = {1, 3, 11, 7}; private static final String[] STRING_SORTED = {"abc", "cde", "fgh"}; private static final String[] STRING_NOT_SORTED = {"abc", "fgh", "cde", "ijk"}; - private final Employee[] EMPLOYEES_SORTED_BY_NAME = { + private static final Employee[] EMPLOYEES_SORTED_BY_NAME = { new Employee(1, "Carlos", 26), new Employee(2, "Daniel", 31), new Employee(3, "Marta", 27)}; - private final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = { + private static final Employee[] EMPLOYEES_NOT_SORTED_BY_NAME = { new Employee(1, "Daniel", 31), new Employee(2, "Carlos", 26), new Employee(3, "Marta", 27)}; - private final Employee[] EMPLOYEES_SORTED_BY_AGE = { + private static final Employee[] EMPLOYEES_SORTED_BY_AGE = { new Employee(1, "Carlos", 26), new Employee(2, "Marta", 27), new Employee(3, "Daniel", 31)}; - private final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = { + private static final Employee[] EMPLOYEES_NOT_SORTED_BY_AGE = { new Employee(1, "Marta", 27), new Employee(2, "Carlos", 26), new Employee(3, "Daniel", 31)}; @@ -61,13 +62,18 @@ class SortedArrayCheckerUnitTest { @Test public void givenEmployeeArray_thenReturnIfItIsSortedOrNot() { - assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_SORTED_BY_NAME)).isEqualTo(true); - assertThat(sortedArrayChecker.isSortedByName(EMPLOYEES_NOT_SORTED_BY_NAME)).isEqualTo(false); + assertThat(sortedArrayChecker.isSorted(EMPLOYEES_SORTED_BY_NAME, Comparator.comparing(Employee::getName))).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(EMPLOYEES_NOT_SORTED_BY_NAME, Comparator.comparing(Employee::getName))).isEqualTo(false); - assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE)).isEqualTo(true); - assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE)).isEqualTo(false); + assertThat(sortedArrayChecker.isSorted(EMPLOYEES_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge))).isEqualTo(true); + assertThat(sortedArrayChecker.isSorted(EMPLOYEES_NOT_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge))).isEqualTo(false); - assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_SORTED_BY_AGE, EMPLOYEES_SORTED_BY_AGE.length)).isEqualTo(true); - assertThat(sortedArrayChecker.isSortedByAge(EMPLOYEES_NOT_SORTED_BY_AGE, EMPLOYEES_NOT_SORTED_BY_AGE.length)).isEqualTo(false); + assertThat(sortedArrayChecker + .isSorted(EMPLOYEES_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge), EMPLOYEES_SORTED_BY_AGE.length)) + .isEqualTo(true); + assertThat(sortedArrayChecker + .isSorted(EMPLOYEES_NOT_SORTED_BY_AGE, Comparator.comparingInt(Employee::getAge), EMPLOYEES_NOT_SORTED_BY_AGE.length)) + .isEqualTo(false); } + } \ No newline at end of file From 5b5733239c06b595649324d744e97c6a2dc97d68 Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 25 Jul 2019 23:11:26 +0300 Subject: [PATCH 303/352] depth first search --- .../main/java/com/baeldung/graph/Graph.java | 71 +++++++++++++++++++ .../java/com/baeldung/tree/BinaryTree.java | 63 ++++++++++++++++ .../com/baeldung/graph/GraphUnitTest.java | 31 ++++++++ .../com/baeldung/tree/BinaryTreeUnitTest.java | 6 ++ 4 files changed, 171 insertions(+) create mode 100644 data-structures/src/main/java/com/baeldung/graph/Graph.java create mode 100644 data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java diff --git a/data-structures/src/main/java/com/baeldung/graph/Graph.java b/data-structures/src/main/java/com/baeldung/graph/Graph.java new file mode 100644 index 0000000000..b20301f86f --- /dev/null +++ b/data-structures/src/main/java/com/baeldung/graph/Graph.java @@ -0,0 +1,71 @@ +package com.baeldung.graph; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public class Graph { + + private List> neighbours; + private int n; + + public Graph(int n) { + this.n = n; + this.neighbours = new ArrayList>(n); + for (int i = 0; i < n; i++) { + this.neighbours.add(new ArrayList()); + } + } + + public void addEdge(int src, int dest) { + this.neighbours.get(src) + .add(dest); + } + + public void dfsWithoutRecursion(int start) { + Stack stack = new Stack(); + boolean[] isVisited = new boolean[n]; + stack.push(start); + while (!stack.isEmpty()) { + int current = stack.pop(); + isVisited[current] = true; + System.out.print(" " + current); + for (int dest : neighbours.get(current)) { + if (!isVisited[dest]) + stack.push(dest); + } + } + } + + public void dfs(int start) { + boolean[] isVisited = new boolean[n]; + dfsRecursive(start, isVisited); + } + + private void dfsRecursive(int current, boolean[] isVisited) { + isVisited[current] = true; + System.out.print(" " + current); + for (int dest : neighbours.get(current)) { + if (!isVisited[dest]) + dfsRecursive(dest, isVisited); + } + } + + public void topologicalSort(int start) { + Stack result = new Stack(); + boolean[] isVisited = new boolean[n]; + topologicalSortRecursive(start, isVisited, result); + while (!result.isEmpty()) { + System.out.print(" " + result.pop()); + } + } + + private void topologicalSortRecursive(int current, boolean[] isVisited, Stack result) { + isVisited[current] = true; + for (int dest : neighbours.get(current)) { + if (!isVisited[dest]) + topologicalSortRecursive(dest, isVisited, result); + } + result.push(current); + } +} diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java index f435e41afa..ff73ee8e54 100644 --- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java @@ -2,6 +2,7 @@ package com.baeldung.tree; import java.util.LinkedList; import java.util.Queue; +import java.util.Stack; public class BinaryTree { @@ -147,6 +148,68 @@ public class BinaryTree { } } + + public void traverseInOrderWithoutRecursion() { + Stack stack = new Stack(); + Node current = root; + stack.push(root); + while(! stack.isEmpty()) { + while(current.left != null) { + current = current.left; + stack.push(current); + } + current = stack.pop(); + System.out.print(" " + current.value); + if(current.right != null) { + current = current.right; + stack.push(current); + } + } + } + + public void traversePreOrderWithoutRecursion() { + Stack stack = new Stack(); + Node current = root; + stack.push(root); + while(! stack.isEmpty()) { + current = stack.pop(); + System.out.print(" " + current.value); + + if(current.right != null) + stack.push(current.right); + + if(current.left != null) + stack.push(current.left); + } + } + + public void traversePostOrderWithoutRecursion() { + Stack stack = new Stack(); + Node prev = root; + Node current = root; + stack.push(root); + + while (!stack.isEmpty()) { + current = stack.peek(); + boolean hasChild = (current.left != null || current.right != null); + boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null)); + + if (!hasChild || isPrevLastChild) { + current = stack.pop(); + System.out.print(" " + current.value); + prev = current; + } else { + if (current.right != null) { + stack.push(current.right); + } + if (current.left != null) { + stack.push(current.left); + } + } + } + } + + class Node { int value; Node left; diff --git a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java new file mode 100644 index 0000000000..837f83b494 --- /dev/null +++ b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.graph; + +import org.junit.Test; + +public class GraphUnitTest { + + @Test + public void givenDirectedGraph_whenDFS_thenPrintAllValues() { + Graph graph = createDirectedGraph(); + graph.dfs(0); + System.out.println(); + graph.dfsWithoutRecursion(0); + } + + @Test + public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() { + Graph graph = createDirectedGraph(); + graph.topologicalSort(0); + } + + private Graph createDirectedGraph() { + Graph graph = new Graph(6); + graph.addEdge(0, 1); + graph.addEdge(0, 2); + graph.addEdge(1, 3); + graph.addEdge(2, 3); + graph.addEdge(3, 4); + graph.addEdge(4, 5); + return graph; + } +} diff --git a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java index f81247b74d..f99cb52ed7 100644 --- a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java +++ b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java @@ -87,6 +87,8 @@ public class BinaryTreeUnitTest { BinaryTree bt = createBinaryTree(); bt.traverseInOrder(bt.root); + System.out.println(); + bt.traverseInOrderWithoutRecursion(); } @Test @@ -95,6 +97,8 @@ public class BinaryTreeUnitTest { BinaryTree bt = createBinaryTree(); bt.traversePreOrder(bt.root); + System.out.println(); + bt.traversePreOrderWithoutRecursion(); } @Test @@ -103,6 +107,8 @@ public class BinaryTreeUnitTest { BinaryTree bt = createBinaryTree(); bt.traversePostOrder(bt.root); + System.out.println(); + bt.traversePostOrderWithoutRecursion(); } @Test From ba8d468603c6544d3269b495080e2858d6ae1695 Mon Sep 17 00:00:00 2001 From: vatsalgosar Date: Fri, 26 Jul 2019 02:01:33 +0530 Subject: [PATCH 304/352] module changed --- .../spring-boot-configuration/README.md | 6 --- .../spring-boot-configuration/pom.xml | 42 ------------------- .../ServiceImpl/PersonServiceImpl.java | 6 --- .../com/baeldung/service/PersonService.java | 4 -- .../java/com/baeldung/ApplicationTests.java | 16 ------- .../springbootconfiguration}/Application.java | 6 +-- .../ServiceImpl/PersonServiceImpl.java | 6 +++ .../service/PersonService.java | 4 ++ 8 files changed, 13 insertions(+), 77 deletions(-) delete mode 100644 spring-boot-bootstrap/spring-boot-configuration/README.md delete mode 100644 spring-boot-bootstrap/spring-boot-configuration/pom.xml delete mode 100644 spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/ServiceImpl/PersonServiceImpl.java delete mode 100644 spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java delete mode 100644 spring-boot-bootstrap/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java rename spring-boot-bootstrap/{spring-boot-configuration/src/main/java/com/baeldung => src/main/java/com/baeldung/springbootconfiguration}/Application.java (74%) create mode 100644 spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/ServiceImpl/PersonServiceImpl.java create mode 100644 spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/service/PersonService.java diff --git a/spring-boot-bootstrap/spring-boot-configuration/README.md b/spring-boot-bootstrap/spring-boot-configuration/README.md deleted file mode 100644 index d5ec5f63da..0000000000 --- a/spring-boot-bootstrap/spring-boot-configuration/README.md +++ /dev/null @@ -1,6 +0,0 @@ -Article: -SprintBootConfiguration annotation - -commands: -mvn clean install -mvn spring-boot:run diff --git a/spring-boot-bootstrap/spring-boot-configuration/pom.xml b/spring-boot-bootstrap/spring-boot-configuration/pom.xml deleted file mode 100644 index d7b4122c20..0000000000 --- a/spring-boot-bootstrap/spring-boot-configuration/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.1.6.RELEASE - - - com.baeldung - spring-boot-configuration - 0.0.1-SNAPSHOT - spring-boot-configuration - Demo project for Spring Boot Configuration - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/ServiceImpl/PersonServiceImpl.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/ServiceImpl/PersonServiceImpl.java deleted file mode 100644 index f08fbaa7f2..0000000000 --- a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/ServiceImpl/PersonServiceImpl.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.ServiceImpl; - -import com.baeldung.service.PersonService; - -public class PersonServiceImpl implements PersonService { -} diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java b/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java deleted file mode 100644 index e959e3b835..0000000000 --- a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/service/PersonService.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.baeldung.service; - -public interface PersonService { -} diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java b/spring-boot-bootstrap/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java deleted file mode 100644 index 3bd3cc2ec6..0000000000 --- a/spring-boot-bootstrap/spring-boot-configuration/src/test/java/com/baeldung/ApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class ApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/Application.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java similarity index 74% rename from spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/Application.java rename to spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java index 15adb4bb3e..ef9df2bf4a 100644 --- a/spring-boot-bootstrap/spring-boot-configuration/src/main/java/com/baeldung/Application.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java @@ -1,12 +1,12 @@ -package com.baeldung; +package com.baeldung.springbootconfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -import com.baeldung.ServiceImpl.PersonServiceImpl; -import com.baeldung.service.PersonService; +import com.baeldung.springbootconfiguration.ServiceImpl.PersonServiceImpl; +import com.baeldung.springbootconfiguration.service.PersonService; @ComponentScan(basePackages = { "com.baeldung.*" }) @SpringBootConfiguration diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/ServiceImpl/PersonServiceImpl.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/ServiceImpl/PersonServiceImpl.java new file mode 100644 index 0000000000..3bec4e4b12 --- /dev/null +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/ServiceImpl/PersonServiceImpl.java @@ -0,0 +1,6 @@ +package com.baeldung.springbootconfiguration.ServiceImpl; + +import com.baeldung.springbootconfiguration.service.PersonService; + +public class PersonServiceImpl implements PersonService { +} diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/service/PersonService.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/service/PersonService.java new file mode 100644 index 0000000000..5a18edde33 --- /dev/null +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/service/PersonService.java @@ -0,0 +1,4 @@ +package com.baeldung.springbootconfiguration.service; + +public interface PersonService { +} From 8358d5b2ecc5e9fe6889bfc593f31c8387d0028d Mon Sep 17 00:00:00 2001 From: Rodrigo Graciano Date: Thu, 25 Jul 2019 22:14:58 -0400 Subject: [PATCH 305/352] Rename unit test to follow naming standards --- .../{HelloResourceTest.java => HelloResourceUnitTest.java} | 2 +- .../test/java/com/baeldung/quarkus/NativeHelloResourceIT.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename quarkus/src/test/java/com/baeldung/quarkus/{HelloResourceTest.java => HelloResourceUnitTest.java} (91%) diff --git a/quarkus/src/test/java/com/baeldung/quarkus/HelloResourceTest.java b/quarkus/src/test/java/com/baeldung/quarkus/HelloResourceUnitTest.java similarity index 91% rename from quarkus/src/test/java/com/baeldung/quarkus/HelloResourceTest.java rename to quarkus/src/test/java/com/baeldung/quarkus/HelloResourceUnitTest.java index 3d0fff7562..a5ed99f585 100644 --- a/quarkus/src/test/java/com/baeldung/quarkus/HelloResourceTest.java +++ b/quarkus/src/test/java/com/baeldung/quarkus/HelloResourceUnitTest.java @@ -7,7 +7,7 @@ import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; @QuarkusTest -public class HelloResourceTest { +public class HelloResourceUnitTest { @Test public void testHelloEndpoint() { diff --git a/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java b/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java index 4b0606f588..9ada64b6a5 100644 --- a/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java +++ b/quarkus/src/test/java/com/baeldung/quarkus/NativeHelloResourceIT.java @@ -3,7 +3,7 @@ package com.baeldung.quarkus; import io.quarkus.test.junit.SubstrateTest; @SubstrateTest -public class NativeHelloResourceIT extends HelloResourceTest { +public class NativeHelloResourceIT extends HelloResourceUnitTest { // Execute the same tests but in native mode. } \ No newline at end of file From c7433926c5122f639a90fa646b661531640ac064 Mon Sep 17 00:00:00 2001 From: Sam Millington Date: Fri, 26 Jul 2019 05:18:20 +0100 Subject: [PATCH 306/352] [BAEL-2951] - Sorting a string that may contain a number code (#7388) --- .../NaturalOrderComparators.java | 30 +++++++ .../NaturalOrderComparatorsUnitTest.java | 79 +++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java create mode 100644 algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java new file mode 100644 index 0000000000..376b196aa1 --- /dev/null +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java @@ -0,0 +1,30 @@ +package com.baeldung.algorithms.stringsortingbynumber; + +import java.util.Comparator; + +public final class NaturalOrderComparators { + + private static final String DIGIT_AND_DECIMAL_REGEX = "[^\\d.]"; + + private NaturalOrderComparators() { + throw new AssertionError("Let's keep this static"); + } + + public static Comparator createNaturalOrderRegexComparator() { + return Comparator.comparingDouble(NaturalOrderComparators::parseStringToNumber); + } + + private static double parseStringToNumber(String input){ + + final String digitsOnly = input.replaceAll(DIGIT_AND_DECIMAL_REGEX, ""); + + if("".equals(digitsOnly)) return 0; + + try{ + return Double.parseDouble(digitsOnly); + }catch (NumberFormatException nfe){ + return 0; + } + } + +} diff --git a/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java new file mode 100644 index 0000000000..549151bc93 --- /dev/null +++ b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java @@ -0,0 +1,79 @@ +package com.baeldung.algorithms.stringsortingbynumber; + +import com.baeldung.algorithms.stringsortingbynumber.NaturalOrderComparators; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +public class NaturalOrderComparatorsUnitTest { + + @Test + public void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() { + + List testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d"); + + testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); + + List expected = Arrays.asList("a1", "d2.2", "d2.3d", "d2.4", "b3", "c4"); + + assertEquals(expected, testStrings); + + + } + + @Test + public void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() { + + List testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d"); + + testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); + + List expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.4", "b3", "c4"); + + assertEquals(expected, testStrings); + + + } + + @Test + public void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() { + + List testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d"); + + testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); + + List expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.f4", "b3", "c4"); + + assertEquals(expected, testStrings); + + + } + + @Test + public void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() { + + List testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5 + + List expected = Arrays.asList("b3ght3.2", "something65.thensomething5", "a1b2c5" ); + + testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); + + assertEquals(expected, testStrings); + + } + + @Test + public void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() { + + List testStrings = Arrays.asList("a", "c", "d", "e"); + List expected = new ArrayList<>(testStrings); + + testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator()); + + assertEquals(expected, testStrings); + } +} \ No newline at end of file From 76bb391379d56032ce55b4559c5fc0e67638e279 Mon Sep 17 00:00:00 2001 From: psevestre Date: Fri, 26 Jul 2019 01:32:23 -0300 Subject: [PATCH 307/352] [BAEL-2284] R2DBC Sample Project (#7314) * [BAEL-2284] Sample project * [BAEL-2284] Sample project * [BAEL-2284] Sample code adjustments * [BAEL-2284] Sample code adjustments * [BAEL-2284] Sample code adjustments * [BAEL-2284] Add README --- persistence-modules/pom.xml | 1 + persistence-modules/r2dbc/.gitignore | 31 ++ .../.mvn/wrapper/MavenWrapperDownloader.java | 114 +++++++ .../r2dbc/.mvn/wrapper/maven-wrapper.jar | Bin 0 -> 48337 bytes .../.mvn/wrapper/maven-wrapper.properties | 1 + persistence-modules/r2dbc/README.md | 3 + persistence-modules/r2dbc/mvnw | 286 ++++++++++++++++++ persistence-modules/r2dbc/mvnw.cmd | 161 ++++++++++ persistence-modules/r2dbc/pom.xml | 90 ++++++ .../org/baeldung/examples/r2dbc/Account.java | 68 +++++ .../examples/r2dbc/AccountResource.java | 56 ++++ .../examples/r2dbc/DatasourceConfig.java | 65 ++++ .../r2dbc/R2DBCConfigurationProperties.java | 58 ++++ .../r2dbc/R2dbcExampleApplication.java | 17 ++ .../examples/r2dbc/ReactiveAccountDao.java | 76 +++++ ...itional-spring-configuration-metadata.json | 5 + .../r2dbc/src/main/resources/application.yml | 13 + .../r2dbc/R2dbcExampleApplicationTests.java | 102 +++++++ .../r2dbc/src/test/resources/application.yml | 6 + spring-cloud/spring-cloud-vault/pom.xml | 12 + .../spring/cloud/vaultsample/AccountRepo.java | 10 + .../cloud/vaultsample/AccountResource.java | 27 ++ .../cloud/vaultsample/SecretResource.java | 37 +++ .../cloud/vaultsample/domain/Account.java | 133 ++++++++ .../src/main/resources/application.yml | 17 +- .../src/main/resources/bootstrap.yml | 20 +- .../src/test/vault-config/vault-test.hcl | 3 + .../spring-cloud-vault/vault-cheatsheet.txt | 19 +- .../spring-cloud-vault/vault-unseal.bat | 8 +- 29 files changed, 1408 insertions(+), 31 deletions(-) create mode 100644 persistence-modules/r2dbc/.gitignore create mode 100644 persistence-modules/r2dbc/.mvn/wrapper/MavenWrapperDownloader.java create mode 100644 persistence-modules/r2dbc/.mvn/wrapper/maven-wrapper.jar create mode 100644 persistence-modules/r2dbc/.mvn/wrapper/maven-wrapper.properties create mode 100644 persistence-modules/r2dbc/README.md create mode 100644 persistence-modules/r2dbc/mvnw create mode 100644 persistence-modules/r2dbc/mvnw.cmd create mode 100644 persistence-modules/r2dbc/pom.xml create mode 100644 persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/Account.java create mode 100644 persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/AccountResource.java create mode 100644 persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/DatasourceConfig.java create mode 100644 persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2DBCConfigurationProperties.java create mode 100644 persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2dbcExampleApplication.java create mode 100644 persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/ReactiveAccountDao.java create mode 100644 persistence-modules/r2dbc/src/main/resources/META-INF/additional-spring-configuration-metadata.json create mode 100644 persistence-modules/r2dbc/src/main/resources/application.yml create mode 100644 persistence-modules/r2dbc/src/test/java/org/baeldung/examples/r2dbc/R2dbcExampleApplicationTests.java create mode 100644 persistence-modules/r2dbc/src/test/resources/application.yml create mode 100644 spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountRepo.java create mode 100644 spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountResource.java create mode 100644 spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/SecretResource.java create mode 100644 spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/domain/Account.java diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 390bcc9d51..849c904604 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -58,5 +58,6 @@ spring-jpa spring-persistence-simple jpa-hibernate-cascade-type + r2dbc
    diff --git a/persistence-modules/r2dbc/.gitignore b/persistence-modules/r2dbc/.gitignore new file mode 100644 index 0000000000..a2a3040aa8 --- /dev/null +++ b/persistence-modules/r2dbc/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/persistence-modules/r2dbc/.mvn/wrapper/MavenWrapperDownloader.java b/persistence-modules/r2dbc/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000000..72308aa479 --- /dev/null +++ b/persistence-modules/r2dbc/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: : " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/persistence-modules/r2dbc/.mvn/wrapper/maven-wrapper.jar b/persistence-modules/r2dbc/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..01e67997377a393fd672c7dcde9dccbedf0cb1e9 GIT binary patch literal 48337 zcmbTe1CV9Qwl>;j+wQV$+qSXFw%KK)%eHN!%U!l@+x~l>b1vR}@9y}|TM-#CBjy|< zb7YRpp)Z$$Gzci_H%LgxZ{NNV{%Qa9gZlF*E2<($D=8;N5Asbx8se{Sz5)O13x)rc z5cR(k$_mO!iis+#(8-D=#R@|AF(8UQ`L7dVNSKQ%v^P|1A%aF~Lye$@HcO@sMYOb3 zl`5!ThJ1xSJwsg7hVYFtE5vS^5UE0$iDGCS{}RO;R#3y#{w-1hVSg*f1)7^vfkxrm!!N|oTR0Hj?N~IbVk+yC#NK} z5myv()UMzV^!zkX@O=Yf!(Z_bF7}W>k*U4@--&RH0tHiHY0IpeezqrF#@8{E$9d=- z7^kT=1Bl;(Q0k{*_vzz1Et{+*lbz%mkIOw(UA8)EE-Pkp{JtJhe@VXQ8sPNTn$Vkj zicVp)sV%0omhsj;NCmI0l8zzAipDV#tp(Jr7p_BlL$}Pys_SoljztS%G-Wg+t z&Q#=<03Hoga0R1&L!B);r{Cf~b$G5p#@?R-NNXMS8@cTWE^7V!?ixz(Ag>lld;>COenWc$RZ61W+pOW0wh>sN{~j; zCBj!2nn|4~COwSgXHFH?BDr8pK323zvmDK-84ESq25b;Tg%9(%NneBcs3;r znZpzntG%E^XsSh|md^r-k0Oen5qE@awGLfpg;8P@a-s<{Fwf?w3WapWe|b-CQkqlo z46GmTdPtkGYdI$e(d9Zl=?TU&uv94VR`g|=7xB2Ur%=6id&R2 z4e@fP7`y58O2sl;YBCQFu7>0(lVt-r$9|06Q5V>4=>ycnT}Fyz#9p;3?86`ZD23@7 z7n&`!LXzjxyg*P4Tz`>WVvpU9-<5MDSDcb1 zZaUyN@7mKLEPGS$^odZcW=GLe?3E$JsMR0kcL4#Z=b4P94Q#7O%_60{h>0D(6P*VH z3}>$stt2s!)w4C4 z{zsj!EyQm$2ARSHiRm49r7u)59ZyE}ZznFE7AdF&O&!-&(y=?-7$LWcn4L_Yj%w`qzwz`cLqPRem1zN; z)r)07;JFTnPODe09Z)SF5@^uRuGP~Mjil??oWmJTaCb;yx4?T?d**;AW!pOC^@GnT zaY`WF609J>fG+h?5&#}OD1<%&;_lzM2vw70FNwn2U`-jMH7bJxdQM#6+dPNiiRFGT z7zc{F6bo_V%NILyM?rBnNsH2>Bx~zj)pJ}*FJxW^DC2NLlOI~18Mk`7sl=t`)To6Ui zu4GK6KJx^6Ms4PP?jTn~jW6TOFLl3e2-q&ftT=31P1~a1%7=1XB z+H~<1dh6%L)PbBmtsAr38>m~)?k3}<->1Bs+;227M@?!S+%X&M49o_e)X8|vZiLVa z;zWb1gYokP;Sbao^qD+2ZD_kUn=m=d{Q9_kpGxcbdQ0d5<_OZJ!bZJcmgBRf z!Cdh`qQ_1NLhCulgn{V`C%|wLE8E6vq1Ogm`wb;7Dj+xpwik~?kEzDT$LS?#%!@_{ zhOoXOC95lVcQU^pK5x$Da$TscVXo19Pps zA!(Mk>N|tskqBn=a#aDC4K%jV#+qI$$dPOK6;fPO)0$0j$`OV+mWhE+TqJoF5dgA=TH-}5DH_)H_ zh?b(tUu@65G-O)1ah%|CsU8>cLEy0!Y~#ut#Q|UT92MZok0b4V1INUL-)Dvvq`RZ4 zTU)YVX^r%_lXpn_cwv`H=y49?!m{krF3Rh7O z^z7l4D<+^7E?ji(L5CptsPGttD+Z7{N6c-`0V^lfFjsdO{aJMFfLG9+wClt<=Rj&G zf6NgsPSKMrK6@Kvgarmx{&S48uc+ZLIvk0fbH}q-HQ4FSR33$+%FvNEusl6xin!?e z@rrWUP5U?MbBDeYSO~L;S$hjxISwLr&0BOSd?fOyeCWm6hD~)|_9#jo+PVbAY3wzf zcZS*2pX+8EHD~LdAl>sA*P>`g>>+&B{l94LNLp#KmC)t6`EPhL95s&MMph46Sk^9x%B$RK!2MI--j8nvN31MNLAJBsG`+WMvo1}xpaoq z%+W95_I`J1Pr&Xj`=)eN9!Yt?LWKs3-`7nf)`G6#6#f+=JK!v943*F&veRQxKy-dm(VcnmA?K_l~ zfDWPYl6hhN?17d~^6Zuo@>Hswhq@HrQ)sb7KK^TRhaM2f&td)$6zOn7we@ zd)x4-`?!qzTGDNS-E(^mjM%d46n>vPeMa;%7IJDT(nC)T+WM5F-M$|p(78W!^ck6)A_!6|1o!D97tw8k|5@0(!8W&q9*ovYl)afk z2mxnniCOSh7yHcSoEu8k`i15#oOi^O>uO_oMpT=KQx4Ou{&C4vqZG}YD0q!{RX=`#5wmcHT=hqW3;Yvg5Y^^ ziVunz9V)>2&b^rI{ssTPx26OxTuCw|+{tt_M0TqD?Bg7cWN4 z%UH{38(EW1L^!b~rtWl)#i}=8IUa_oU8**_UEIw+SYMekH;Epx*SA7Hf!EN&t!)zuUca@_Q^zW(u_iK_ zrSw{nva4E6-Npy9?lHAa;b(O z`I74A{jNEXj(#r|eS^Vfj-I!aHv{fEkzv4=F%z0m;3^PXa27k0Hq#RN@J7TwQT4u7 ztisbp3w6#k!RC~!5g-RyjpTth$lf!5HIY_5pfZ8k#q!=q*n>~@93dD|V>=GvH^`zn zVNwT@LfA8^4rpWz%FqcmzX2qEAhQ|_#u}md1$6G9qD%FXLw;fWWvqudd_m+PzI~g3 z`#WPz`M1XUKfT3&T4~XkUie-C#E`GN#P~S(Zx9%CY?EC?KP5KNK`aLlI1;pJvq@d z&0wI|dx##t6Gut6%Y9c-L|+kMov(7Oay++QemvI`JOle{8iE|2kZb=4x%a32?>-B~ z-%W$0t&=mr+WJ3o8d(|^209BapD`@6IMLbcBlWZlrr*Yrn^uRC1(}BGNr!ct z>xzEMV(&;ExHj5cce`pk%6!Xu=)QWtx2gfrAkJY@AZlHWiEe%^_}mdzvs(6>k7$e; ze4i;rv$_Z$K>1Yo9f4&Jbx80?@X!+S{&QwA3j#sAA4U4#v zwZqJ8%l~t7V+~BT%j4Bwga#Aq0&#rBl6p$QFqS{DalLd~MNR8Fru+cdoQ78Dl^K}@l#pmH1-e3?_0tZKdj@d2qu z_{-B11*iuywLJgGUUxI|aen-((KcAZZdu8685Zi1b(#@_pmyAwTr?}#O7zNB7U6P3 zD=_g*ZqJkg_9_X3lStTA-ENl1r>Q?p$X{6wU6~e7OKNIX_l9T# z>XS?PlNEM>P&ycY3sbivwJYAqbQH^)z@PobVRER*Ud*bUi-hjADId`5WqlZ&o+^x= z-Lf_80rC9>tqFBF%x#`o>69>D5f5Kp->>YPi5ArvgDwV#I6!UoP_F0YtfKoF2YduA zCU!1`EB5;r68;WyeL-;(1K2!9sP)at9C?$hhy(dfKKBf}>skPqvcRl>UTAB05SRW! z;`}sPVFFZ4I%YrPEtEsF(|F8gnfGkXI-2DLsj4_>%$_ZX8zVPrO=_$7412)Mr9BH{ zwKD;e13jP2XK&EpbhD-|`T~aI`N(*}*@yeDUr^;-J_`fl*NTSNbupyHLxMxjwmbuw zt3@H|(hvcRldE+OHGL1Y;jtBN76Ioxm@UF1K}DPbgzf_a{`ohXp_u4=ps@x-6-ZT>F z)dU`Jpu~Xn&Qkq2kg%VsM?mKC)ArP5c%r8m4aLqimgTK$atIxt^b8lDVPEGDOJu!) z%rvASo5|v`u_}vleP#wyu1$L5Ta%9YOyS5;w2I!UG&nG0t2YL|DWxr#T7P#Ww8MXDg;-gr`x1?|V`wy&0vm z=hqozzA!zqjOm~*DSI9jk8(9nc4^PL6VOS$?&^!o^Td8z0|eU$9x8s{8H!9zK|)NO zqvK*dKfzG^Dy^vkZU|p9c+uVV3>esY)8SU1v4o{dZ+dPP$OT@XCB&@GJ<5U&$Pw#iQ9qzuc`I_%uT@%-v zLf|?9w=mc;b0G%%{o==Z7AIn{nHk`>(!e(QG%(DN75xfc#H&S)DzSFB6`J(cH!@mX3mv_!BJv?ByIN%r-i{Y zBJU)}Vhu)6oGoQjT2tw&tt4n=9=S*nQV`D_MSw7V8u1-$TE>F-R6Vo0giKnEc4NYZ zAk2$+Tba~}N0wG{$_7eaoCeb*Ubc0 zq~id50^$U>WZjmcnIgsDione)f+T)0ID$xtgM zpGZXmVez0DN!)ioW1E45{!`G9^Y1P1oXhP^rc@c?o+c$^Kj_bn(Uo1H2$|g7=92v- z%Syv9Vo3VcibvH)b78USOTwIh{3%;3skO_htlfS?Cluwe`p&TMwo_WK6Z3Tz#nOoy z_E17(!pJ>`C2KECOo38F1uP0hqBr>%E=LCCCG{j6$b?;r?Fd$4@V-qjEzgWvzbQN%_nlBg?Ly`x-BzO2Nnd1 zuO|li(oo^Rubh?@$q8RVYn*aLnlWO_dhx8y(qzXN6~j>}-^Cuq4>=d|I>vhcjzhSO zU`lu_UZ?JaNs1nH$I1Ww+NJI32^qUikAUfz&k!gM&E_L=e_9}!<(?BfH~aCmI&hfzHi1~ zraRkci>zMPLkad=A&NEnVtQQ#YO8Xh&K*;6pMm$ap_38m;XQej5zEqUr`HdP&cf0i z5DX_c86@15jlm*F}u-+a*^v%u_hpzwN2eT66Zj_1w)UdPz*jI|fJb#kSD_8Q-7q9gf}zNu2h=q{)O*XH8FU)l|m;I;rV^QpXRvMJ|7% zWKTBX*cn`VY6k>mS#cq!uNw7H=GW3?wM$8@odjh$ynPiV7=Ownp}-|fhULZ)5{Z!Q z20oT!6BZTK;-zh=i~RQ$Jw>BTA=T(J)WdnTObDM#61lUm>IFRy@QJ3RBZr)A9CN!T z4k7%)I4yZ-0_n5d083t!=YcpSJ}M5E8`{uIs3L0lIaQws1l2}+w2(}hW&evDlMnC!WV?9U^YXF}!N*iyBGyCyJ<(2(Ca<>!$rID`( zR?V~-53&$6%DhW=)Hbd-oetTXJ-&XykowOx61}1f`V?LF=n8Nb-RLFGqheS7zNM_0 z1ozNap9J4GIM1CHj-%chrCdqPlP307wfrr^=XciOqn?YPL1|ozZ#LNj8QoCtAzY^q z7&b^^K&?fNSWD@*`&I+`l9 zP2SlD0IO?MK60nbucIQWgz85l#+*<{*SKk1K~|x{ux+hn=SvE_XE`oFlr7$oHt-&7 zP{+x)*y}Hnt?WKs_Ymf(J^aoe2(wsMMRPu>Pg8H#x|zQ_=(G5&ieVhvjEXHg1zY?U zW-hcH!DJPr+6Xnt)MslitmnHN(Kgs4)Y`PFcV0Qvemj;GG`kf<>?p})@kd9DA7dqs zNtGRKVr0%x#Yo*lXN+vT;TC{MR}}4JvUHJHDLd-g88unUj1(#7CM<%r!Z1Ve>DD)FneZ| z8Q0yI@i4asJaJ^ge%JPl>zC3+UZ;UDUr7JvUYNMf=M2t{It56OW1nw#K8%sXdX$Yg zpw3T=n}Om?j3-7lu)^XfBQkoaZ(qF0D=Aw&D%-bsox~`8Y|!whzpd5JZ{dmM^A5)M zOwWEM>bj}~885z9bo{kWFA0H(hv(vL$G2;pF$@_M%DSH#g%V*R(>;7Z7eKX&AQv1~ z+lKq=488TbTwA!VtgSHwduwAkGycunrg}>6oiX~;Kv@cZlz=E}POn%BWt{EEd;*GV zmc%PiT~k<(TA`J$#6HVg2HzF6Iw5w9{C63y`Y7?OB$WsC$~6WMm3`UHaWRZLN3nKiV# zE;iiu_)wTr7ZiELH$M^!i5eC9aRU#-RYZhCl1z_aNs@f`tD4A^$xd7I_ijCgI!$+| zsulIT$KB&PZ}T-G;Ibh@UPafvOc-=p7{H-~P)s{3M+;PmXe7}}&Mn+9WT#(Jmt5DW%73OBA$tC#Ug!j1BR~=Xbnaz4hGq zUOjC*z3mKNbrJm1Q!Ft^5{Nd54Q-O7<;n})TTQeLDY3C}RBGwhy*&wgnl8dB4lwkG zBX6Xn#hn|!v7fp@@tj9mUPrdD!9B;tJh8-$aE^t26n_<4^=u~s_MfbD?lHnSd^FGGL6the7a|AbltRGhfET*X;P7=AL?WPjBtt;3IXgUHLFMRBz(aWW_ zZ?%%SEPFu&+O?{JgTNB6^5nR@)rL6DFqK$KS$bvE#&hrPs>sYsW=?XzOyD6ixglJ8rdt{P8 zPAa*+qKt(%ju&jDkbB6x7aE(={xIb*&l=GF(yEnWPj)><_8U5m#gQIIa@l49W_=Qn^RCsYqlEy6Om%!&e~6mCAfDgeXe3aYpHQAA!N|kmIW~Rk}+p6B2U5@|1@7iVbm5&e7E3;c9q@XQlb^JS(gmJl%j9!N|eNQ$*OZf`3!;raRLJ z;X-h>nvB=S?mG!-VH{65kwX-UwNRMQB9S3ZRf`hL z#WR)+rn4C(AG(T*FU}`&UJOU4#wT&oDyZfHP^s9#>V@ens??pxuu-6RCk=Er`DF)X z>yH=P9RtrtY;2|Zg3Tnx3Vb!(lRLedVRmK##_#;Kjnlwq)eTbsY8|D{@Pjn_=kGYO zJq0T<_b;aB37{U`5g6OSG=>|pkj&PohM%*O#>kCPGK2{0*=m(-gKBEOh`fFa6*~Z! zVxw@7BS%e?cV^8{a`Ys4;w=tH4&0izFxgqjE#}UfsE^?w)cYEQjlU|uuv6{>nFTp| zNLjRRT1{g{?U2b6C^w{!s+LQ(n}FfQPDfYPsNV?KH_1HgscqG7z&n3Bh|xNYW4i5i zT4Uv-&mXciu3ej=+4X9h2uBW9o(SF*N~%4%=g|48R-~N32QNq!*{M4~Y!cS4+N=Zr z?32_`YpAeg5&r_hdhJkI4|i(-&BxCKru`zm9`v+CN8p3r9P_RHfr{U$H~RddyZKw{ zR?g5i>ad^Ge&h?LHlP7l%4uvOv_n&WGc$vhn}2d!xIWrPV|%x#2Q-cCbQqQ|-yoTe z_C(P))5e*WtmpB`Fa~#b*yl#vL4D_h;CidEbI9tsE%+{-4ZLKh#9^{mvY24#u}S6oiUr8b0xLYaga!(Fe7Dxi}v6 z%5xNDa~i%tN`Cy_6jbk@aMaY(xO2#vWZh9U?mrNrLs5-*n>04(-Dlp%6AXsy;f|a+ z^g~X2LhLA>xy(8aNL9U2wr=ec%;J2hEyOkL*D%t4cNg7WZF@m?kF5YGvCy`L5jus# zGP8@iGTY|ov#t&F$%gkWDoMR7v*UezIWMeg$C2~WE9*5%}$3!eFiFJ?hypfIA(PQT@=B|^Ipcu z{9cM3?rPF|gM~{G)j*af1hm+l92W7HRpQ*hSMDbh(auwr}VBG7`ldp>`FZ^amvau zTa~Y7%tH@>|BB6kSRGiWZFK?MIzxEHKGz#P!>rB-90Q_UsZ=uW6aTzxY{MPP@1rw- z&RP^Ld%HTo($y?6*aNMz8h&E?_PiO{jq%u4kr#*uN&Q+Yg1Rn831U4A6u#XOzaSL4 zrcM+0v@%On8N*Mj!)&IzXW6A80bUK&3w|z06cP!UD^?_rb_(L-u$m+#%YilEjkrlxthGCLQ@Q?J!p?ggv~0 z!qipxy&`w48T0(Elsz<^hp_^#1O1cNJ1UG=61Nc=)rlRo_P6v&&h??Qvv$ifC3oJh zo)ZZhU5enAqU%YB>+FU!1vW)i$m-Z%w!c&92M1?))n4z1a#4-FufZ$DatpJ^q)_Zif z;Br{HmZ|8LYRTi`#?TUfd;#>c4@2qM5_(H+Clt@kkQT+kx78KACyvY)?^zhyuN_Z& z-*9_o_f3IC2lX^(aLeqv#>qnelb6_jk+lgQh;TN>+6AU9*6O2h_*=74m;xSPD1^C9 zE0#!+B;utJ@8P6_DKTQ9kNOf`C*Jj0QAzsngKMQVDUsp=k~hd@wt}f{@$O*xI!a?p z6Gti>uE}IKAaQwKHRb0DjmhaF#+{9*=*^0)M-~6lPS-kCI#RFGJ-GyaQ+rhbmhQef zwco))WNA1LFr|J3Qsp4ra=_j?Y%b{JWMX6Zr`$;*V`l`g7P0sP?Y1yOY;e0Sb!AOW0Em=U8&i8EKxTd$dX6=^Iq5ZC%zMT5Jjj%0_ zbf|}I=pWjBKAx7wY<4-4o&E6vVStcNlT?I18f5TYP9!s|5yQ_C!MNnRyDt7~u~^VS@kKd}Zwc~? z=_;2}`Zl^xl3f?ce8$}g^V)`b8Pz88=9FwYuK_x%R?sbAF-dw`*@wokEC3mp0Id>P z>OpMGxtx!um8@gW2#5|)RHpRez+)}_p;`+|*m&3&qy{b@X>uphcgAVgWy`?Nc|NlH z75_k2%3h7Fy~EkO{vBMuzV7lj4B}*1Cj(Ew7oltspA6`d69P`q#Y+rHr5-m5&be&( zS1GcP5u#aM9V{fUQTfHSYU`kW&Wsxeg;S*{H_CdZ$?N>S$JPv!_6T(NqYPaS{yp0H7F~7vy#>UHJr^lV?=^vt4?8$v8vkI-1eJ4{iZ!7D5A zg_!ZxZV+9Wx5EIZ1%rbg8`-m|=>knmTE1cpaBVew_iZpC1>d>qd3`b6<(-)mtJBmd zjuq-qIxyKvIs!w4$qpl{0cp^-oq<=-IDEYV7{pvfBM7tU+ zfX3fc+VGtqjPIIx`^I0i>*L-NfY=gFS+|sC75Cg;2<)!Y`&p&-AxfOHVADHSv1?7t zlOKyXxi|7HdwG5s4T0))dWudvz8SZpxd<{z&rT<34l}XaaP86x)Q=2u5}1@Sgc41D z2gF)|aD7}UVy)bnm788oYp}Es!?|j73=tU<_+A4s5&it~_K4 z;^$i0Vnz8y&I!abOkzN|Vz;kUTya#Wi07>}Xf^7joZMiHH3Mdy@e_7t?l8^A!r#jTBau^wn#{|!tTg=w01EQUKJOca!I zV*>St2399#)bMF++1qS8T2iO3^oA`i^Px*i)T_=j=H^Kp4$Zao(>Y)kpZ=l#dSgcUqY=7QbGz9mP9lHnII8vl?yY9rU+i%X)-j0&-- zrtaJsbkQ$;DXyIqDqqq)LIJQ!`MIsI;goVbW}73clAjN;1Rtp7%{67uAfFNe_hyk= zn=8Q1x*zHR?txU)x9$nQu~nq7{Gbh7?tbgJ>i8%QX3Y8%T{^58W^{}(!9oPOM+zF3 zW`%<~q@W}9hoes56uZnNdLkgtcRqPQ%W8>o7mS(j5Sq_nN=b0A`Hr%13P{uvH?25L zMfC&Z0!{JBGiKoVwcIhbbx{I35o}twdI_ckbs%1%AQ(Tdb~Xw+sXAYcOoH_9WS(yM z2dIzNLy4D%le8Fxa31fd;5SuW?ERAsagZVEo^i};yjBhbxy9&*XChFtOPV8G77{8! zlYemh2vp7aBDMGT;YO#=YltE~(Qv~e7c=6$VKOxHwvrehtq>n|w}vY*YvXB%a58}n zqEBR4zueP@A~uQ2x~W-{o3|-xS@o>Ad@W99)ya--dRx;TZLL?5E(xstg(6SwDIpL5 zMZ)+)+&(hYL(--dxIKB*#v4mDq=0ve zNU~~jk426bXlS8%lcqsvuqbpgn zbFgxap;17;@xVh+Y~9@+-lX@LQv^Mw=yCM&2!%VCfZsiwN>DI=O?vHupbv9!4d*>K zcj@a5vqjcjpwkm@!2dxzzJGQ7#ujW(IndUuYC)i3N2<*doRGX8a$bSbyRO#0rA zUpFyEGx4S9$TKuP9BybRtjcAn$bGH-9>e(V{pKYPM3waYrihBCQf+UmIC#E=9v?or z_7*yzZfT|)8R6>s(lv6uzosT%WoR`bQIv(?llcH2Bd@26?zU%r1K25qscRrE1 z9TIIP_?`78@uJ{%I|_K;*syVinV;pCW!+zY-!^#n{3It^6EKw{~WIA0pf_hVzEZy zFzE=d-NC#mge{4Fn}we02-%Zh$JHKpXX3qF<#8__*I}+)Npxm?26dgldWyCmtwr9c zOXI|P0zCzn8M_Auv*h9;2lG}x*E|u2!*-s}moqS%Z`?O$<0amJG9n`dOV4**mypG- zE}In1pOQ|;@@Jm;I#m}jkQegIXag4K%J;C7<@R2X8IdsCNqrbsaUZZRT|#6=N!~H} zlc2hPngy9r+Gm_%tr9V&HetvI#QwUBKV&6NC~PK>HNQ3@fHz;J&rR7XB>sWkXKp%A ziLlogA`I*$Z7KzLaX^H_j)6R|9Q>IHc? z{s0MsOW>%xW|JW=RUxY@@0!toq`QXa=`j;)o2iDBiDZ7c4Bc>BiDTw+zk}Jm&vvH8qX$R`M6Owo>m%n`eizBf!&9X6 z)f{GpMak@NWF+HNg*t#H5yift5@QhoYgT7)jxvl&O=U54Z>FxT5prvlDER}AwrK4Q z*&JP9^k332OxC$(E6^H`#zw|K#cpwy0i*+!z{T23;dqUKbjP!-r*@_!sp+Uec@^f0 zIJMjqhp?A#YoX5EB%iWu;mxJ1&W6Nb4QQ@GElqNjFNRc*=@aGc$PHdoUptckkoOZC zk@c9i+WVnDI=GZ1?lKjobDl%nY2vW~d)eS6Lch&J zDi~}*fzj9#<%xg<5z-4(c}V4*pj~1z2z60gZc}sAmys^yvobWz)DKDGWuVpp^4-(!2Nn7 z3pO})bO)({KboXlQA>3PIlg@Ie$a=G;MzVeft@OMcKEjIr=?;=G0AH?dE_DcNo%n$_bFjqQ8GjeIyJP^NkX~7e&@+PqnU-c3@ABap z=}IZvC0N{@fMDOpatOp*LZ7J6Hz@XnJzD!Yh|S8p2O($2>A4hbpW{8?#WM`uJG>?} zwkDF3dimqejl$3uYoE7&pr5^f4QP-5TvJ;5^M?ZeJM8ywZ#Dm`kR)tpYieQU;t2S! z05~aeOBqKMb+`vZ2zfR*2(&z`Y1VROAcR(^Q7ZyYlFCLHSrTOQm;pnhf3Y@WW#gC1 z7b$_W*ia0@2grK??$pMHK>a$;J)xIx&fALD4)w=xlT=EzrwD!)1g$2q zy8GQ+r8N@?^_tuCKVi*q_G*!#NxxY#hpaV~hF} zF1xXy#XS|q#)`SMAA|46+UnJZ__lETDwy}uecTSfz69@YO)u&QORO~F^>^^j-6q?V z-WK*o?XSw~ukjoIT9p6$6*OStr`=+;HrF#)p>*>e|gy0D9G z#TN(VSC11^F}H#?^|^ona|%;xCC!~H3~+a>vjyRC5MPGxFqkj6 zttv9I_fv+5$vWl2r8+pXP&^yudvLxP44;9XzUr&a$&`?VNhU^$J z`3m68BAuA?ia*IF%Hs)@>xre4W0YoB^(X8RwlZ?pKR)rvGX?u&K`kb8XBs^pe}2v* z_NS*z7;4%Be$ts_emapc#zKjVMEqn8;aCX=dISG3zvJP>l4zHdpUwARLixQSFzLZ0 z$$Q+9fAnVjA?7PqANPiH*XH~VhrVfW11#NkAKjfjQN-UNz?ZT}SG#*sk*)VUXZ1$P zdxiM@I2RI7Tr043ZgWd3G^k56$Non@LKE|zLwBgXW#e~{7C{iB3&UjhKZPEj#)cH9 z%HUDubc0u@}dBz>4zU;sTluxBtCl!O4>g9ywc zhEiM-!|!C&LMjMNs6dr6Q!h{nvTrNN0hJ+w*h+EfxW=ro zxAB%*!~&)uaqXyuh~O`J(6e!YsD0o0l_ung1rCAZt~%4R{#izD2jT~${>f}m{O!i4 z`#UGbiSh{L=FR`Q`e~9wrKHSj?I>eXHduB`;%TcCTYNG<)l@A%*Ld?PK=fJi}J? z9T-|Ib8*rLE)v_3|1+Hqa!0ch>f% zfNFz@o6r5S`QQJCwRa4zgx$7AyQ7ZTv2EM7ZQHh!72CFL+qT`Y)k!)|Zr;7mcfV8T z)PB$1r*5rUzgE@y^E_kDG3Ol5n6q}eU2hJcXY7PI1}N=>nwC6k%nqxBIAx4Eix*`W zch0}3aPFe5*lg1P(=7J^0ZXvpOi9v2l*b?j>dI%iamGp$SmFaxpZod*TgYiyhF0= za44lXRu%9MA~QWN;YX@8LM32BqKs&W4&a3ve9C~ndQq>S{zjRNj9&&8k-?>si8)^m zW%~)EU)*$2YJzTXjRV=-dPAu;;n2EDYb=6XFyz`D0f2#29(mUX}*5~KU3k>$LwN#OvBx@ zl6lC>UnN#0?mK9*+*DMiboas!mmGnoG%gSYeThXI<=rE(!Pf-}oW}?yDY0804dH3o zo;RMFJzxP|srP-6ZmZ_peiVycfvH<`WJa9R`Z#suW3KrI*>cECF(_CB({ToWXSS18#3%vihZZJ{BwJPa?m^(6xyd1(oidUkrOU zlqyRQUbb@W_C)5Q)%5bT3K0l)w(2cJ-%?R>wK35XNl&}JR&Pn*laf1M#|s4yVXQS# zJvkT$HR;^3k{6C{E+{`)J+~=mPA%lv1T|r#kN8kZP}os;n39exCXz^cc{AN(Ksc%} zA561&OeQU8gIQ5U&Y;Ca1TatzG`K6*`9LV<|GL-^=qg+nOx~6 zBEMIM7Q^rkuhMtw(CZtpU(%JlBeV?KC+kjVDL34GG1sac&6(XN>nd+@Loqjo%i6I~ zjNKFm^n}K=`z8EugP20fd_%~$Nfu(J(sLL1gvXhxZt|uvibd6rLXvM%!s2{g0oNA8 z#Q~RfoW8T?HE{ge3W>L9bx1s2_L83Odx)u1XUo<`?a~V-_ZlCeB=N-RWHfs1(Yj!_ zP@oxCRysp9H8Yy@6qIc69TQx(1P`{iCh)8_kH)_vw1=*5JXLD(njxE?2vkOJ z>qQz!*r`>X!I69i#1ogdVVB=TB40sVHX;gak=fu27xf*}n^d>@*f~qbtVMEW!_|+2 zXS`-E%v`_>(m2sQnc6+OA3R z-6K{6$KZsM+lF&sn~w4u_md6J#+FzqmtncY;_ z-Q^D=%LVM{A0@VCf zV9;?kF?vV}*=N@FgqC>n-QhKJD+IT7J!6llTEH2nmUxKiBa*DO4&PD5=HwuD$aa(1 z+uGf}UT40OZAH@$jjWoI7FjOQAGX6roHvf_wiFKBfe4w|YV{V;le}#aT3_Bh^$`Pp zJZGM_()iFy#@8I^t{ryOKQLt%kF7xq&ZeD$$ghlTh@bLMv~||?Z$#B2_A4M&8)PT{ zyq$BzJpRrj+=?F}zH+8XcPvhRP+a(nnX2^#LbZqgWQ7uydmIM&FlXNx4o6m;Q5}rB z^ryM&o|~a-Zb20>UCfSFwdK4zfk$*~<|90v0=^!I?JnHBE{N}74iN;w6XS=#79G+P zB|iewe$kk;9^4LinO>)~KIT%%4Io6iFFXV9gJcIvu-(!um{WfKAwZDmTrv=wb#|71 zWqRjN8{3cRq4Ha2r5{tw^S>0DhaC3m!i}tk9q08o>6PtUx1GsUd{Z17FH45rIoS+oym1>3S0B`>;uo``+ADrd_Um+8s$8V6tKsA8KhAm z{pTv@zj~@+{~g&ewEBD3um9@q!23V_8Nb0_R#1jcg0|MyU)?7ua~tEY63XSvqwD`D zJ+qY0Wia^BxCtXpB)X6htj~*7)%un+HYgSsSJPAFED7*WdtlFhuJj5d3!h8gt6$(s ztrx=0hFH8z(Fi9}=kvPI?07j&KTkssT=Vk!d{-M50r!TsMD8fPqhN&%(m5LGpO>}L zse;sGl_>63FJ)(8&8(7Wo2&|~G!Lr^cc!uuUBxGZE)ac7Jtww7euxPo)MvxLXQXlk zeE>E*nMqAPwW0&r3*!o`S7wK&078Q#1bh!hNbAw0MFnK-2gU25&8R@@j5}^5-kHeR z!%krca(JG%&qL2mjFv380Gvb*eTLllTaIpVr3$gLH2e3^xo z=qXjG0VmES%OXAIsOQG|>{aj3fv+ZWdoo+a9tu8)4AyntBP>+}5VEmv@WtpTo<-aH zF4C(M#dL)MyZmU3sl*=TpAqU#r>c8f?-zWMq`wjEcp^jG2H`8m$p-%TW?n#E5#Th+ z7Zy#D>PPOA4|G@-I$!#Yees_9Ku{i_Y%GQyM)_*u^nl+bXMH!f_ z8>BM|OTex;vYWu`AhgfXFn)0~--Z7E0WR-v|n$XB-NOvjM156WR(eu z(qKJvJ%0n+%+%YQP=2Iz-hkgI_R>7+=)#FWjM#M~Y1xM8m_t8%=FxV~Np$BJ{^rg9 z5(BOvYfIY{$h1+IJyz-h`@jhU1g^Mo4K`vQvR<3wrynWD>p{*S!kre-(MT&`7-WK! zS}2ceK+{KF1yY*x7FH&E-1^8b$zrD~Ny9|9(!1Y)a#)*zf^Uo@gy~#%+*u`U!R`^v zCJ#N!^*u_gFq7;-XIYKXvac$_=booOzPgrMBkonnn%@#{srUC<((e*&7@YR?`CP;o zD2*OE0c%EsrI72QiN`3FpJ#^Bgf2~qOa#PHVmbzonW=dcrs92>6#{pEnw19AWk%;H zJ4uqiD-dx*w2pHf8&Jy{NXvGF^Gg!ungr2StHpMQK5^+ zEmDjjBonrrT?d9X;BHSJeU@lX19|?On)(Lz2y-_;_!|}QQMsq4Ww9SmzGkzVPQTr* z)YN>_8i^rTM>Bz@%!!v)UsF&Nb{Abz>`1msFHcf{)Ufc_a-mYUPo@ei#*%I_jWm#7 zX01=Jo<@6tl`c;P_uri^gJxDVHOpCano2Xc5jJE8(;r@y6THDE>x*#-hSKuMQ_@nc z68-JLZyag_BTRE(B)Pw{B;L0+Zx!5jf%z-Zqug*og@^ zs{y3{Za(0ywO6zYvES>SW*cd4gwCN^o9KQYF)Lm^hzr$w&spGNah6g>EQBufQCN!y zI5WH$K#67$+ic{yKAsX@el=SbBcjRId*cs~xk~3BBpQsf%IsoPG)LGs zdK0_rwz7?L0XGC^2$dktLQ9qjwMsc1rpGx2Yt?zmYvUGnURx(1k!kmfPUC@2Pv;r9 z`-Heo+_sn+!QUJTAt;uS_z5SL-GWQc#pe0uA+^MCWH=d~s*h$XtlN)uCI4$KDm4L$ zIBA|m0o6@?%4HtAHRcDwmzd^(5|KwZ89#UKor)8zNI^EsrIk z1QLDBnNU1!PpE3iQg9^HI){x7QXQV{&D>2U%b_II>*2*HF2%>KZ>bxM)Jx4}|CCEa`186nD_B9h`mv6l45vRp*L+z_nx5i#9KvHi>rqxJIjKOeG(5lCeo zLC|-b(JL3YP1Ds=t;U!Y&Gln*Uwc0TnDSZCnh3m$N=xWMcs~&Rb?w}l51ubtz=QUZsWQhWOX;*AYb)o(^<$zU_v=cFwN~ZVrlSLx| zpr)Q7!_v*%U}!@PAnZLqOZ&EbviFbej-GwbeyaTq)HSBB+tLH=-nv1{MJ-rGW%uQ1 znDgP2bU@}!Gd=-;3`KlJYqB@U#Iq8Ynl%eE!9g;d*2|PbC{A}>mgAc8LK<69qcm)piu?`y~3K8zlZ1>~K_4T{%4zJG6H?6%{q3B-}iP_SGXELeSv*bvBq~^&C=3TsP z9{cff4KD2ZYzkArq=;H(Xd)1CAd%byUXZdBHcI*%a24Zj{Hm@XA}wj$=7~$Q*>&4} z2-V62ek{rKhPvvB711`qtAy+q{f1yWuFDcYt}hP)Vd>G?;VTb^P4 z(QDa?zvetCoB_)iGdmQ4VbG@QQ5Zt9a&t(D5Rf#|hC`LrONeUkbV)QF`ySE5x+t_v z-(cW{S13ye9>gtJm6w&>WwJynxJQm8U2My?#>+(|)JK}bEufIYSI5Y}T;vs?rzmLE zAIk%;^qbd@9WUMi*cGCr=oe1-nthYRQlhVHqf{ylD^0S09pI}qOQO=3&dBsD)BWo# z$NE2Ix&L&4|Aj{;ed*A?4z4S!7o_Kg^8@%#ZW26_F<>y4ghZ0b|3+unIoWDUVfen~ z`4`-cD7qxQSm9hF-;6WvCbu$t5r$LCOh}=`k1(W<&bG-xK{VXFl-cD%^Q*x-9eq;k8FzxAqZB zH@ja_3%O7XF~>owf3LSC_Yn!iO}|1Uc5uN{Wr-2lS=7&JlsYSp3IA%=E?H6JNf()z zh>jA>JVsH}VC>3Be>^UXk&3o&rK?eYHgLwE-qCHNJyzDLmg4G(uOFX5g1f(C{>W3u zn~j`zexZ=sawG8W+|SErqc?uEvQP(YT(YF;u%%6r00FP;yQeH)M9l+1Sv^yddvGo- z%>u>5SYyJ|#8_j&%h3#auTJ!4y@yEg<(wp#(~NH zXP7B#sv@cW{D4Iz1&H@5wW(F82?-JmcBt@Gw1}WK+>FRXnX(8vwSeUw{3i%HX6-pvQS-~Omm#x-udgp{=9#!>kDiLwqs_7fYy{H z)jx_^CY?5l9#fR$wukoI>4aETnU>n<$UY!JDlIvEti908)Cl2Ziyjjtv|P&&_8di> z<^amHu|WgwMBKHNZ)t)AHII#SqDIGTAd<(I0Q_LNPk*?UmK>C5=rIN^gs}@65VR*!J{W;wp5|&aF8605*l-Sj zQk+C#V<#;=Sl-)hzre6n0n{}|F=(#JF)X4I4MPhtm~qKeR8qM?a@h!-kKDyUaDrqO z1xstrCRCmDvdIFOQ7I4qesby8`-5Y>t_E1tUTVOPuNA1De9| z8{B0NBp*X2-ons_BNzb*Jk{cAJ(^F}skK~i;p0V(R7PKEV3bB;syZ4(hOw47M*-r8 z3qtuleeteUl$FHL$)LN|q8&e;QUN4(id`Br{rtsjpBdriO}WHLcr<;aqGyJP{&d6? zMKuMeLbc=2X0Q_qvSbl3r?F8A^oWw9Z{5@uQ`ySGm@DUZ=XJ^mKZ-ipJtmiXjcu<%z?Nj%-1QY*O{NfHd z=V}Y(UnK=f?xLb-_~H1b2T&0%O*2Z3bBDf06-nO*q%6uEaLs;=omaux7nqqW%tP$i zoF-PC%pxc(ymH{^MR_aV{@fN@0D1g&zv`1$Pyu3cvdR~(r*3Y%DJ@&EU?EserVEJ` zEprux{EfT+(Uq1m4F?S!TrZ+!AssSdX)fyhyPW6C`}ko~@y#7acRviE(4>moNe$HXzf zY@@fJa~o_r5nTeZ7ceiXI=k=ISkdp1gd1p)J;SlRn^5;rog!MlTr<<6-U9|oboRBN zlG~o*dR;%?9+2=g==&ZK;Cy0pyQFe)x!I!8g6;hGl`{{3q1_UzZy)J@c{lBIEJVZ& z!;q{8h*zI!kzY#RO8z3TNlN$}l;qj10=}du!tIKJs8O+?KMJDoZ+y)Iu`x`yJ@krO zwxETN$i!bz8{!>BKqHpPha{96eriM?mST)_9Aw-1X^7&;Bf=c^?17k)5&s08^E$m^ zRt02U_r!99xfiow-XC~Eo|Yt8t>32z=rv$Z;Ps|^26H73JS1Xle?;-nisDq$K5G3y znR|l8@rlvv^wj%tdgw+}@F#Ju{SkrQdqZ?5zh;}|IPIdhy3ivi0Q41C@4934naAaY z%+otS8%Muvrr{S-Y96G?b2j0ldu1&coOqsq^vfcUT3}#+=#;fii6@M+hDp}dr9A0Y zjbhvqmB03%4jhsZ{_KQfGh5HKm-=dFxN;3tnwBej^uzcVLrrs z>eFP-jb#~LE$qTP9JJ;#$nVOw%&;}y>ezA6&i8S^7YK#w&t4!A36Ub|or)MJT z^GGrzgcnQf6D+!rtfuX|Pna`Kq*ScO#H=de2B7%;t+Ij<>N5@(Psw%>nT4cW338WJ z>TNgQ^!285hS1JoHJcBk;3I8%#(jBmcpEkHkQDk%!4ygr;Q2a%0T==W zT#dDH>hxQx2E8+jE~jFY$FligkN&{vUZeIn*#I_Ca!l&;yf){eghi z>&?fXc-C$z8ab$IYS`7g!2#!3F@!)cUquAGR2oiR0~1pO<$3Y$B_@S2dFwu~B0e4D z6(WiE@O{(!vP<(t{p|S5#r$jl6h;3@+ygrPg|bBDjKgil!@Sq)5;rXNjv#2)N5_nn zuqEURL>(itBYrT&3mu-|q;soBd52?jMT75cvXYR!uFuVP`QMot+Yq?CO%D9$Jv24r zhq1Q5`FD$r9%&}9VlYcqNiw2#=3dZsho0cKKkv$%X&gmVuv&S__zyz@0zmZdZI59~s)1xFs~kZS0C^271hR*O z9nt$5=y0gjEI#S-iV0paHx!|MUNUq&$*zi>DGt<#?;y;Gms|dS{2#wF-S`G3$^$7g z1#@7C65g$=4Ij?|Oz?X4=zF=QfixmicIw{0oDL5N7iY}Q-vcVXdyQNMb>o_?3A?e6 z$4`S_=6ZUf&KbMgpn6Zt>6n~)zxI1>{HSge3uKBiN$01WB9OXscO?jd!)`?y5#%yp zJvgJU0h+|^MdA{!g@E=dJuyHPOh}i&alC+cY*I3rjB<~DgE{`p(FdHuXW;p$a+%5` zo{}x#Ex3{Sp-PPi)N8jGVo{K!$^;z%tVWm?b^oG8M?Djk)L)c{_-`@F|8LNu|BTUp zQY6QJVzVg8S{8{Pe&o}Ux=ITQ6d42;0l}OSEA&Oci$p?-BL187L6rJ>Q)aX0)Wf%T zneJF2;<-V%-VlcA?X03zpf;wI&8z9@Hy0BZm&ac-Gdtgo>}VkZYk##OOD+nVOKLFJ z5hgXAhkIzZtCU%2M#xl=D7EQPwh?^gZ_@0p$HLd*tF>qgA_P*dP;l^cWm&iQSPJZE zBoipodanrwD0}}{H#5o&PpQpCh61auqlckZq2_Eg__8;G-CwyH#h1r0iyD#Hd_$WgM89n+ldz;=b!@pvr4;x zs|YH}rQuCyZO!FWMy%lUyDE*0)(HR}QEYxIXFexCkq7SHmSUQ)2tZM2s`G<9dq;Vc ziNVj5hiDyqET?chgEA*YBzfzYh_RX#0MeD@xco%)ON%6B7E3#3iFBkPK^P_=&8$pf zpM<0>QmE~1FX1>mztm>JkRoosOq8cdJ1gF5?%*zMDak%qubN}SM!dW6fgH<*F>4M7 zX}%^g{>ng^2_xRNGi^a(epr8SPSP>@rg7s=0PO-#5*s}VOH~4GpK9<4;g=+zuJY!& ze_ld=ybcca?dUI-qyq2Mwl~-N%iCGL;LrE<#N}DRbGow7@5wMf&d`kT-m-@geUI&U z0NckZmgse~(#gx;tsChgNd|i1Cz$quL>qLzEO}ndg&Pg4f zy`?VSk9X5&Ab_TyKe=oiIiuNTWCsk6s9Ie2UYyg1y|i}B7h0k2X#YY0CZ;B7!dDg7 z_a#pK*I7#9-$#Iev5BpN@xMq@mx@TH@SoNWc5dv%^8!V}nADI&0K#xu_#y)k%P2m~ zqNqQ{(fj6X8JqMe5%;>MIkUDd#n@J9Dm~7_wC^z-Tcqqnsfz54jPJ1*+^;SjJzJhG zIq!F`Io}+fRD>h#wjL;g+w?Wg`%BZ{f()%Zj)sG8permeL0eQ9vzqcRLyZ?IplqMg zpQaxM11^`|6%3hUE9AiM5V)zWpPJ7nt*^FDga?ZP!U1v1aeYrV2Br|l`J^tgLm;~%gX^2l-L9L`B?UDHE9_+jaMxy|dzBY4 zjsR2rcZ6HbuyyXsDV(K0#%uPd#<^V%@9c7{6Qd_kQEZL&;z_Jf+eabr)NF%@Ulz_a1e(qWqJC$tTC! zwF&P-+~VN1Vt9OPf`H2N{6L@UF@=g+xCC_^^DZ`8jURfhR_yFD7#VFmklCR*&qk;A zzyw8IH~jFm+zGWHM5|EyBI>n3?2vq3W?aKt8bC+K1`YjklQx4*>$GezfU%E|>Or9Y zNRJ@s(>L{WBXdNiJiL|^In*1VA`xiE#D)%V+C;KuoQi{1t3~4*8 z;tbUGJ2@2@$XB?1!U;)MxQ}r67D&C49k{ceku^9NyFuSgc}DC2pD|+S=qLH&L}Vd4 zM=-UK4{?L?xzB@v;qCy}Ib65*jCWUh(FVc&rg|+KnopG`%cb>t;RNv=1%4= z#)@CB7i~$$JDM>q@4ll8{Ja5Rsq0 z$^|nRac)f7oZH^=-VdQldC~E_=5%JRZSm!z8TJocv`w<_e0>^teZ1en^x!yQse%Lf z;JA5?0vUIso|MS03y${dX19A&bU4wXS~*T7h+*4cgSIX11EB?XGiBS39hvWWuyP{!5AY^x5j{!c?z<}7f-kz27%b>llPq%Z7hq+CU|Ev2 z*jh(wt-^7oL`DQ~Zw+GMH}V*ndCc~ zr>WVQHJQ8ZqF^A7sH{N5~PbeDihT$;tUP`OwWn=j6@L+!=T|+ze%YQ zO+|c}I)o_F!T(^YLygYOTxz&PYDh9DDiv_|Ewm~i7|&Ck^$jsv_0n_}q-U5|_1>*L44)nt!W|;4q?n&k#;c4wpSx5atrznZbPc;uQI^I}4h5Fy`9J)l z7yYa7Rg~f@0oMHO;seQl|E@~fd|532lLG#e6n#vXrfdh~?NP){lZ z&3-33d;bUTEAG=!4_{YHd3%GCV=WS|2b)vZgX{JC)?rsljjzWw@Hflbwg3kIs^l%y zm3fVP-55Btz;<-p`X(ohmi@3qgdHmwXfu=gExL!S^ve^MsimP zNCBV>2>=BjLTobY^67f;8mXQ1YbM_NA3R^s z{zhY+5@9iYKMS-)S>zSCQuFl!Sd-f@v%;;*fW5hme#xAvh0QPtJ##}b>&tth$)6!$ z0S&b2OV-SE<|4Vh^8rs*jN;v9aC}S2EiPKo(G&<6C|%$JQ{;JEg-L|Yob*<-`z?AsI(~U(P>cC=1V$OETG$7i# zG#^QwW|HZuf3|X|&86lOm+M+BE>UJJSSAAijknNp*eyLUq=Au z7&aqR(x8h|>`&^n%p#TPcC@8@PG% zM&7k6IT*o-NK61P1XGeq0?{8kA`x;#O+|7`GTcbmyWgf^JvWU8Y?^7hpe^85_VuRq7yS~8uZ=Cf%W^OfwF_cbBhr`TMw^MH0<{3y zU=y;22&oVlrH55eGNvoklhfPM`bPX`|C_q#*etS^O@5PeLk(-DrK`l|P*@#T4(kRZ z`AY7^%&{!mqa5}q%<=x1e29}KZ63=O>89Q)yO4G@0USgbGhR#r~OvWI4+yu4*F8o`f?EG~x zBCEND=ImLu2b(FDF3sOk_|LPL!wrzx_G-?&^EUof1C~A{feam{2&eAf@2GWem7! z|LV-lff1Dk+mvTw@=*8~0@_Xu@?5u?-u*r8E7>_l1JRMpi{9sZqYG+#Ty4%Mo$`ds zsVROZH*QoCErDeU7&=&-ma>IUM|i_Egxp4M^|%^I7ecXzq@K8_oz!}cHK#>&+$E4rs2H8Fyc)@Bva?(KO%+oc!+3G0&Rv1cP)e9u_Y|dXr#!J;n%T4+9rTF>^m_4X3 z(g+$G6Zb@RW*J-IO;HtWHvopoVCr7zm4*h{rX!>cglE`j&;l_m(FTa?hUpgv%LNV9 zkSnUu1TXF3=tX)^}kDZk|AF%7FmLv6sh?XCORzhTU%d>y4cC;4W5mn=i6vLf2 ztbTQ8RM@1gn|y$*jZa8&u?yTOlNo{coXPgc%s;_Y!VJw2Z1bf%57p%kC1*5e{bepl zwm?2YGk~x=#69_Ul8A~(BB}>UP27=M)#aKrxWc-)rLL+97=>x|?}j)_5ewvoAY?P| z{ekQQbmjbGC%E$X*x-M=;Fx}oLHbzyu=Dw>&WtypMHnOc92LSDJ~PL7sU!}sZw`MY z&3jd_wS8>a!si2Y=ijCo(rMnAqq z-o2uzz}Fd5wD%MAMD*Y&=Ct?|B6!f0jfiJt;hvkIyO8me(u=fv_;C;O4X^vbO}R_% zo&Hx7C@EcZ!r%oy}|S-8CvPR?Ns0$j`FtMB;h z`#0Qq)+6Fxx;RCVnhwp`%>0H4hk(>Kd!(Y}>U+Tr_6Yp?W%jt_zdusOcA$pTA z(4l9$K=VXT2ITDs!OcShuUlG=R6#x@t74B2x7Dle%LGwsZrtiqtTuZGFUio_Xwpl} z=T7jdfT~ld#U${?)B67E*mP*E)XebDuMO(=3~Y=}Z}rm;*4f~7ka196QIHj;JK%DU z?AQw4I4ZufG}gmfVQ3w{snkpkgU~Xi;}V~S5j~;No^-9eZEYvA`Et=Q4(5@qcK=Pr zk9mo>v!%S>YD^GQc7t4c!C4*qU76b}r(hJhO*m-s9OcsktiXY#O1<OoH z#J^Y@1A;nRrrxNFh?3t@Hx9d>EZK*kMb-oe`2J!gZ;~I*QJ*f1p93>$lU|4qz!_zH z&mOaj#(^uiFf{*Nq?_4&9ZssrZeCgj1J$1VKn`j+bH%9#C5Q5Z@9LYX1mlm^+jkHf z+CgcdXlX5);Ztq6OT@;UK_zG(M5sv%I`d2(i1)>O`VD|d1_l(_aH(h>c7fP_$LA@d z6Wgm))NkU!v^YaRK_IjQy-_+>f_y(LeS@z+B$5be|FzXqqg}`{eYpO;sXLrU{*fJT zQHUEXoWk%wh%Kal`E~jiu@(Q@&d&dW*!~9;T=gA{{~NJwQvULf;s43Ku#A$NgaR^1 z%U3BNX`J^YE-#2dM*Ov*CzGdP9^`iI&`tmD~Bwqy4*N=DHt%RycykhF* zc7BcXG28Jvv(5G8@-?OATk6|l{Rg1 zwdU2Md1Qv?#$EO3E}zk&9>x1sQiD*sO0dGSUPkCN-gjuppdE*%*d*9tEWyQ%hRp*7 zT`N^=$PSaWD>f;h@$d2Ca7 z8bNsm14sdOS%FQhMn9yC83$ z-YATg3X!>lWbLUU7iNk-`O%W8MrgI03%}@6l$9+}1KJ1cTCiT3>^e}-cTP&aEJcUt zCTh_xG@Oa-v#t_UDKKfd#w0tJfA+Ash!0>X&`&;2%qv$!Gogr4*rfMcKfFl%@{ztA zwoAarl`DEU&W_DUcIq-{xaeRu(ktyQ64-uw?1S*A>7pRHH5_F)_yC+2o@+&APivkn zwxDBp%e=?P?3&tiVQb8pODI}tSU8cke~T#JLAxhyrZ(yx)>fUhig`c`%;#7Ot9le# zSaep4L&sRBd-n&>6=$R4#mU8>T>=pB)feU9;*@j2kyFHIvG`>hWYJ_yqv?Kk2XTw` z42;hd=hm4Iu0h{^M>-&c9zKPtqD>+c$~>k&Wvq#>%FjOyifO%RoFgh*XW$%Hz$y2-W!@W6+rFJja=pw-u_s0O3WMVgLb&CrCQ)8I^6g!iQj%a%#h z<~<0S#^NV4n!@tiKb!OZbkiSPp~31?f9Aj#fosfd*v}j6&7YpRGgQ5hI_eA2m+Je) zT2QkD;A@crBzA>7T zw4o1MZ_d$)puHvFA2J|`IwSXKZyI_iK_}FvkLDaFj^&6}e|5@mrHr^prr{fPVuN1+ z4=9}DkfKLYqUq7Q7@qa$)o6&2)kJx-3|go}k9HCI6ahL?NPA&khLUL}k_;mU&7GcN zNG6(xXW}(+a%IT80=-13-Q~sBo>$F2m`)7~wjW&XKndrz8soC*br=F*A_>Sh_Y}2Mt!#A1~2l?|hj) z9wpN&jISjW)?nl{@t`yuLviwvj)vyZQ4KR#mU-LE)mQ$yThO1oohRv;93oEXE8mYE zXPQSVCK~Lp3hIA_46A{8DdA+rguh@98p?VG2+Nw(4mu=W(sK<#S`IoS9nwuOM}C0) zH9U|6N=BXf!jJ#o;z#6vi=Y3NU5XT>ZNGe^z4u$i&x4ty^Sl;t_#`|^hmur~;r;o- z*CqJb?KWBoT`4`St5}10d*RL?!hm`GaFyxLMJPgbBvjVD??f7GU9*o?4!>NabqqR! z{BGK7%_}96G95B299eErE5_rkGmSWKP~590$HXvsRGJN5-%6d@=~Rs_68BLA1RkZb zD%ccBqGF0oGuZ?jbulkt!M}{S1;9gwAVkgdilT^_AS`w6?UH5Jd=wTUA-d$_O0DuM z|9E9XZFl$tZctd`Bq=OfI(cw4A)|t zl$W~3_RkP zFA6wSu+^efs79KH@)0~c3Dn1nSkNj_s)qBUGs6q?G0vjT&C5Y3ax-seA_+_}m`aj} zvW04)0TSIpqQkD@#NXZBg9z@GK1^ru*aKLrc4{J0PjhNfJT}J;vEeJ1ov?*KVNBy< zXtNIY3TqLZ=o1Byc^wL!1L6#i6n(088T9W<_iu~$S&VWGfmD|wNj?Q?Dnc#6iskoG zt^u26JqFnt=xjS-=|ACC%(=YQh{_alLW1tk;+tz1ujzeQ--lEu)W^Jk>UmHK(H303f}P2i zrsrQ*nEz`&{V!%2O446^8qLR~-Pl;2Y==NYj^B*j1vD}R5plk>%)GZSSjbi|tx>YM zVd@IS7b>&Uy%v==*35wGwIK4^iV{31mc)dS^LnN8j%#M}s%B@$=bPFI_ifcyPd4hilEWm71chIwfIR(-SeQaf20{;EF*(K(Eo+hu{}I zZkjXyF}{(x@Ql~*yig5lAq7%>-O5E++KSzEe(sqiqf1>{Em)pN`wf~WW1PntPpzKX zn;14G3FK7IQf!~n>Y=cd?=jhAw1+bwlVcY_kVuRyf!rSFNmR4fOc(g7(fR{ANvcO< zbG|cnYvKLa>dU(Z9YP796`Au?gz)Ys?w!af`F}1#W>x_O|k9Q z>#<6bKDt3Y}?KT2tmhU>H6Umn}J5M zarILVggiZs=kschc2TKib2`gl^9f|(37W93>80keUkrC3ok1q{;PO6HMbm{cZ^ROcT#tWWsQy?8qKWt<42BGryC(Dx>^ohIa0u7$^)V@Bn17^(VUgBD> zAr*Wl6UwQ&AAP%YZ;q2cZ;@2M(QeYFtW@PZ+mOO5gD1v-JzyE3^zceyE5H?WLW?$4 zhBP*+3i<09M$#XU;jwi7>}kW~v%9agMDM_V1$WlMV|U-Ldmr|<_nz*F_kcgrJnrViguEnJt{=Mk5f4Foin7(3vUXC>4gyJ>sK<;-p{h7 z2_mr&Fca!E^7R6VvodGznqJn3o)Ibd`gk>uKF7aemX*b~Sn#=NYl5j?v*T4FWZF2D zaX(M9hJ2YuEi%b~4?RkJwT*?aCRT@ecBkq$O!i}EJJEw`*++J_a>gsMo0CG^pZ3x+ zdfTSbCgRwtvAhL$p=iIf7%Vyb!j*UJsmOMler--IauWQ;(ddOk+U$WgN-RBle~v9v z9m2~@h|x*3t@m+4{U2}fKzRoVePrF-}U{`YT|vW?~64Bv*7|Dz03 zRYM^Yquhf*ZqkN?+NK4Ffm1;6BR0ZyW3MOFuV1ljP~V(=-tr^Tgu#7$`}nSd<8?cP z`VKtIz5$~InI0YnxAmn|pJZj+nPlI3zWsykXTKRnDCBm~Dy*m^^qTuY+8dSl@>&B8~0H$Y0Zc25APo|?R= z>_#h^kcfs#ae|iNe{BWA7K1mLuM%K!_V?fDyEqLkkT&<`SkEJ;E+Py^%hPVZ(%a2P4vL=vglF|X_`Z$^}q470V+7I4;UYdcZ7vU=41dd{d#KmI+|ZGa>C10g6w1a?wxAc&?iYsEv zuCwWvcw4FoG=Xrq=JNyPG*yIT@xbOeV`$s_kx`pH0DXPf0S7L?F208x4ET~j;yQ2c zhtq=S{T%82U7GxlUUKMf-NiuhHD$5*x{6}}_eZ8_kh}(}BxSPS9<(x2m$Rn0sx>)a zt$+qLRJU}0)5X>PXVxE?Jxpw(kD0W43ctKkj8DjpYq}lFZE98Je+v2t7uxuKV;p0l z5b9smYi5~k2%4aZe+~6HyobTQ@4_z#*lRHl# zSA`s~Jl@RGq=B3SNQF$+puBQv>DaQ--V!alvRSI~ZoOJx3VP4sbk!NdgMNBVbG&BX zdG*@)^g4#M#qoT`^NTR538vx~rdyOZcfzd7GBHl68-rG|fkofiGAXTJx~`~%a&boY zZ#M4sYwHIOnu-Mr!Ltpl8!NrX^p74tq{f_F4%M@&<=le;>xc5pAi&qn4P>04D$fp` z(OuJXQia--?vD0DIE6?HC|+DjH-?Cl|GqRKvs8PSe027_NH=}+8km9Ur8(JrVx@*x z0lHuHd=7*O+&AU_B;k{>hRvV}^Uxl^L1-c-2j4V^TG?2v66BRxd~&-GMfcvKhWgwu z60u{2)M{ZS)r*=&J4%z*rtqs2syPiOQq(`V0UZF)boPOql@E0U39>d>MP=BqFeJzz zh?HDKtY3%mR~reR7S2rsR0aDMA^a|L^_*8XM9KjabpYSBu z;zkfzU~12|X_W_*VNA=e^%Za14PMOC!z`5Xt|Fl$2bP9fz>(|&VJFZ9{z;;eEGhOl zl7OqqDJzvgZvaWc7Nr!5lfl*Qy7_-fy9%f(v#t#&2#9o-ba%J3(%s#C=@dagx*I{d zB&AzGT9EEiknWJU^naNdz7Logo%#OFV!eyCIQuzgpZDDN-1F}JJTdGXiLN85p|GT! zGOfNd8^RD;MsK*^3gatg2#W0J<8j)UCkUYoZRR|R*UibOm-G)S#|(`$hPA7UmH+fT ziZxTgeiR_yzvNS1s+T!xw)QgNSH(_?B@O?uTBwMj`G)2c^8%g8zu zxMu5SrQ^J+K91tkPrP%*nTpyZor#4`)}(T-Y8eLd(|sv8xcIoHnicKyAlQfm1YPyI z!$zimjMlEcmJu?M6z|RtdouAN1U5lKmEWY3gajkPuUHYRvTVeM05CE@`@VZ%dNoZN z>=Y3~f$~Gosud$AN{}!DwV<6CHm3TPU^qcR!_0$cY#S5a+GJU-2I2Dv;ktonSLRRH zALlc(lvX9rm-b5`09uNu904c}sU(hlJZMp@%nvkcgwkT;Kd7-=Z_z9rYH@8V6Assf zKpXju&hT<=x4+tCZ{elYtH+_F$V=tq@-`oC%vdO>0Wmu#w*&?_=LEWRJpW|spYc8V z=$)u#r}Pu7kvjSuM{FSyy9_&851CO^B zTm$`pF+lBWU!q>X#;AO1&=tOt=i!=9BVPC#kPJU}K$pO&8Ads)XOFr336_Iyn z$d{MTGYQLX9;@mdO;_%2Ayw3hv}_$UT00*e{hWxS?r=KT^ymEwBo429b5i}LFmSk` zo)-*bF1g;y@&o=34TW|6jCjUx{55EH&DZ?7wB_EmUg*B4zc6l7x-}qYLQR@^7o6rrgkoujRNym9O)K>wNfvY+uy+4Om{XgRHi#Hpg*bZ36_X%pP`m7FIF z?n?G*g&>kt$>J_PiXIDzgw3IupL3QZbysSzP&}?JQ-6TN-aEYbA$X>=(Zm}0{hm6J zJnqQnEFCZGmT06LAdJ^T#o`&)CA*eIYu?zzDJi#c$1H9zX}hdATSA|zX0Vb^q$mgg z&6kAJ=~gIARct>}4z&kzWWvaD9#1WK=P>A_aQxe#+4cpJtcRvd)TCu! z>eqrt)r(`qYw6JPKRXSU#;zYNB7a@MYoGuAT0Nzxr`>$=vk`uEq2t@k9?jYqg)MXl z67MA3^5_}Ig*mycsGeH0_VtK3bNo;8#0fFQ&qDAj=;lMU9%G)&HL>NO|lWU3z+m4t7 zfV*3gSuZ++rIWsinX@QaT>dsbD>Xp8%8c`HLamm~(i{7L&S0uZ;`W-tqU4XAgQclM$PxE76OH(PSjHjR$(nh({vsNnawhP!!HcP!l)5 zG;C=k0xL<^q+4rpbp{sGzcc~ZfGv9J*k~PPl}e~t$>WPSxzi0}05(D6d<=5+E}Y4e z@_QZtDcC7qh4#dQFYb6Pulf_8iAYYE z1SWJfNe5@auBbE5O=oeO@o*H5mS(pm%$!5yz-71~lEN5=x0eN|V`xAeP;eTje?eC= z53WneK;6n35{OaIH2Oh6Hx)kV-jL-wMzFlynGI8Wk_A<~_|06rKB#Pi_QY2XtIGW_ zYr)RECK_JRzR1tMd(pM(L=F98y~7wd4QBKAmFF(AF(e~+80$GLZpFc;a{kj1h}g4l z3SxIRlV=h%Pl1yRacl^g>9q%>U+`P(J`oh-w8i82mFCn|NJ5oX*^VKODX2>~HLUky z3D(ak0Sj=Kv^&8dUhU(3Ab!U5TIy97PKQ))&`Ml~hik%cHNspUpCn24cqH@dq6ZVo zO9xz!cEMm;NL;#z-tThlFF%=^ukE8S0;hDMR_`rv#eTYg7io1w9n_vJpK+6%=c#Y?wjAs_(#RQA0gr&Va2BQTq` zUc8)wHEDl&Uyo<>-PHksM;b-y(`E_t8Rez@Iw+eogcEI*FDg@Bc;;?3j3&kPsq(mx z+Yr_J#?G6D?t2G%O9o&e7Gbf&>#(-)|8)GIbG_a${TU26cVrIQSt=% zQ~XY-b1VQVc>IV=7um0^Li>dF z`zSm_o*i@ra4B+Tw5jdguVqx`O(f4?_USIMJzLvS$*kvBfEuToq-VR%K*%1VHu=++ zQ`=cG3cCnEv{ZbP-h9qbkF}%qT$j|Z7ZB2?s7nK@gM{bAD=eoDKCCMlm4LG~yre!- zzPP#Rn9ZDUgb4++M78-V&VX<1ah(DN z(4O5b`Fif%*k?L|t%!WY`W$C_C`tzC`tI7XC`->oJs_Ezs=K*O_{*#SgNcvYdmBbG zHd8!UTzGApZC}n7LUp1fe0L<3|B5GdLbxX@{ETeUB2vymJgWP0q2E<&!Dtg4>v`aa zw(QcLoA&eK{6?Rb&6P0kY+YszBLXK49i~F!jr)7|xcnA*mOe1aZgkdmt4{Nq2!!SL z`aD{6M>c00muqJt4$P+RAj*cV^vn99UtJ*s${&agQ;C>;SEM|l%KoH_^kAcmX=%)* zHpByMU_F12iGE#68rHGAHO_ReJ#<2ijo|T7`{PSG)V-bKw}mpTJwtCl%cq2zxB__m zM_p2k8pDmwA*$v@cmm>I)TW|7a7ng*X7afyR1dcuVGl|BQzy$MM+zD{d~n#)9?1qW zdk(th4Ljb-vpv5VUt&9iuQBnQ$JicZ)+HoL`&)B^Jr9F1wvf=*1and~v}3u{+7u7F zf0U`l4Qx-ANfaB3bD1uIeT^zeXerps8nIW(tmIxYSL;5~!&&ZOLVug2j4t7G=zzK+ zmPy5<4h%vq$Fw)i1)ya{D;GyEm3fybsc8$=$`y^bRdmO{XU#95EZ$I$bBg)FW#=}s z@@&c?xwLF3|C7$%>}T7xl0toBc6N^C{!>a8vWc=G!bAFKmn{AKS6RxOWIJBZXP&0CyXAiHd?7R#S46K6UXYXl#c_#APL5SfW<<-|rcfX&B6e*isa|L^RK=0}D`4q-T0VAs0 zToyrF6`_k$UFGAGhY^&gg)(Fq0p%J{h?E)WQ(h@Gy=f6oxUSAuT4ir}jI)36|NnmnI|vtij;t!jT?6Jf-E19}9Lf9(+N+ z)+0)I5mST_?3diP*n2=ZONTYdXkjKsZ%E$jjU@0w_lL+UHJOz|K{{Uh%Zy0dhiqyh zofWXzgRyFzY>zpMC8-L^43>u#+-zlaTMOS(uS!p{Jw#u3_9s)(s)L6j-+`M5sq?f+ zIIcjq$}~j9b`0_hIz~?4?b(Sqdpi(;1=8~wkIABU+APWQdf5v@g=1c{c{d*J(X5+cfEdG?qxq z{GKkF;)8^H&Xdi~fb~hwtJRsfg#tdExEuDRY^x9l6=E+|fxczIW4Z29NS~-oLa$Iq z93;5$(M0N8ba%8&q>vFc=1}a8T?P~_nrL5tYe~X>G=3QoFlBae8vVt-K!^@vusN<8gQJ!WD7H%{*YgY0#(tXxXy##C@o^U7ysxe zLmUWN@4)JBjjZ3G-_)mrA`|NPCc8Oe!%Ios4$HWpBmJse7q?)@Xk%$x&lIY>vX$7L zpfNWlXxy2p7TqW`Wq22}Q3OC2OWTP_X(*#kRx1WPe%}$C!Qn^FvdYmvqgk>^nyk;6 zXv*S#P~NVx1n6pdbXuX9x_}h1SY#3ZyvLZ&VnWVva4)9D|i7kjGY{>am&^ z-_x1UYM1RU#z17=AruK~{BK$A65Sajj_OW|cpYQBGWO*xfGJXSn4E&VMWchq%>0yP z{M2q=zx!VnO71gb8}Al2i+uxb=ffIyx@oso@8Jb88ld6M#wgXd=WcX$q$91o(94Ek zjeBqQ+CZ64hI>sZ@#tjdL}JeJu?GS7N^s$WCIzO`cvj60*d&#&-BQ>+qK#7l+!u1t zBuyL-Cqups?2>)ek2Z|QnAqs_`u1#y8=~Hvsn^2Jtx-O`limc*w;byk^2D-!*zqRi zVcX+4lzwcCgb+(lROWJ~qi;q2!t6;?%qjGcIza=C6{T7q6_?A@qrK#+)+?drrs3U}4Fov+Y}`>M z#40OUPpwpaC-8&q8yW0XWGw`RcSpBX+7hZ@xarfCNnrl-{k@`@Vv> zYWB*T=4hLJ1SObSF_)2AaX*g(#(88~bVG9w)ZE91eIQWflNecYC zzUt}ov<&)S&i$}?LlbIi9i&-g=UUgjWTq*v$!0$;8u&hwL*S^V!GPSpM3PR3Ra5*d z7d77UC4M{#587NcZS4+JN=m#i)7T0`jWQ{HK3rIIlr3cDFt4odV25yu9H1!}BVW-& zrqM5DjDzbd^pE^Q<-$1^_tX)dX8;97ILK{ z!{kF{!h`(`6__+1UD5=8sS&#!R>*KqN9_?(Z$4cY#B)pG8>2pZqI;RiYW6aUt7kk*s^D~Rml_fg$m+4+O5?J&p1)wE zp5L-X(6og1s(?d7X#l-RWO+5Jj(pAS{nz1abM^O;8hb^X4pC7ADpzUlS{F~RUoZp^ zuJCU_fq}V!9;knx^uYD2S9E`RnEsyF^ZO$;`8uWNI%hZzKq=t`q12cKEvQjJ9dww9 zCerpM3n@Ag+XZJztlqHRs!9X(Dv&P;_}zz$N&xwA@~Kfnd3}YiABK*T)Ar2E?OG6V z<;mFs`D?U7>Rradv7(?3oCZZS_0Xr#3NNkpM1@qn-X$;aNLYL;yIMX4uubh^Xb?HloImt$=^s8vm)3g!{H1D|k zmbg_Rr-ypQokGREIcG<8u(=W^+oxelI&t0U`dT=bBMe1fl+9!l&vEPFFu~yAu!XIv4@S{;| z8?%<1@hJp%7AfZPYRARF1hf`cq_VFQ-y74;EdMob{z&qec2hiQJOQa>f-?Iz^VXOr z-wnfu*uT$(5WmLsGsVkHULPBvTRy0H(}S0SQ18W0kp_U}8Phc3gz!Hj#*VYh$AiDE245!YA0M$Q@rM zT;}1DQ}MxV<)*j{hknSHyihgMPCK=H)b-iz9N~KT%<&Qmjf39L@&7b;;>9nQkDax- zk%7ZMA%o41l#(G5K=k{D{80E@P|I;aufYpOlIJXv!dS+T^plIVpPeZ)Gp`vo+?BWt z8U8u=C51u%>yDCWt>`VGkE5~2dD4y_8+n_+I9mFN(4jHJ&x!+l*>%}b4Z>z#(tb~< z+<+X~GIi`sDb=SI-7m>*krlqE3aQD?D5WiYX;#8m|ENYKw}H^95u!=n=xr3jxhCB&InJ7>zgLJg;i?Sjjd`YW!2; z%+y=LwB+MMnSGF@iu#I%!mvt)aXzQ*NW$cHNHwjoaLtqKCHqB}LW^ozBX?`D4&h%# zeMZ3ZumBn}5y9&odo3=hN$Q&SRte*^-SNZg2<}6>OzRpF91oy0{RuZU(Q0I zvx%|9>;)-Ca9#L)HQt~axu0q{745Ac;s1XQKV ze3D9I5gV5SP-J>&3U!lg1`HN>n5B6XxYpwhL^t0Z)4$`YK93vTd^7BD%<)cIm|4e!;*%9}B-3NX+J*Nr@;5(27Zmf(TmfHsej^Bz+J1 zXKIjJ)H{thL4WOuro|6&aPw=-JW8G=2 z|L4YL)^rYf7J7DOKXpTX$4$Y{-2B!jT4y^w8yh3LKRKO3-4DOshFk}N^^Q{r(0K0+ z?7w}x>(s{Diq6K)8sy)>%*g&{u>)l+-Lg~=gteW?pE`B@FE`N!F-+aE;XhjF+2|RV z8vV2((yeA-VDO;3=^E;fhW~b=Wd5r8otQrO{Vu)M1{j(+?+^q%xpYCojc6rmQ<&ytZ2ly?bw*X)WB8(n^B4Gmxr^1bQ&=m;I4O$g{ z3m|M{tmkOyAPnMHu(Z}Q1X1GM|A+)VDP3Fz934zSl)z>N|D^`G-+>Mej|VcK+?iew zQ3=DH4zz;i>z{Yv_l@j*?{936kxM{c7eK$1cf8wxL>>O#`+vsu*KR)te$adfTD*w( zAStXnZk<6N3V-Vs#GB%vXZat+(EFWbkbky#{yGY`rOvN)?{5qUuFv=r=dyYZrULf%MppWuNRUWc z8|YaIn}P0DGkwSZ(njAO$Zhr3Yw`3O1A+&F*2UjO{0`P%kK(qL;kEkfjRC=lxPRjL z{{4PO3-*5RZ_B3LUB&?ZpJ4nk1E4L&eT~HX0Jo(|uGQCW3utB@p)rF@W*n$==TlS zKiTfzhrLbAeRqru%D;fUwXOUcHud{pw@Ib1xxQ}<2)?KC&%y5PVef<7rcu2l!8dsy z?lvdaHJ#s$0m18y{x#fB$o=l)-sV?Qya5GWf#8Vd{~Grn@qgX#!EI`Y>++l%1A;eL z{_7t6jMeEr@a+oxyCL^+_}9Qc;i0&Xd%LXp?to*R|26LKHG(m0)*QF4*h;5%YG5<9)c> z1vq!7bIJSv1^27i-mcH!zX>ep3Iw0^{nx<1jOy)N_UoFD8v}x~2mEWapI3m~kMQkR z#&@4FuEGBn`mgtSx6jeY7vUQNf=^}sTZErIEpH!cy|@7Z zU4h_Oxxd2s=f{}$XXy4}%JqTSjRC \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/persistence-modules/r2dbc/mvnw.cmd b/persistence-modules/r2dbc/mvnw.cmd new file mode 100644 index 0000000000..fef5a8f7f9 --- /dev/null +++ b/persistence-modules/r2dbc/mvnw.cmd @@ -0,0 +1,161 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/persistence-modules/r2dbc/pom.xml b/persistence-modules/r2dbc/pom.xml new file mode 100644 index 0000000000..388abafdaf --- /dev/null +++ b/persistence-modules/r2dbc/pom.xml @@ -0,0 +1,90 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.6.RELEASE + + + org.baeldung.examples.r2dbc + r2dbc-example + 0.0.1-SNAPSHOT + r2dbc-example + Sample R2DBC Project + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework.boot + spring-boot-starter-test + test + + + io.projectreactor + reactor-test + test + + + + + + io.r2dbc + r2dbc-h2 + 0.8.0.M8 + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-devtools + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + diff --git a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/Account.java b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/Account.java new file mode 100644 index 0000000000..65bf33168e --- /dev/null +++ b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/Account.java @@ -0,0 +1,68 @@ +package org.baeldung.examples.r2dbc; + +import java.math.BigDecimal; + +public class Account { + + private Long id; + private String iban; + private BigDecimal balance; + + + public Account() {} + + public Account(Long id, String iban, BigDecimal balance) { + this.id = id; + this.iban = iban; + this.balance = balance; + } + + public Account(Long id, String iban, Double balance) { + this.id = id; + this.iban = iban; + this.balance = new BigDecimal(balance); + } + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the iban + */ + public String getIban() { + return iban; + } + + /** + * @param iban the iban to set + */ + public void setIban(String iban) { + this.iban = iban; + } + + /** + * @return the balance + */ + public BigDecimal getBalance() { + return balance; + } + + /** + * @param balance the balance to set + */ + public void setBalance(BigDecimal balance) { + this.balance = balance; + } + +} diff --git a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/AccountResource.java b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/AccountResource.java new file mode 100644 index 0000000000..90816a7522 --- /dev/null +++ b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/AccountResource.java @@ -0,0 +1,56 @@ +/** + * + */ +package org.baeldung.examples.r2dbc; + +import java.math.BigDecimal; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import io.r2dbc.spi.Connection; +import io.r2dbc.spi.ConnectionFactory; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * @author Philippe + * + */ +@RestController +public class AccountResource { + + private final ReactiveAccountDao accountDao; + + public AccountResource(ReactiveAccountDao accountDao) { + this.accountDao = accountDao; + } + + @GetMapping("/accounts/{id}") + public Mono> getAccount(@PathVariable("id") Long id) { + + return accountDao.findById(id) + .map(acc -> new ResponseEntity<>(acc, HttpStatus.OK)) + .switchIfEmpty(Mono.just(new ResponseEntity<>(null, HttpStatus.NOT_FOUND))); + } + + @GetMapping("/accounts") + public Flux getAllAccounts() { + return accountDao.findAll(); + } + + @PostMapping("/accounts") + public Mono> postAccount(@RequestBody Account account) { + return accountDao.createAccount(account) + .map(acc -> new ResponseEntity<>(acc, HttpStatus.CREATED)) + .log(); + } + +} diff --git a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/DatasourceConfig.java b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/DatasourceConfig.java new file mode 100644 index 0000000000..5b695f39f5 --- /dev/null +++ b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/DatasourceConfig.java @@ -0,0 +1,65 @@ +package org.baeldung.examples.r2dbc; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; + +import io.netty.util.internal.StringUtil; +import io.r2dbc.spi.ConnectionFactories; +import io.r2dbc.spi.ConnectionFactory; +import io.r2dbc.spi.ConnectionFactoryOptions; +import io.r2dbc.spi.ConnectionFactoryOptions.Builder; +import io.r2dbc.spi.Option; +import reactor.core.publisher.Flux; + +import static io.r2dbc.spi.ConnectionFactoryOptions.*; + + +@Configuration +public class DatasourceConfig { + + @Bean + public ConnectionFactory connectionFactory(R2DBCConfigurationProperties properties) { + + ConnectionFactoryOptions baseOptions = ConnectionFactoryOptions.parse(properties.getUrl()); + Builder ob = ConnectionFactoryOptions.builder().from(baseOptions); + if ( !StringUtil.isNullOrEmpty(properties.getUser())) { + ob = ob.option(USER, properties.getUser()); + } + + if ( !StringUtil.isNullOrEmpty(properties.getPassword())) { + ob = ob.option(PASSWORD, properties.getPassword()); + } + + ConnectionFactory cf = ConnectionFactories.get(ob.build()); + return cf; + } + + + @Bean + public CommandLineRunner initDatabase(ConnectionFactory cf) { + + return (args) -> + Flux.from(cf.create()) + .flatMap(c -> + Flux.from(c.createBatch() + .add("drop table if exists Account") + .add("create table Account(" + + "id IDENTITY(1,1)," + + "iban varchar(80) not null," + + "balance DECIMAL(18,2) not null)") + .add("insert into Account(iban,balance)" + + "values('BR430120980198201982',100.00)") + .add("insert into Account(iban,balance)" + + "values('BR430120998729871000',250.00)") + .execute()) + .doFinally((st) -> c.close()) + ) + .log() + .blockLast(); + } + + +} + diff --git a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2DBCConfigurationProperties.java b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2DBCConfigurationProperties.java new file mode 100644 index 0000000000..02733ebed9 --- /dev/null +++ b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2DBCConfigurationProperties.java @@ -0,0 +1,58 @@ +package org.baeldung.examples.r2dbc; + +import javax.validation.constraints.NotEmpty; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "r2dbc") +public class R2DBCConfigurationProperties { + + @NotEmpty + private String url; + + private String user; + private String password; + + /** + * @return the url + */ + public String getUrl() { + return url; + } + + /** + * @param url the url to set + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * @return the user + */ + public String getUser() { + return user; + } + + /** + * @param user the user to set + */ + public void setUser(String user) { + this.user = user; + } + + /** + * @return the password + */ + public String getPassword() { + return password; + } + + /** + * @param password the password to set + */ + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2dbcExampleApplication.java b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2dbcExampleApplication.java new file mode 100644 index 0000000000..1147936e2d --- /dev/null +++ b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/R2dbcExampleApplication.java @@ -0,0 +1,17 @@ +package org.baeldung.examples.r2dbc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; + +@SpringBootApplication +@EnableConfigurationProperties(R2DBCConfigurationProperties.class) +public class R2dbcExampleApplication { + + public static void main(String[] args) { + SpringApplication.run(R2dbcExampleApplication.class, args); + } + + + +} diff --git a/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/ReactiveAccountDao.java b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/ReactiveAccountDao.java new file mode 100644 index 0000000000..f9717d4b9b --- /dev/null +++ b/persistence-modules/r2dbc/src/main/java/org/baeldung/examples/r2dbc/ReactiveAccountDao.java @@ -0,0 +1,76 @@ +package org.baeldung.examples.r2dbc; + +import java.math.BigDecimal; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +import io.r2dbc.spi.Connection; +import io.r2dbc.spi.ConnectionFactory; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@Component +public class ReactiveAccountDao { + + private ConnectionFactory connectionFactory; + + public ReactiveAccountDao(ConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } + + public Mono findById(long id) { + + return Mono.from(connectionFactory.create()) + .flatMap(c -> Mono.from(c.createStatement("select id,iban,balance from Account where id = $1") + .bind("$1", id) + .execute()) + .doFinally((st) -> close(c))) + .map(result -> result.map((row, meta) -> + new Account(row.get("id", Long.class), + row.get("iban", String.class), + row.get("balance", BigDecimal.class)))) + .flatMap( p -> Mono.from(p)); + } + + public Flux findAll() { + + return Mono.from(connectionFactory.create()) + .flatMap((c) -> Mono.from(c.createStatement("select id,iban,balance from Account") + .execute()) + .doFinally((st) -> close(c))) + .flatMapMany(result -> Flux.from(result.map((row, meta) -> { + Account acc = new Account(); + acc.setId(row.get("id", Long.class)); + acc.setIban(row.get("iban", String.class)); + acc.setBalance(row.get("balance", BigDecimal.class)); + return acc; + }))); + } + + public Mono createAccount(Account account) { + + return Mono.from(connectionFactory.create()) + .flatMap(c -> Mono.from(c.beginTransaction()) + .then(Mono.from(c.createStatement("insert into Account(iban,balance) values($1,$2)") + .bind("$1", account.getIban()) + .bind("$2", account.getBalance()) + .returnGeneratedValues("id") + .execute())) + .map(result -> result.map((row, meta) -> + new Account(row.get("id", Long.class), + account.getIban(), + account.getBalance()))) + .flatMap(pub -> Mono.from(pub)) + .delayUntil(r -> c.commitTransaction()) + .doFinally((st) -> c.close())); + + } + + private Mono close(Connection connection) { + return Mono.from(connection.close()) + .then(Mono.empty()); + } + +} diff --git a/persistence-modules/r2dbc/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/persistence-modules/r2dbc/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 0000000000..55eb5659a7 --- /dev/null +++ b/persistence-modules/r2dbc/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,5 @@ +{"properties": [{ + "name": "r2dbc", + "type": "org.baeldung.examples.r2dbc.R2DBCConfigurationProperties", + "description": "R2DBC Connection properties" +}]} \ No newline at end of file diff --git a/persistence-modules/r2dbc/src/main/resources/application.yml b/persistence-modules/r2dbc/src/main/resources/application.yml new file mode 100644 index 0000000000..bb47c7261c --- /dev/null +++ b/persistence-modules/r2dbc/src/main/resources/application.yml @@ -0,0 +1,13 @@ +spring: + application: + name: r2dbc-test + +# R2DBC URL +r2dbc: + url: r2dbc:h2:mem://./testdb + + + + + + diff --git a/persistence-modules/r2dbc/src/test/java/org/baeldung/examples/r2dbc/R2dbcExampleApplicationTests.java b/persistence-modules/r2dbc/src/test/java/org/baeldung/examples/r2dbc/R2dbcExampleApplicationTests.java new file mode 100644 index 0000000000..a1d433847b --- /dev/null +++ b/persistence-modules/r2dbc/src/test/java/org/baeldung/examples/r2dbc/R2dbcExampleApplicationTests.java @@ -0,0 +1,102 @@ +package org.baeldung.examples.r2dbc; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import java.util.List; + +import org.hamcrest.core.IsNull; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +import io.r2dbc.spi.ConnectionFactory; +import reactor.core.publisher.Flux; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class R2dbcExampleApplicationTests { + + + @Autowired + private WebTestClient webTestClient; + + @Autowired + ConnectionFactory cf; + + @Before + public void initDatabase() { + + Flux.from(cf.create()) + .flatMap(c -> + c.createBatch() + .add("drop table if exists Account") + .add("create table Account(id IDENTITY(1,1), iban varchar(80) not null, balance DECIMAL(18,2) not null)") + .add("insert into Account(iban,balance) values ( 'BR430120980198201982', 100.00 ) ") + .add("insert into Account(iban,balance) values ( 'BR430120998729871000', 250.00 ) ") + .execute() + ) + .log() + .blockLast(); + } + + @Test + public void givenExistingAccountId_whenGetAccount_thenReturnExistingAccountInfo() { + + webTestClient + .get() + .uri("/accounts/1") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(Account.class) + .value((acc) -> { + assertThat(acc.getId(),is(1l)); + }); + } + + @Test + public void givenDatabaseHasSomeAccounts_whenGetAccount_thenReturnExistingAccounts() { + + webTestClient + .get() + .uri("/accounts") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isOk() + .expectBody(List.class) + .value((accounts) -> { + assertThat(accounts.size(),not(is(0))); + }); + } + + + @Test + public void givenNewAccountData_whenPostAccount_thenReturnNewAccountInfo() { + + webTestClient + .post() + .uri("/accounts") + .syncBody(new Account(null,"BR4303010298012098", 151.00 )) + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .is2xxSuccessful() + .expectBody(Account.class) + .value((acc) -> { + assertThat(acc.getId(),is(notNullValue())); + }); + + } + +} diff --git a/persistence-modules/r2dbc/src/test/resources/application.yml b/persistence-modules/r2dbc/src/test/resources/application.yml new file mode 100644 index 0000000000..8925116e4a --- /dev/null +++ b/persistence-modules/r2dbc/src/test/resources/application.yml @@ -0,0 +1,6 @@ +# R2DBC Test configuration +r2dbc: + url: r2dbc:h2:mem://./testdb + + + diff --git a/spring-cloud/spring-cloud-vault/pom.xml b/spring-cloud/spring-cloud-vault/pom.xml index 9a1be3f5c0..faf27b6ac8 100644 --- a/spring-cloud/spring-cloud-vault/pom.xml +++ b/spring-cloud/spring-cloud-vault/pom.xml @@ -42,6 +42,18 @@ org.springframework.boot spring-boot-starter-jdbc + + org.springframework.boot + spring-boot-devtools + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountRepo.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountRepo.java new file mode 100644 index 0000000000..318cc84957 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountRepo.java @@ -0,0 +1,10 @@ +package org.baeldung.spring.cloud.vaultsample; + +import org.baeldung.spring.cloud.vaultsample.domain.Account; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface AccountRepo extends JpaRepository{ + +} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountResource.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountResource.java new file mode 100644 index 0000000000..8fcaa9e2aa --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/AccountResource.java @@ -0,0 +1,27 @@ +package org.baeldung.spring.cloud.vaultsample; + +import org.baeldung.spring.cloud.vaultsample.domain.Account; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class AccountResource { + @Autowired + private AccountRepo repo; + + @GetMapping("/account/{id}") + public ResponseEntity getAccount(@PathVariable("id") Long id) { + + Account acc = repo.findById(id).orElse(null); + if ( acc != null ) { + return new ResponseEntity(acc, HttpStatus.OK); + } + else { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + } +} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/SecretResource.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/SecretResource.java new file mode 100644 index 0000000000..c4579da045 --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/SecretResource.java @@ -0,0 +1,37 @@ +/** + * + */ +package org.baeldung.spring.cloud.vaultsample; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author Philippe + * + */ +@RestController +public class SecretResource { + + @Autowired + Environment env; + + @GetMapping("/secret/{key}") + public ResponseEntity readSecret(@PathVariable("key") String key) { + + String value = env.getProperty(key); + + if ( value != null ) { + return new ResponseEntity(value, HttpStatus.OK); + } + else { + return new ResponseEntity("not found", HttpStatus.NOT_FOUND); + } + } +} diff --git a/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/domain/Account.java b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/domain/Account.java new file mode 100644 index 0000000000..df4778831b --- /dev/null +++ b/spring-cloud/spring-cloud-vault/src/main/java/org/baeldung/spring/cloud/vaultsample/domain/Account.java @@ -0,0 +1,133 @@ +/** + * + */ +package org.baeldung.spring.cloud.vaultsample.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.constraints.NotNull; + +/** + * @author Philippe + * + */ +@Entity +@Table(name = "account") +public class Account { + + @Id + private Long id; + + @NotNull + private String name; + + private Long branchId; + private Long customerId; + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the branchId + */ + public Long getBranchId() { + return branchId; + } + + /** + * @param branchId the branchId to set + */ + public void setBranchId(Long branchId) { + this.branchId = branchId; + } + + /** + * @return the customerId + */ + public Long getCustomerId() { + return customerId; + } + + /** + * @param customerId the customerId to set + */ + public void setCustomerId(Long customerId) { + this.customerId = customerId; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((branchId == null) ? 0 : branchId.hashCode()); + result = prime * result + ((customerId == null) ? 0 : customerId.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Account other = (Account) obj; + if (branchId == null) { + if (other.branchId != null) + return false; + } else if (!branchId.equals(other.branchId)) + return false; + if (customerId == null) { + if (other.customerId != null) + return false; + } else if (!customerId.equals(other.customerId)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + +} diff --git a/spring-cloud/spring-cloud-vault/src/main/resources/application.yml b/spring-cloud/spring-cloud-vault/src/main/resources/application.yml index 3d347ec855..1c75ac21e6 100644 --- a/spring-cloud/spring-cloud-vault/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-vault/src/main/resources/application.yml @@ -1,6 +1,11 @@ -spring: - application: - name: fakebank - - datasource: - url: jdbc:mysql://localhost:3306/fakebank +spring: + application: + name: fakebank + + datasource: + url: jdbc:mysql://localhost:3306/fakebank?serverTimezone=GMT-3 + hikari: connection-test-query: select 1 + idle-timeout: 5000 + max-lifetime: 120000 + maximum-pool-size: 5 + minimum-idle: 5 diff --git a/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml b/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml index 1e837c4920..7d38b06c0f 100644 --- a/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml +++ b/spring-cloud/spring-cloud-vault/src/main/resources/bootstrap.yml @@ -4,8 +4,6 @@ spring: uri: https://localhost:8200 connection-timeout: 5000 read-timeout: 15000 - config: - order: -10 ssl: trust-store: classpath:/vault.jks @@ -15,17 +13,19 @@ spring: enabled: true application-name: fakebank - kv: - enabled: false - backend: kv - application-name: fakebank - +# kv: +# enabled: false +# backend: kv +# application-name: fakebank +# database: enabled: true role: fakebank-accounts-rw -# backend: database -# username-property: spring.datasource.username -# password-property: spring.datasource.password + backend: database + username-property: spring.datasource.username + password-property: spring.datasource.password +# +# diff --git a/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl b/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl index c880f2d744..d16665a744 100644 --- a/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl +++ b/spring-cloud/spring-cloud-vault/src/test/vault-config/vault-test.hcl @@ -17,4 +17,7 @@ listener "tcp" { tls_key_file = "./src/test/vault-config/localhost.key" } +// Audit to stdout + + diff --git a/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt b/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt index b965a95321..2d5f2363ac 100644 --- a/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt +++ b/spring-cloud/spring-cloud-vault/vault-cheatsheet.txt @@ -5,16 +5,13 @@ 2. Open another shell and execute the command below: > vault operator init -Vault will output the unseal keys and root token: STORE THEM SAFELY !!! +Unseal Key 1: Iwvpd4IVofhcmQ2HEIPs5HMUbz4tz6JhqmLZ6+1MhAPx +Unseal Key 2: ANQDXUFGGtLtt6grX25YsdmeKELhM/ioKWzwFukJIe2f +Unseal Key 3: 8MHyzFnOvlwVQzdWYJ3BIN4xPDOn8a4VemZ/Qe5HgurU +Unseal Key 4: ywT9YR9OfxIpA4l1RniNNCvSZWAuNZsAEFRyD7aqFOrp +Unseal Key 5: q1c7M+lnlT72jGLoCH+jjri6KGSBhc5lCzlT0I1R9URU -Example output: -Unseal Key 1: OfCseaSZzjTZmrxhfx+5clKobwLGCNiJdAlfixSG9E3o -Unseal Key 2: iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT -Unseal Key 3: K0TleK3OYUvWFF+uIDsQuf5a+/gkv1PtZ3O47ornzRoF -Unseal Key 4: +5zhysLAO4hIdZs0kiZpkrRovw11uQacfloiBwnZBJA/ -Unseal Key 5: GDwSq18lXV3Cw4MoHsKIH137kuI0mdl36UiD9WxOdulc - -Initial Root Token: d341fdaf-1cf9-936a-3c38-cf5eec94b5c0 +Initial Root Token: dee7107a-8819-0719-62a3-cea3ea854589 ... @@ -73,8 +70,8 @@ flush privileges; > vault write database/roles/fakebank-accounts-rw ^ db_name=mysql-fakebank ^ creation_statements="CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}';GRANT SELECT,INSERT,UPDATE ON fakebank.* TO '{{name}}'@'%';" ^ - default_ttl="1m" ^ - max_ttl="2m" + default_ttl="5m" ^ + max_ttl="30m" === Get credentials > vault read database/creds/fakebank-accounts-rw diff --git a/spring-cloud/spring-cloud-vault/vault-unseal.bat b/spring-cloud/spring-cloud-vault/vault-unseal.bat index 8133f90892..1e3f229fcf 100644 --- a/spring-cloud/spring-cloud-vault/vault-unseal.bat +++ b/spring-cloud/spring-cloud-vault/vault-unseal.bat @@ -1,7 +1,7 @@ call %~dp0%/vault-env.bat -vault operator unseal OfCseaSZzjTZmrxhfx+5clKobwLGCNiJdAlfixSG9E3o -vault operator unseal iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT -vault operator unseal iplVLPTHW0n0WL5XuI6QWwyNtWbKTek1SoKcG0gR7vdT -vault operator unseal K0TleK3OYUvWFF+uIDsQuf5a+/gkv1PtZ3O47ornzRoF +vault operator unseal Iwvpd4IVofhcmQ2HEIPs5HMUbz4tz6JhqmLZ6+1MhAPx +vault operator unseal ANQDXUFGGtLtt6grX25YsdmeKELhM/ioKWzwFukJIe2f +vault operator unseal 8MHyzFnOvlwVQzdWYJ3BIN4xPDOn8a4VemZ/Qe5HgurU + From 85f4a100db5e80263911470eac65bb365dfa31be Mon Sep 17 00:00:00 2001 From: vatsalgosar Date: Fri, 26 Jul 2019 10:05:46 +0530 Subject: [PATCH 308/352] updated packages --- .../com/baeldung/springbootconfiguration/Application.java | 3 --- .../com/baeldung/springbootconfiguration/PersonService.java | 4 ++++ .../baeldung/springbootconfiguration/PersonServiceImpl.java | 4 ++++ .../ServiceImpl/PersonServiceImpl.java | 6 ------ .../springbootconfiguration/service/PersonService.java | 4 ---- 5 files changed, 8 insertions(+), 13 deletions(-) create mode 100644 spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java create mode 100644 spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java delete mode 100644 spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/ServiceImpl/PersonServiceImpl.java delete mode 100644 spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/service/PersonService.java diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java index ef9df2bf4a..146d59a81b 100644 --- a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java @@ -5,9 +5,6 @@ import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -import com.baeldung.springbootconfiguration.ServiceImpl.PersonServiceImpl; -import com.baeldung.springbootconfiguration.service.PersonService; - @ComponentScan(basePackages = { "com.baeldung.*" }) @SpringBootConfiguration public class Application { diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java new file mode 100644 index 0000000000..4909d957e5 --- /dev/null +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonService.java @@ -0,0 +1,4 @@ +package com.baeldung.springbootconfiguration; + +public interface PersonService { +} diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java new file mode 100644 index 0000000000..9f2af33e8e --- /dev/null +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/PersonServiceImpl.java @@ -0,0 +1,4 @@ +package com.baeldung.springbootconfiguration; + +public class PersonServiceImpl implements PersonService { +} diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/ServiceImpl/PersonServiceImpl.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/ServiceImpl/PersonServiceImpl.java deleted file mode 100644 index 3bec4e4b12..0000000000 --- a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/ServiceImpl/PersonServiceImpl.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.springbootconfiguration.ServiceImpl; - -import com.baeldung.springbootconfiguration.service.PersonService; - -public class PersonServiceImpl implements PersonService { -} diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/service/PersonService.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/service/PersonService.java deleted file mode 100644 index 5a18edde33..0000000000 --- a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/service/PersonService.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.baeldung.springbootconfiguration.service; - -public interface PersonService { -} From aa0658c823736fdc2d8c171f2f852a328674a76f Mon Sep 17 00:00:00 2001 From: vatsalgosar Date: Fri, 26 Jul 2019 10:09:08 +0530 Subject: [PATCH 309/352] changed package scan --- .../java/com/baeldung/springbootconfiguration/Application.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java index 146d59a81b..ae81b4872f 100644 --- a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java @@ -5,7 +5,7 @@ import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -@ComponentScan(basePackages = { "com.baeldung.*" }) +@ComponentScan(basePackages = {"com.baeldung.springbootconfiguration"}) @SpringBootConfiguration public class Application { From 78881a0a016ed94d139f85d9dab158bf19bf8ec4 Mon Sep 17 00:00:00 2001 From: vatsalgosar Date: Fri, 26 Jul 2019 10:10:46 +0530 Subject: [PATCH 310/352] package scan --- .../java/com/baeldung/springbootconfiguration/Application.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java index ae81b4872f..d4c8010d2b 100644 --- a/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java +++ b/spring-boot-bootstrap/src/main/java/com/baeldung/springbootconfiguration/Application.java @@ -5,7 +5,7 @@ import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -@ComponentScan(basePackages = {"com.baeldung.springbootconfiguration"}) +@ComponentScan(basePackages = {"com.baeldung.springbootconfiguration.*"}) @SpringBootConfiguration public class Application { From dee7128b928056d4fadf6e840035f47a0d1c6986 Mon Sep 17 00:00:00 2001 From: Maiklins Date: Fri, 26 Jul 2019 07:01:03 +0200 Subject: [PATCH 311/352] BAEL-3012 Spring Request Parameters with Thymeleaf (#7412) --- .../controller/ParticipantController.java | 28 ++++++++++++++++ .../resources/templates/participants.html | 32 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java create mode 100644 spring-thymeleaf/src/main/resources/templates/participants.html diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java new file mode 100644 index 0000000000..eebe37e000 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java @@ -0,0 +1,28 @@ +package com.example.demo; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import java.util.List; + +import static java.util.Arrays.asList; + +@Controller +public class ParticipantController { + + @RequestMapping("/") + public String index( + @RequestParam(value = "participant", required = false) String participant, + @RequestParam(value = "country", required = false) String country, + @RequestParam(value = "action", required = false) String action, + @RequestParam(value = "id", required = false) Integer id, + Model model + ) { + model.addAttribute("id", id); + List userIds = asList(1,2,3,4); + model.addAttribute("userIds", userIds); + return "participants"; + } +} diff --git a/spring-thymeleaf/src/main/resources/templates/participants.html b/spring-thymeleaf/src/main/resources/templates/participants.html new file mode 100644 index 0000000000..8d4e552093 --- /dev/null +++ b/spring-thymeleaf/src/main/resources/templates/participants.html @@ -0,0 +1,32 @@ + + + + + +

    Enter participant

    +
    + + + + + +
    + + +

    User Details

    +

    Details for user [[${id}]] ...

    +
    + +

    Users

    + +

    + User [[${userId}]] +

    +
    + + From f1d68f74f6298025354adb494feae9f7df5e5d65 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Fri, 26 Jul 2019 12:33:04 +0200 Subject: [PATCH 312/352] add new module --- persistence-modules/java-jpa-2/README.md | 1 + persistence-modules/java-jpa-2/pom.xml | 115 ++++++++++++++++++ .../java/com/baeldung/jpa/entity/Article.java | 0 .../java-jpa-2/src/main/resources/logback.xml | 13 ++ persistence-modules/pom.xml | 1 + pom.xml | 2 + 6 files changed, 132 insertions(+) create mode 100644 persistence-modules/java-jpa-2/README.md create mode 100644 persistence-modules/java-jpa-2/pom.xml rename persistence-modules/{java-jpa => java-jpa-2}/src/main/java/com/baeldung/jpa/entity/Article.java (100%) create mode 100644 persistence-modules/java-jpa-2/src/main/resources/logback.xml diff --git a/persistence-modules/java-jpa-2/README.md b/persistence-modules/java-jpa-2/README.md new file mode 100644 index 0000000000..e65ce65a95 --- /dev/null +++ b/persistence-modules/java-jpa-2/README.md @@ -0,0 +1 @@ +# Relevant Articles diff --git a/persistence-modules/java-jpa-2/pom.xml b/persistence-modules/java-jpa-2/pom.xml new file mode 100644 index 0000000000..c8c9a24599 --- /dev/null +++ b/persistence-modules/java-jpa-2/pom.xml @@ -0,0 +1,115 @@ + + + 4.0.0 + java-jpa-2 + java-jpa-2 + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + ../../pom.xml + + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + + + com.h2database + h2 + ${h2.version} + + + + + javax.persistence + javax.persistence-api + ${javax.persistence-api.version} + + + + + org.eclipse.persistence + eclipselink + ${eclipselink.version} + runtime + + + org.postgresql + postgresql + ${postgres.version} + runtime + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + -proc:none + + + + org.bsc.maven + maven-processor-plugin + 3.3.3 + + + process + + process + + generate-sources + + target/metamodel + + org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + target/metamodel + + + + + + + + + + 5.4.0.Final + 2.7.4-RC1 + 42.2.5 + 2.2 + + + diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Article.java b/persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/entity/Article.java similarity index 100% rename from persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Article.java rename to persistence-modules/java-jpa-2/src/main/java/com/baeldung/jpa/entity/Article.java diff --git a/persistence-modules/java-jpa-2/src/main/resources/logback.xml b/persistence-modules/java-jpa-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/java-jpa-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 390bcc9d51..79879fc2ff 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -29,6 +29,7 @@ java-cockroachdb java-jdbi java-jpa + java-jpa-2 java-mongodb jnosql liquibase diff --git a/pom.xml b/pom.xml index 2e34254bf5..a4e74f8423 100644 --- a/pom.xml +++ b/pom.xml @@ -988,6 +988,7 @@ persistence-modules/hibernate5 persistence-modules/hibernate-mapping persistence-modules/java-jpa + persistence-modules/java-jpa-2 persistence-modules/java-mongodb persistence-modules/jnosql @@ -1500,6 +1501,7 @@ persistence-modules/hibernate5 persistence-modules/java-jpa + persistence-modules/java-jpa-2 persistence-modules/java-mongodb persistence-modules/jnosql From 7486e228856e486261a2459276c9969c39c176e3 Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Fri, 26 Jul 2019 11:42:52 -0400 Subject: [PATCH 313/352] =?UTF-8?q?=C2=96BAEL-3153:=20Reverted=20READ=20fi?= =?UTF-8?q?le=20to=20original=20contents.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- java-strings-2/README.MD | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/java-strings-2/README.MD b/java-strings-2/README.MD index 4db93f64e0..c6d4f0222a 100644 --- a/java-strings-2/README.MD +++ b/java-strings-2/README.MD @@ -1,7 +1,7 @@ -## Relevant Articles - -- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) -- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) -- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) -- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) -- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) +## Relevant Articles + +- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) +- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) +- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) +- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) +- [String Initialization in Java](https://www.baeldung.com/java-string-initialization) From e67462412e8deb5b0a23ed162ce82c5b8ecaf097 Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Fri, 26 Jul 2019 23:33:34 -0400 Subject: [PATCH 314/352] BAEL-3153: Corrected name of foreign lower case variable in tests --- .../com/baeldung/string/changecase/ToUpperCaseUnitTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java index 365b5ae52f..1807f854b2 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java +++ b/java-strings-2/src/test/java/com/baeldung/string/changecase/ToUpperCaseUnitTest.java @@ -10,7 +10,7 @@ public class ToUpperCaseUnitTest { private static final Locale TURKISH = new Locale("tr"); private String name = "John Doe"; - private String foreignUppercase = "\u0069"; + private String foreignLowercase = "\u0069"; @Test public void givenMixedCaseString_WhenToUpperCase_ThenResultIsUpperCase() { @@ -19,11 +19,11 @@ public class ToUpperCaseUnitTest { @Test public void givenForeignString_WhenToUpperCaseWithoutLocale_ThenResultIsUpperCase() { - assertEquals("\u0049", foreignUppercase.toUpperCase()); + assertEquals("\u0049", foreignLowercase.toUpperCase()); } @Test public void givenForeignString_WhenToUpperCaseWithLocale_ThenResultIsUpperCase() { - assertEquals("\u0130", foreignUppercase.toUpperCase(TURKISH)); + assertEquals("\u0130", foreignLowercase.toUpperCase(TURKISH)); } } From f1232810e2f3b569a72ce145d2e4d08ba072e0ea Mon Sep 17 00:00:00 2001 From: rpvilao Date: Sat, 27 Jul 2019 09:40:59 +0200 Subject: [PATCH 315/352] Fixes the parent boot (#7409) --- parent-boot-performance/README.md | 1 - parent-boot-performance/pom.xml | 92 ------------------------------- spring-boot-performance/pom.xml | 6 +- 3 files changed, 3 insertions(+), 96 deletions(-) delete mode 100644 parent-boot-performance/README.md delete mode 100644 parent-boot-performance/pom.xml diff --git a/parent-boot-performance/README.md b/parent-boot-performance/README.md deleted file mode 100644 index fce9e101da..0000000000 --- a/parent-boot-performance/README.md +++ /dev/null @@ -1 +0,0 @@ -This is a parent module for projects that want to take advantage of the latest Spring Boot improvements/features. \ No newline at end of file diff --git a/parent-boot-performance/pom.xml b/parent-boot-performance/pom.xml deleted file mode 100644 index b7d12e2ba4..0000000000 --- a/parent-boot-performance/pom.xml +++ /dev/null @@ -1,92 +0,0 @@ - - 4.0.0 - parent-boot-performance - 0.0.1-SNAPSHOT - parent-boot-performance - pom - Parent for all modules that want to take advantage of the latest Spring Boot improvements/features. Current version: 2.2 - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - - - - io.rest-assured - rest-assured - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - ${start-class} - - - - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - - - - thin-jar - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.springframework.boot.experimental - spring-boot-thin-layout - ${thin.version} - - - - - - - - - - 3.1.0 - - 1.0.21.RELEASE - 2.2.0.M3 - - diff --git a/spring-boot-performance/pom.xml b/spring-boot-performance/pom.xml index f51df8bc0c..a4efa4a8d7 100644 --- a/spring-boot-performance/pom.xml +++ b/spring-boot-performance/pom.xml @@ -8,10 +8,10 @@ This is a simple Spring Boot application taking advantage of the latest Spring Boot improvements/features. Current version: 2.2 - parent-boot-performance + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-performance + ../parent-boot-2 @@ -42,4 +42,4 @@ com.baeldung.lazyinitialization.Application -
    \ No newline at end of file +
    From 8d62e17b8e05f07f14b9fdf3f9c0c86063d13046 Mon Sep 17 00:00:00 2001 From: maryarm <45322329+maryarm@users.noreply.github.com> Date: Sat, 27 Jul 2019 16:50:52 +0430 Subject: [PATCH 316/352] #BAEL-2888- Reloading Properties Files in Spring (#7392) Code samples for BAEL-2888 --- spring-boot-properties/.gitignore | 17 ++ spring-boot-properties/README.md | 2 + spring-boot-properties/extra.properties | 1 + spring-boot-properties/extra2.properties | 1 + spring-boot-properties/pom.xml | 104 +++++++++++ .../SpringBootPropertiesApplication.java | 44 +++++ .../configs/PropertiesException.java | 10 ++ .../configs/ReloadableProperties.java | 49 ++++++ .../configs/ReloadablePropertySource.java | 33 ++++ .../ReloadablePropertySourceConfig.java | 29 ++++ .../ReloadablePropertySourceFactory.java | 25 +++ .../src/main/resources/application.properties | 3 + .../PropertiesReloadIntegrationTest.java | 161 ++++++++++++++++++ .../SpringBootPropertiesTestApplication.java | 28 +++ ...figurationPropertiesRefreshConfigBean.java | 20 +++ .../beans/EnvironmentConfigBean.java | 26 +++ .../beans/PropertiesConfigBean.java | 19 +++ .../beans/ValueRefreshConfigBean.java | 13 ++ .../src/test/resources/application.properties | 3 + 19 files changed, 588 insertions(+) create mode 100644 spring-boot-properties/.gitignore create mode 100644 spring-boot-properties/README.md create mode 100644 spring-boot-properties/extra.properties create mode 100644 spring-boot-properties/extra2.properties create mode 100644 spring-boot-properties/pom.xml create mode 100644 spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java create mode 100644 spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java create mode 100644 spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java create mode 100644 spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java create mode 100644 spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java create mode 100644 spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java create mode 100644 spring-boot-properties/src/main/resources/application.properties create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java create mode 100644 spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java create mode 100644 spring-boot-properties/src/test/resources/application.properties diff --git a/spring-boot-properties/.gitignore b/spring-boot-properties/.gitignore new file mode 100644 index 0000000000..0532ef1888 --- /dev/null +++ b/spring-boot-properties/.gitignore @@ -0,0 +1,17 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear + +*.ipr +*.iml +*.iws diff --git a/spring-boot-properties/README.md b/spring-boot-properties/README.md new file mode 100644 index 0000000000..c43cf4865c --- /dev/null +++ b/spring-boot-properties/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Reloading Properties in Spring](https://www.baeldung.com/reloading-properties-files-in-spring/) \ No newline at end of file diff --git a/spring-boot-properties/extra.properties b/spring-boot-properties/extra.properties new file mode 100644 index 0000000000..8e28a6f889 --- /dev/null +++ b/spring-boot-properties/extra.properties @@ -0,0 +1 @@ +application.theme.color=blue \ No newline at end of file diff --git a/spring-boot-properties/extra2.properties b/spring-boot-properties/extra2.properties new file mode 100644 index 0000000000..2c46edc584 --- /dev/null +++ b/spring-boot-properties/extra2.properties @@ -0,0 +1 @@ +application.theme.background=red \ No newline at end of file diff --git a/spring-boot-properties/pom.xml b/spring-boot-properties/pom.xml new file mode 100644 index 0000000000..27ac48252b --- /dev/null +++ b/spring-boot-properties/pom.xml @@ -0,0 +1,104 @@ + + + 4.0.0 + spring-boot-properties + jar + spring-boot-properties + Spring Boot Properties Module + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + commons-configuration + commons-configuration + ${commons-configuration.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.cloud + spring-cloud-starter + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + spring-boot-properties + + + src/main/resources + true + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + + + + + json + + + + + + + + + + 1.8 + Greenwich.SR1 + 1.10 + + + diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java b/spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java new file mode 100644 index 0000000000..67bbddf9f1 --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java @@ -0,0 +1,44 @@ +package com.baeldung.properties; + +import com.baeldung.properties.configs.ReloadableProperties; +import java.io.File; +import java.util.Properties; +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; + +@SpringBootApplication +public class SpringBootPropertiesApplication { + + @Bean + @ConditionalOnProperty(name = "spring.config.location", matchIfMissing = false) + public PropertiesConfiguration propertiesConfiguration( + @Value("${spring.config.location}") String path, + @Value("${spring.properties.refreshDelay}") long refreshDelay) throws Exception { + String filePath = path.substring("file:".length()); + PropertiesConfiguration configuration = new PropertiesConfiguration(new File(filePath).getCanonicalPath()); + FileChangedReloadingStrategy fileChangedReloadingStrategy = new FileChangedReloadingStrategy(); + fileChangedReloadingStrategy.setRefreshDelay(refreshDelay); + configuration.setReloadingStrategy(fileChangedReloadingStrategy); + return configuration; + } + + @Bean + @ConditionalOnBean(PropertiesConfiguration.class) + @Primary + public Properties properties(PropertiesConfiguration propertiesConfiguration) throws Exception { + ReloadableProperties properties = new ReloadableProperties(propertiesConfiguration); + return properties; + } + + public static void main(String[] args) { + SpringApplication.run(SpringBootPropertiesApplication.class, args); + } + +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java new file mode 100644 index 0000000000..5ec3a042f7 --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java @@ -0,0 +1,10 @@ +package com.baeldung.properties.configs; + +public class PropertiesException extends RuntimeException { + public PropertiesException() { + } + + public PropertiesException(Throwable cause) { + super(cause); + } +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java new file mode 100644 index 0000000000..33d503b9bd --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java @@ -0,0 +1,49 @@ +package com.baeldung.properties.configs; + +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.util.Properties; +import javax.naming.OperationNotSupportedException; +import org.apache.commons.configuration.PropertiesConfiguration; + +public class ReloadableProperties extends Properties { + private PropertiesConfiguration propertiesConfiguration; + + public ReloadableProperties(PropertiesConfiguration propertiesConfiguration) throws IOException { + super.load(new FileReader(propertiesConfiguration.getFile())); + this.propertiesConfiguration = propertiesConfiguration; + } + + @Override + public synchronized Object setProperty(String key, String value) { + propertiesConfiguration.setProperty(key, value); + return super.setProperty(key, value); + } + + @Override + public String getProperty(String key) { + String val = propertiesConfiguration.getString(key); + super.setProperty(key, val); + return val; + } + + @Override + public String getProperty(String key, String defaultValue) { + String val = propertiesConfiguration.getString(key, defaultValue); + super.setProperty(key, val); + return val; + } + + @Override + public synchronized void load(Reader reader) throws IOException { + throw new PropertiesException(new OperationNotSupportedException()); + } + + @Override + public synchronized void load(InputStream inStream) throws IOException { + throw new PropertiesException(new OperationNotSupportedException()); + } + +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java new file mode 100644 index 0000000000..8a0cef955f --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java @@ -0,0 +1,33 @@ +package com.baeldung.properties.configs; + +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy; +import org.springframework.core.env.PropertySource; +import org.springframework.util.StringUtils; + +public class ReloadablePropertySource extends PropertySource { + + PropertiesConfiguration propertiesConfiguration; + + public ReloadablePropertySource(String name, PropertiesConfiguration propertiesConfiguration) { + super(name); + this.propertiesConfiguration = propertiesConfiguration; + } + + public ReloadablePropertySource(String name, String path) { + super(StringUtils.isEmpty(name) ? path : name); + try { + this.propertiesConfiguration = new PropertiesConfiguration(path); + FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy(); + strategy.setRefreshDelay(1000); + this.propertiesConfiguration.setReloadingStrategy(strategy); + } catch (Exception e) { + throw new PropertiesException(e); + } + } + + @Override + public Object getProperty(String s) { + return propertiesConfiguration.getProperty(s); + } +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java new file mode 100644 index 0000000000..37e1a04839 --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java @@ -0,0 +1,29 @@ +package com.baeldung.properties.configs; + +import org.apache.commons.configuration.PropertiesConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MutablePropertySources; + +@Configuration +public class ReloadablePropertySourceConfig { + + private ConfigurableEnvironment env; + + public ReloadablePropertySourceConfig(@Autowired ConfigurableEnvironment env) { + this.env = env; + } + + @Bean + @ConditionalOnProperty(name = "spring.config.location", matchIfMissing = false) + public ReloadablePropertySource reloadablePropertySource(PropertiesConfiguration properties) { + ReloadablePropertySource ret = new ReloadablePropertySource("dynamic", properties); + MutablePropertySources sources = env.getPropertySources(); + sources.addFirst(ret); + return ret; + } + +} diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java new file mode 100644 index 0000000000..574362b3bf --- /dev/null +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java @@ -0,0 +1,25 @@ +package com.baeldung.properties.configs; + +import java.io.IOException; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.FileUrlResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.DefaultPropertySourceFactory; +import org.springframework.core.io.support.EncodedResource; + +public class ReloadablePropertySourceFactory extends DefaultPropertySourceFactory { + @Override + public PropertySource createPropertySource(String s, EncodedResource encodedResource) throws IOException { + Resource internal = encodedResource.getResource(); + if (internal instanceof FileSystemResource) { + return new ReloadablePropertySource(s, ((FileSystemResource) internal).getPath()); + } + if (internal instanceof FileUrlResource) { + return new ReloadablePropertySource(s, ((FileUrlResource) internal) + .getURL() + .getPath()); + } + return super.createPropertySource(s, encodedResource); + } +} diff --git a/spring-boot-properties/src/main/resources/application.properties b/spring-boot-properties/src/main/resources/application.properties new file mode 100644 index 0000000000..f976004a04 --- /dev/null +++ b/spring-boot-properties/src/main/resources/application.properties @@ -0,0 +1,3 @@ +management.endpoints.web.exposure.include=refresh +spring.properties.refreshDelay=1000 +spring.config.location=file:extra.properties diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java b/spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java new file mode 100644 index 0000000000..a73311ded8 --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java @@ -0,0 +1,161 @@ +package com.baeldung.properties; + +import com.baeldung.properties.beans.ConfigurationPropertiesRefreshConfigBean; +import com.baeldung.properties.beans.EnvironmentConfigBean; +import com.baeldung.properties.beans.PropertiesConfigBean; +import com.baeldung.properties.beans.ValueRefreshConfigBean; +import java.io.FileOutputStream; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = SpringBootPropertiesTestApplication.class) +public class PropertiesReloadIntegrationTest { + + protected MockMvc mvc; + + protected long refreshDelay = 3000; + + @Autowired + WebApplicationContext webApplicationContext; + + @Autowired + ValueRefreshConfigBean valueRefreshConfigBean; + + @Autowired + ConfigurationPropertiesRefreshConfigBean configurationPropertiesRefreshConfigBean; + + @Autowired + EnvironmentConfigBean environmentConfigBean; + + @Autowired + PropertiesConfigBean propertiesConfigBean; + + @Autowired + @Qualifier("singletonValueRefreshConfigBean") + ValueRefreshConfigBean singletonValueRefreshConfigBean; + + + @Before + public void setUp() throws Exception { + mvc = MockMvcBuilders + .webAppContextSetup(webApplicationContext) + .build(); + createConfig("extra.properties", "application.theme.color", "blue"); + createConfig("extra2.properties", "application.theme.background", "red"); + Thread.sleep(refreshDelay); + callRefresh(); + } + + @After + public void tearDown() throws Exception { + createConfig("extra.properties", "application.theme.color", "blue"); + createConfig("extra2.properties", "application.theme.background", "red"); + } + + @Test + public void givenEnvironmentReader_whenColorChanged_thenExpectChangeValue() throws Exception { + Assert.assertEquals("blue", environmentConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("red", environmentConfigBean.getColor()); + } + + @Test + public void givenEnvironmentReader_whenBackgroundChanged_thenExpectChangeValue() throws Exception { + Assert.assertEquals("red", environmentConfigBean.getBackgroundColor()); + + createConfig("extra2.properties", "application.theme.background", "blue"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("blue", environmentConfigBean.getBackgroundColor()); + } + + @Test + public void givenPropertiesReader_whenColorChanged_thenExpectChangeValue() throws Exception { + Assert.assertEquals("blue", propertiesConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("red", propertiesConfigBean.getColor()); + } + + @Test + public void givenRefreshScopedValueReader_whenColorChangedAndRefreshCalled_thenExpectChangeValue() throws Exception { + Assert.assertEquals("blue", valueRefreshConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("blue", valueRefreshConfigBean.getColor()); + + callRefresh(); + + Assert.assertEquals("red", valueRefreshConfigBean.getColor()); + } + + @Test + public void givenSingletonRefreshScopedValueReader_whenColorChangedAndRefreshCalled_thenExpectOldValue() throws Exception { + + Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor()); + + callRefresh(); + + Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor()); + } + + @Test + public void givenRefreshScopedConfigurationPropertiesReader_whenColorChangedAndRefreshCalled_thenExpectChangeValue() throws Exception { + + Assert.assertEquals("blue", configurationPropertiesRefreshConfigBean.getColor()); + + createConfig("extra.properties", "application.theme.color", "red"); + Thread.sleep(refreshDelay); + + Assert.assertEquals("blue", configurationPropertiesRefreshConfigBean.getColor()); + + callRefresh(); + + Assert.assertEquals("red", configurationPropertiesRefreshConfigBean.getColor()); + } + + public void callRefresh() throws Exception { + MvcResult mvcResult = mvc + .perform(MockMvcRequestBuilders + .post("/actuator/refresh") + .accept(MediaType.APPLICATION_JSON_VALUE)) + .andReturn(); + MockHttpServletResponse response = mvcResult.getResponse(); + Assert.assertEquals(response.getStatus(), 200); + } + + public void createConfig(String file, String key, String value) throws Exception { + FileOutputStream fo = new FileOutputStream(file); + fo.write(String + .format("%s=%s", key, value) + .getBytes()); + fo.close(); + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java b/spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java new file mode 100644 index 0000000000..c572a6c053 --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java @@ -0,0 +1,28 @@ +package com.baeldung.properties; + +import com.baeldung.properties.beans.ValueRefreshConfigBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Scope; +import org.springframework.test.context.web.WebAppConfiguration; + +@SpringBootApplication +@WebAppConfiguration +public class SpringBootPropertiesTestApplication { + + @Bean("singletonValueRefreshConfigBean") + @RefreshScope + @Scope("singleton") + public ValueRefreshConfigBean singletonValueRefreshConfigBean(@Value("${application.theme.color:null}") String val) { + return new ValueRefreshConfigBean(val); + } + + @Bean + @RefreshScope + public ValueRefreshConfigBean valueRefreshConfigBean(@Value("${application.theme.color:null}") String val) { + return new ValueRefreshConfigBean(val); + } + +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java new file mode 100644 index 0000000000..31f168fdcc --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java @@ -0,0 +1,20 @@ +package com.baeldung.properties.beans; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "application.theme") +@RefreshScope +public class ConfigurationPropertiesRefreshConfigBean { + private String color; + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java new file mode 100644 index 0000000000..fef12f8656 --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java @@ -0,0 +1,26 @@ +package com.baeldung.properties.beans; + +import com.baeldung.properties.configs.ReloadablePropertySourceFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@PropertySource(value = "file:extra2.properties", factory = ReloadablePropertySourceFactory.class) +public class EnvironmentConfigBean { + + private Environment environment; + + public EnvironmentConfigBean(@Autowired Environment environment) { + this.environment = environment; + } + + public String getColor() { + return environment.getProperty("application.theme.color"); + } + + public String getBackgroundColor() { + return environment.getProperty("application.theme.background"); + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java new file mode 100644 index 0000000000..da773b283a --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java @@ -0,0 +1,19 @@ +package com.baeldung.properties.beans; + +import java.util.Properties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class PropertiesConfigBean { + + private Properties properties; + + public PropertiesConfigBean(@Autowired Properties properties) { + this.properties = properties; + } + + public String getColor() { + return properties.getProperty("application.theme.color"); + } +} diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java new file mode 100644 index 0000000000..d806938092 --- /dev/null +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java @@ -0,0 +1,13 @@ +package com.baeldung.properties.beans; + +public class ValueRefreshConfigBean { + private String color; + + public ValueRefreshConfigBean(String color) { + this.color = color; + } + + public String getColor() { + return color; + } +} diff --git a/spring-boot-properties/src/test/resources/application.properties b/spring-boot-properties/src/test/resources/application.properties new file mode 100644 index 0000000000..6fc241a106 --- /dev/null +++ b/spring-boot-properties/src/test/resources/application.properties @@ -0,0 +1,3 @@ +management.endpoints.web.exposure.include=refresh +spring.properties.refreshDelay=1000 +spring.config.location=file:extra.properties \ No newline at end of file From 1be61beeb38de84a792550fbd4af889f38eeb086 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 27 Jul 2019 17:58:14 +0530 Subject: [PATCH 317/352] [BAEL-16086] - Moved core-java-arrays module, added missing pom.xml, fixed pmd errors --- .../core-java-arrays-2/.gitignore | 25 ++++++++++ .../core-java-arrays-2}/README.MD | 0 core-java-modules/core-java-arrays-2/pom.xml | 50 +++++++++++++++++++ .../conversions/StreamArrayConversion.java | 0 .../array/looping/LoopDiagonally.java | 0 .../StreamArrayConversionUnitTest.java | 0 .../array/looping/LoopDiagonallyUnitTest.java | 2 +- pom.xml | 2 + 8 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-arrays-2/.gitignore rename {core-java-arrays => core-java-modules/core-java-arrays-2}/README.MD (100%) create mode 100644 core-java-modules/core-java-arrays-2/pom.xml rename {core-java-arrays => core-java-modules/core-java-arrays-2}/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java (100%) rename {core-java-arrays => core-java-modules/core-java-arrays-2}/src/main/java/com/baeldung/array/looping/LoopDiagonally.java (100%) rename {core-java-arrays => core-java-modules/core-java-arrays-2}/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java (100%) rename core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java => core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java (93%) diff --git a/core-java-modules/core-java-arrays-2/.gitignore b/core-java-modules/core-java-arrays-2/.gitignore new file mode 100644 index 0000000000..374c8bf907 --- /dev/null +++ b/core-java-modules/core-java-arrays-2/.gitignore @@ -0,0 +1,25 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-arrays/README.MD b/core-java-modules/core-java-arrays-2/README.MD similarity index 100% rename from core-java-arrays/README.MD rename to core-java-modules/core-java-arrays-2/README.MD diff --git a/core-java-modules/core-java-arrays-2/pom.xml b/core-java-modules/core-java-arrays-2/pom.xml new file mode 100644 index 0000000000..bfe8a349e1 --- /dev/null +++ b/core-java-modules/core-java-arrays-2/pom.xml @@ -0,0 +1,50 @@ + + 4.0.0 + com.baeldung + core-java-arrays-2 + 0.1.0-SNAPSHOT + core-java-arrays-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + core-java-arrays-2 + + + src/main/resources + true + + + + + + + + 3.9 + + 3.10.0 + + + diff --git a/core-java-arrays/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java similarity index 100% rename from core-java-arrays/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java rename to core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java diff --git a/core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java b/core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java similarity index 100% rename from core-java-arrays/src/main/java/com/baeldung/array/looping/LoopDiagonally.java rename to core-java-modules/core-java-arrays-2/src/main/java/com/baeldung/array/looping/LoopDiagonally.java diff --git a/core-java-arrays/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java similarity index 100% rename from core-java-arrays/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java rename to core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java diff --git a/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java similarity index 93% rename from core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java rename to core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java index df6079270b..5f670f4a59 100644 --- a/core-java-arrays/src/test/java/com/baeldung/array/looping/LoopDiagonallyTest.java +++ b/core-java-modules/core-java-arrays-2/src/test/java/com/baeldung/array/looping/LoopDiagonallyUnitTest.java @@ -4,7 +4,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; -public class LoopDiagonallyTest { +public class LoopDiagonallyUnitTest { @Test public void twoArrayIsLoopedDiagonallyAsExpected() { diff --git a/pom.xml b/pom.xml index c46a9a5d5a..6cdb35063e 100644 --- a/pom.xml +++ b/pom.xml @@ -392,6 +392,7 @@ core-java-modules/core-java-arrays + core-java-modules/core-java-arrays-2 core-java-modules/core-java-collections core-java-modules/core-java-collections-list core-java-modules/core-java-collections-list-2 @@ -1088,6 +1089,7 @@ core-java-modules/core-java-arrays + core-java-modules/core-java-arrays-2 core-java-modules/core-java-collections core-java-modules/core-java-collections-list core-java-modules/core-java-collections-list-2 From 49cfd94439b2283051ab2587043544e97b0a740e Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 27 Jul 2019 18:06:02 +0530 Subject: [PATCH 318/352] [BAEL-15959] - Removed spring-security dependency --- spring-5-mvc/pom.xml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 302080a8b4..1d96df3d03 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -23,10 +23,6 @@ org.springframework.boot spring-boot-starter-data-jpa - - org.springframework.boot - spring-boot-starter-security - org.springframework.boot spring-boot-starter-validation From 24135c03cfea302b60a9cd66fc18735f407d5592 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sun, 28 Jul 2019 00:01:06 +0300 Subject: [PATCH 319/352] modify graph implementation --- .../main/java/com/baeldung/graph/Graph.java | 33 ++++++++++--------- .../com/baeldung/graph/GraphUnitTest.java | 8 ++++- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/data-structures/src/main/java/com/baeldung/graph/Graph.java b/data-structures/src/main/java/com/baeldung/graph/Graph.java index b20301f86f..16b7e04297 100644 --- a/data-structures/src/main/java/com/baeldung/graph/Graph.java +++ b/data-structures/src/main/java/com/baeldung/graph/Graph.java @@ -1,36 +1,36 @@ package com.baeldung.graph; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Stack; public class Graph { - private List> neighbours; - private int n; + private Map> adjVertices; - public Graph(int n) { - this.n = n; - this.neighbours = new ArrayList>(n); - for (int i = 0; i < n; i++) { - this.neighbours.add(new ArrayList()); - } + public Graph() { + this.adjVertices = new HashMap>(); + } + + public void addVertex(int vertex) { + adjVertices.putIfAbsent(vertex, new ArrayList<>()); } public void addEdge(int src, int dest) { - this.neighbours.get(src) - .add(dest); + adjVertices.get(src).add(dest); } public void dfsWithoutRecursion(int start) { Stack stack = new Stack(); - boolean[] isVisited = new boolean[n]; + boolean[] isVisited = new boolean[adjVertices.size()]; stack.push(start); while (!stack.isEmpty()) { int current = stack.pop(); isVisited[current] = true; System.out.print(" " + current); - for (int dest : neighbours.get(current)) { + for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) stack.push(dest); } @@ -38,14 +38,14 @@ public class Graph { } public void dfs(int start) { - boolean[] isVisited = new boolean[n]; + boolean[] isVisited = new boolean[adjVertices.size()]; dfsRecursive(start, isVisited); } private void dfsRecursive(int current, boolean[] isVisited) { isVisited[current] = true; System.out.print(" " + current); - for (int dest : neighbours.get(current)) { + for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) dfsRecursive(dest, isVisited); } @@ -53,7 +53,7 @@ public class Graph { public void topologicalSort(int start) { Stack result = new Stack(); - boolean[] isVisited = new boolean[n]; + boolean[] isVisited = new boolean[adjVertices.size()]; topologicalSortRecursive(start, isVisited, result); while (!result.isEmpty()) { System.out.print(" " + result.pop()); @@ -62,10 +62,11 @@ public class Graph { private void topologicalSortRecursive(int current, boolean[] isVisited, Stack result) { isVisited[current] = true; - for (int dest : neighbours.get(current)) { + for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) topologicalSortRecursive(dest, isVisited, result); } result.push(current); } + } diff --git a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java index 837f83b494..249cb6e093 100644 --- a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java +++ b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java @@ -19,7 +19,13 @@ public class GraphUnitTest { } private Graph createDirectedGraph() { - Graph graph = new Graph(6); + Graph graph = new Graph(); + graph.addVertex(0); + graph.addVertex(1); + graph.addVertex(2); + graph.addVertex(3); + graph.addVertex(4); + graph.addVertex(5); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 3); From c4110e5fe8a297c9688f6530de973b443382808f Mon Sep 17 00:00:00 2001 From: Devender Kumar <47500074+kumar-devender@users.noreply.github.com> Date: Sun, 28 Jul 2019 06:19:16 +0200 Subject: [PATCH 320/352] Added big decimal validation (#7379) * Added cascading type mudule * fix compile error * updated dependency version in pom * Added BigDecimal validation classes * Updated test cases * Remove syso from test cases * Updated test cases --- .../bigdecimal/Invoice.java | 19 ++++++ .../bigdecimal/InvoiceUnitTest.java | 62 +++++++++++++++++++ .../jpa-hibernate-cascade-type/pom.xml | 8 +-- 3 files changed, 85 insertions(+), 4 deletions(-) create mode 100644 javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java create mode 100644 javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java new file mode 100644 index 0000000000..6df1b79a60 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/bigdecimal/Invoice.java @@ -0,0 +1,19 @@ +package org.baeldung.javabeanconstraints.bigdecimal; + +import java.math.BigDecimal; + +import javax.validation.constraints.DecimalMin; +import javax.validation.constraints.Digits; + +public class Invoice { + + @DecimalMin(value = "0.0", inclusive = false) + @Digits(integer=3, fraction=2) + private BigDecimal price; + private String description; + + public Invoice(BigDecimal price, String description) { + this.price = price; + this.description = description; + } +} diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java new file mode 100644 index 0000000000..525dd7d1ad --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java @@ -0,0 +1,62 @@ +package org.baeldung.javabeanconstraints.bigdecimal; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.math.BigDecimal; +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class InvoiceUnitTest { + + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenPriceIntegerDigitLessThanThreeWithDecimalValue_thenShouldGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(10.21), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)")); + } + + @Test + public void whenPriceIntegerDigitLessThanThreeWithIntegerValue_thenShouldNotGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(10), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenPriceIntegerDigitGreaterThanThree_thenShouldGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(1021.21), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)")); + } + + @Test + public void whenPriceIsZero_thenShouldGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(000.00), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("must be greater than 0.0")); + } + + @Test + public void whenPriceIsGreaterThanZero_thenShouldNotGiveConstraintViolations() { + Invoice invoice = new Invoice(new BigDecimal(100.50), "Book purchased"); + Set> violations = validator.validate(invoice); + assertThat(violations.size()).isEqualTo(0); + } + +} diff --git a/persistence-modules/jpa-hibernate-cascade-type/pom.xml b/persistence-modules/jpa-hibernate-cascade-type/pom.xml index a45f297a6b..8cfc2a5fa2 100644 --- a/persistence-modules/jpa-hibernate-cascade-type/pom.xml +++ b/persistence-modules/jpa-hibernate-cascade-type/pom.xml @@ -2,10 +2,6 @@ - jpa-hibernate-cascade-type - 4.0.0 - 1.0.0-SNAPSHOT - com.baeldung parent-modules @@ -13,6 +9,10 @@ ../../ + jpa-hibernate-cascade-type + 4.0.0 + 1.0.0-SNAPSHOT + org.hibernate From 76aa185add844f125c481171236e17a5fcbca07f Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:32:42 +0300 Subject: [PATCH 321/352] changing case --- {Twitter4J => twitter4J-temp}/README.md | 0 {Twitter4J => twitter4J-temp}/pom.xml | 0 .../src/main/java/com/baeldung/Application.java | 0 {Twitter4J => twitter4J-temp}/src/main/resources/logback.xml | 0 .../src/main/resources/twitter4j.properties | 0 .../src/test/java/com/baeldung/ApplicationIntegrationTest.java | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename {Twitter4J => twitter4J-temp}/README.md (100%) rename {Twitter4J => twitter4J-temp}/pom.xml (100%) rename {Twitter4J => twitter4J-temp}/src/main/java/com/baeldung/Application.java (100%) rename {Twitter4J => twitter4J-temp}/src/main/resources/logback.xml (100%) rename {Twitter4J => twitter4J-temp}/src/main/resources/twitter4j.properties (100%) rename {Twitter4J => twitter4J-temp}/src/test/java/com/baeldung/ApplicationIntegrationTest.java (100%) diff --git a/Twitter4J/README.md b/twitter4J-temp/README.md similarity index 100% rename from Twitter4J/README.md rename to twitter4J-temp/README.md diff --git a/Twitter4J/pom.xml b/twitter4J-temp/pom.xml similarity index 100% rename from Twitter4J/pom.xml rename to twitter4J-temp/pom.xml diff --git a/Twitter4J/src/main/java/com/baeldung/Application.java b/twitter4J-temp/src/main/java/com/baeldung/Application.java similarity index 100% rename from Twitter4J/src/main/java/com/baeldung/Application.java rename to twitter4J-temp/src/main/java/com/baeldung/Application.java diff --git a/Twitter4J/src/main/resources/logback.xml b/twitter4J-temp/src/main/resources/logback.xml similarity index 100% rename from Twitter4J/src/main/resources/logback.xml rename to twitter4J-temp/src/main/resources/logback.xml diff --git a/Twitter4J/src/main/resources/twitter4j.properties b/twitter4J-temp/src/main/resources/twitter4j.properties similarity index 100% rename from Twitter4J/src/main/resources/twitter4j.properties rename to twitter4J-temp/src/main/resources/twitter4j.properties diff --git a/Twitter4J/src/test/java/com/baeldung/ApplicationIntegrationTest.java b/twitter4J-temp/src/test/java/com/baeldung/ApplicationIntegrationTest.java similarity index 100% rename from Twitter4J/src/test/java/com/baeldung/ApplicationIntegrationTest.java rename to twitter4J-temp/src/test/java/com/baeldung/ApplicationIntegrationTest.java From 7502f58b990b8f761d001035e60e8b7751593015 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:33:07 +0300 Subject: [PATCH 322/352] changing case --- {twitter4J-temp => twitter4j}/README.md | 0 {twitter4J-temp => twitter4j}/pom.xml | 0 .../src/main/java/com/baeldung/Application.java | 0 {twitter4J-temp => twitter4j}/src/main/resources/logback.xml | 0 .../src/main/resources/twitter4j.properties | 0 .../src/test/java/com/baeldung/ApplicationIntegrationTest.java | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename {twitter4J-temp => twitter4j}/README.md (100%) rename {twitter4J-temp => twitter4j}/pom.xml (100%) rename {twitter4J-temp => twitter4j}/src/main/java/com/baeldung/Application.java (100%) rename {twitter4J-temp => twitter4j}/src/main/resources/logback.xml (100%) rename {twitter4J-temp => twitter4j}/src/main/resources/twitter4j.properties (100%) rename {twitter4J-temp => twitter4j}/src/test/java/com/baeldung/ApplicationIntegrationTest.java (100%) diff --git a/twitter4J-temp/README.md b/twitter4j/README.md similarity index 100% rename from twitter4J-temp/README.md rename to twitter4j/README.md diff --git a/twitter4J-temp/pom.xml b/twitter4j/pom.xml similarity index 100% rename from twitter4J-temp/pom.xml rename to twitter4j/pom.xml diff --git a/twitter4J-temp/src/main/java/com/baeldung/Application.java b/twitter4j/src/main/java/com/baeldung/Application.java similarity index 100% rename from twitter4J-temp/src/main/java/com/baeldung/Application.java rename to twitter4j/src/main/java/com/baeldung/Application.java diff --git a/twitter4J-temp/src/main/resources/logback.xml b/twitter4j/src/main/resources/logback.xml similarity index 100% rename from twitter4J-temp/src/main/resources/logback.xml rename to twitter4j/src/main/resources/logback.xml diff --git a/twitter4J-temp/src/main/resources/twitter4j.properties b/twitter4j/src/main/resources/twitter4j.properties similarity index 100% rename from twitter4J-temp/src/main/resources/twitter4j.properties rename to twitter4j/src/main/resources/twitter4j.properties diff --git a/twitter4J-temp/src/test/java/com/baeldung/ApplicationIntegrationTest.java b/twitter4j/src/test/java/com/baeldung/ApplicationIntegrationTest.java similarity index 100% rename from twitter4J-temp/src/test/java/com/baeldung/ApplicationIntegrationTest.java rename to twitter4j/src/test/java/com/baeldung/ApplicationIntegrationTest.java From b8d65f954b72cb10f2c1ec808195e687c777f086 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:34:07 +0300 Subject: [PATCH 323/352] changing case --- {JGit => jgit-temp}/README.md | 0 {JGit => jgit-temp}/pom.xml | 0 .../src/main/java/com/baeldung/jgit/CreateNewRepository.java | 0 .../src/main/java/com/baeldung/jgit/OpenRepository.java | 0 .../src/main/java/com/baeldung/jgit/helper/Helper.java | 0 .../src/main/java/com/baeldung/jgit/porcelain/AddFile.java | 0 .../src/main/java/com/baeldung/jgit/porcelain/CommitAll.java | 0 .../main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java | 0 .../src/main/java/com/baeldung/jgit/porcelain/Log.java | 0 {JGit => jgit-temp}/src/main/resources/logback.xml | 0 .../src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java | 0 .../test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java | 0 12 files changed, 0 insertions(+), 0 deletions(-) rename {JGit => jgit-temp}/README.md (100%) rename {JGit => jgit-temp}/pom.xml (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/CreateNewRepository.java (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/OpenRepository.java (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/helper/Helper.java (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/porcelain/AddFile.java (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java (100%) rename {JGit => jgit-temp}/src/main/java/com/baeldung/jgit/porcelain/Log.java (100%) rename {JGit => jgit-temp}/src/main/resources/logback.xml (100%) rename {JGit => jgit-temp}/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java (100%) rename {JGit => jgit-temp}/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java (100%) diff --git a/JGit/README.md b/jgit-temp/README.md similarity index 100% rename from JGit/README.md rename to jgit-temp/README.md diff --git a/JGit/pom.xml b/jgit-temp/pom.xml similarity index 100% rename from JGit/pom.xml rename to jgit-temp/pom.xml diff --git a/JGit/src/main/java/com/baeldung/jgit/CreateNewRepository.java b/jgit-temp/src/main/java/com/baeldung/jgit/CreateNewRepository.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/CreateNewRepository.java rename to jgit-temp/src/main/java/com/baeldung/jgit/CreateNewRepository.java diff --git a/JGit/src/main/java/com/baeldung/jgit/OpenRepository.java b/jgit-temp/src/main/java/com/baeldung/jgit/OpenRepository.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/OpenRepository.java rename to jgit-temp/src/main/java/com/baeldung/jgit/OpenRepository.java diff --git a/JGit/src/main/java/com/baeldung/jgit/helper/Helper.java b/jgit-temp/src/main/java/com/baeldung/jgit/helper/Helper.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/helper/Helper.java rename to jgit-temp/src/main/java/com/baeldung/jgit/helper/Helper.java diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/AddFile.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java rename to jgit-temp/src/main/java/com/baeldung/jgit/porcelain/AddFile.java diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java rename to jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java rename to jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/Log.java similarity index 100% rename from JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java rename to jgit-temp/src/main/java/com/baeldung/jgit/porcelain/Log.java diff --git a/JGit/src/main/resources/logback.xml b/jgit-temp/src/main/resources/logback.xml similarity index 100% rename from JGit/src/main/resources/logback.xml rename to jgit-temp/src/main/resources/logback.xml diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/jgit-temp/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java similarity index 100% rename from JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java rename to jgit-temp/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java diff --git a/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java b/jgit-temp/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java similarity index 100% rename from JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java rename to jgit-temp/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java From 38b37df87367bbeff2746b634dcaea7576632add Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:35:40 +0300 Subject: [PATCH 324/352] changing case --- jgit-temp/README.md | 3 - jgit-temp/pom.xml | 53 ------------- .../baeldung/jgit/CreateNewRepository.java | 30 -------- .../com/baeldung/jgit/OpenRepository.java | 65 ---------------- .../java/com/baeldung/jgit/helper/Helper.java | 33 --------- .../com/baeldung/jgit/porcelain/AddFile.java | 36 --------- .../baeldung/jgit/porcelain/CommitAll.java | 51 ------------- .../jgit/porcelain/CreateAndDeleteTag.java | 56 -------------- .../java/com/baeldung/jgit/porcelain/Log.java | 74 ------------------- jgit-temp/src/main/resources/logback.xml | 13 ---- .../baeldung/jgit/JGitBugIntegrationTest.java | 33 --------- .../jgit/porcelain/PorcelainUnitTest.java | 17 ----- 12 files changed, 464 deletions(-) delete mode 100644 jgit-temp/README.md delete mode 100644 jgit-temp/pom.xml delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/CreateNewRepository.java delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/OpenRepository.java delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/helper/Helper.java delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/porcelain/AddFile.java delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java delete mode 100644 jgit-temp/src/main/java/com/baeldung/jgit/porcelain/Log.java delete mode 100644 jgit-temp/src/main/resources/logback.xml delete mode 100644 jgit-temp/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java delete mode 100644 jgit-temp/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java diff --git a/jgit-temp/README.md b/jgit-temp/README.md deleted file mode 100644 index 5c65f1101b..0000000000 --- a/jgit-temp/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Relevant articles: - -- [A Guide to JGit](http://www.baeldung.com/jgit) diff --git a/jgit-temp/pom.xml b/jgit-temp/pom.xml deleted file mode 100644 index deae1e45e3..0000000000 --- a/jgit-temp/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - 4.0.0 - com.baeldung - JGit - 1.0-SNAPSHOT - JGit - jar - http://maven.apache.org - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - jgit-repository - https://repo.eclipse.org/content/groups/releases/ - - - - - - - org.eclipse.jgit - org.eclipse.jgit - ${org.eclipse.jgit.version} - - - org.eclipse.jgit - org.eclipse.jgit.archive - ${org.eclipse.jgit.version} - - - commons-io - commons-io - ${commons-io.version} - - - org.slf4j - slf4j-simple - ${org.slf4j.version} - - - - - 4.5.0.201609210915-r - - - \ No newline at end of file diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/CreateNewRepository.java b/jgit-temp/src/main/java/com/baeldung/jgit/CreateNewRepository.java deleted file mode 100644 index 1702efc315..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/CreateNewRepository.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.jgit; - -import java.io.File; -import java.io.IOException; -import org.apache.commons.io.FileUtils; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; - -/** - * Simple snippet which shows how to create a new repository - * - * - */ -public class CreateNewRepository { - - public static void main(String[] args) throws IOException, IllegalStateException, GitAPIException { - // prepare a new folder - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // create the directory - try (Git git = Git.init().setDirectory(localPath).call()) { - System.out.println("Having repository: " + git.getRepository().getDirectory()); - } - - FileUtils.deleteDirectory(localPath); - } -} diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/OpenRepository.java b/jgit-temp/src/main/java/com/baeldung/jgit/OpenRepository.java deleted file mode 100644 index 671df2a844..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/OpenRepository.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.baeldung.jgit; - -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; -import java.io.File; -import java.io.IOException; - -/** - * Simple snippet which shows how to open an existing repository - * - * - */ -public class OpenRepository { - - public static void main(String[] args) throws IOException, GitAPIException { - // first create a test-repository, the return is including the .get directory here! - File repoDir = createSampleGitRepo(); - - // now open the resulting repository with a FileRepositoryBuilder - FileRepositoryBuilder builder = new FileRepositoryBuilder(); - try (Repository repository = builder.setGitDir(repoDir) - .readEnvironment() // scan environment GIT_* variables - .findGitDir() // scan up the file system tree - .build()) { - System.out.println("Having repository: " + repository.getDirectory()); - - // the Ref holds an ObjectId for any type of object (tree, commit, blob, tree) - Ref head = repository.exactRef("refs/heads/master"); - System.out.println("Ref of refs/heads/master: " + head); - } - } - - private static File createSampleGitRepo() throws IOException, GitAPIException { - try (Repository repository = Helper.createNewRepository()) { - System.out.println("Temporary repository at " + repository.getDirectory()); - - // create the file - File myfile = new File(repository.getDirectory().getParent(), "testfile"); - if(!myfile.createNewFile()) { - throw new IOException("Could not create file " + myfile); - } - - // run the add-call - try (Git git = new Git(repository)) { - git.add() - .addFilepattern("testfile") - .call(); - - - // and then commit the changes - git.commit() - .setMessage("Added testfile") - .call(); - } - - System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); - - return repository.getDirectory(); - } - } -} diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/helper/Helper.java b/jgit-temp/src/main/java/com/baeldung/jgit/helper/Helper.java deleted file mode 100644 index 39d7b767d2..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/helper/Helper.java +++ /dev/null @@ -1,33 +0,0 @@ - -package com.baeldung.jgit.helper; - -import java.io.File; -import java.io.IOException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; - -public class Helper { - - public static Repository openJGitRepository() throws IOException { - FileRepositoryBuilder builder = new FileRepositoryBuilder(); - return builder - .readEnvironment() // scan environment GIT_* variables - .findGitDir() // scan up the file system tree - .build(); - } - - public static Repository createNewRepository() throws IOException { - // prepare a new folder - File localPath = File.createTempFile("TestGitRepository", ""); - if(!localPath.delete()) { - throw new IOException("Could not delete temporary file " + localPath); - } - - // create the directory - Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git")); - repository.create(); - - return repository; - } - -} diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/AddFile.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/AddFile.java deleted file mode 100644 index 314366f08c..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/AddFile.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.jgit.porcelain; - -import java.io.File; -import java.io.IOException; -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; - -/** - * Simple snippet which shows how to add a file to the index - * - * - */ -public class AddFile { - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare a new test-repository - try (Repository repository = Helper.createNewRepository()) { - try (Git git = new Git(repository)) { - // create the file - File myfile = new File(repository.getDirectory().getParent(), "testfile"); - if(!myfile.createNewFile()) { - throw new IOException("Could not create file " + myfile); - } - - // run the add-call - git.add() - .addFilepattern("testfile") - .call(); - - System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); - } - } - } -} diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java deleted file mode 100644 index 4c0956ebf8..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.jgit.porcelain; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; - -/** - * Simple snippet which shows how to commit all files - * - * - */ -public class CommitAll { - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare a new test-repository - try (Repository repository = Helper.createNewRepository()) { - try (Git git = new Git(repository)) { - // create the file - File myfile = new File(repository.getDirectory().getParent(), "testfile"); - if(!myfile.createNewFile()) { - throw new IOException("Could not create file " + myfile); - } - - // Stage all files in the repo including new files - git.add().addFilepattern(".").call(); - - // and then commit the changes. - git.commit() - .setMessage("Commit all changes including additions") - .call(); - - try(PrintWriter writer = new PrintWriter(myfile)) { - writer.append("Hello, world!"); - } - - // Stage all changed files, omitting new files, and commit with one command - git.commit() - .setAll(true) - .setMessage("Commit changes to all files") - .call(); - - - System.out.println("Committed all changes to repository at " + repository.getDirectory()); - } - } - } -} diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java deleted file mode 100644 index 0f735daf8c..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.jgit.porcelain; - -import java.io.IOException; -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; - -/** - * Simple snippet which shows how to create a tag - * - * - */ -public class CreateAndDeleteTag { - - public static void main(String[] args) throws IOException, GitAPIException { - // prepare test-repository - try (Repository repository = Helper.openJGitRepository()) { - try (Git git = new Git(repository)) { - // remove the tag before creating it - git.tagDelete().setTags("tag_for_testing").call(); - - // set it on the current HEAD - Ref tag = git.tag().setName("tag_for_testing").call(); - System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); - - // remove the tag again - git.tagDelete().setTags("tag_for_testing").call(); - - // read some other commit and set the tag on it - ObjectId id = repository.resolve("HEAD^"); - try (RevWalk walk = new RevWalk(repository)) { - RevCommit commit = walk.parseCommit(id); - tag = git.tag().setObjectId(commit).setName("tag_for_testing").call(); - System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); - - // remove the tag again - git.tagDelete().setTags("tag_for_testing").call(); - - // create an annotated tag - tag = git.tag().setName("tag_for_testing").setAnnotated(true).call(); - System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); - - // remove the tag again - git.tagDelete().setTags("tag_for_testing").call(); - - walk.dispose(); - } - } - } - } -} diff --git a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/Log.java b/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/Log.java deleted file mode 100644 index a50028a9ae..0000000000 --- a/jgit-temp/src/main/java/com/baeldung/jgit/porcelain/Log.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.jgit.porcelain; - -import java.io.IOException; -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; - -/** - * Simple snippet which shows how to get the commit-ids for a file to provide log information. - * - * - */ -public class Log { - - @SuppressWarnings("unused") - public static void main(String[] args) throws IOException, GitAPIException { - try (Repository repository = Helper.openJGitRepository()) { - try (Git git = new Git(repository)) { - Iterable logs = git.log() - .call(); - int count = 0; - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits overall on current branch"); - - logs = git.log() - .add(repository.resolve(git.getRepository().getFullBranch())) - .call(); - count = 0; - for (RevCommit rev : logs) { - System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch()); - - logs = git.log() - .all() - .call(); - count = 0; - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits overall in repository"); - - logs = git.log() - // for all log.all() - .addPath("README.md") - .call(); - count = 0; - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits on README.md"); - - logs = git.log() - // for all log.all() - .addPath("pom.xml") - .call(); - count = 0; - for (RevCommit rev : logs) { - //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); - count++; - } - System.out.println("Had " + count + " commits on pom.xml"); - } - } - } -} diff --git a/jgit-temp/src/main/resources/logback.xml b/jgit-temp/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/jgit-temp/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/jgit-temp/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/jgit-temp/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java deleted file mode 100644 index ad34890996..0000000000 --- a/jgit-temp/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.jgit; - -import com.baeldung.jgit.helper.Helper; -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.ObjectReader; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevWalk; -import org.junit.Test; -import java.io.IOException; -import static org.junit.Assert.assertNotNull; - -/** - * Tests which show issues with JGit that we reported upstream. - */ -public class JGitBugIntegrationTest { - @Test - public void testRevWalkDisposeClosesReader() throws IOException { - try (Repository repo = Helper.openJGitRepository()) { - try (ObjectReader reader = repo.newObjectReader()) { - try (RevWalk walk = new RevWalk(reader)) { - walk.dispose(); - - Ref head = repo.exactRef("refs/heads/master"); - System.out.println("Found head: " + head); - - ObjectLoader loader = reader.open(head.getObjectId()); - assertNotNull(loader); - } - } - } - } -} diff --git a/jgit-temp/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java b/jgit-temp/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java deleted file mode 100644 index d3b3358664..0000000000 --- a/jgit-temp/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.jgit.porcelain; - -import org.junit.Test; - -public class PorcelainUnitTest { - @Test - public void runSamples() throws Exception { - // simply call all the samples to see any severe problems with the samples - AddFile.main(null); - - CommitAll.main(null); - - CreateAndDeleteTag.main(null); - - Log.main(null); - } -} From 1db074d22d61b5ebca3ba3d6116ae03cabc48bf1 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:35:46 +0300 Subject: [PATCH 325/352] changing case --- jgit/README.md | 3 + jgit/pom.xml | 53 +++++++++++++ .../baeldung/jgit/CreateNewRepository.java | 30 ++++++++ .../com/baeldung/jgit/OpenRepository.java | 65 ++++++++++++++++ .../java/com/baeldung/jgit/helper/Helper.java | 33 +++++++++ .../com/baeldung/jgit/porcelain/AddFile.java | 36 +++++++++ .../baeldung/jgit/porcelain/CommitAll.java | 51 +++++++++++++ .../jgit/porcelain/CreateAndDeleteTag.java | 56 ++++++++++++++ .../java/com/baeldung/jgit/porcelain/Log.java | 74 +++++++++++++++++++ jgit/src/main/resources/logback.xml | 13 ++++ .../baeldung/jgit/JGitBugIntegrationTest.java | 33 +++++++++ .../jgit/porcelain/PorcelainUnitTest.java | 17 +++++ 12 files changed, 464 insertions(+) create mode 100644 jgit/README.md create mode 100644 jgit/pom.xml create mode 100644 jgit/src/main/java/com/baeldung/jgit/CreateNewRepository.java create mode 100644 jgit/src/main/java/com/baeldung/jgit/OpenRepository.java create mode 100644 jgit/src/main/java/com/baeldung/jgit/helper/Helper.java create mode 100644 jgit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java create mode 100644 jgit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java create mode 100644 jgit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java create mode 100644 jgit/src/main/java/com/baeldung/jgit/porcelain/Log.java create mode 100644 jgit/src/main/resources/logback.xml create mode 100644 jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java create mode 100644 jgit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java diff --git a/jgit/README.md b/jgit/README.md new file mode 100644 index 0000000000..5c65f1101b --- /dev/null +++ b/jgit/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [A Guide to JGit](http://www.baeldung.com/jgit) diff --git a/jgit/pom.xml b/jgit/pom.xml new file mode 100644 index 0000000000..deae1e45e3 --- /dev/null +++ b/jgit/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + com.baeldung + JGit + 1.0-SNAPSHOT + JGit + jar + http://maven.apache.org + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + jgit-repository + https://repo.eclipse.org/content/groups/releases/ + + + + + + + org.eclipse.jgit + org.eclipse.jgit + ${org.eclipse.jgit.version} + + + org.eclipse.jgit + org.eclipse.jgit.archive + ${org.eclipse.jgit.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.slf4j + slf4j-simple + ${org.slf4j.version} + + + + + 4.5.0.201609210915-r + + + \ No newline at end of file diff --git a/jgit/src/main/java/com/baeldung/jgit/CreateNewRepository.java b/jgit/src/main/java/com/baeldung/jgit/CreateNewRepository.java new file mode 100644 index 0000000000..1702efc315 --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/CreateNewRepository.java @@ -0,0 +1,30 @@ +package com.baeldung.jgit; + +import java.io.File; +import java.io.IOException; +import org.apache.commons.io.FileUtils; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; + +/** + * Simple snippet which shows how to create a new repository + * + * + */ +public class CreateNewRepository { + + public static void main(String[] args) throws IOException, IllegalStateException, GitAPIException { + // prepare a new folder + File localPath = File.createTempFile("TestGitRepository", ""); + if(!localPath.delete()) { + throw new IOException("Could not delete temporary file " + localPath); + } + + // create the directory + try (Git git = Git.init().setDirectory(localPath).call()) { + System.out.println("Having repository: " + git.getRepository().getDirectory()); + } + + FileUtils.deleteDirectory(localPath); + } +} diff --git a/jgit/src/main/java/com/baeldung/jgit/OpenRepository.java b/jgit/src/main/java/com/baeldung/jgit/OpenRepository.java new file mode 100644 index 0000000000..671df2a844 --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/OpenRepository.java @@ -0,0 +1,65 @@ +package com.baeldung.jgit; + +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Ref; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.storage.file.FileRepositoryBuilder; +import java.io.File; +import java.io.IOException; + +/** + * Simple snippet which shows how to open an existing repository + * + * + */ +public class OpenRepository { + + public static void main(String[] args) throws IOException, GitAPIException { + // first create a test-repository, the return is including the .get directory here! + File repoDir = createSampleGitRepo(); + + // now open the resulting repository with a FileRepositoryBuilder + FileRepositoryBuilder builder = new FileRepositoryBuilder(); + try (Repository repository = builder.setGitDir(repoDir) + .readEnvironment() // scan environment GIT_* variables + .findGitDir() // scan up the file system tree + .build()) { + System.out.println("Having repository: " + repository.getDirectory()); + + // the Ref holds an ObjectId for any type of object (tree, commit, blob, tree) + Ref head = repository.exactRef("refs/heads/master"); + System.out.println("Ref of refs/heads/master: " + head); + } + } + + private static File createSampleGitRepo() throws IOException, GitAPIException { + try (Repository repository = Helper.createNewRepository()) { + System.out.println("Temporary repository at " + repository.getDirectory()); + + // create the file + File myfile = new File(repository.getDirectory().getParent(), "testfile"); + if(!myfile.createNewFile()) { + throw new IOException("Could not create file " + myfile); + } + + // run the add-call + try (Git git = new Git(repository)) { + git.add() + .addFilepattern("testfile") + .call(); + + + // and then commit the changes + git.commit() + .setMessage("Added testfile") + .call(); + } + + System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); + + return repository.getDirectory(); + } + } +} diff --git a/jgit/src/main/java/com/baeldung/jgit/helper/Helper.java b/jgit/src/main/java/com/baeldung/jgit/helper/Helper.java new file mode 100644 index 0000000000..39d7b767d2 --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/helper/Helper.java @@ -0,0 +1,33 @@ + +package com.baeldung.jgit.helper; + +import java.io.File; +import java.io.IOException; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.storage.file.FileRepositoryBuilder; + +public class Helper { + + public static Repository openJGitRepository() throws IOException { + FileRepositoryBuilder builder = new FileRepositoryBuilder(); + return builder + .readEnvironment() // scan environment GIT_* variables + .findGitDir() // scan up the file system tree + .build(); + } + + public static Repository createNewRepository() throws IOException { + // prepare a new folder + File localPath = File.createTempFile("TestGitRepository", ""); + if(!localPath.delete()) { + throw new IOException("Could not delete temporary file " + localPath); + } + + // create the directory + Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git")); + repository.create(); + + return repository; + } + +} diff --git a/jgit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java new file mode 100644 index 0000000000..314366f08c --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/porcelain/AddFile.java @@ -0,0 +1,36 @@ +package com.baeldung.jgit.porcelain; + +import java.io.File; +import java.io.IOException; +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Repository; + +/** + * Simple snippet which shows how to add a file to the index + * + * + */ +public class AddFile { + + public static void main(String[] args) throws IOException, GitAPIException { + // prepare a new test-repository + try (Repository repository = Helper.createNewRepository()) { + try (Git git = new Git(repository)) { + // create the file + File myfile = new File(repository.getDirectory().getParent(), "testfile"); + if(!myfile.createNewFile()) { + throw new IOException("Could not create file " + myfile); + } + + // run the add-call + git.add() + .addFilepattern("testfile") + .call(); + + System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); + } + } + } +} diff --git a/jgit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java new file mode 100644 index 0000000000..4c0956ebf8 --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/porcelain/CommitAll.java @@ -0,0 +1,51 @@ +package com.baeldung.jgit.porcelain; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Repository; + +/** + * Simple snippet which shows how to commit all files + * + * + */ +public class CommitAll { + + public static void main(String[] args) throws IOException, GitAPIException { + // prepare a new test-repository + try (Repository repository = Helper.createNewRepository()) { + try (Git git = new Git(repository)) { + // create the file + File myfile = new File(repository.getDirectory().getParent(), "testfile"); + if(!myfile.createNewFile()) { + throw new IOException("Could not create file " + myfile); + } + + // Stage all files in the repo including new files + git.add().addFilepattern(".").call(); + + // and then commit the changes. + git.commit() + .setMessage("Commit all changes including additions") + .call(); + + try(PrintWriter writer = new PrintWriter(myfile)) { + writer.append("Hello, world!"); + } + + // Stage all changed files, omitting new files, and commit with one command + git.commit() + .setAll(true) + .setMessage("Commit changes to all files") + .call(); + + + System.out.println("Committed all changes to repository at " + repository.getDirectory()); + } + } + } +} diff --git a/jgit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java new file mode 100644 index 0000000000..0f735daf8c --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/porcelain/CreateAndDeleteTag.java @@ -0,0 +1,56 @@ +package com.baeldung.jgit.porcelain; + +import java.io.IOException; +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.ObjectId; +import org.eclipse.jgit.lib.Ref; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.revwalk.RevCommit; +import org.eclipse.jgit.revwalk.RevWalk; + +/** + * Simple snippet which shows how to create a tag + * + * + */ +public class CreateAndDeleteTag { + + public static void main(String[] args) throws IOException, GitAPIException { + // prepare test-repository + try (Repository repository = Helper.openJGitRepository()) { + try (Git git = new Git(repository)) { + // remove the tag before creating it + git.tagDelete().setTags("tag_for_testing").call(); + + // set it on the current HEAD + Ref tag = git.tag().setName("tag_for_testing").call(); + System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); + + // remove the tag again + git.tagDelete().setTags("tag_for_testing").call(); + + // read some other commit and set the tag on it + ObjectId id = repository.resolve("HEAD^"); + try (RevWalk walk = new RevWalk(repository)) { + RevCommit commit = walk.parseCommit(id); + tag = git.tag().setObjectId(commit).setName("tag_for_testing").call(); + System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); + + // remove the tag again + git.tagDelete().setTags("tag_for_testing").call(); + + // create an annotated tag + tag = git.tag().setName("tag_for_testing").setAnnotated(true).call(); + System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); + + // remove the tag again + git.tagDelete().setTags("tag_for_testing").call(); + + walk.dispose(); + } + } + } + } +} diff --git a/jgit/src/main/java/com/baeldung/jgit/porcelain/Log.java b/jgit/src/main/java/com/baeldung/jgit/porcelain/Log.java new file mode 100644 index 0000000000..a50028a9ae --- /dev/null +++ b/jgit/src/main/java/com/baeldung/jgit/porcelain/Log.java @@ -0,0 +1,74 @@ +package com.baeldung.jgit.porcelain; + +import java.io.IOException; +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.revwalk.RevCommit; + +/** + * Simple snippet which shows how to get the commit-ids for a file to provide log information. + * + * + */ +public class Log { + + @SuppressWarnings("unused") + public static void main(String[] args) throws IOException, GitAPIException { + try (Repository repository = Helper.openJGitRepository()) { + try (Git git = new Git(repository)) { + Iterable logs = git.log() + .call(); + int count = 0; + for (RevCommit rev : logs) { + //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits overall on current branch"); + + logs = git.log() + .add(repository.resolve(git.getRepository().getFullBranch())) + .call(); + count = 0; + for (RevCommit rev : logs) { + System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch()); + + logs = git.log() + .all() + .call(); + count = 0; + for (RevCommit rev : logs) { + //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits overall in repository"); + + logs = git.log() + // for all log.all() + .addPath("README.md") + .call(); + count = 0; + for (RevCommit rev : logs) { + //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits on README.md"); + + logs = git.log() + // for all log.all() + .addPath("pom.xml") + .call(); + count = 0; + for (RevCommit rev : logs) { + //System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); + count++; + } + System.out.println("Had " + count + " commits on pom.xml"); + } + } + } +} diff --git a/jgit/src/main/resources/logback.xml b/jgit/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/jgit/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java new file mode 100644 index 0000000000..ad34890996 --- /dev/null +++ b/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.jgit; + +import com.baeldung.jgit.helper.Helper; +import org.eclipse.jgit.lib.ObjectLoader; +import org.eclipse.jgit.lib.ObjectReader; +import org.eclipse.jgit.lib.Ref; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.revwalk.RevWalk; +import org.junit.Test; +import java.io.IOException; +import static org.junit.Assert.assertNotNull; + +/** + * Tests which show issues with JGit that we reported upstream. + */ +public class JGitBugIntegrationTest { + @Test + public void testRevWalkDisposeClosesReader() throws IOException { + try (Repository repo = Helper.openJGitRepository()) { + try (ObjectReader reader = repo.newObjectReader()) { + try (RevWalk walk = new RevWalk(reader)) { + walk.dispose(); + + Ref head = repo.exactRef("refs/heads/master"); + System.out.println("Found head: " + head); + + ObjectLoader loader = reader.open(head.getObjectId()); + assertNotNull(loader); + } + } + } + } +} diff --git a/jgit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java b/jgit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java new file mode 100644 index 0000000000..d3b3358664 --- /dev/null +++ b/jgit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.jgit.porcelain; + +import org.junit.Test; + +public class PorcelainUnitTest { + @Test + public void runSamples() throws Exception { + // simply call all the samples to see any severe problems with the samples + AddFile.main(null); + + CommitAll.main(null); + + CreateAndDeleteTag.main(null); + + Log.main(null); + } +} From 0094c08a3d86338a402e6401cc04a8d7a349a7dc Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:39:48 +0300 Subject: [PATCH 326/352] changing case in the pom --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 6cdb35063e..0754b186cf 100644 --- a/pom.xml +++ b/pom.xml @@ -483,7 +483,7 @@ jee-7 --> jee-7-security jersey - JGit + jgit jgroups jhipster-5 jib @@ -781,7 +781,7 @@ testing-modules twilio - Twitter4J + twitter4j undertow From 0a5d51461ce8e581ff1bc98972e99584bfc3b85e Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:40:25 +0300 Subject: [PATCH 327/352] changing case in the pom --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 0754b186cf..5b5058763d 100644 --- a/pom.xml +++ b/pom.xml @@ -1176,7 +1176,7 @@ jee-7 --> jee-7-security jersey - JGit + jgit jgroups jhipster-5 jib @@ -1451,7 +1451,7 @@ testing-modules twilio - Twitter4J + twitter4j undertow From c0308756da53ba3486bec13915de4d27fbca76e6 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:45:13 +0300 Subject: [PATCH 328/352] Update README.md --- README.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 7f78cf1515..cc3f48d8ed 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,16 @@ -The "REST with Spring" Classes +The Courses ============================== -Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material):
    -**[>> THE REST WITH SPRING - MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)** -And here's the Master Class of Learn Spring Security:
    -**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)** +Here's the new "Learn Spring" course:
    +**[>> LEARN SPRING - THE MASTER CLASS](https://www.baeldung.com/learn-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=ls#master-class)** + +Here's the Master Class of "REST With Spring" (along with the new announced Boot 2 material):
    +**[>> THE REST WITH SPRING - MASTER CLASS](https://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)** + +And here's the Master Class of "Learn Spring Security":
    +**[>> LEARN SPRING SECURITY - MASTER CLASS](https://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)** @@ -15,7 +19,7 @@ Java and Spring Tutorials This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem. A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security. -In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`. +In additional to Spring, the modules here are covering a number of aspects in Java. Building the project @@ -32,6 +36,7 @@ Running a Spring Boot module ==================== To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory + ###Running Tests The command `mvn clean install` will run the unit tests in a module. From 8ae248ce42bde06937b5477f8b114bb0ad061408 Mon Sep 17 00:00:00 2001 From: Eugen Date: Sun, 28 Jul 2019 09:47:03 +0300 Subject: [PATCH 329/352] Update README.md --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cc3f48d8ed..4cad075cc3 100644 --- a/README.md +++ b/README.md @@ -37,8 +37,14 @@ Running a Spring Boot module To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory -###Running Tests +Working with the IDE +==================== +This repo contains a large number of modules. +When you're working with an individual module, there's no need to import all of them (or build all of them) - you can simply import that particular module in either Eclipse or IntelliJ. + +Running Tests +============= The command `mvn clean install` will run the unit tests in a module. To run the integration tests, use the command `mvn clean install -Pintegration-lite-first` From a16e5eb4afb278127ff2e337e12150bf205d650d Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 28 Jul 2019 10:21:08 +0300 Subject: [PATCH 330/352] remove extra files --- .../server/web/AuthorizationEndpoint.java | 209 ------------------ .../server/web/TokenEndpoint.java | 70 ------ 2 files changed, 279 deletions(-) delete mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java delete mode 100644 oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java deleted file mode 100644 index 84b9a89c54..0000000000 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/AuthorizationEndpoint.java +++ /dev/null @@ -1,209 +0,0 @@ -//package com.baeldung.security.oauth2.server.web; -// -//import AuthorizationCode; -//import Client; -//import User; -//import com.baeldung.security.oauth2.server.service.AuthCodeService; -// -//import javax.ejb.EJB; -//import javax.enterprise.context.RequestScoped; -//import javax.inject.Inject; -//import javax.persistence.EntityManager; -//import javax.persistence.PersistenceContext; -//import javax.security.enterprise.SecurityContext; -//import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition; -//import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; -//import javax.servlet.ServletException; -//import javax.servlet.annotation.HttpConstraint; -//import javax.servlet.annotation.ServletSecurity; -//import javax.servlet.annotation.WebServlet; -//import javax.servlet.http.HttpServlet; -//import javax.servlet.http.HttpServletRequest; -//import javax.servlet.http.HttpServletResponse; -//import java.io.IOException; -//import java.security.Principal; -//import java.util.*; -// -///** -// * 1. GET http://localhost:8080/app/ (302) -// * 2. GET http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (302) -// * 3. GET http://localhost:8080/uaa/login (200) with initial request as hidden input -// * 4. POST http://localhost:8080/uaa/login (username, password, initial client request) (302) -// * 5. GET http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (200) -// * 7. POST http://localhost:8080/uaa/authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 (302) -// * 8. GET http://localhost:8080/app/?code=rkWijq06mL&state=A123 (200) -// */ -///* -// -//Query Params: -// client_id: app -// redirect_uri: http://localhost:8080/app/ -// response_type: code -// state: A123 -// -// ==> GET user login WITH client request as hidden input: -// -// -// ==> After user login ==> Initial client request -// ==> gen code -// == redirect to redirect uri + params code & state : 302, location : http://localhost:8080/app/?code=w6A0YQFzzg&state=A123 -//*/ -// -////authorize?client_id=app&redirect_uri=http://localhost:8080/app/&response_type=code&state=A123 -////http://localhost:9080/authorize?response_type=code&client_id=client_id_1&redirect_uri=http://localhost:9080/app&state=A123 -// -////@RequestScoped -//@FormAuthenticationMechanismDefinition( -// loginToContinue = @LoginToContinue( -// loginPage = "/login-servlet", -// errorPage = "/login-error-servlet" -// ) -//) -//@WebServlet({"/authorize"}) -//@ServletSecurity(@HttpConstraint(rolesAllowed = "user")) -////@Stateless -//@RequestScoped -//public class AuthorizationEndpoint extends HttpServlet { -// -// private static final List authorizedResponseTypes = Arrays.asList("code", "token"); -// -// @Inject -// private SecurityContext securityContext; -// -// @PersistenceContext(name = "jpa-oauth2-pu") -// private EntityManager entityManager; -// -// @EJB -// private AuthCodeService authCodeService; -// -// //HTTP GET IS A MUST, POST IS OPTIONAL -// @Override -// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { -// -// String error = ""; -// -// //1. User Authentication -// Principal principal = securityContext.getCallerPrincipal(); -// -// //2. Check for a valid client_id -// String clientId = request.getParameter("client_id"); -// if (clientId == null) { -// request.setAttribute("error", "The client " + clientId + " doesn't exist."); -// } -// request.setAttribute("clientId", clientId); -// Client client = entityManager.find(Client.class, clientId); -// if (client == null) { -// request.setAttribute("error", "The client " + clientId + " doesn't exist."); -// } -// -// //3. check for a valid response_type -// String responseType = request.getParameter("response_type"); -// if (!authorizedResponseTypes.contains(responseType)) { -// error = "invalid_grant :" + responseType + ", response_type params should be one of :" + authorizedResponseTypes; -// request.setAttribute("error", error); -// request.getRequestDispatcher("/error.jsp") -// .forward(request, response); -// } -// -// //4. Optional redirect_uri, if provided should match -// String redirectUri = request.getParameter("redirect_uri"); -// checkRedirectUri(client, redirectUri); -// -// //save params -// String currentUri = request.getRequestURI(); -// request.setAttribute("post_redirect_uri", currentUri); -// -// String state = request.getParameter("state"); -// Map requestMap = new HashMap<>(); -// requestMap.put("response_type", responseType); -// requestMap.put("client_id", clientId); -// requestMap.put("redirect_uri", redirectUri); -// requestMap.put("state", state); -// request.setAttribute("requestMap", requestMap); -// -// //5.scope: Optional -// String requestedScope = request.getParameter("scope"); -// if (requestedScope.isEmpty()) { -// requestedScope = client.getScope(); -// } -// //requestedScope should be a subset of the client scope: clientScopes.containsAll(requestedScopes) -// //checkRequestedScope(requestedScope, client.getScope()); -// -// //sub set of user scope -// //allowed scope by the user -// -// User user = entityManager.find(User.class, principal.getName()); -// request.setAttribute("scopes", requestedScope); -// -// -// forward("/authorize.jsp", request, response); -// } -// -// @Override -// protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { -// String clientId = request.getParameter("client_id"); -// -// String responseType = request.getParameter("response_type"); -// if (!authorizedResponseTypes.contains(responseType)) { -// String error = "invalid_grant :" + responseType + ", response_type params should be one of :" + authorizedResponseTypes; -// request.setAttribute("error", error); -// forward("/error.jsp", request, response); -// } -// -// Client client = entityManager.find(Client.class, clientId); -// Objects.requireNonNull(client); -// -// String userId = securityContext.getCallerPrincipal().getName(); -// AuthorizationCode authorizationCode = new AuthorizationCode(); -// authorizationCode.setClientId(clientId); -// authorizationCode.setUserId(userId); -// String redirectUri = request.getParameter("redirect_uri"); -// authorizationCode.setRedirectUri(redirectUri); -// -// redirectUri = checkRedirectUri(client, redirectUri); -// -// String[] scope = request.getParameterValues("scope"); -// if (scope == null) { -// request.setAttribute("error", "User doesn't approved any scope"); -// forward("/error.jsp", request, response); -// } -// -// String approvedScopes = String.join(" ", scope); -// authorizationCode.setApprovedScopes(approvedScopes); -// -// //entityManager.persist(authorizationCode); -// authCodeService.save(authorizationCode); -// String code = authorizationCode.getCode(); -// -// StringBuilder sb = new StringBuilder(redirectUri); -// sb.append("?code=").append(code); -// -// //If the client send a state, Send it back -// String state = request.getParameter("state"); -// if (state != null) { -// sb.append("&state=").append(state); -// } -// response.sendRedirect(sb.toString()); -// } -// -// private String checkRedirectUri(Client client, String redirectUri) { -// //redirect uri -// if (redirectUri == null) { -// //erreur: param redirect_uri && client redirect_uri don't match. -// redirectUri = client.getRedirectUri(); -// if (redirectUri == null) { -// throw new IllegalStateException("redirectUri shloud be not null, unless a registred client have a redirect_uri."); -// } -// } else if (!redirectUri.equals(client.getRedirectUri())) { -// throw new IllegalStateException("request redirectUri and client registred redirect_uri should match."); -// } -// return redirectUri; -// } -// -// private void forward(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { -// request.getRequestDispatcher(path) -// .forward(request, response); -// } -//} diff --git a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java b/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java deleted file mode 100644 index 73085a68d1..0000000000 --- a/oauth2-framework-impl/oauth2-authorization-server/src/main/java/com/baeldung/oauth2/authorization/server/web/TokenEndpoint.java +++ /dev/null @@ -1,70 +0,0 @@ -//package com.baeldung.security.oauth2.server.web; -// -//import AuthorizationGrantTypeHandler; -//import TokenResponse; -//import com.baeldung.security.oauth2.server.security.Authenticated; -//import com.nimbusds.jose.JOSEException; -// -//import javax.enterprise.inject.Instance; -//import javax.enterprise.inject.literal.NamedLiteral; -//import javax.inject.Inject; -//import javax.security.enterprise.SecurityContext; -//import javax.ws.rs.Consumes; -//import javax.ws.rs.POST; -//import javax.ws.rs.Path; -//import javax.ws.rs.Produces; -//import javax.ws.rs.core.MediaType; -//import javax.ws.rs.core.MultivaluedMap; -//import javax.ws.rs.core.Response; -//import java.security.Principal; -//import java.util.Arrays; -//import java.util.List; -//import java.util.Objects; -// -///** -// * { -// * "access_token" : "acb6803a48114d9fb4761e403c17f812", -// * "token_type" : "bearer", -// * "id_token" : "eyJhbGciOiJIUzI1NiIsImprdSI6Imh0dHBzOi8vbG9jYWxob3N0OjgwODAvdWFhL3Rva2VuX2tleXMiLCJraWQiOiJsZWdhY3ktdG9rZW4ta2V5IiwidHlwIjoiSldUIn0.eyJzdWIiOiIwNzYzZTM2MS02ODUwLTQ3N2ItYjk1Ny1iMmExZjU3MjczMTQiLCJhdWQiOlsibG9naW4iXSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3VhYS9vYXV0aC90b2tlbiIsImV4cCI6MTU1NzgzMDM4NSwiaWF0IjoxNTU3Nzg3MTg1LCJhenAiOiJsb2dpbiIsInNjb3BlIjpbIm9wZW5pZCJdLCJlbWFpbCI6IndyaHBONUB0ZXN0Lm9yZyIsInppZCI6InVhYSIsIm9yaWdpbiI6InVhYSIsImp0aSI6ImFjYjY4MDNhNDgxMTRkOWZiNDc2MWU0MDNjMTdmODEyIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImNsaWVudF9pZCI6ImxvZ2luIiwiY2lkIjoibG9naW4iLCJncmFudF90eXBlIjoiYXV0aG9yaXphdGlvbl9jb2RlIiwidXNlcl9uYW1lIjoid3JocE41QHRlc3Qub3JnIiwicmV2X3NpZyI6ImI3MjE5ZGYxIiwidXNlcl9pZCI6IjA3NjNlMzYxLTY4NTAtNDc3Yi1iOTU3LWIyYTFmNTcyNzMxNCIsImF1dGhfdGltZSI6MTU1Nzc4NzE4NX0.Fo8wZ_Zq9mwFks3LfXQ1PfJ4ugppjWvioZM6jSqAAQQ", -// * "refresh_token" : "f59dcb5dcbca45f981f16ce519d61486-r", -// * "expires_in" : 43199, -// * "scope" : "openid oauth.approvals", -// * "jti" : "acb6803a48114d9fb4761e403c17f812" -// * } -// */ -//@Path("token") -//public class TokenEndpoint { -// -// List supportedGrantTypes = Arrays.asList("authorization_code", "password", "refresh_token", "client_credentials"); -// -// @Inject -// private SecurityContext securityContext; -// -// @Inject -// Instance authorizationGrantTypeHandlers; -// -// @POST -// @Produces(MediaType.APPLICATION_JSON) -// @Consumes(MediaType.APPLICATION_FORM_URLENCODED) -// @Authenticated -// public Response token(MultivaluedMap params) throws JOSEException { -// //Authenticate client with [basic] http authentication mechanism -// Principal principal = securityContext.getCallerPrincipal(); -// Objects.requireNonNull(principal, "Client not authenticated!"); -// -// //Check grant_type params -// String grantType = params.getFirst("grant_type"); -// Objects.requireNonNull(grantType, "grant_type params is required"); -// //authorization_code, password, refresh, client_credentials -// if (!supportedGrantTypes.contains(grantType)) { -// throw new RuntimeException("grant_type parameter should be one of the following :" + supportedGrantTypes); -// } -// AuthorizationGrantTypeHandler authorizationGrantTypeHandler = authorizationGrantTypeHandlers.select(NamedLiteral.of(grantType)).get(); -// TokenResponse tokenResponse = authorizationGrantTypeHandler.createAccessToken(principal.getName(), params); -// Response response = Response.ok(tokenResponse) -// .header("Cache-Control", "no-store") -// .header("Pragma", "no-cache") -// .build(); -// return response; -// } -//} From 8a664d7689802641cd553e30c949be80778aa170 Mon Sep 17 00:00:00 2001 From: binary-joe Date: Tue, 16 Jul 2019 21:16:37 +0200 Subject: [PATCH 331/352] BAEL-3006 WebClient filters --- spring-5-reactive/pom.xml | 8 + .../client/filter/WebClientFilters.java | 57 +++++++ .../filter/FilteredWebClientUnitTest.java | 145 ++++++++++++++++++ 3 files changed, 210 insertions(+) create mode 100644 spring-5-reactive/src/main/java/com/baeldung/debugging/client/filter/WebClientFilters.java create mode 100644 spring-5-reactive/src/test/java/com/baeldung/debugging/client/filter/FilteredWebClientUnitTest.java diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index 8d5324a673..4932ac79e4 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -120,6 +120,13 @@ ${project-reactor-test} test
    + + + com.github.tomakehurst + wiremock-jre8 + ${wiremock.version} + test +
    @@ -165,6 +172,7 @@ 1.0 4.1 3.2.3.RELEASE + 2.24.0
    diff --git a/spring-5-reactive/src/main/java/com/baeldung/debugging/client/filter/WebClientFilters.java b/spring-5-reactive/src/main/java/com/baeldung/debugging/client/filter/WebClientFilters.java new file mode 100644 index 0000000000..3aa757c815 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/debugging/client/filter/WebClientFilters.java @@ -0,0 +1,57 @@ +package com.baeldung.debugging.client.filter; + +import java.io.PrintStream; +import java.net.URI; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpMethod; +import org.springframework.web.reactive.function.client.ClientRequest; +import org.springframework.web.reactive.function.client.ExchangeFilterFunction; + +public class WebClientFilters { + + private static final Logger LOG = LoggerFactory.getLogger(WebClientFilters.class); + + public static ExchangeFilterFunction demoFilter() { + ExchangeFilterFunction filterFunction = (clientRequest, nextFilter) -> { + LOG.info("WebClient fitler executed"); + return nextFilter.exchange(clientRequest); + }; + return filterFunction; + } + + public static ExchangeFilterFunction countingFilter(AtomicInteger getCounter) { + ExchangeFilterFunction countingFilter = (clientRequest, nextFilter) -> { + HttpMethod httpMethod = clientRequest.method(); + if (httpMethod == HttpMethod.GET) { + getCounter.incrementAndGet(); + } + return nextFilter.exchange(clientRequest); + }; + return countingFilter; + } + + public static ExchangeFilterFunction urlModifyingFilter(String version) { + ExchangeFilterFunction urlModifyingFilter = (clientRequest, nextFilter) -> { + String oldUrl = clientRequest.url() + .toString(); + URI newUrl = URI.create(oldUrl + "/" + version); + ClientRequest filteredRequest = ClientRequest.from(clientRequest) + .url(newUrl) + .build(); + return nextFilter.exchange(filteredRequest); + }; + return urlModifyingFilter; + } + + public static ExchangeFilterFunction loggingFilter(PrintStream printStream) { + ExchangeFilterFunction loggingFilter = (clientRequest, nextFilter) -> { + printStream.print("Sending request " + clientRequest.method() + " " + clientRequest.url()); + return nextFilter.exchange(clientRequest); + }; + return loggingFilter; + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/debugging/client/filter/FilteredWebClientUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/debugging/client/filter/FilteredWebClientUnitTest.java new file mode 100644 index 0000000000..11cc76029a --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/debugging/client/filter/FilteredWebClientUnitTest.java @@ -0,0 +1,145 @@ +package com.baeldung.debugging.client.filter; + +import static com.baeldung.debugging.client.filter.WebClientFilters.countingFilter; +import static com.baeldung.debugging.client.filter.WebClientFilters.loggingFilter; +import static com.baeldung.debugging.client.filter.WebClientFilters.urlModifyingFilter; +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.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.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.verify; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.net.URI; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Rule; +import org.junit.Test; +import org.springframework.web.reactive.function.client.ExchangeFilterFunctions; +import org.springframework.web.reactive.function.client.WebClient; + +import com.github.tomakehurst.wiremock.junit.WireMockRule; + +public class FilteredWebClientUnitTest { + + private static final String PATH = "/filter/test"; + + @Rule + public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort() + .dynamicHttpsPort()); + + @Test + public void whenNoUrlModifyingFilter_thenPathUnchanged() { + stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200) + .withBody("done"))); + + WebClient webClient = WebClient.create(); + String actual = sendGetRequest(webClient); + + assertThat(actual).isEqualTo("done"); + verify(getRequestedFor(urlPathEqualTo(PATH))); + } + + @Test + public void whenUrlModifyingFilter_thenPathModified() { + stubFor(get(urlPathEqualTo(PATH + "/1.0")).willReturn(aResponse().withStatus(200) + .withBody("done"))); + + WebClient webClient = WebClient.builder() + .filter(urlModifyingFilter("1.0")) + .build(); + String actual = sendGetRequest(webClient); + + assertThat(actual).isEqualTo("done"); + verify(getRequestedFor(urlPathEqualTo(PATH + "/1.0"))); + } + + @Test + public void givenCountingFilter_whenGet_thenIncreaseCounter() { + stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200) + .withBody("done"))); + AtomicInteger counter = new AtomicInteger(10); + + WebClient webClient = WebClient.builder() + .filter(countingFilter(counter)) + .build(); + String actual = sendGetRequest(webClient); + + assertThat(actual).isEqualTo("done"); + assertThat(counter.get()).isEqualTo(11); + } + + @Test + public void givenCountingFilter_whenPost_thenDoNotIncreaseCounter() { + stubFor(post(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200) + .withBody("done"))); + AtomicInteger counter = new AtomicInteger(10); + + WebClient webClient = WebClient.builder() + .filter(countingFilter(counter)) + .build(); + String actual = sendPostRequest(webClient); + + assertThat(actual).isEqualTo("done"); + assertThat(counter.get()).isEqualTo(10); + } + + @Test + public void testLoggingFilter() throws IOException { + stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200) + .withBody("done"))); + + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos);) { + WebClient webClient = WebClient.builder() + .filter(loggingFilter(ps)) + .build(); + String actual = sendGetRequest(webClient); + + assertThat(actual).isEqualTo("done"); + assertThat(baos.toString()).isEqualTo("Sending request GET " + getUrl()); + } + } + + @Test + public void testBasicAuthFilter() { + stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200) + .withBody("authorized"))); + + WebClient webClient = WebClient.builder() + .filter(ExchangeFilterFunctions.basicAuthentication("user", "password")) + .build(); + String actual = sendGetRequest(webClient); + + assertThat(actual).isEqualTo("authorized"); + verify(getRequestedFor(urlPathEqualTo(PATH)).withHeader("Authorization", containing("Basic"))); + } + + private String sendGetRequest(WebClient webClient) { + return webClient.get() + .uri(getUrl()) + .retrieve() + .bodyToMono(String.class) + .block(); + } + + private String sendPostRequest(WebClient webClient) { + return webClient.post() + .uri(URI.create(getUrl())) + .retrieve() + .bodyToMono(String.class) + .block(); + } + + private String getUrl() { + return "http://localhost:" + wireMockRule.port() + PATH; + + } + +} From d187a05fbe752e190df12045e085feb2632e5057 Mon Sep 17 00:00:00 2001 From: pazis Date: Sun, 28 Jul 2019 19:19:43 +0000 Subject: [PATCH 332/352] MyHttpServlet --- .../com/baeldung/servlets/MyHttpServlet.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java new file mode 100644 index 0000000000..b4d80db0ab --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/MyHttpServlet.java @@ -0,0 +1,57 @@ +package com.baeldung.servlets; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet(name = "MyHttpServlet", urlPatterns = "/servlet-mapping") +public class MyHttpServlet extends HttpServlet { + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + PrintWriter writer = response.getWriter(); + writer.println(request.getParameter("function")); + if ("getContextPath".equals(request.getParameter("function"))) { + writer.println(request.getContextPath()); + } else if ("getLocalAddr".equals(request.getParameter("function"))) { + writer.println(request.getLocalAddr()); + } else if ("getLocalName".equals(request.getParameter("function"))) { + writer.println(request.getLocalName()); + } else if ("getLocalAPort".equals(request.getParameter("function"))) { + writer.println(request.getLocalPort()); + } else if ("getMethod".equals(request.getParameter("function"))) { + writer.println(request.getMethod()); + } else if ("getParameterNames".equals(request.getParameter("function"))) { + writer.println(request.getParameterNames()); + } else if ("getPathInfo".equals(request.getParameter("function"))) { + writer.println(request.getPathInfo()); + } else if ("getProtocol".equals(request.getParameter("function"))) { + writer.println(request.getProtocol()); + } else if ("getQueryString".equals(request.getParameter("function"))) { + writer.println(request.getQueryString()); + } else if ("getRequestedSessionId".equals(request.getParameter("function"))) { + writer.println(request.getRequestedSessionId()); + } else if ("getRequestURI".equals(request.getParameter("function"))) { + writer.println(request.getRequestURI()); + } else if ("getRequestURL".equals(request.getParameter("function"))) { + writer.println(request.getRequestURL()); + } else if ("getScheme".equals(request.getParameter("function"))) { + writer.println(request.getScheme()); + } else if ("getServerName".equals(request.getParameter("function"))) { + writer.println(request.getServerName()); + } else if ("getServerPort".equals(request.getParameter("function"))) { + writer.println(request.getServerPort()); + } else if ("getServletPath".equals(request.getParameter("function"))) { + writer.println(request.getServletPath()); + } else { + writer.println("INVALID FUNCTION"); + } + writer.flush(); + } + +} + + From 9b97533de725e7050db6da71774b8866822ad023 Mon Sep 17 00:00:00 2001 From: fanatixan Date: Mon, 29 Jul 2019 07:46:22 +0200 Subject: [PATCH 333/352] bael-3119 (#7436) --- .../relationships/aggregation/Car.java | 9 ++++++ .../aggregation/CarWithStaticInnerWheel.java | 13 +++++++++ .../relationships/aggregation/Wheel.java | 7 +++++ .../relationships/association/Child.java | 7 +++++ .../relationships/association/Mother.java | 9 ++++++ .../relationships/composition/Building.java | 18 ++++++++++++ .../BuildingWithDefinitionRoomInMethod.java | 28 +++++++++++++++++++ .../relationships/university/Department.java | 9 ++++++ .../relationships/university/Professor.java | 10 +++++++ .../relationships/university/University.java | 9 ++++++ 10 files changed, 119 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java create mode 100644 core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java new file mode 100644 index 0000000000..6be9a18781 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Car.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.aggregation; + +import java.util.List; + +public class Car { + + private List wheels; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java new file mode 100644 index 0000000000..96c07f13a4 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/CarWithStaticInnerWheel.java @@ -0,0 +1,13 @@ +package com.baeldung.relationships.aggregation; + +import java.util.List; + +public class CarWithStaticInnerWheel { + + private List wheels; + + public static class Wheel { + + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java new file mode 100644 index 0000000000..1f38ea85ad --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/aggregation/Wheel.java @@ -0,0 +1,7 @@ +package com.baeldung.relationships.aggregation; + +public class Wheel { + + private Car car; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java new file mode 100644 index 0000000000..4c748e8084 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Child.java @@ -0,0 +1,7 @@ +package com.baeldung.relationships.association; + +public class Child { + + private Mother mother; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java new file mode 100644 index 0000000000..0e8edef125 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/association/Mother.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.association; + +import java.util.List; + +public class Mother { + + private List children; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java new file mode 100644 index 0000000000..1ab44f73fa --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/Building.java @@ -0,0 +1,18 @@ +package com.baeldung.relationships.composition; + +import java.util.List; + +public class Building { + + private String address; + private List rooms; + + public class Room { + + public String getBuildingAddress() { + return Building.this.address; + } + + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java new file mode 100644 index 0000000000..4e3411cf30 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/composition/BuildingWithDefinitionRoomInMethod.java @@ -0,0 +1,28 @@ +package com.baeldung.relationships.composition; + +public class BuildingWithDefinitionRoomInMethod { + + public Room createAnonymousRoom() { + return new Room() { + @Override + public void doInRoom() {} + }; + } + + public Room createInlineRoom() { + class InlineRoom implements Room { + @Override + public void doInRoom() {} + } + return new InlineRoom(); + } + + public Room createLambdaRoom() { + return () -> {}; + } + + public interface Room { + void doInRoom(); + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java new file mode 100644 index 0000000000..63cfd1b89e --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Department.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.university; + +import java.util.List; + +public class Department { + + private List professors; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java new file mode 100644 index 0000000000..8e1258c3e6 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/Professor.java @@ -0,0 +1,10 @@ +package com.baeldung.relationships.university; + +import java.util.List; + +public class Professor { + + private List department; + private List friends; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java new file mode 100644 index 0000000000..e5e518e0f1 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/relationships/university/University.java @@ -0,0 +1,9 @@ +package com.baeldung.relationships.university; + +import java.util.List; + +public class University { + + private List department; + +} From 5aecdeb0211c9dc44e3e5138d4a30bf837d19204 Mon Sep 17 00:00:00 2001 From: Ger Roza Date: Mon, 29 Jul 2019 02:56:21 -0300 Subject: [PATCH 334/352] [BAEL-3066] Spring Security: Exploring JDBC Authentication (#7441) * created multi-module project from spring-security-mvc-boot * Added JDBC Authentication application to spring-security-mvc-boot-default * Added JDBC Authentication application to spring-security-mvc-boot-mysql * Added JDBC Authentication application to spring-security-mvc-boot-postgre * adding new modules to parent spring-security-mvc-boot module, reformatting sql scripts, and added form fields to H2 LiveTest --- spring-security-mvc-boot/pom.xml | 32 ++++------- .../spring-security-mvc-boot-default/pom.xml | 42 +++++++++++++++ .../src/main/java/com/baeldung/AppConfig.java | 0 .../com/baeldung/SpringSecurityConfig.java | 0 .../data/repositories/TweetRepository.java | 0 .../data/repositories/UserRepository.java | 0 .../java/com/baeldung/models/AppUser.java | 0 .../main/java/com/baeldung/models/Tweet.java | 0 .../baeldung/security/AppUserPrincipal.java | 0 .../AuthenticationSuccessHandlerImpl.java | 0 .../security/CustomUserDetailsService.java | 0 .../com/baeldung/util/DummyContentUtil.java | 0 .../java/org/baeldung/custom/Application.java | 4 -- .../custom/config/MethodSecurityConfig.java | 0 .../org/baeldung/custom/config/MvcConfig.java | 0 .../custom/config/SecurityConfig.java | 0 .../custom/persistence/SetupData.java | 0 .../dao/OrganizationRepository.java | 0 .../persistence/dao/PrivilegeRepository.java | 0 .../persistence/dao/UserRepository.java | 0 .../custom/persistence/model/Foo.java | 0 .../persistence/model/Organization.java | 0 .../custom/persistence/model/Privilege.java | 0 .../custom/persistence/model/User.java | 0 ...CustomMethodSecurityExpressionHandler.java | 0 .../CustomMethodSecurityExpressionRoot.java | 0 .../security/CustomPermissionEvaluator.java | 0 .../security/MySecurityExpressionRoot.java | 0 .../custom/security/MyUserDetailsService.java | 0 .../custom/security/MyUserPrincipal.java | 0 .../baeldung/custom/web/MainController.java | 0 .../java/org/baeldung/ip/IpApplication.java | 0 .../CustomIpAuthenticationProvider.java | 0 .../baeldung/ip/config/SecurityConfig.java | 0 .../baeldung/ip/config/SecurityXmlConfig.java | 0 .../org/baeldung/ip/web/MainController.java | 0 .../h2/H2JdbcAuthenticationApplication.java | 15 ++++++ .../h2/config/SecurityConfiguration.java | 51 ++++++++++++++++++ .../h2/web/UserController.java | 17 ++++++ .../CustomAuthenticationProvider.java | 0 .../MultipleAuthController.java | 0 .../MultipleAuthProvidersApplication.java | 0 .../MultipleAuthProvidersSecurityConfig.java | 0 .../MultipleEntryPointsApplication.java | 0 .../MultipleEntryPointsSecurityConfig.java | 0 .../multipleentrypoints/PagesController.java | 0 .../MultipleLoginApplication.java | 5 +- .../multiplelogin/MultipleLoginMvcConfig.java | 0 .../MultipleLoginSecurityConfig.java | 0 .../multiplelogin/UsersController.java | 0 .../CustomAuthenticationProvider.java | 0 .../MyLogoutSuccessHandler.java | 0 .../MyUserDetailsService.java | 0 .../RolesAuthoritiesApplication.java | 0 .../rolesauthorities/config/MvcConfig.java | 0 .../config/SecurityConfig.java | 0 .../rolesauthorities/model/Privilege.java | 0 .../baeldung/rolesauthorities/model/Role.java | 0 .../baeldung/rolesauthorities/model/User.java | 0 .../persistence/IUserService.java | 0 .../persistence/PrivilegeRepository.java | 0 .../persistence/RoleRepository.java | 0 .../persistence/SetupDataLoader.java | 0 .../persistence/UserRepository.java | 0 .../persistence/UserService.java | 0 .../baeldung/ssl/HttpsEnabledApplication.java | 0 .../java/org/baeldung/ssl/SecurityConfig.java | 0 .../org/baeldung/ssl/WelcomeController.java | 0 .../org/baeldung/voter/MinuteBasedVoter.java | 0 .../org/baeldung/voter/VoterApplication.java | 0 .../org/baeldung/voter/VoterMvcConfig.java | 0 .../org/baeldung/voter/WebSecurityConfig.java | 0 .../org/baeldung/voter/XmlSecurityConfig.java | 0 .../main/resources/application-ssl.properties | 0 .../src/main/resources/application.properties | 4 +- .../src/main/resources/keystore/baeldung.p12 | Bin .../src/main/resources/logback.xml | 0 .../main/resources/persistence-h2.properties | 0 .../spring-security-custom-voter.xml | 0 .../src/main/resources/spring-security-ip.xml | 0 ...pring-security-multiple-auth-providers.xml | 0 .../spring-security-multiple-entry.xml | 0 .../src/main/resources/templates/403.html | 0 .../main/resources/templates/adminPage.html | 0 .../src/main/resources/templates/index.html | 0 .../src/main/resources/templates/login.html | 0 .../main/resources/templates/loginAdmin.html | 0 .../main/resources/templates/loginUser.html | 0 .../templates/multipleHttpElems/login.html | 0 .../multipleHttpElems/loginWithWarning.html | 0 .../multipleHttpElems/multipleHttpLinks.html | 0 .../multipleHttpElems/myAdminPage.html | 0 .../multipleHttpElems/myGuestPage.html | 0 .../multipleHttpElems/myPrivateUserPage.html | 0 .../multipleHttpElems/myUserPage.html | 0 .../src/main/resources/templates/private.html | 0 .../resources/templates/protectedLinks.html | 0 .../templates/rolesauthorities/home.html | 0 .../templates/rolesauthorities/login.html | 0 .../protectedbyauthority.html | 0 .../rolesauthorities/protectedbynothing.html | 0 .../rolesauthorities/protectedbyrole.html | 0 .../main/resources/templates/ssl/welcome.html | 0 .../main/resources/templates/userPage.html | 0 ...SpringDataWithSecurityIntegrationTest.java | 0 .../SpringContextIntegrationTest.java | 0 .../h2/web/UserControllerLiveTest.java | 35 ++++++++++++ .../org/baeldung/web/ApplicationLiveTest.java | 0 ...stomUserDetailsServiceIntegrationTest.java | 0 .../web/HttpsApplicationIntegrationTest.java | 0 .../java/org/baeldung/web/IpLiveTest.java | 0 ...thProvidersApplicationIntegrationTest.java | 0 .../MultipleEntryPointsIntegrationTest.java | 0 .../spring-security-mvc-boot-mysql/pom.xml | 28 ++++++++++ .../MySqlJdbcAuthenticationApplication.java | 13 +++++ .../mysql/config/SecurityConfiguration.java | 35 ++++++++++++ .../mysql/web/UserController.java | 17 ++++++ .../src/main/resources/application.properties | 8 +++ .../src/main/resources/data.sql | 4 ++ .../src/main/resources/schema.sql | 18 +++++++ .../mysql/SpringContextIntegrationTest.java | 15 ++++++ .../mysql/web/UserControllerLiveTest.java | 35 ++++++++++++ .../spring-security-mvc-boot-postgre/pom.xml | 28 ++++++++++ .../PostgreJdbcAuthenticationApplication.java | 13 +++++ .../postgre/config/SecurityConfiguration.java | 29 ++++++++++ .../postgre/web/UserController.java | 17 ++++++ .../src/main/resources/application.properties | 8 +++ .../src/main/resources/data.sql | 4 ++ .../src/main/resources/schema.sql | 16 ++++++ .../postgre/SpringContextIntegrationTest.java | 17 ++++++ .../postgre/web/UserControllerLiveTest.java | 35 ++++++++++++ 131 files changed, 514 insertions(+), 31 deletions(-) create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/AppConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/SpringSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/data/repositories/TweetRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/data/repositories/UserRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/models/AppUser.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/models/Tweet.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/security/AppUserPrincipal.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/security/CustomUserDetailsService.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/com/baeldung/util/DummyContentUtil.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/Application.java (61%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/config/MvcConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/config/SecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/SetupData.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/model/Foo.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/model/Organization.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/model/Privilege.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/persistence/model/User.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/custom/web/MainController.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ip/IpApplication.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ip/config/SecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ip/web/MainController.java (100%) create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multipleentrypoints/PagesController.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java (69%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/multiplelogin/UsersController.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/model/Role.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/model/User.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ssl/SecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/ssl/WelcomeController.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/voter/MinuteBasedVoter.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/voter/VoterApplication.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/voter/VoterMvcConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/voter/WebSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/java/org/baeldung/voter/XmlSecurityConfig.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/application-ssl.properties (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/application.properties (74%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/keystore/baeldung.p12 (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/logback.xml (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/persistence-h2.properties (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/spring-security-custom-voter.xml (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/spring-security-ip.xml (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/spring-security-multiple-auth-providers.xml (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/spring-security-multiple-entry.xml (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/403.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/adminPage.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/index.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/login.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/loginAdmin.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/loginUser.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/login.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/loginWithWarning.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/myAdminPage.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/myGuestPage.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/multipleHttpElems/myUserPage.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/private.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/protectedLinks.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/rolesauthorities/home.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/rolesauthorities/login.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/rolesauthorities/protectedbyauthority.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/rolesauthorities/protectedbynothing.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/rolesauthorities/protectedbyrole.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/ssl/welcome.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/main/resources/templates/userPage.html (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/SpringContextIntegrationTest.java (100%) create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/web/ApplicationLiveTest.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/web/IpLiveTest.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java (100%) rename spring-security-mvc-boot/{ => spring-security-mvc-boot-default}/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java (100%) create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java create mode 100644 spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index 4c25dc01e8..906bebf442 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -1,12 +1,13 @@ - + 4.0.0 com.baeldung spring-security-mvc-boot 0.0.1-SNAPSHOT spring-security-mvc-boot - war + pom Spring Security MVC Boot @@ -45,10 +46,6 @@ org.springframework.security spring-security-data
    - - com.h2database - h2 - org.hamcrest hamcrest-core @@ -198,7 +195,7 @@ **/*LiveTest.java **/*IntegrationTest.java - **/*IntTest.java + **/*IntTest.java **/*EntryPointsTest.java @@ -217,22 +214,13 @@ + + spring-security-mvc-boot-default + spring-security-mvc-boot-mysql + spring-security-mvc-boot-postgre + - org.baeldung.custom.Application - - - - - - - - - 1.1.2 1.6.1 2.6.11 diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml new file mode 100644 index 0000000000..8f7f18f093 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + com.baeldung + spring-security-mvc-boot-default + 0.0.1-SNAPSHOT + spring-security-mvc-boot-default + jar + Spring Security MVC Boot + + + spring-security-mvc-boot + com.baeldung + 0.0.1-SNAPSHOT + ../ + + + + + com.h2database + h2 + + + + + org.baeldung.custom.Application + + + + + + + + + + + diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/AppConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/AppConfig.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/SpringSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/SpringSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/TweetRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/TweetRepository.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/UserRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/UserRepository.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/AppUser.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/AppUser.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/Tweet.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/Tweet.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AppUserPrincipal.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AppUserPrincipal.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/CustomUserDetailsService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/CustomUserDetailsService.java diff --git a/spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/util/DummyContentUtil.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/util/DummyContentUtil.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/Application.java similarity index 61% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/Application.java index f932ac3066..682d429963 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/Application.java @@ -1,12 +1,8 @@ package org.baeldung.custom; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication public class Application extends SpringBootServletInitializer { diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MvcConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MvcConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/SecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/SetupData.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/SetupData.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Foo.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Foo.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Organization.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Organization.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Privilege.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Privilege.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/User.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/User.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/web/MainController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/web/MainController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/IpApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/IpApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/web/MainController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/web/MainController.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java new file mode 100644 index 0000000000..6bd30414ef --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java @@ -0,0 +1,15 @@ +package org.baeldung.jdbcauthentication.h2; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; + +@SpringBootApplication +@EnableWebSecurity +public class H2JdbcAuthenticationApplication { + + public static void main(String[] args) { + SpringApplication.run(H2JdbcAuthenticationApplication.class, args); + } + +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java new file mode 100644 index 0000000000..8b8696f0b2 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java @@ -0,0 +1,51 @@ +package org.baeldung.jdbcauthentication.h2.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity httpSecurity) throws Exception { + httpSecurity.authorizeRequests() + .antMatchers("/h2-console/**") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin() + .permitAll(); + httpSecurity.csrf() + .ignoringAntMatchers("/h2-console/**"); + httpSecurity.headers() + .frameOptions() + .sameOrigin(); + } + + @Autowired + private DataSource dataSource; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource) + .withDefaultSchema() + .withUser(User.withUsername("user") + .password(passwordEncoder().encode("pass")) + .roles("USER")); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java new file mode 100644 index 0000000000..0955061614 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java @@ -0,0 +1,17 @@ +package org.baeldung.jdbcauthentication.h2.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/principal") +public class UserController { + + @GetMapping + public Principal retrievePrincipal(Principal principal) { + return principal; + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/PagesController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/PagesController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/PagesController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/PagesController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java similarity index 69% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java index e9dc541ad3..d25324eb54 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java @@ -1,11 +1,8 @@ package org.baeldung.multiplelogin; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan("org.baeldung.multiplelogin") diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/UsersController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/UsersController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Role.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Role.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/User.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/User.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/SecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/WelcomeController.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/WelcomeController.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/MinuteBasedVoter.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/MinuteBasedVoter.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/MinuteBasedVoter.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/MinuteBasedVoter.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterApplication.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterApplication.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterApplication.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterMvcConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterMvcConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/WebSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/WebSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/XmlSecurityConfig.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/XmlSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/src/main/java/org/baeldung/voter/XmlSecurityConfig.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/XmlSecurityConfig.java diff --git a/spring-security-mvc-boot/src/main/resources/application-ssl.properties b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application-ssl.properties similarity index 100% rename from spring-security-mvc-boot/src/main/resources/application-ssl.properties rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application-ssl.properties diff --git a/spring-security-mvc-boot/src/main/resources/application.properties b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application.properties similarity index 74% rename from spring-security-mvc-boot/src/main/resources/application.properties rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application.properties index 25eac743d1..365dedab9e 100644 --- a/spring-security-mvc-boot/src/main/resources/application.properties +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application.properties @@ -8,5 +8,7 @@ spring.jpa.database=H2 spring.jpa.show-sql=false spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect +logging.level.org.springframework.security.web.FilterChainProxy=DEBUG -#logging.level.org.springframework.security.web.FilterChainProxy=DEBUG \ No newline at end of file +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/keystore/baeldung.p12 b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/keystore/baeldung.p12 similarity index 100% rename from spring-security-mvc-boot/src/main/resources/keystore/baeldung.p12 rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/keystore/baeldung.p12 diff --git a/spring-security-mvc-boot/src/main/resources/logback.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/logback.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/logback.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/logback.xml diff --git a/spring-security-mvc-boot/src/main/resources/persistence-h2.properties b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-security-mvc-boot/src/main/resources/persistence-h2.properties rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/persistence-h2.properties diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-custom-voter.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-custom-voter.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/spring-security-custom-voter.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-custom-voter.xml diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-ip.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-ip.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/spring-security-ip.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-ip.xml diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-multiple-auth-providers.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-auth-providers.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/spring-security-multiple-auth-providers.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-auth-providers.xml diff --git a/spring-security-mvc-boot/src/main/resources/spring-security-multiple-entry.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-entry.xml similarity index 100% rename from spring-security-mvc-boot/src/main/resources/spring-security-multiple-entry.xml rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-entry.xml diff --git a/spring-security-mvc-boot/src/main/resources/templates/403.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/403.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/403.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/403.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/adminPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/adminPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/adminPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/adminPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/index.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/index.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/index.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/index.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/login.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/login.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/login.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/login.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/loginAdmin.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginAdmin.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/loginAdmin.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginAdmin.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/loginUser.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginUser.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/loginUser.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginUser.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/login.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/login.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/login.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/login.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/loginWithWarning.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/loginWithWarning.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/loginWithWarning.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/loginWithWarning.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myAdminPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myAdminPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myAdminPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myAdminPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myGuestPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myGuestPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myGuestPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myGuestPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myUserPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myUserPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myUserPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myUserPage.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/private.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/private.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/private.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/private.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/protectedLinks.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/protectedLinks.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/protectedLinks.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/protectedLinks.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/home.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/home.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/login.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/login.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyauthority.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyauthority.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbynothing.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbynothing.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyrole.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyrole.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/ssl/welcome.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/ssl/welcome.html diff --git a/spring-security-mvc-boot/src/main/resources/templates/userPage.html b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/userPage.html similarity index 100% rename from spring-security-mvc-boot/src/main/resources/templates/userPage.html rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/userPage.html diff --git a/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/SpringContextIntegrationTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java new file mode 100644 index 0000000000..638e9d7919 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java @@ -0,0 +1,35 @@ +package org.baeldung.jdbcauthentication.h2.web; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +import io.restassured.authentication.FormAuthConfig; +import io.restassured.filter.session.SessionFilter; + +/** + * This Live Test requires the H2JdbcAuthenticationApplication application to be up and running + */ +public class UserControllerLiveTest { + + private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; + + @Test + public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { + SessionFilter filter = new SessionFilter(); + given().auth() + .form("user", "pass", new FormAuthConfig("/login", "username", "password").withCsrfFieldName("_csrf")) + .and() + .filter(filter) + .when() + .get(PRINCIPAL_SVC_URL) + .then() + .statusCode(HttpStatus.OK.value()) + .and() + .body("authorities[0].authority", is("ROLE_USER")) + .body("principal.username", is("user")) + .body("name", is("user")); + } +} diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/ApplicationLiveTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/ApplicationLiveTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/IpLiveTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/IpLiveTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java rename to spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml new file mode 100644 index 0000000000..765953c557 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + com.baeldung + spring-security-mvc-boot-mysql + 0.0.1-SNAPSHOT + spring-security-mvc-boot-mysql + jar + Spring Security MVC Boot using MySQL + + + spring-security-mvc-boot + com.baeldung + 0.0.1-SNAPSHOT + .. + + + + + mysql + mysql-connector-java + runtime + + + + diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java new file mode 100644 index 0000000000..238a48730c --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.jdbcauthentication.mysql; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MySqlJdbcAuthenticationApplication { + + public static void main(String[] args) { + SpringApplication.run(MySqlJdbcAuthenticationApplication.class, args); + } + +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java new file mode 100644 index 0000000000..a0584818cd --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.mysql.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration { + + @Autowired + private DataSource dataSource; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource) + .usersByUsernameQuery("select email,password,enabled " + + "from bael_users " + + "where email = ?") + .authoritiesByUsernameQuery("select email,authority " + + "from authorities " + + "where email = ?"); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java new file mode 100644 index 0000000000..ed15f8bfe6 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java @@ -0,0 +1,17 @@ +package com.baeldung.jdbcauthentication.mysql.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/principal") +public class UserController { + + @GetMapping + public Principal retrievePrincipal(Principal principal) { + return principal; + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties new file mode 100644 index 0000000000..2962475108 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.port=8082 + +spring.datasource.url=jdbc:mysql://localhost:3306/jdbc_authentication +spring.datasource.username=root +spring.datasource.password=pass + +spring.datasource.initialization-mode=always +spring.jpa.hibernate.ddl-auto=none diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql new file mode 100644 index 0000000000..8214fd8204 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql @@ -0,0 +1,4 @@ +-- User user@email.com/pass +INSERT INTO bael_users (name, email, password, enabled) values ('user', 'user@email.com', '$2a$10$8.UnVuG9HHgffUDAlk8qfOuVGkqRzgVymGe07xd00DMxs.AQubh4a', 1); + +INSERT INTO authorities (email, authority) values ('user@email.com', 'ROLE_USER'); \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql new file mode 100644 index 0000000000..bb38c74366 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql @@ -0,0 +1,18 @@ +DROP TABLE IF EXISTS authorities; +DROP TABLE IF EXISTS bael_users; + +CREATE TABLE bael_users ( + name VARCHAR(50) NOT NULL, + email VARCHAR(50) NOT NULL, + password VARCHAR(100) NOT NULL, + enabled TINYINT NOT NULL DEFAULT 1, + PRIMARY KEY (email) +); + +CREATE TABLE authorities ( + email VARCHAR(50) NOT NULL, + authority VARCHAR(50) NOT NULL, + FOREIGN KEY (email) REFERENCES bael_users(email) +); + +CREATE UNIQUE INDEX ix_auth_email on authorities (email,authority); \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2c19e2c0ca --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung.jdbcauthentication.mysql; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = MySqlJdbcAuthenticationApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java new file mode 100644 index 0000000000..79bc84ea69 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.mysql.web; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +/** + * This Live Test requires: + * * a MySql instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication + * (e.g. with the following command `docker run -p 3306:3306 --name bael-mysql -e MYSQL_ROOT_PASSWORD=pass -e MYSQL_DATABASE=jdbc_authentication mysql:latest`) + * * the service up and running + * + */ +public class UserControllerLiveTest { + + private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; + + @Test + public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { + given().auth() + .preemptive() + .basic("user@email.com", "pass") + .when() + .get(PRINCIPAL_SVC_URL) + .then() + .statusCode(HttpStatus.OK.value()) + .and() + .body("authorities[0].authority", is("ROLE_USER")) + .body("principal.username", is("user@email.com")) + .body("name", is("user@email.com")); + } + +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml new file mode 100644 index 0000000000..e68e47b596 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + com.baeldung + spring-security-mvc-boot-postgre + 0.0.1-SNAPSHOT + spring-security-mvc-boot-postgre + jar + Spring Security MVC Boot using PostgreSQL + + + spring-security-mvc-boot + com.baeldung + 0.0.1-SNAPSHOT + .. + + + + + org.postgresql + postgresql + runtime + + + + diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java new file mode 100644 index 0000000000..d4b555e8c6 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.jdbcauthentication.postgre; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PostgreJdbcAuthenticationApplication { + + public static void main(String[] args) { + SpringApplication.run(PostgreJdbcAuthenticationApplication.class, args); + } + +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java new file mode 100644 index 0000000000..85dc9d364c --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.jdbcauthentication.postgre.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfiguration { + + @Autowired + private DataSource dataSource; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.jdbcAuthentication() + .dataSource(dataSource); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java new file mode 100644 index 0000000000..da85a46562 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java @@ -0,0 +1,17 @@ +package com.baeldung.jdbcauthentication.postgre.web; + +import java.security.Principal; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/principal") +public class UserController { + + @GetMapping + public Principal retrievePrincipal(Principal principal) { + return principal; + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties new file mode 100644 index 0000000000..2940c5121e --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties @@ -0,0 +1,8 @@ +server.port=8082 + +spring.datasource.url=jdbc:postgresql://localhost:5432/jdbc_authentication +spring.datasource.username=postgres +spring.datasource.password=pass + +spring.datasource.initialization-mode=always +spring.jpa.hibernate.ddl-auto=none diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql new file mode 100644 index 0000000000..fcc6b54949 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql @@ -0,0 +1,4 @@ +-- User user/pass +INSERT INTO users (username, password, enabled) values ('user', '$2a$10$8.UnVuG9HHgffUDAlk8qfOuVGkqRzgVymGe07xd00DMxs.AQubh4a', true); + +INSERT INTO authorities (username, authority) values ('user', 'ROLE_USER'); \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql new file mode 100644 index 0000000000..d78edfb528 --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql @@ -0,0 +1,16 @@ +DROP TABLE IF EXISTS authorities; +DROP TABLE IF EXISTS users; + +CREATE TABLE users ( + username varchar(50) NOT NULL PRIMARY KEY, + password varchar(100) NOT NULL, + enabled boolean not null DEFAULT true +); + +CREATE TABLE authorities ( + username varchar(50) NOT NULL, + authority varchar(50) NOT NULL, + CONSTRAINT foreign_authorities_users_1 foreign key(username) references users(username) +); + +CREATE UNIQUE INDEX ix_auth_username on authorities (username,authority); \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..f133ef73be --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung.jdbcauthentication.postgre; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.jdbcauthentication.postgre.PostgreJdbcAuthenticationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PostgreJdbcAuthenticationApplication.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java new file mode 100644 index 0000000000..b5f4379c0a --- /dev/null +++ b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jdbcauthentication.postgre.web; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +/** + * This Live Test requires: + * * a PostgreSQL instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication + * (e.g. with the following command `docker run -p 5432:5432 --name bael-postgre -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=jdbc_authentication postgres:latest`) + * * the service up and running + * + */ +public class UserControllerLiveTest { + + private static final String PRINCIPAL_SVC_URL = "http://localhost:8082/principal"; + + @Test + public void givenExisting_whenRequestPrincipal_thenRetrieveData() throws Exception { + given().auth() + .preemptive() + .basic("user", "pass") + .when() + .get(PRINCIPAL_SVC_URL) + .then() + .statusCode(HttpStatus.OK.value()) + .and() + .body("authorities[0].authority", is("ROLE_USER")) + .body("principal.username", is("user")) + .body("name", is("user")); + } + +} From f174fa0ae93e46820456607a141fa3fcfb52e53e Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 29 Jul 2019 09:55:54 -0300 Subject: [PATCH 335/352] Fix test naming, now renamed as LiveTest --- ...onIntegrationTest.java => SessionConfigurationLiveTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-security-mvc/src/test/java/com/baeldung/session/{SessionConfigurationIntegrationTest.java => SessionConfigurationLiveTest.java} (98%) diff --git a/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java b/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationLiveTest.java similarity index 98% rename from spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java rename to spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationLiveTest.java index 5a9bf72077..7d9a03d5f6 100644 --- a/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationIntegrationTest.java +++ b/spring-security-mvc/src/test/java/com/baeldung/session/SessionConfigurationLiveTest.java @@ -15,7 +15,7 @@ import io.restassured.specification.RequestSpecification; /** * This Live Test requires the service to be up and running. */ -public class SessionConfigurationIntegrationTest { +public class SessionConfigurationLiveTest { private static final String USER = "user1"; private static final String PASSWORD = "user1Pass"; From 8f5bb3c6a94e64660abac317e0a52bd54908996a Mon Sep 17 00:00:00 2001 From: Paul Latzelsperger <43503240+beardyinc@users.noreply.github.com> Date: Mon, 29 Jul 2019 22:38:42 +0200 Subject: [PATCH 336/352] Bael 3082 (#7446) * added example code for BAEL-3082 * added another test case, refactored method names * moved to basics module --- .../failure_vs_error/SimpleCalculator.java | 15 +++++++ .../SimpleCalculatorUnitTest.java | 39 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 testing-modules/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java create mode 100644 testing-modules/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java diff --git a/testing-modules/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java b/testing-modules/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java new file mode 100644 index 0000000000..d018aa939f --- /dev/null +++ b/testing-modules/junit-5-basics/src/main/java/com/baeldung/failure_vs_error/SimpleCalculator.java @@ -0,0 +1,15 @@ +package com.baeldung.failure_vs_error; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +public class SimpleCalculator { + + public static double divideNumbers(double dividend, double divisor) { + if (divisor == 0) { + throw new ArithmeticException("Division by zero!"); + } + return dividend / divisor; + } +} diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java new file mode 100644 index 0000000000..6833834959 --- /dev/null +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/failure_vs_error/SimpleCalculatorUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.failure_vs_error; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * @author paullatzelsperger + * @since 2019-07-17 + */ +class SimpleCalculatorUnitTest { + + @Test + void whenDivideByValidNumber_thenAssertCorrectResult() { + double result = SimpleCalculator.divideNumbers(6, 3); + assertEquals(2, result); + } + + @Test + @Disabled("test is expected to fail, disabled so that CI build still goes through") + void whenDivideNumbers_thenExpectWrongResult() { + double result = SimpleCalculator.divideNumbers(6, 3); + assertEquals(15, result); + } + + @Test + @Disabled("test is expected to raise an error, disabled so that CI build still goes through") + void whenDivideByZero_thenThrowsException() { + SimpleCalculator.divideNumbers(10, 0); + } + + @Test + void whenDivideByZero_thenAssertException(){ + assertThrows(ArithmeticException.class, () -> SimpleCalculator.divideNumbers(10, 0)); + } + +} From d9a20d17641f8a769cefe474684b955187de2b51 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Tue, 30 Jul 2019 03:14:52 +0530 Subject: [PATCH 337/352] BAEL-2906 Functional Controllers in Spring MVC (#6972) * BAEL-2906 Functional Controllers in Spring MVC * BAEL-2906 Functional Controllers in Spring MVC * BAEL-2906 Functional Controllers in Spring MVC * BAEL-2906 Removed unnecessary files * BAEL-2906 Removed project * BAEL-2906 Removed comments --- spring-boot-mvc-2/.gitignore | 25 +++++++ spring-boot-mvc-2/README.md | 3 + spring-boot-mvc-2/pom.xml | 68 +++++++++++++++++ .../SpringBootMvcFnApplication.java | 74 +++++++++++++++++++ .../springbootmvc/ctrl/ProductController.java | 59 +++++++++++++++ .../baeldung/springbootmvc/model/Product.java | 72 ++++++++++++++++++ .../springbootmvc/svc/ProductService.java | 63 ++++++++++++++++ .../src/main/resources/application.properties | 1 + .../src/main/resources/logback.xml | 13 ++++ 9 files changed, 378 insertions(+) create mode 100644 spring-boot-mvc-2/.gitignore create mode 100644 spring-boot-mvc-2/README.md create mode 100644 spring-boot-mvc-2/pom.xml create mode 100644 spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java create mode 100644 spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java create mode 100644 spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java create mode 100644 spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java create mode 100644 spring-boot-mvc-2/src/main/resources/application.properties create mode 100644 spring-boot-mvc-2/src/main/resources/logback.xml diff --git a/spring-boot-mvc-2/.gitignore b/spring-boot-mvc-2/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/spring-boot-mvc-2/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-mvc-2/README.md b/spring-boot-mvc-2/README.md new file mode 100644 index 0000000000..a405298cbe --- /dev/null +++ b/spring-boot-mvc-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Functional Controllers in Spring MVC]() \ No newline at end of file diff --git a/spring-boot-mvc-2/pom.xml b/spring-boot-mvc-2/pom.xml new file mode 100644 index 0000000000..18121325a5 --- /dev/null +++ b/spring-boot-mvc-2/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + spring-boot-mvc-2 + spring-boot-mvc-2 + jar + Module For Spring Boot MVC Web Fn + + + org.springframework.boot + spring-boot-starter-parent + 2.2.0.BUILD-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.springbootmvc.SpringBootMvcFnApplication + JAR + + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + \ No newline at end of file diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java new file mode 100644 index 0000000000..2a85550bd7 --- /dev/null +++ b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/SpringBootMvcFnApplication.java @@ -0,0 +1,74 @@ +package com.baeldung.springbootmvc; + +import static org.springframework.web.servlet.function.RouterFunctions.route; +import static org.springframework.web.servlet.function.ServerResponse.notFound; +import static org.springframework.web.servlet.function.ServerResponse.status; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.http.HttpStatus; +import org.springframework.web.servlet.function.RequestPredicates; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.ServerResponse; + +import com.baeldung.springbootmvc.ctrl.ProductController; +import com.baeldung.springbootmvc.svc.ProductService; + +@SpringBootApplication +public class SpringBootMvcFnApplication { + + private static final Logger LOG = LoggerFactory.getLogger(SpringBootMvcFnApplication.class); + + public static void main(String[] args) { + SpringApplication.run(SpringBootMvcFnApplication.class, args); + } + + @Bean + RouterFunction productListing(ProductController pc, ProductService ps) { + return pc.productListing(ps); + } + + @Bean + RouterFunction allApplicationRoutes(ProductController pc, ProductService ps) { + return route().add(pc.remainingProductRoutes(ps)) + .before(req -> { + LOG.info("Found a route which matches " + req.uri() + .getPath()); + return req; + }) + .after((req, res) -> { + if (res.statusCode() == HttpStatus.OK) { + LOG.info("Finished processing request " + req.uri() + .getPath()); + } else { + LOG.info("There was an error while processing request" + req.uri()); + } + return res; + }) + .onError(Throwable.class, (e, res) -> { + LOG.error("Fatal exception has occurred", e); + return status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + }) + .build() + .and(route(RequestPredicates.all(), req -> notFound().build())); + } + + public static class Error { + private String errorMessage; + + public Error(String message) { + this.errorMessage = message; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + } +} diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java new file mode 100644 index 0000000000..6a77e72cea --- /dev/null +++ b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/ctrl/ProductController.java @@ -0,0 +1,59 @@ +package com.baeldung.springbootmvc.ctrl; + +import static org.springframework.web.servlet.function.RouterFunctions.route; +import static org.springframework.web.servlet.function.ServerResponse.ok; +import static org.springframework.web.servlet.function.ServerResponse.status; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.function.EntityResponse; +import org.springframework.web.servlet.function.RequestPredicates; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.ServerRequest; +import org.springframework.web.servlet.function.ServerResponse; + +import com.baeldung.springbootmvc.SpringBootMvcFnApplication.Error; +import com.baeldung.springbootmvc.model.Product; +import com.baeldung.springbootmvc.svc.ProductService; + +@Component +public class ProductController { + + public RouterFunction productListing(ProductService ps) { + return route().GET("/product", req -> ok().body(ps.findAll())) + .build(); + } + + public RouterFunction productSearch(ProductService ps) { + return route().nest(RequestPredicates.path("/product"), builder -> { + builder.GET("/name/{name}", req -> ok().body(ps.findByName(req.pathVariable("name")))) + .GET("/id/{id}", req -> ok().body(ps.findById(Integer.parseInt(req.pathVariable("id"))))); + }) + .onError(ProductService.ItemNotFoundException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage())) + .status(HttpStatus.NOT_FOUND) + .build()) + .build(); + } + + public RouterFunction adminFunctions(ProductService ps) { + return route().POST("/product", req -> ok().body(ps.save(req.body(Product.class)))) + .filter((req, next) -> authenticate(req) ? next.handle(req) : status(HttpStatus.UNAUTHORIZED).build()) + .onError(IllegalArgumentException.class, (e, req) -> EntityResponse.fromObject(new Error(e.getMessage())) + .status(HttpStatus.BAD_REQUEST) + .build()) + .build(); + } + + public RouterFunction remainingProductRoutes(ProductService ps) { + return route().add(productSearch(ps)) + .add(adminFunctions(ps)) + .build(); + } + + private boolean authenticate(ServerRequest req) { + return Boolean.TRUE; + } + +} diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java new file mode 100644 index 0000000000..1213b3c11e --- /dev/null +++ b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/model/Product.java @@ -0,0 +1,72 @@ +package com.baeldung.springbootmvc.model; + +public class Product { + private String name; + private double price; + private int id; + + public Product(String name, double price, int id) { + super(); + this.name = name; + this.price = price; + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + long temp; + temp = Double.doubleToLongBits(price); + result = prime * result + (int) (temp ^ (temp >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Product other = (Product) obj; + if (id != other.id) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price)) + return false; + return true; + } + +} diff --git a/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java new file mode 100644 index 0000000000..e2d281d54f --- /dev/null +++ b/spring-boot-mvc-2/src/main/java/com/baeldung/springbootmvc/svc/ProductService.java @@ -0,0 +1,63 @@ +package com.baeldung.springbootmvc.svc; + +import java.util.HashSet; +import java.util.Set; + +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import com.baeldung.springbootmvc.model.Product; + +@Service +public class ProductService { + + private final Set products = new HashSet<>(); + + { + products.add(new Product("Book", 23.90, 1)); + products.add(new Product("Pen", 44.34, 2)); + } + + public Product findById(int id) { + return products.stream() + .filter(obj -> obj.getId() == id) + .findFirst() + .orElseThrow(() -> new ItemNotFoundException("Product not found")); + } + + public Product findByName(String name) { + return products.stream() + .filter(obj -> obj.getName() + .equalsIgnoreCase(name)) + .findFirst() + .orElseThrow(() -> new ItemNotFoundException("Product not found")); + } + + public Set findAll() { + return products; + } + + public Product save(Product product) { + if (StringUtils.isEmpty(product.getName()) || product.getPrice() == 0.0) { + throw new IllegalArgumentException(); + } + int newId = products.stream() + .mapToInt(Product::getId) + .max() + .getAsInt() + 1; + product.setId(newId); + products.add(product); + return product; + } + + public static class ItemNotFoundException extends RuntimeException { + /** + * + */ + private static final long serialVersionUID = 1L; + + public ItemNotFoundException(String msg) { + super(msg); + } + } +} diff --git a/spring-boot-mvc-2/src/main/resources/application.properties b/spring-boot-mvc-2/src/main/resources/application.properties new file mode 100644 index 0000000000..709574239b --- /dev/null +++ b/spring-boot-mvc-2/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-mvc-2/src/main/resources/logback.xml b/spring-boot-mvc-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-mvc-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file From 627fb4f1d114c81ceae4bbbbc04860ef026af182 Mon Sep 17 00:00:00 2001 From: maryarm <45322329+maryarm@users.noreply.github.com> Date: Tue, 30 Jul 2019 09:49:08 +0430 Subject: [PATCH 338/352] #BAEL-2888: Reloading Properties Files in Spring (#7427) -change package name to "com.baeldung.properties.reloading" -remove module 's ".gitignore" --- spring-boot-properties/.gitignore | 17 ----------------- .../SpringBootPropertiesApplication.java | 4 ++-- .../configs/PropertiesException.java | 2 +- .../configs/ReloadableProperties.java | 2 +- .../configs/ReloadablePropertySource.java | 2 +- .../configs/ReloadablePropertySourceConfig.java | 2 +- .../ReloadablePropertySourceFactory.java | 2 +- .../PropertiesReloadIntegrationTest.java | 10 +++++----- .../SpringBootPropertiesTestApplication.java | 4 ++-- ...onfigurationPropertiesRefreshConfigBean.java | 2 +- .../beans/EnvironmentConfigBean.java | 4 ++-- .../beans/PropertiesConfigBean.java | 2 +- .../beans/ValueRefreshConfigBean.java | 2 +- 13 files changed, 19 insertions(+), 36 deletions(-) delete mode 100644 spring-boot-properties/.gitignore rename spring-boot-properties/src/main/java/com/baeldung/properties/{ => reloading}/SpringBootPropertiesApplication.java (94%) rename spring-boot-properties/src/main/java/com/baeldung/properties/{ => reloading}/configs/PropertiesException.java (78%) rename spring-boot-properties/src/main/java/com/baeldung/properties/{ => reloading}/configs/ReloadableProperties.java (96%) rename spring-boot-properties/src/main/java/com/baeldung/properties/{ => reloading}/configs/ReloadablePropertySource.java (95%) rename spring-boot-properties/src/main/java/com/baeldung/properties/{ => reloading}/configs/ReloadablePropertySourceConfig.java (95%) rename spring-boot-properties/src/main/java/com/baeldung/properties/{ => reloading}/configs/ReloadablePropertySourceFactory.java (95%) rename spring-boot-properties/src/test/java/com/baeldung/properties/{ => reloading}/PropertiesReloadIntegrationTest.java (94%) rename spring-boot-properties/src/test/java/com/baeldung/properties/{ => reloading}/SpringBootPropertiesTestApplication.java (89%) rename spring-boot-properties/src/test/java/com/baeldung/properties/{ => reloading}/beans/ConfigurationPropertiesRefreshConfigBean.java (91%) rename spring-boot-properties/src/test/java/com/baeldung/properties/{ => reloading}/beans/EnvironmentConfigBean.java (85%) rename spring-boot-properties/src/test/java/com/baeldung/properties/{ => reloading}/beans/PropertiesConfigBean.java (90%) rename spring-boot-properties/src/test/java/com/baeldung/properties/{ => reloading}/beans/ValueRefreshConfigBean.java (81%) diff --git a/spring-boot-properties/.gitignore b/spring-boot-properties/.gitignore deleted file mode 100644 index 0532ef1888..0000000000 --- a/spring-boot-properties/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear - -*.ipr -*.iml -*.iws diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java similarity index 94% rename from spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java rename to spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java index 67bbddf9f1..6f76379a99 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/SpringBootPropertiesApplication.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/SpringBootPropertiesApplication.java @@ -1,6 +1,6 @@ -package com.baeldung.properties; +package com.baeldung.properties.reloading; -import com.baeldung.properties.configs.ReloadableProperties; +import com.baeldung.properties.reloading.configs.ReloadableProperties; import java.io.File; import java.util.Properties; import org.apache.commons.configuration.PropertiesConfiguration; diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java similarity index 78% rename from spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java rename to spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java index 5ec3a042f7..09c18aef33 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/PropertiesException.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/PropertiesException.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.configs; +package com.baeldung.properties.reloading.configs; public class PropertiesException extends RuntimeException { public PropertiesException() { diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java similarity index 96% rename from spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java rename to spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java index 33d503b9bd..e90e68d09a 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadableProperties.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadableProperties.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.configs; +package com.baeldung.properties.reloading.configs; import java.io.FileReader; import java.io.IOException; diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java similarity index 95% rename from spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java rename to spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java index 8a0cef955f..6d76a2e1e2 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySource.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySource.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.configs; +package com.baeldung.properties.reloading.configs; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy; diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java similarity index 95% rename from spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java rename to spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java index 37e1a04839..dd70e3842e 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceConfig.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.configs; +package com.baeldung.properties.reloading.configs; import org.apache.commons.configuration.PropertiesConfiguration; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java similarity index 95% rename from spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java rename to spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java index 574362b3bf..2a620b0b2d 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/configs/ReloadablePropertySourceFactory.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/reloading/configs/ReloadablePropertySourceFactory.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.configs; +package com.baeldung.properties.reloading.configs; import java.io.IOException; import org.springframework.core.env.PropertySource; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java similarity index 94% rename from spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java rename to spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java index a73311ded8..0c28cb085b 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/PropertiesReloadIntegrationTest.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/PropertiesReloadIntegrationTest.java @@ -1,9 +1,9 @@ -package com.baeldung.properties; +package com.baeldung.properties.reloading; -import com.baeldung.properties.beans.ConfigurationPropertiesRefreshConfigBean; -import com.baeldung.properties.beans.EnvironmentConfigBean; -import com.baeldung.properties.beans.PropertiesConfigBean; -import com.baeldung.properties.beans.ValueRefreshConfigBean; +import com.baeldung.properties.reloading.beans.ConfigurationPropertiesRefreshConfigBean; +import com.baeldung.properties.reloading.beans.EnvironmentConfigBean; +import com.baeldung.properties.reloading.beans.PropertiesConfigBean; +import com.baeldung.properties.reloading.beans.ValueRefreshConfigBean; import java.io.FileOutputStream; import org.junit.After; import org.junit.Assert; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java similarity index 89% rename from spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java rename to spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java index c572a6c053..50e8ef5b62 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/SpringBootPropertiesTestApplication.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/SpringBootPropertiesTestApplication.java @@ -1,6 +1,6 @@ -package com.baeldung.properties; +package com.baeldung.properties.reloading; -import com.baeldung.properties.beans.ValueRefreshConfigBean; +import com.baeldung.properties.reloading.beans.ValueRefreshConfigBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.context.config.annotation.RefreshScope; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java similarity index 91% rename from spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java rename to spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java index 31f168fdcc..16892b904b 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ConfigurationPropertiesRefreshConfigBean.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ConfigurationPropertiesRefreshConfigBean.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.beans; +package com.baeldung.properties.reloading.beans; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java similarity index 85% rename from spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java rename to spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java index fef12f8656..325e8c658e 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/EnvironmentConfigBean.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/EnvironmentConfigBean.java @@ -1,6 +1,6 @@ -package com.baeldung.properties.beans; +package com.baeldung.properties.reloading.beans; -import com.baeldung.properties.configs.ReloadablePropertySourceFactory; +import com.baeldung.properties.reloading.configs.ReloadablePropertySourceFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java similarity index 90% rename from spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java rename to spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java index da773b283a..8118f6156e 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/PropertiesConfigBean.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/PropertiesConfigBean.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.beans; +package com.baeldung.properties.reloading.beans; import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java similarity index 81% rename from spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java rename to spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java index d806938092..1018d7c9f5 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/beans/ValueRefreshConfigBean.java +++ b/spring-boot-properties/src/test/java/com/baeldung/properties/reloading/beans/ValueRefreshConfigBean.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.beans; +package com.baeldung.properties.reloading.beans; public class ValueRefreshConfigBean { private String color; From 36ad6f15ef1b1f5db8aeb1e6d0257d12a1adccb2 Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Tue, 30 Jul 2019 11:39:34 +0530 Subject: [PATCH 339/352] Adding code for the tutorial tracked under BAEL-3073. (#7442) --- .../baeldung/sasl/ClientCallbackHandler.java | 29 +++++++ .../baeldung/sasl/ServerCallbackHandler.java | 34 +++++++++ .../java/com/baeldung/sasl/SaslUnitTest.java | 76 +++++++++++++++++++ 3 files changed, 139 insertions(+) create mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java create mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java create mode 100644 core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java new file mode 100644 index 0000000000..d73f2a2708 --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ClientCallbackHandler.java @@ -0,0 +1,29 @@ +package com.baeldung.sasl; + +import java.io.IOException; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.sasl.RealmCallback; + +public class ClientCallbackHandler implements CallbackHandler { + + @Override + public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException { + for (Callback cb : cbs) { + if (cb instanceof NameCallback) { + NameCallback nc = (NameCallback) cb; + nc.setName("username"); + } else if (cb instanceof PasswordCallback) { + PasswordCallback pc = (PasswordCallback) cb; + pc.setPassword("password".toCharArray()); + } else if (cb instanceof RealmCallback) { + RealmCallback rc = (RealmCallback) cb; + rc.setText("myServer"); + } + } + } +} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java new file mode 100644 index 0000000000..3e071d68cc --- /dev/null +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java @@ -0,0 +1,34 @@ +package com.baeldung.sasl; + +import java.io.IOException; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.sasl.AuthorizeCallback; +import javax.security.sasl.RealmCallback; + +public class ServerCallbackHandler implements CallbackHandler { + + @Override + public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException { + for (Callback cb : cbs) { + if (cb instanceof AuthorizeCallback) { + AuthorizeCallback ac = (AuthorizeCallback) cb; + ac.setAuthorized(true); + } else if (cb instanceof NameCallback) { + NameCallback nc = (NameCallback) cb; + nc.setName("username"); + + } else if (cb instanceof PasswordCallback) { + PasswordCallback pc = (PasswordCallback) cb; + pc.setPassword("password".toCharArray()); + } else if (cb instanceof RealmCallback) { + RealmCallback rc = (RealmCallback) cb; + rc.setText("myServer"); + } + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java new file mode 100644 index 0000000000..6601654781 --- /dev/null +++ b/core-java-modules/core-java-security/src/test/java/com/baeldung/sasl/SaslUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.sasl; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import javax.security.sasl.Sasl; +import javax.security.sasl.SaslClient; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SaslUnitTest { + + private static final String MECHANISM = "DIGEST-MD5"; + private static final String SERVER_NAME = "myServer"; + private static final String PROTOCOL = "myProtocol"; + private static final String AUTHORIZATION_ID = null; + private static final String QOP_LEVEL = "auth-conf"; + + private SaslServer saslServer; + private SaslClient saslClient; + + @Before + public void setUp() throws SaslException { + + ServerCallbackHandler serverHandler = new ServerCallbackHandler(); + ClientCallbackHandler clientHandler = new ClientCallbackHandler(); + + Map props = new HashMap<>(); + props.put(Sasl.QOP, QOP_LEVEL); + + saslServer = Sasl.createSaslServer(MECHANISM, PROTOCOL, SERVER_NAME, props, serverHandler); + saslClient = Sasl.createSaslClient(new String[] { MECHANISM }, AUTHORIZATION_ID, PROTOCOL, SERVER_NAME, props, clientHandler); + + } + + @Test + public void givenHandlers_whenStarted_thenAutenticationWorks() throws SaslException { + + byte[] challenge; + byte[] response; + + challenge = saslServer.evaluateResponse(new byte[0]); + response = saslClient.evaluateChallenge(challenge); + + challenge = saslServer.evaluateResponse(response); + response = saslClient.evaluateChallenge(challenge); + + assertTrue(saslServer.isComplete()); + assertTrue(saslClient.isComplete()); + + String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP); + assertEquals("auth-conf", qop); + + byte[] outgoing = "Baeldung".getBytes(); + byte[] secureOutgoing = saslClient.wrap(outgoing, 0, outgoing.length); + + byte[] secureIncoming = secureOutgoing; + byte[] incoming = saslServer.unwrap(secureIncoming, 0, secureIncoming.length); + assertEquals("Baeldung", new String(incoming, StandardCharsets.UTF_8)); + } + + @After + public void tearDown() throws SaslException { + saslClient.dispose(); + saslServer.dispose(); + } + +} From 8e3f2ae495116db8bfaf35f035351fe2c4d73218 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Tue, 30 Jul 2019 08:35:24 +0200 Subject: [PATCH 340/352] update --- persistence-modules/java-jpa-2/pom.xml | 96 +++++++++---------- .../java-jpa-2/src/main/resources/logback.xml | 13 --- 2 files changed, 48 insertions(+), 61 deletions(-) delete mode 100644 persistence-modules/java-jpa-2/src/main/resources/logback.xml diff --git a/persistence-modules/java-jpa-2/pom.xml b/persistence-modules/java-jpa-2/pom.xml index c8c9a24599..12586db1b7 100644 --- a/persistence-modules/java-jpa-2/pom.xml +++ b/persistence-modules/java-jpa-2/pom.xml @@ -19,11 +19,11 @@ hibernate-core ${hibernate.version} - - org.hibernate - hibernate-jpamodelgen - ${hibernate.version} - + + org.hibernate + hibernate-jpamodelgen + ${hibernate.version} + com.h2database h2 @@ -52,8 +52,8 @@ - - + + org.apache.maven.plugins maven-compiler-plugin @@ -62,48 +62,48 @@ -proc:none
    - - org.bsc.maven - maven-processor-plugin - 3.3.3 - - - process - - process - - generate-sources - - target/metamodel - - org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor - - - - - + + org.bsc.maven + maven-processor-plugin + 3.3.3 + + + process + + process + + generate-sources + + target/metamodel + + org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor + + + + + - - org.codehaus.mojo - build-helper-maven-plugin - 3.0.0 - - - add-source - generate-sources - - add-source - - - - target/metamodel - - - - - - - + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add-source + generate-sources + + add-source + + + + target/metamodel + + + + + + + 5.4.0.Final diff --git a/persistence-modules/java-jpa-2/src/main/resources/logback.xml b/persistence-modules/java-jpa-2/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/persistence-modules/java-jpa-2/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file From 2aa2f078ddb720ebf555f84cdd98bc237a363012 Mon Sep 17 00:00:00 2001 From: "sreekanth.nair" Date: Tue, 30 Jul 2019 12:55:29 +0530 Subject: [PATCH 341/352] [BAEL-3121] Added source for finding number of lines in a file --- .../main/java/com/baeldung/files/Main.java | 24 ++++ .../baeldung/files/NumberOfLineFinder.java | 112 ++++++++++++++++++ .../file/NumberOfLineFinderUnitTest.java | 60 ++++++++++ 3 files changed, 196 insertions(+) create mode 100644 core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java create mode 100644 core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java create mode 100644 core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java new file mode 100644 index 0000000000..c3bcd048a4 --- /dev/null +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/Main.java @@ -0,0 +1,24 @@ +package com.baeldung.files; + +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner; + +public class Main { + + private static final String INPUT_FILE_NAME = "src/main/resources/input.txt"; + + public static void main(String... args) throws Exception { + System.out.printf("Total Number of Lines Using BufferedReader: %s%n", getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using LineNumberReader: %s%n", getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using Scanner: %s%n", getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using NIO Files: %s%n", getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using NIO FileChannel: %s%n", getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using Apache Commons IO: %s%n", getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME)); + System.out.printf("Total Number of Lines Using NIO Google Guava: %s%n", getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME)); + } +} diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java new file mode 100644 index 0000000000..076825d76c --- /dev/null +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/files/NumberOfLineFinder.java @@ -0,0 +1,112 @@ +package com.baeldung.files; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.LineNumberReader; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.FileChannel.MapMode; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.List; +import java.util.Scanner; +import java.util.stream.Stream; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.LineIterator; + +public class NumberOfLineFinder { + + public static int getTotalNumberOfLinesUsingBufferedReader(String fileName) { + int lines = 0; + try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { + while (reader.readLine() != null) { + lines++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingLineNumberReader(String fileName) { + int lines = 0; + try (LineNumberReader reader = new LineNumberReader(new FileReader(fileName))) { + reader.skip(Integer.MAX_VALUE); + lines = reader.getLineNumber() + 1; + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingScanner(String fileName) { + int lines = 0; + try (Scanner scanner = new Scanner(new FileReader(fileName))) { + while (scanner.hasNextLine()) { + scanner.nextLine(); + lines++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingNIOFiles(String fileName) { + int lines = 0; + try (Stream fileStream = Files.lines(Paths.get(fileName))) { + lines = (int) fileStream.count(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingNIOFileChannel(String fileName) { + int lines = 1; + try (FileChannel channel = FileChannel.open(Paths.get(fileName), StandardOpenOption.READ)) { + ByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, 0, channel.size()); + while (byteBuffer.hasRemaining()) { + byte currentChar = byteBuffer.get(); + if (currentChar == '\n') { + lines++; + } + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingApacheCommonsIO(String fileName) { + int lines = 0; + try { + LineIterator lineIterator = FileUtils.lineIterator(new File(fileName)); + while (lineIterator.hasNext()) { + lineIterator.nextLine(); + lines++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + + public static int getTotalNumberOfLinesUsingGoogleGuava(String fileName) { + int lines = 0; + try { + List lineItems = com.google.common.io.Files.readLines(Paths.get(fileName) + .toFile(), Charset.defaultCharset()); + lines = lineItems.size(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + return lines; + } + +} diff --git a/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java b/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java new file mode 100644 index 0000000000..6f0427ebd2 --- /dev/null +++ b/core-java-modules/core-java-io/src/test/java/com/baeldung/file/NumberOfLineFinderUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.file; + +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles; +import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class NumberOfLineFinderUnitTest { + private static final String INPUT_FILE_NAME = "src/main/resources/input.txt"; + private static final int ACTUAL_LINE_COUNT = 45; + + @Test + public void whenUsingBufferedReader_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingLineNumberReader_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingScanner_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingNIOFiles_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingNIOFileChannel_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingApacheCommonsIO_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + + @Test + public void whenUsingGoogleGuava_thenReturnTotalNumberOfLines() { + int lines = getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME); + assertEquals(ACTUAL_LINE_COUNT, lines); + } + +} From 19d73e961173a82aa8822589986d113f75355b68 Mon Sep 17 00:00:00 2001 From: Alessio Stalla Date: Tue, 30 Jul 2019 14:36:32 +0200 Subject: [PATCH 342/352] Fix parent POM --- persistence-modules/java-sql2o/pom.xml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/persistence-modules/java-sql2o/pom.xml b/persistence-modules/java-sql2o/pom.xml index 54838c32cb..fe5a0e5dc8 100644 --- a/persistence-modules/java-sql2o/pom.xml +++ b/persistence-modules/java-sql2o/pom.xml @@ -2,7 +2,6 @@ 4.0.0 - com.baeldung java-sql2o 1.0-SNAPSHOT @@ -19,12 +18,12 @@ java-sql2o - + From db90a53e38b269698646678c4a6c20ad2d69cbc7 Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Tue, 30 Jul 2019 15:54:17 -0400 Subject: [PATCH 343/352] BAEL-3141: Added test cases for String to Double conversion. (#7448) These tests exercise the conversion of Strings that can be converted to Doubles, as well as the exceptions that are thrown for invalid Strings. --- .../StringToDoubleConversionUnitTest.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java diff --git a/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java new file mode 100644 index 0000000000..9abb7ac453 --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/todouble/StringToDoubleConversionUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.string.todouble; + +import static org.junit.Assert.assertEquals; + +import java.text.DecimalFormat; +import java.text.ParseException; + +import org.junit.Test; + +public class StringToDoubleConversionUnitTest { + + @Test + public void givenValidString_WhenParseDouble_ThenResultIsPrimitiveDouble() { + assertEquals(1.23, Double.parseDouble("1.23"), 0.000001); + } + + @Test(expected = NullPointerException.class) + public void givenNullString_WhenParseDouble_ThenNullPointerExceptionIsThrown() { + Double.parseDouble(null); + } + + @Test(expected = NumberFormatException.class) + public void givenInalidString_WhenParseDouble_ThenNumberFormatExceptionIsThrown() { + Double.parseDouble("&"); + } + + @Test + public void givenValidString_WhenValueOf_ThenResultIsPrimitiveDouble() { + assertEquals(1.23, Double.valueOf("1.23"), 0.000001); + } + + @Test(expected = NullPointerException.class) + public void givenNullString_WhenValueOf_ThenNullPointerExceptionIsThrown() { + Double.valueOf(null); + } + + @Test(expected = NumberFormatException.class) + public void givenInalidString_WhenValueOf_ThenNumberFormatExceptionIsThrown() { + Double.valueOf("&"); + } + + @Test + public void givenValidString_WhenDecimalFormat_ThenResultIsValidDouble() throws ParseException { + assertEquals(1.23, new DecimalFormat("#").parse("1.23").doubleValue(), 0.000001); + } + + @Test(expected = NullPointerException.class) + public void givenNullString_WhenDecimalFormat_ThenNullPointerExceptionIsThrown() throws ParseException { + new DecimalFormat("#").parse(null); + } + + @Test(expected = ParseException.class) + public void givenInvalidString_WhenDecimalFormat_ThenParseExceptionIsThrown() throws ParseException { + new DecimalFormat("#").parse("&"); + } +} From ecf8bd76cc7232e6d1a23cc16a651fea7abeb435 Mon Sep 17 00:00:00 2001 From: Sumeet Gajbhar Date: Wed, 31 Jul 2019 01:42:25 +0530 Subject: [PATCH 344/352] BAEL-3027 binary number arithmetic operations (#7437) * BAEL-3027 binary number arithmetic operations * BAEL-3127 updated the unit test case names * added unit test cases for built-in java functions * updated function name * BAEL-3127 updated unit test case names * BAEL-3127 removed comments from code --- .../baeldung/binarynumbers/BinaryNumbers.java | 148 ++++++++++++++++++ .../binarynumbers/BinaryNumbersUnitTest.java | 73 +++++++++ 2 files changed, 221 insertions(+) create mode 100644 java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java create mode 100644 java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java diff --git a/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java b/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java new file mode 100644 index 0000000000..effdee07ad --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/binarynumbers/BinaryNumbers.java @@ -0,0 +1,148 @@ +package com.baeldung.binarynumbers; + +public class BinaryNumbers { + + /** + * This method takes a decimal number and convert it into a binary number. + * example:- input:10, output:1010 + * + * @param decimalNumber + * @return binary number + */ + public Integer convertDecimalToBinary(Integer decimalNumber) { + + if (decimalNumber == 0) { + return decimalNumber; + } + + StringBuilder binaryNumber = new StringBuilder(); + + while (decimalNumber > 0) { + + int remainder = decimalNumber % 2; + int result = decimalNumber / 2; + + binaryNumber.append(remainder); + decimalNumber = result; + } + + binaryNumber = binaryNumber.reverse(); + + return Integer.valueOf(binaryNumber.toString()); + } + + /** + * This method takes a binary number and convert it into a decimal number. + * example:- input:101, output:5 + * + * @param binary number + * @return decimal Number + */ + public Integer convertBinaryToDecimal(Integer binaryNumber) { + + Integer result = 0; + Integer base = 1; + + while (binaryNumber > 0) { + + int lastDigit = binaryNumber % 10; + binaryNumber = binaryNumber / 10; + + result += lastDigit * base; + + base = base * 2; + } + return result; + } + + /** + * This method accepts two binary numbers and returns sum of input numbers. + * Example:- firstNum: 101, secondNum: 100, output: 1001 + * + * @param firstNum + * @param secondNum + * @return addition of input numbers + */ + public Integer addBinaryNumber(Integer firstNum, Integer secondNum) { + + StringBuilder output = new StringBuilder(); + + int carry = 0; + int temp; + + while (firstNum != 0 || secondNum != 0) { + + temp = (firstNum % 10 + secondNum % 10 + carry) % 2; + output.append(temp); + + carry = (firstNum % 10 + secondNum % 10 + carry) / 2; + + firstNum = firstNum / 10; + secondNum = secondNum / 10; + } + + if (carry != 0) { + output.append(carry); + } + + return Integer.valueOf(output.reverse() + .toString()); + } + + /** + * This method takes two binary number as input and subtract second number from the first number. + * example:- firstNum: 1000, secondNum: 11, output: 101 + * @param firstNum + * @param secondNum + * @return Result of subtraction of secondNum from first + */ + public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) { + + int onesComplement = Integer.valueOf(getOnesComplement(secondNum)); + + StringBuilder output = new StringBuilder(); + + int carry = 0; + int temp; + + while (firstNum != 0 || onesComplement != 0) { + + temp = (firstNum % 10 + onesComplement % 10 + carry) % 2; + output.append(temp); + + carry = (firstNum % 10 + onesComplement % 10 + carry) / 2; + + firstNum = firstNum / 10; + onesComplement = onesComplement / 10; + } + + String additionOfFirstNumAndOnesComplement = output.reverse() + .toString(); + + if (carry == 1) { + return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry); + } else { + return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement)); + } + + } + + public Integer getOnesComplement(Integer num) { + + StringBuilder onesComplement = new StringBuilder(); + + while (num > 0) { + int lastDigit = num % 10; + if (lastDigit == 0) { + onesComplement.append(1); + } else { + onesComplement.append(0); + } + num = num / 10; + } + + return Integer.valueOf(onesComplement.reverse() + .toString()); + } + +} diff --git a/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java new file mode 100644 index 0000000000..ca6022261d --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/binarynumbers/BinaryNumbersUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.binarynumbers; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class BinaryNumbersUnitTest { + + private BinaryNumbers binaryNumbers = new BinaryNumbers(); + + @Test + public void given_decimalNumber_then_returnBinaryNumber() { + assertEquals(Integer.valueOf(1000), binaryNumbers.convertDecimalToBinary(8)); + assertEquals(Integer.valueOf(10100), binaryNumbers.convertDecimalToBinary(20)); + } + + @Test + public void given_decimalNumber_then_convertToBinaryNumber() { + assertEquals("1000", Integer.toBinaryString(8)); + assertEquals("10100", Integer.toBinaryString(20)); + } + + @Test + public void given_binaryNumber_then_ConvertToDecimalNumber() { + assertEquals(8, Integer.parseInt("1000", 2)); + assertEquals(20, Integer.parseInt("10100", 2)); + } + + @Test + public void given_binaryNumber_then_returnDecimalNumber() { + assertEquals(Integer.valueOf(8), binaryNumbers.convertBinaryToDecimal(1000)); + assertEquals(Integer.valueOf(20), binaryNumbers.convertBinaryToDecimal(10100)); + } + + @Test + public void given_twoBinaryNumber_then_returnAddition() { + // adding 4 and 10 + assertEquals(Integer.valueOf(1110), binaryNumbers.addBinaryNumber(100, 1010)); + + // adding 26 and 14 + assertEquals(Integer.valueOf(101000), binaryNumbers.addBinaryNumber(11010, 1110)); + } + + @Test + public void given_twoBinaryNumber_then_returnSubtraction() { + // subtracting 16 from 25 + assertEquals(Integer.valueOf(1001), binaryNumbers.substractBinaryNumber(11001, 10000)); + + // subtracting 29 from 16, the output here is negative + assertEquals(Integer.valueOf(1101), binaryNumbers.substractBinaryNumber(10000, 11101)); + } + + @Test + public void given_binaryLiteral_thenReturnDecimalValue() { + + byte five = 0b101; + assertEquals((byte) 5, five); + + short three = 0b11; + assertEquals((short) 3, three); + + int nine = 0B1001; + assertEquals(9, nine); + + long twentyNine = 0B11101; + assertEquals(29, twentyNine); + + int minusThirtySeven = -0B100101; + assertEquals(-37, minusThirtySeven); + + } + +} From 970889ad14d80da42f3b7eff5c23f48fb17f3141 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Wed, 31 Jul 2019 12:04:14 +0300 Subject: [PATCH 345/352] minor cleanup work --- pom.xml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 5b5058763d..f66250a8fd 100644 --- a/pom.xml +++ b/pom.xml @@ -10,10 +10,6 @@ parent-modules pom - - quarkus - - @@ -1589,4 +1585,5 @@ 1.16.12 1.4.197 + From 704f68c8da890a1aa31c1b15b8d87c7539ec6ac6 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 31 Jul 2019 20:04:40 +0300 Subject: [PATCH 346/352] Delete SpringContextTest.java --- .../java/org/baeldung/SpringContextTest.java | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 spring-userservice/src/test/java/org/baeldung/SpringContextTest.java diff --git a/spring-userservice/src/test/java/org/baeldung/SpringContextTest.java b/spring-userservice/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 2853a955fa..0000000000 --- a/spring-userservice/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.baeldung.custom.config.MvcConfig; -import org.baeldung.custom.config.PersistenceDerbyJPAConfig; -import org.baeldung.custom.config.SecSecurityConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} From 4b6871b1fc6b6a1b2ffb8c4c3b68576e3181b713 Mon Sep 17 00:00:00 2001 From: vatsalgosar Date: Fri, 2 Aug 2019 00:12:03 +0530 Subject: [PATCH 347/352] BAEL-3118 (#7458) * BAEL-3118 - Increment Decrement Unary Operators * BAEL-3118 - Added UnitTests for Increment Decrement Unary Operators * BAEL-3118 --- ...crementDecrementUnaryOperatorUnitTest.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/incrementdecrementunaryoperator/IncrementDecrementUnaryOperatorUnitTest.java diff --git a/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/incrementdecrementunaryoperator/IncrementDecrementUnaryOperatorUnitTest.java b/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/incrementdecrementunaryoperator/IncrementDecrementUnaryOperatorUnitTest.java new file mode 100644 index 0000000000..ee17c1e8ea --- /dev/null +++ b/core-java-modules/core-java-lang-syntax/src/test/java/com/baeldung/incrementdecrementunaryoperator/IncrementDecrementUnaryOperatorUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.incrementdecrementunaryoperator; + +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class IncrementDecrementUnaryOperatorUnitTest { + + @Test + public void givenAnOperand_whenUsingPreIncrementUnaryOperator_thenOperandIsIncrementedByOne() { + int operand = 1; + ++operand; + assertThat(operand).isEqualTo(2); + } + + @Test + public void givenANumber_whenUsingPreIncrementUnaryOperatorInEvaluation_thenNumberIsIncrementedByOne() { + int operand = 1; + int number = ++operand; + assertThat(number).isEqualTo(2); + } + + @Test + public void givenAnOperand_whenUsingPreDecrementUnaryOperator_thenOperandIsDecrementedByOne() { + int operand = 1; + --operand; + assertThat(operand).isEqualTo(0); + } + + @Test + public void givenANumber_whenUsingPreDecrementUnaryOperatorInEvaluation_thenNumberIsDecrementedByOne() { + int operand = 1; + int number = --operand; + assertThat(number).isEqualTo(0); + } + + @Test + public void givenAnOperand_whenUsingPostIncrementUnaryOperator_thenOperandIsIncrementedByOne() { + int operand = 1; + operand++; + assertThat(operand).isEqualTo(2); + } + + @Test + public void givenANumber_whenUsingPostIncrementUnaryOperatorInEvaluation_thenNumberIsSameAsOldValue() { + int operand = 1; + int number = operand++; + assertThat(number).isEqualTo(1); + } + + @Test + public void givenAnOperand_whenUsingPostDecrementUnaryOperator_thenOperandIsDecrementedByOne() { + int operand = 1; + operand--; + assertThat(operand).isEqualTo(0); + } + + @Test + public void givenANumber_whenUsingPostDecrementUnaryOperatorInEvaluation_thenNumberIsSameAsOldValue() { + int operand = 1; + int number = operand--; + assertThat(number).isEqualTo(1); + } +} From ec46f6de26060e3e92eaed8a10f71cbb7a84935c Mon Sep 17 00:00:00 2001 From: Amit Pandey Date: Fri, 2 Aug 2019 10:14:32 +0530 Subject: [PATCH 348/352] [BAEL-12899] - Splitted the java-strings module (#7410) --- java-strings-2/README.MD | 15 +++ java-strings-2/pom.xml | 52 ++++++++- .../java/com/baeldung/string/MatchWords.java | 0 .../java/com/baeldung/string/Pangram.java | 0 .../string/padding/StringPaddingUtil.java | 0 .../password/RandomPasswordGenerator.java | 0 .../RemoveLeadingAndTrailingZeroes.java | 0 .../RemoveDuplicateFromString.java | 0 .../baeldung/ConvertStringToListUnitTest.java | 0 .../baeldung/StringConcatenationUnitTest.java | 0 .../FileToBase64StringConversionUnitTest.java | 0 .../ApacheCommonsEncodeDecodeUnitTest.java | 0 .../base64/Java8EncodeDecodeUnitTest.java | 0 .../base64/StringToByteArrayUnitTest.java | 0 .../baeldung/string/MatchWordsUnitTest.java | 0 .../com/baeldung/string/PangramUnitTest.java | 0 .../RemovingEmojiFromStringUnitTest.java | 0 .../StringFromPrimitiveArrayUnitTest.java | 0 .../DateToStringFormatterUnitTest.java | 0 .../StringFormatterExampleUnitTest.java | 0 .../string/interview/LocaleUnitTest.java | 0 .../interview/StringAnagramUnitTest.java | 0 .../interview/StringChangeCaseUnitTest.java | 0 .../StringCountOccurrencesUnitTest.java | 0 .../interview/StringFormatUnitTest.java | 0 .../interview/StringInternUnitTest.java | 0 .../interview/StringJoinerUnitTest.java | 0 .../interview/StringPalindromeUnitTest.java | 0 .../interview/StringReverseUnitTest.java | 0 .../string/interview/StringSplitUnitTest.java | 0 .../interview/StringToByteArrayUnitTest.java | 0 .../interview/StringToCharArrayUnitTest.java | 0 .../interview/StringToIntegerUnitTest.java | 0 .../padding/StringPaddingUtilUnitTest.java | 0 .../password/StringPasswordUnitTest.java | 0 ...emoveLeadingAndTrailingZeroesUnitTest.java | 0 .../RemoveDuplicateFromStringUnitTest.java | 0 .../src/test/resources/test_image.jpg | Bin java-strings-ops/README.md | 22 ++++ java-strings-ops/pom.xml | 99 ++++++++++++++++++ .../baeldung/datetime/UseLocalDateTime.java | 0 .../string/AppendCharAtPositionX.java | 0 .../java/com/baeldung/string/Palindrome.java | 0 .../com/baeldung/string/StringHelper.java | 0 .../baeldung/string/tostring/Customer.java | 0 .../tostring/CustomerArrayToString.java | 0 .../CustomerComplexObjectToString.java | 0 .../tostring/CustomerPrimitiveToString.java | 0 .../tostring/CustomerReflectionToString.java | 0 .../CustomerWrapperCollectionToString.java | 0 .../com/baeldung/string/tostring/Order.java | 0 .../src/main/resources/logback.xml | 13 +++ .../com/baeldung/CharToStringUnitTest.java | 0 .../com/baeldung/java/conversion/README.md | 0 .../conversion/StringConversionUnitTest.java | 0 .../CountCharsExampleUnitTest.java | 0 .../string/AppendCharAtPositionXUnitTest.java | 0 .../string/CharSequenceVsStringUnitTest.java | 0 .../baeldung/string/PalindromeUnitTest.java | 0 .../com/baeldung/string/SplitUnitTest.java | 0 .../string/StringBufferStringBuilder.java | 0 .../string/StringComparisonUnitTest.java | 0 .../baeldung/string/StringHelperUnitTest.java | 0 .../baeldung/string/SubstringUnitTest.java | 0 .../conversion/ByteArrayToStringUnitTest.java | 0 .../conversion/StringToByteArrayUnitTest.java | 0 .../CustomerArrayToStringUnitTest.java | 0 ...CustomerComplexObjectToStringUnitTest.java | 0 .../CustomerPrimitiveToStringUnitTest.java | 0 ...omerWrapperCollectionToStringUnitTest.java | 0 .../CoreJavaIsNumericUnitTest.java | 0 .../stringpool/StringPoolUnitTest.java | 0 .../src/test/resources/.gitignore | 13 +++ java-strings/README.md | 35 +------ java-strings/pom.xml | 27 ----- pom.xml | 2 + 76 files changed, 212 insertions(+), 66 deletions(-) rename {java-strings => java-strings-2}/src/main/java/com/baeldung/string/MatchWords.java (100%) rename {java-strings => java-strings-2}/src/main/java/com/baeldung/string/Pangram.java (100%) rename {java-strings => java-strings-2}/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java (100%) rename {java-strings => java-strings-2}/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java (100%) rename {java-strings => java-strings-2}/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java (100%) rename {java-strings => java-strings-2}/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/ConvertStringToListUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/StringConcatenationUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/MatchWordsUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/PangramUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java (100%) rename {java-strings => java-strings-2}/src/test/resources/test_image.jpg (100%) create mode 100644 java-strings-ops/README.md create mode 100644 java-strings-ops/pom.xml rename {java-strings => java-strings-ops}/src/main/java/com/baeldung/datetime/UseLocalDateTime.java (100%) rename {java-strings => java-strings-ops}/src/main/java/com/baeldung/string/AppendCharAtPositionX.java (100%) rename {java-strings => java-strings-ops}/src/main/java/com/baeldung/string/Palindrome.java (100%) rename {java-strings => java-strings-ops}/src/main/java/com/baeldung/string/StringHelper.java (100%) rename {java-strings => java-strings-ops}/src/main/java/com/baeldung/string/tostring/Customer.java (100%) rename {java-strings => java-strings-ops}/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java (100%) rename {java-strings => java-strings-ops}/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java (100%) rename {java-strings => java-strings-ops}/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java (100%) rename {java-strings => java-strings-ops}/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java (100%) rename {java-strings => java-strings-ops}/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java (100%) rename {java-strings => java-strings-ops}/src/main/java/com/baeldung/string/tostring/Order.java (100%) create mode 100644 java-strings-ops/src/main/resources/logback.xml rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/CharToStringUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/java/conversion/README.md (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/PalindromeUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/SplitUnitTest.java (100%) rename {java-strings/src/main => java-strings-ops/src/test}/java/com/baeldung/string/StringBufferStringBuilder.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/StringComparisonUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/StringHelperUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/SubstringUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java (100%) rename {java-strings => java-strings-ops}/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java (100%) create mode 100644 java-strings-ops/src/test/resources/.gitignore diff --git a/java-strings-2/README.MD b/java-strings-2/README.MD index c6d4f0222a..b4b16fbaef 100644 --- a/java-strings-2/README.MD +++ b/java-strings-2/README.MD @@ -3,5 +3,20 @@ - [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting) - [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) - [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) +- [Java – Generate Random String](http://www.baeldung.com/java-random-string) +- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string) +- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) +- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password) +- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) +- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) +- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) +- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) +- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list) +- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter) +- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) +- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) +- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) +- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) +- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) - [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) - [String Initialization in Java](https://www.baeldung.com/java-string-initialization) diff --git a/java-strings-2/pom.xml b/java-strings-2/pom.xml index 7342953d15..be47b1ec89 100755 --- a/java-strings-2/pom.xml +++ b/java-strings-2/pom.xml @@ -40,6 +40,16 @@ commons-lang3 ${commons-lang3.version} + + commons-io + commons-io + ${commons-io.version} + + + commons-codec + commons-codec + ${commons-codec.version} + junit junit @@ -52,32 +62,54 @@ ${org.hamcrest.version} test + + org.assertj + assertj-core + ${assertj.version} + test + + + + + org.passay + passay + ${passay.version} + org.apache.commons commons-text ${commons-text.version} + + com.vdurmont + emoji-java + ${emoji-java.version} + + + org.ahocorasick + ahocorasick + ${ahocorasick.version} + javax.validation validation-api - 2.0.0.Final + ${validation-api.version} org.hibernate.validator hibernate-validator - 6.0.2.Final + ${hibernate-validator.version} javax.el javax.el-api - 3.0.0 + ${javax.el-api.version} org.glassfish.web javax.el - 2.2.6 + ${javax.el.version} - @@ -105,9 +137,19 @@ 3.8.1 + 1.10 + 1.3.1 + + 3.6.1 + 4.0.0 + 0.4.0 61.1 28.0-jre 1.4 + 2.0.0.Final + 6.0.2.Final + 3.0.0 + 2.2.6 \ No newline at end of file diff --git a/java-strings/src/main/java/com/baeldung/string/MatchWords.java b/java-strings-2/src/main/java/com/baeldung/string/MatchWords.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/MatchWords.java rename to java-strings-2/src/main/java/com/baeldung/string/MatchWords.java diff --git a/java-strings/src/main/java/com/baeldung/string/Pangram.java b/java-strings-2/src/main/java/com/baeldung/string/Pangram.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/Pangram.java rename to java-strings-2/src/main/java/com/baeldung/string/Pangram.java diff --git a/java-strings/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java b/java-strings-2/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java rename to java-strings-2/src/main/java/com/baeldung/string/padding/StringPaddingUtil.java diff --git a/java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java b/java-strings-2/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java rename to java-strings-2/src/main/java/com/baeldung/string/password/RandomPasswordGenerator.java diff --git a/java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java b/java-strings-2/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java rename to java-strings-2/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java diff --git a/java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java b/java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java rename to java-strings-2/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java diff --git a/java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java b/java-strings-2/src/test/java/com/baeldung/ConvertStringToListUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/ConvertStringToListUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/StringConcatenationUnitTest.java b/java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/StringConcatenationUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/StringConcatenationUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java b/java-strings-2/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/MatchWordsUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/MatchWordsUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/MatchWordsUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/PangramUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/PangramUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/PangramUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/RemovingEmojiFromStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/formatter/DateToStringFormatterUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/LocaleUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringAnagramUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringChangeCaseUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringCountOccurrencesUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringFormatUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringInternUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringJoinerUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringPalindromeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringReverseUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringSplitUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringToByteArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringToCharArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/interview/StringToIntegerUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/padding/StringPaddingUtilUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/password/StringPasswordUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java b/java-strings-2/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java diff --git a/java-strings/src/test/resources/test_image.jpg b/java-strings-2/src/test/resources/test_image.jpg similarity index 100% rename from java-strings/src/test/resources/test_image.jpg rename to java-strings-2/src/test/resources/test_image.jpg diff --git a/java-strings-ops/README.md b/java-strings-ops/README.md new file mode 100644 index 0000000000..d909f171a7 --- /dev/null +++ b/java-strings-ops/README.md @@ -0,0 +1,22 @@ +========= + +## Java Strings Cookbooks and Examples + +### Relevant Articles: +- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) +- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) +- [Java String Conversions](https://www.baeldung.com/java-string-conversions) +- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome) +- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings) +- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) +- [Get Substring from String in Java](https://www.baeldung.com/java-substring) +- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string) +- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) +- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars) +- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) +- [Split a String in Java](http://www.baeldung.com/java-split-string) +- [Common String Operations in Java](https://www.baeldung.com/java-string-operations) +- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) +- [Java toString() Method](https://www.baeldung.com/java-tostring) +- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string) +- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) \ No newline at end of file diff --git a/java-strings-ops/pom.xml b/java-strings-ops/pom.xml new file mode 100644 index 0000000000..b6a7ea2728 --- /dev/null +++ b/java-strings-ops/pom.xml @@ -0,0 +1,99 @@ + + 4.0.0 + com.baeldung + java-strings-ops + 0.1.0-SNAPSHOT + jar + java-strings-ops + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + com.google.guava + guava + ${guava.version} + + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter-api.version} + test + + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + + + java-strings-ops + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + -parameters + + + + + + + + 3.8.1 + + 3.6.1 + 27.0.1-jre + 5.3.1 + + + diff --git a/java-strings/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/java-strings-ops/src/main/java/com/baeldung/datetime/UseLocalDateTime.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/datetime/UseLocalDateTime.java rename to java-strings-ops/src/main/java/com/baeldung/datetime/UseLocalDateTime.java diff --git a/java-strings/src/main/java/com/baeldung/string/AppendCharAtPositionX.java b/java-strings-ops/src/main/java/com/baeldung/string/AppendCharAtPositionX.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/AppendCharAtPositionX.java rename to java-strings-ops/src/main/java/com/baeldung/string/AppendCharAtPositionX.java diff --git a/java-strings/src/main/java/com/baeldung/string/Palindrome.java b/java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/Palindrome.java rename to java-strings-ops/src/main/java/com/baeldung/string/Palindrome.java diff --git a/java-strings/src/main/java/com/baeldung/string/StringHelper.java b/java-strings-ops/src/main/java/com/baeldung/string/StringHelper.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/StringHelper.java rename to java-strings-ops/src/main/java/com/baeldung/string/StringHelper.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/Customer.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/Customer.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/Customer.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/Customer.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerArrayToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerComplexObjectToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerPrimitiveToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerReflectionToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/CustomerWrapperCollectionToString.java diff --git a/java-strings/src/main/java/com/baeldung/string/tostring/Order.java b/java-strings-ops/src/main/java/com/baeldung/string/tostring/Order.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/tostring/Order.java rename to java-strings-ops/src/main/java/com/baeldung/string/tostring/Order.java diff --git a/java-strings-ops/src/main/resources/logback.xml b/java-strings-ops/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-strings-ops/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-strings/src/test/java/com/baeldung/CharToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/CharToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/CharToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/CharToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java/conversion/README.md b/java-strings-ops/src/test/java/com/baeldung/java/conversion/README.md similarity index 100% rename from java-strings/src/test/java/com/baeldung/java/conversion/README.md rename to java-strings-ops/src/test/java/com/baeldung/java/conversion/README.md diff --git a/java-strings/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/java/conversion/StringConversionUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/java/countingChars/CountCharsExampleUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/CharSequenceVsStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/PalindromeUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/PalindromeUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/PalindromeUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/SplitUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/SplitUnitTest.java diff --git a/java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java b/java-strings-ops/src/test/java/com/baeldung/string/StringBufferStringBuilder.java similarity index 100% rename from java-strings/src/main/java/com/baeldung/string/StringBufferStringBuilder.java rename to java-strings-ops/src/test/java/com/baeldung/string/StringBufferStringBuilder.java diff --git a/java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/StringComparisonUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/StringComparisonUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/StringComparisonUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/StringHelperUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/StringHelperUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/StringHelperUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/StringHelperUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/SubstringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/SubstringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/SubstringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerArrayToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerComplexObjectToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerPrimitiveToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/string/tostring/CustomerWrapperCollectionToStringUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/stringisnumeric/CoreJavaIsNumericUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java b/java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java similarity index 100% rename from java-strings/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java rename to java-strings-ops/src/test/java/com/baeldung/stringpool/StringPoolUnitTest.java diff --git a/java-strings-ops/src/test/resources/.gitignore b/java-strings-ops/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/java-strings-ops/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/java-strings/README.md b/java-strings/README.md index b342f53918..ef536b4099 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -6,51 +6,18 @@ - [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings) - [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream) - [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner) -- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string) -- [Java – Generate Random String](http://www.baeldung.com/java-random-string) -- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) -- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) -- [Java String Conversions](https://www.baeldung.com/java-string-conversions) - [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum) - [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer) -- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars) -- [Split a String in Java](http://www.baeldung.com/java-split-string) -- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string) -- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string) -- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) -- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) -- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome) -- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings) -- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) - [Use char[] Array Over a String for Manipulating Passwords in Java?](http://www.baeldung.com/java-storing-passwords) - [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case) - [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string) - [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex) - [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string) -- [Get Substring from String in Java](https://www.baeldung.com/java-substring) - [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string) - [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) -- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) - [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) - [String Performance Hints](https://www.baeldung.com/java-string-performance) - [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences) -- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) -- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) -- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password) -- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char) -- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array) -- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) -- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string) - [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) - [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part) -- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index) -- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list) -- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter) -- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) -- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters) -- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation) -- [Java toString() Method](https://www.baeldung.com/java-tostring) -- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) -- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram) -- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words) -- [Common String Operations in Java](https://www.baeldung.com/java-string-operations) +- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index) \ No newline at end of file diff --git a/java-strings/pom.xml b/java-strings/pom.xml index 7f66b95355..42a57bfb42 100755 --- a/java-strings/pom.xml +++ b/java-strings/pom.xml @@ -62,12 +62,6 @@ guava ${guava.version} - - - com.vdurmont - emoji-java - ${emoji-java.version} - org.junit.jupiter @@ -83,24 +77,6 @@ test - - - org.passay - passay - ${passay.version} - - - org.apache.commons - commons-text - ${commons-text.version} - - - - org.ahocorasick - ahocorasick - ${ahocorasick.version} - - @@ -134,11 +110,8 @@ 3.6.1 61.1 27.0.1-jre - 4.0.0 5.3.1 - 1.3.1 1.4 - 0.4.0 diff --git a/pom.xml b/pom.xml index 9b47ffe3a6..352da33fee 100644 --- a/pom.xml +++ b/pom.xml @@ -469,6 +469,7 @@ java-strings java-strings-2 + java-strings-ops java-vavr-stream java-websocket javafx @@ -1163,6 +1164,7 @@ java-strings java-strings-2 + java-strings-ops java-vavr-stream java-websocket javafx From 21eb2764288b739ae646ad634202f5b6460bb899 Mon Sep 17 00:00:00 2001 From: Rodrigo Graciano Date: Fri, 2 Aug 2019 02:10:36 -0400 Subject: [PATCH 349/352] Fix quarkus version on pom.xml (#7466) --- quarkus/pom.xml | 2 +- quarkus/src/main/java/com/baeldung/quarkus/HelloService.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/quarkus/pom.xml b/quarkus/pom.xml index d8f274df6d..ceb2e2c0d4 100644 --- a/quarkus/pom.xml +++ b/quarkus/pom.xml @@ -7,7 +7,7 @@ 1.0-SNAPSHOT 2.22.0 - 0.13.1 + 0.15.0 1.8 UTF-8 1.8 diff --git a/quarkus/src/main/java/com/baeldung/quarkus/HelloService.java b/quarkus/src/main/java/com/baeldung/quarkus/HelloService.java index 4b19de1b63..4c505fbabe 100644 --- a/quarkus/src/main/java/com/baeldung/quarkus/HelloService.java +++ b/quarkus/src/main/java/com/baeldung/quarkus/HelloService.java @@ -8,7 +8,7 @@ import javax.enterprise.context.ApplicationScoped; public class HelloService { @ConfigProperty(name = "greeting") - private String greeting; + String greeting; public String politeHello(String name){ return greeting + " " + name; From 5fabe70b8acac154b1e820ac8ebe05b7c3f489b3 Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 2 Aug 2019 14:35:36 +0300 Subject: [PATCH 350/352] move upload files code to new package --- .../baeldung/mongodb/{ => file}/daos/PhotoRepository.java | 4 ++-- .../java/com/baeldung/mongodb/{ => file}/models/Photo.java | 2 +- .../java/com/baeldung/mongodb/{ => file}/models/Video.java | 2 +- .../baeldung/mongodb/{ => file}/services/PhotoService.java | 6 +++--- .../baeldung/mongodb/{ => file}/services/VideoService.java | 4 ++-- .../baeldung/mongodb/{ => file}/web/PhotoController.java | 6 +++--- .../baeldung/mongodb/{ => file}/web/VideoController.java | 6 +++--- 7 files changed, 15 insertions(+), 15 deletions(-) rename persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/{ => file}/daos/PhotoRepository.java (62%) rename persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/{ => file}/models/Photo.java (95%) rename persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/{ => file}/models/Video.java (93%) rename persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/{ => file}/services/PhotoService.java (83%) rename persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/{ => file}/services/VideoService.java (94%) rename persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/{ => file}/web/PhotoController.java (90%) rename persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/{ => file}/web/VideoController.java (92%) diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/daos/PhotoRepository.java similarity index 62% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java rename to persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/daos/PhotoRepository.java index d38e11c055..dc18df7b0a 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/daos/PhotoRepository.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/daos/PhotoRepository.java @@ -1,8 +1,8 @@ -package com.baeldung.mongodb.daos; +package com.baeldung.mongodb.file.daos; import org.springframework.data.mongodb.repository.MongoRepository; -import com.baeldung.mongodb.models.Photo; +import com.baeldung.mongodb.file.models.Photo; public interface PhotoRepository extends MongoRepository { diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/models/Photo.java similarity index 95% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java rename to persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/models/Photo.java index 13f1a3cd19..afb79b4dbb 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Photo.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/models/Photo.java @@ -1,4 +1,4 @@ -package com.baeldung.mongodb.models; +package com.baeldung.mongodb.file.models; import org.bson.types.Binary; import org.springframework.data.annotation.Id; diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/models/Video.java similarity index 93% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java rename to persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/models/Video.java index 617f0cdbfd..9e60fd1746 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/models/Video.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/models/Video.java @@ -1,4 +1,4 @@ -package com.baeldung.mongodb.models; +package com.baeldung.mongodb.file.models; import java.io.InputStream; diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/services/PhotoService.java similarity index 83% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java rename to persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/services/PhotoService.java index d8d7541c76..8d0313b280 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/PhotoService.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/services/PhotoService.java @@ -1,4 +1,4 @@ -package com.baeldung.mongodb.services; +package com.baeldung.mongodb.file.services; import java.io.IOException; @@ -8,8 +8,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; -import com.baeldung.mongodb.daos.PhotoRepository; -import com.baeldung.mongodb.models.Photo; +import com.baeldung.mongodb.file.daos.PhotoRepository; +import com.baeldung.mongodb.file.models.Photo; @Service public class PhotoService { diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/services/VideoService.java similarity index 94% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java rename to persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/services/VideoService.java index ade1f7c73a..e4d3237bb1 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/services/VideoService.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/services/VideoService.java @@ -1,4 +1,4 @@ -package com.baeldung.mongodb.services; +package com.baeldung.mongodb.file.services; import java.io.IOException; @@ -11,7 +11,7 @@ import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; -import com.baeldung.mongodb.models.Video; +import com.baeldung.mongodb.file.models.Video; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.client.gridfs.model.GridFSFile; diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/web/PhotoController.java similarity index 90% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java rename to persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/web/PhotoController.java index 4d5746f0d8..55de8ffd1d 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/PhotoController.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/web/PhotoController.java @@ -1,4 +1,4 @@ -package com.baeldung.mongodb.web; +package com.baeldung.mongodb.file.web; import java.io.IOException; import java.util.Base64; @@ -12,8 +12,8 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; -import com.baeldung.mongodb.models.Photo; -import com.baeldung.mongodb.services.PhotoService; +import com.baeldung.mongodb.file.models.Photo; +import com.baeldung.mongodb.file.services.PhotoService; @Controller public class PhotoController { diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/web/VideoController.java similarity index 92% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java rename to persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/web/VideoController.java index 313ce9e650..cbe8c5d7da 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/web/VideoController.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/mongodb/file/web/VideoController.java @@ -1,4 +1,4 @@ -package com.baeldung.mongodb.web; +package com.baeldung.mongodb.file.web; import java.io.IOException; @@ -14,8 +14,8 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; -import com.baeldung.mongodb.models.Video; -import com.baeldung.mongodb.services.VideoService; +import com.baeldung.mongodb.file.models.Video; +import com.baeldung.mongodb.file.services.VideoService; @Controller public class VideoController { From b96425265b7cb59946ecb2bbf871741675e9d2d0 Mon Sep 17 00:00:00 2001 From: DOHA Date: Fri, 2 Aug 2019 14:35:52 +0300 Subject: [PATCH 351/352] minor fix --- .../main/java/com/baeldung/graph/Graph.java | 20 ++++++++++--------- .../java/com/baeldung/tree/BinaryTree.java | 15 ++++++++------ .../com/baeldung/graph/GraphUnitTest.java | 5 ++++- 3 files changed, 24 insertions(+), 16 deletions(-) diff --git a/data-structures/src/main/java/com/baeldung/graph/Graph.java b/data-structures/src/main/java/com/baeldung/graph/Graph.java index 16b7e04297..40df2c713a 100644 --- a/data-structures/src/main/java/com/baeldung/graph/Graph.java +++ b/data-structures/src/main/java/com/baeldung/graph/Graph.java @@ -2,6 +2,7 @@ package com.baeldung.graph; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Stack; @@ -29,7 +30,7 @@ public class Graph { while (!stack.isEmpty()) { int current = stack.pop(); isVisited[current] = true; - System.out.print(" " + current); + visit(current); for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) stack.push(dest); @@ -44,29 +45,30 @@ public class Graph { private void dfsRecursive(int current, boolean[] isVisited) { isVisited[current] = true; - System.out.print(" " + current); + visit(current); for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) dfsRecursive(dest, isVisited); } } - public void topologicalSort(int start) { - Stack result = new Stack(); + public List topologicalSort(int start) { + LinkedList result = new LinkedList(); boolean[] isVisited = new boolean[adjVertices.size()]; topologicalSortRecursive(start, isVisited, result); - while (!result.isEmpty()) { - System.out.print(" " + result.pop()); - } + return result; } - private void topologicalSortRecursive(int current, boolean[] isVisited, Stack result) { + private void topologicalSortRecursive(int current, boolean[] isVisited, LinkedList result) { isVisited[current] = true; for (int dest : adjVertices.get(current)) { if (!isVisited[dest]) topologicalSortRecursive(dest, isVisited, result); } - result.push(current); + result.addFirst(current); } + private void visit(int value) { + System.out.print(" " + value); + } } diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java index ff73ee8e54..bb62714006 100644 --- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java @@ -103,14 +103,14 @@ public class BinaryTree { public void traverseInOrder(Node node) { if (node != null) { traverseInOrder(node.left); - System.out.print(" " + node.value); + visit(node.value); traverseInOrder(node.right); } } public void traversePreOrder(Node node) { if (node != null) { - System.out.print(" " + node.value); + visit(node.value); traversePreOrder(node.left); traversePreOrder(node.right); } @@ -120,7 +120,7 @@ public class BinaryTree { if (node != null) { traversePostOrder(node.left); traversePostOrder(node.right); - System.out.print(" " + node.value); + visit(node.value); } } @@ -159,7 +159,7 @@ public class BinaryTree { stack.push(current); } current = stack.pop(); - System.out.print(" " + current.value); + visit(current.value); if(current.right != null) { current = current.right; stack.push(current); @@ -173,7 +173,7 @@ public class BinaryTree { stack.push(root); while(! stack.isEmpty()) { current = stack.pop(); - System.out.print(" " + current.value); + visit(current.value); if(current.right != null) stack.push(current.right); @@ -196,7 +196,7 @@ public class BinaryTree { if (!hasChild || isPrevLastChild) { current = stack.pop(); - System.out.print(" " + current.value); + visit(current.value); prev = current; } else { if (current.right != null) { @@ -209,6 +209,9 @@ public class BinaryTree { } } + private void visit(int value) { + System.out.print(" " + value); + } class Node { int value; diff --git a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java index 249cb6e093..09b92115d2 100644 --- a/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java +++ b/data-structures/src/test/java/com/baeldung/graph/GraphUnitTest.java @@ -1,5 +1,7 @@ package com.baeldung.graph; +import java.util.List; + import org.junit.Test; public class GraphUnitTest { @@ -15,7 +17,8 @@ public class GraphUnitTest { @Test public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() { Graph graph = createDirectedGraph(); - graph.topologicalSort(0); + List list = graph.topologicalSort(0); + System.out.println(list); } private Graph createDirectedGraph() { From 95c467aa1259b8ef706f1cabc3a782d7dfd984f1 Mon Sep 17 00:00:00 2001 From: eric-martin Date: Fri, 2 Aug 2019 21:38:25 -0500 Subject: [PATCH 352/352] Remove extra .gitignore files --- .../core-java-networking-2/.gitignore | 25 ------------------ java-numbers-2/.gitignore | 26 ------------------- 2 files changed, 51 deletions(-) delete mode 100644 core-java-modules/core-java-networking-2/.gitignore delete mode 100644 java-numbers-2/.gitignore diff --git a/core-java-modules/core-java-networking-2/.gitignore b/core-java-modules/core-java-networking-2/.gitignore deleted file mode 100644 index 374c8bf907..0000000000 --- a/core-java-modules/core-java-networking-2/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -*.class - -0.* - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* -.resourceCache - -# Packaged files # -*.jar -*.war -*.ear - -# Files generated by integration tests -backup-pom.xml -/bin/ -/temp - -#IntelliJ specific -.idea/ -*.iml \ No newline at end of file diff --git a/java-numbers-2/.gitignore b/java-numbers-2/.gitignore deleted file mode 100644 index 3de4cc647e..0000000000 --- a/java-numbers-2/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -*.class - -0.* - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* -.resourceCache - -# Packaged files # -*.jar -*.war -*.ear - -# Files generated by integration tests -*.txt -backup-pom.xml -/bin/ -/temp - -#IntelliJ specific -.idea/ -*.iml \ No newline at end of file