From ace948a705fc62c23b2d81e6f89aecbd9c340517 Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Sun, 1 Jul 2018 17:25:39 +0800 Subject: [PATCH 01/82] BAEL-1846: Java Image to Base64 String --- .../FileToBase64StringConversion.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversion.java diff --git a/core-java-8/src/main/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversion.java b/core-java-8/src/main/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversion.java new file mode 100644 index 0000000000..aa3bc9adee --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversion.java @@ -0,0 +1,32 @@ +package com.baeldung.fileToBase64StringConversion; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Base64; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; + +public class FileToBase64StringConversion { + public static void main(String[] args) throws FileNotFoundException, IOException { + //read file path from first argument + String filePath = args[0]; + + byte[] fileContent = FileUtils.readFileToByteArray(new File(filePath)); + String encodedString = Base64.getEncoder().encodeToString(fileContent); + + //print encoded base64 String + System.out.println(encodedString); + + //construct output file name + String extension = FilenameUtils.getExtension(filePath); + String baseFileName = FilenameUtils.getBaseName(filePath); + String directory = new File(filePath).getParentFile().getAbsolutePath(); + String outputFileName = directory+File.separator+baseFileName+"_copy."+extension; + + //decode the string and write to file + byte[] decodedBytes = Base64.getDecoder().decode(encodedString); + FileUtils.writeByteArrayToFile(new File(outputFileName), decodedBytes); + } +} From 7de2556d6b35381b087744e849e8e455038b0237 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 3 Jul 2018 17:33:01 +0800 Subject: [PATCH 02/82] Move from using main method to Junit test --- .../FileToBase64StringConversion.java | 32 ----------- .../FileToBase64StringConversionTest.java | 53 +++++++++++++++++++ 2 files changed, 53 insertions(+), 32 deletions(-) delete mode 100644 core-java-8/src/main/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversion.java create mode 100644 core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionTest.java diff --git a/core-java-8/src/main/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversion.java b/core-java-8/src/main/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversion.java deleted file mode 100644 index aa3bc9adee..0000000000 --- a/core-java-8/src/main/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversion.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.fileToBase64StringConversion; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Base64; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.FilenameUtils; - -public class FileToBase64StringConversion { - public static void main(String[] args) throws FileNotFoundException, IOException { - //read file path from first argument - String filePath = args[0]; - - byte[] fileContent = FileUtils.readFileToByteArray(new File(filePath)); - String encodedString = Base64.getEncoder().encodeToString(fileContent); - - //print encoded base64 String - System.out.println(encodedString); - - //construct output file name - String extension = FilenameUtils.getExtension(filePath); - String baseFileName = FilenameUtils.getBaseName(filePath); - String directory = new File(filePath).getParentFile().getAbsolutePath(); - String outputFileName = directory+File.separator+baseFileName+"_copy."+extension; - - //decode the string and write to file - byte[] decodedBytes = Base64.getDecoder().decode(encodedString); - FileUtils.writeByteArrayToFile(new File(outputFileName), decodedBytes); - } -} diff --git a/core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionTest.java b/core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionTest.java new file mode 100644 index 0000000000..4e023fbe64 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionTest.java @@ -0,0 +1,53 @@ +package com.baeldung.fileToBase64StringConversion; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collection; + +import org.apache.commons.io.FileUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class FileToBase64StringConversionTest { + + private String inputFilePath; + private String outputFilePath; + + public FileToBase64StringConversionTest(String inputFilePath, String outputFilePath) { + this.inputFilePath = inputFilePath; + this.outputFilePath = outputFilePath; + } + + @Parameterized.Parameters + public static Collection parameters() { + return Arrays.asList(new String[][] { { "", "" } }); + } + + @Test + public void fileToBase64StringConversion() throws FileNotFoundException, IOException { + File outputFile = new File(outputFilePath); + File inputFile = new File(inputFilePath); + + if (!inputFile.exists()) + return; + + byte[] fileContent = FileUtils.readFileToByteArray(inputFile); + String encodedString = Base64.getEncoder().encodeToString(fileContent); + + // print encoded base64 String + System.out.println(encodedString); + + // decode the string and write to file + byte[] decodedBytes = Base64.getDecoder().decode(encodedString); + FileUtils.writeByteArrayToFile(outputFile, decodedBytes); + + assertTrue(outputFile.length() == fileContent.length); + } +} From 06f9a5f445d2235c4ebeaeccc9dfd972b7abf445 Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Tue, 3 Jul 2018 23:38:07 +0800 Subject: [PATCH 03/82] Update to use environment variables for testing --- ...FileToBase64StringConversionUnitTest.java} | 32 ++++++++----------- 1 file changed, 14 insertions(+), 18 deletions(-) rename core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/{FileToBase64StringConversionTest.java => FileToBase64StringConversionUnitTest.java} (62%) diff --git a/core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionTest.java b/core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java similarity index 62% rename from core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionTest.java rename to core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java index 4e023fbe64..1842554534 100644 --- a/core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionTest.java +++ b/core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java @@ -5,33 +5,29 @@ import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; -import java.util.Arrays; import java.util.Base64; -import java.util.Collection; import org.apache.commons.io.FileUtils; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -@RunWith(Parameterized.class) -public class FileToBase64StringConversionTest { +public class FileToBase64StringConversionUnitTest { - private String inputFilePath; - private String outputFilePath; - - public FileToBase64StringConversionTest(String inputFilePath, String outputFilePath) { - this.inputFilePath = inputFilePath; - this.outputFilePath = outputFilePath; - } - - @Parameterized.Parameters - public static Collection parameters() { - return Arrays.asList(new String[][] { { "", "" } }); - } + private String inputFilePath = ""; + private String outputFilePath = ""; @Test + // file paths are from environment arguments: + // mvn test + // -Dtest=com.baeldung.fileToBase64StringConversion.FileToBase64StringConversionUnitTest + // -DinputFilePath="abc.png" -DoutFilePath="abc.png" + public void fileToBase64StringConversion() throws FileNotFoundException, IOException { + inputFilePath = System.getProperty("inputFilePath"); + outputFilePath = System.getProperty("outputFilePath"); + + if (inputFilePath == null || outputFilePath == null) + return; + File outputFile = new File(outputFilePath); File inputFile = new File(inputFilePath); From f325351275eee451ec78c1a5cbfe79e8268f0b24 Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Thu, 5 Jul 2018 21:03:43 +0800 Subject: [PATCH 04/82] reformat and add test file --- .../FileToBase64StringConversionUnitTest.java | 54 ++++++++---------- core-java-8/src/test/resources/test_image.jpg | Bin 0 -> 2865 bytes 2 files changed, 24 insertions(+), 30 deletions(-) create mode 100644 core-java-8/src/test/resources/test_image.jpg diff --git a/core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java b/core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java index 1842554534..eef21a98c9 100644 --- a/core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/fileToBase64StringConversion/FileToBase64StringConversionUnitTest.java @@ -3,7 +3,6 @@ package com.baeldung.fileToBase64StringConversion; import static org.junit.Assert.assertTrue; import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.Base64; @@ -12,38 +11,33 @@ import org.junit.Test; public class FileToBase64StringConversionUnitTest { - private String inputFilePath = ""; - private String outputFilePath = ""; + private String inputFilePath = "test_image.jpg"; + private String outputFilePath = "test_image_copy.jpg"; - @Test - // file paths are from environment arguments: - // mvn test - // -Dtest=com.baeldung.fileToBase64StringConversion.FileToBase64StringConversionUnitTest - // -DinputFilePath="abc.png" -DoutFilePath="abc.png" + @Test + public void fileToBase64StringConversion() throws IOException { + //load file from /src/test/resources + ClassLoader classLoader = getClass().getClassLoader(); + File inputFile = new File(classLoader + .getResource(inputFilePath) + .getFile()); - public void fileToBase64StringConversion() throws FileNotFoundException, IOException { - inputFilePath = System.getProperty("inputFilePath"); - outputFilePath = System.getProperty("outputFilePath"); + byte[] fileContent = FileUtils.readFileToByteArray(inputFile); + String encodedString = Base64 + .getEncoder() + .encodeToString(fileContent); - if (inputFilePath == null || outputFilePath == null) - return; + //create output file + File outputFile = new File(inputFile + .getParentFile() + .getAbsolutePath() + File.pathSeparator + outputFilePath); - File outputFile = new File(outputFilePath); - File inputFile = new File(inputFilePath); + // decode the string and write to file + byte[] decodedBytes = Base64 + .getDecoder() + .decode(encodedString); + FileUtils.writeByteArrayToFile(outputFile, decodedBytes); - if (!inputFile.exists()) - return; - - byte[] fileContent = FileUtils.readFileToByteArray(inputFile); - String encodedString = Base64.getEncoder().encodeToString(fileContent); - - // print encoded base64 String - System.out.println(encodedString); - - // decode the string and write to file - byte[] decodedBytes = Base64.getDecoder().decode(encodedString); - FileUtils.writeByteArrayToFile(outputFile, decodedBytes); - - assertTrue(outputFile.length() == fileContent.length); - } + assertTrue(FileUtils.contentEquals(inputFile, outputFile)); + } } diff --git a/core-java-8/src/test/resources/test_image.jpg b/core-java-8/src/test/resources/test_image.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d0db1627c9b8a4db0fb023a7229e64b282b9a70a GIT binary patch literal 2865 zcmbVO3v5$m6h8OW4u%bbvBAJ`83QI^OUEX362SGbtpi5sHW0D|y6$$ptZU1?w;K>N zFj0_@@bZCVi98hzi2(%xH8Mm{g8_uW251BknSudP#0Ol@fBPIkQ2(a?{q8y6fBy5G zdwTz>9qKpGyS&6+0u%*Mh96Kbz+&5c(E~7L3XBARB;cq%z#yXV15^fZ8U`q*2F9?H z%877jfMp`E5zZ{Ul7W%Q>d2MeNXHnd8<{vJRP`E|9NvHukiCH*Uyx@6li5CnB@uCG zc$fxzpL%p<=PKC6b}jC){_1V>GwMbC6}!bU+u@vAVxMf&MCm(R!Jv=k0UG^^pOvl0gwzCknD2H!D5GFGKopJTI_Dqt>%$m*kXjqY%Qa4w(}J8<#0Iz5Rfl*7 z;!(8;_WA@I&H))1r&RC@lIZ41EgVw7Bl-l*5uP66PGCL=Hu^%SSsR0K?j<)=PQq&r zYF}FCvJ#w!c!%3%t3;fQ_-vCny&{6|1{Jdt@o)e-E7VY3j2L^7F7rqw)rc_;EqOy_ zQM_THw`vC3)6jmblLh>Z`qjO#54#XLVFABa=!pFUszk-S*k^`IR z_f?R6aWB>?$eLb^!)7Ypsxq|WzN}A?sv>LI)gH0L9^vouN@c`O)}9Uev>wIWI9duh ziFVwJ%X3M#Qp6aOa|r%wQcr@LU^?Xj0Rm8qvm5+y2Y7HoDVXsZ1PMJJ5W$BQ0lflR z1iXuKa*mTy&7T|XrJDDBNn%E-X*@^6v>;%?|)*^OXEVcvJL=};Ix^S0poO!sT zpz)@o_BPb0fD7jf$OwQOi_onqt2075aZighTXY{=bv>b0BCc$RF>Y>=P2a-AIE0QP>u)>DL0>S);0dZdTPhTQL54fCE1D0Hh>ADx@-07SJga zlR~M70FN4qqqGqT3>3|8G}OGat)KJ6_3VOLsijBHwDkT1GKLKwk@MKd!pFyqH5EN!vD!*X%k1Tq zRn^mHpgeb-;HmeDb7dve)I5K|!e^I0_x!TuFRWO*?!}j0er5fu8#Zs*y6yEhw!it- zu6N$uz308X`}QCF_|PYZk9_*s=U<*Y)qeU+N9WlK7r(vq-R1AEbp3GS=bOL$dh55_ zzyCpWQNV;{;T%?WkFFHdMYAl!>WMCjZYIK0SZ+wZu21nay=z|ItkFx7Qq5~N?QH8Y zw7_}2U#)baXIggQg<&^{G)>vR6V~#-l*NR_b)Cb*V30P9g9aI`Mx)VMW5rRU)R3X9 zRJ5@&GPY~u5E`e1{td~?vHAc2 literal 0 HcmV?d00001 From e92843493f1b8d2ff34a4f377e56f6472e5ff47b Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Mon, 6 Aug 2018 11:33:13 +0800 Subject: [PATCH 05/82] spring boot jsp security taglibs --- spring-boot-security-taglibs/.gitignore | 13 +++ spring-boot-security-taglibs/README.md | 19 +++++ spring-boot-security-taglibs/pom.xml | 84 +++++++++++++++++++ .../org/baeldung/security/Application.java | 23 +++++ .../org/baeldung/security/HomeController.java | 18 ++++ .../org/baeldung/security/SecurityConfig.java | 70 ++++++++++++++++ .../src/main/resources/application.properties | 8 ++ .../src/main/webapp/WEB-INF/views/home.jsp | 20 +++++ .../baeldung/security/HomeControllerTest.java | 27 ++++++ 9 files changed, 282 insertions(+) create mode 100644 spring-boot-security-taglibs/.gitignore create mode 100644 spring-boot-security-taglibs/README.md create mode 100644 spring-boot-security-taglibs/pom.xml create mode 100644 spring-boot-security-taglibs/src/main/java/org/baeldung/security/Application.java create mode 100644 spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java create mode 100644 spring-boot-security-taglibs/src/main/java/org/baeldung/security/SecurityConfig.java create mode 100644 spring-boot-security-taglibs/src/main/resources/application.properties create mode 100644 spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp create mode 100644 spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java diff --git a/spring-boot-security-taglibs/.gitignore b/spring-boot-security-taglibs/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/spring-boot-security-taglibs/.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-boot-security-taglibs/README.md b/spring-boot-security-taglibs/README.md new file mode 100644 index 0000000000..f7eb314869 --- /dev/null +++ b/spring-boot-security-taglibs/README.md @@ -0,0 +1,19 @@ +========= + +## Spring Security Login Example Project + +###The Course +The "Learn Spring Security" Classes: http://github.learnspringsecurity.com + +### Relevant Articles: +- [Spring Security Form Login](http://www.baeldung.com/spring-security-login) +- [Spring Security Logout](http://www.baeldung.com/spring-security-logout) +- [Spring Security Expressions – hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) +- [Spring HTTP/HTTPS Channel Security](http://www.baeldung.com/spring-channel-security-https) +- [Spring Security - Customize the 403 Forbidden/Access Denied Page](http://www.baeldung.com/spring-security-custom-access-denied-page) +- [Spring Security – Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login) + +### Build the Project +``` +mvn clean install +``` diff --git a/spring-boot-security-taglibs/pom.xml b/spring-boot-security-taglibs/pom.xml new file mode 100644 index 0000000000..bd04ec3c0b --- /dev/null +++ b/spring-boot-security-taglibs/pom.xml @@ -0,0 +1,84 @@ + + 4.0.0 + + spring-boot-security-taglibs + jar + spring-boot-security-taglibs + spring 5 security sample project + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + org.springframework.boot + spring-boot-starter-security + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.security + spring-security-taglibs + + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + javax.servlet + jstl + + + + net.sourceforge.htmlunit + htmlunit + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + spring-5-security-taglibs + + + src/main/resources + true + + + + + + + + + + UTF-8 + UTF-8 + 1.8 + + + \ No newline at end of file diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/Application.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/Application.java new file mode 100644 index 0000000000..eef41bd375 --- /dev/null +++ b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/Application.java @@ -0,0 +1,23 @@ +package org.baeldung.security; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + public Application() { + super(); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return builder.sources(Application.class); + } +} diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java new file mode 100644 index 0000000000..0eb6ee242d --- /dev/null +++ b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java @@ -0,0 +1,18 @@ +package org.baeldung.security; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@Controller +@RequestMapping("/") +public class HomeController { + + @RequestMapping("") + public String home(HttpServletRequest request, HttpServletResponse response) { + return "home"; + } + +} diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/SecurityConfig.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/SecurityConfig.java new file mode 100644 index 0000000000..f6df516a0a --- /dev/null +++ b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/SecurityConfig.java @@ -0,0 +1,70 @@ +package org.baeldung.security; + +import java.util.HashSet; +import java.util.Set; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.BeanIds; +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.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.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + private static final String ROLE_PREFIX = "ROLE_"; + public static final String DEFAULT_PASSWORD = "password"; + @Bean + static PasswordEncoder bCryptPasswordEncoder() { + return new BCryptPasswordEncoder(10); + } + + @Bean + UserDetailsService customUserDetailsService() { + return new UserDetailsService() { + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + //authenticate and return dummy user + Set authorities = new HashSet(); + authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + username)); + return new User(username, bCryptPasswordEncoder().encode(DEFAULT_PASSWORD), authorities); + } + }; + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(customUserDetailsService()).passwordEncoder(bCryptPasswordEncoder()); + + } + + @Bean(name = BeanIds.AUTHENTICATION_MANAGER) + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManager(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf(); + http.headers().frameOptions().sameOrigin(); + + http.antMatcher("/**").userDetailsService(customUserDetailsService()) + .authorizeRequests() + .antMatchers("/**").permitAll() + .and() + .httpBasic(); + } +} diff --git a/spring-boot-security-taglibs/src/main/resources/application.properties b/spring-boot-security-taglibs/src/main/resources/application.properties new file mode 100644 index 0000000000..9c49bd2137 --- /dev/null +++ b/spring-boot-security-taglibs/src/main/resources/application.properties @@ -0,0 +1,8 @@ +#jsp config +spring.mvc.view.prefix: /WEB-INF/views/ +spring.mvc.view.suffix: .jsp +spring.http.encoding.charset=UTF-8 +# Enable http encoding support. +spring.http.encoding.enabled=true +# Force the encoding to the configured charset on HTTP requests and responses. +spring.http.encoding.force=true diff --git a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp new file mode 100644 index 0000000000..9f5d8c34a3 --- /dev/null +++ b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="security" + uri="http://www.springframework.org/security/tags" %> + + + + + +Home Page + + + + AUTHENTICATED + + + ADMIN ROLE + + + \ No newline at end of file diff --git a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java new file mode 100644 index 0000000000..f13b23a10d --- /dev/null +++ b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java @@ -0,0 +1,27 @@ +package org.baeldung.security; + +import static org.junit.Assert.assertTrue; + +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.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class HomeControllerTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void home() throws Exception { + String body = this.restTemplate.withBasicAuth("ADMIN", SecurityConfig.DEFAULT_PASSWORD).getForEntity("/", String.class).getBody(); + System.out.println(body); + assertTrue(body.contains("AUTHENTICATED")); + assertTrue(body.contains("ADMIN ROLE")); + } +} From 4e4d11574ac5f3719d6eb8620ef54bda31b689ca Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Sat, 11 Aug 2018 16:10:53 +0800 Subject: [PATCH 06/82] add more test --- .../src/main/webapp/WEB-INF/views/home.jsp | 25 ++++++++++----- .../baeldung/security/HomeControllerTest.java | 31 ++++++++++++++----- 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp index 9f5d8c34a3..1117749ded 100644 --- a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp +++ b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp @@ -1,20 +1,29 @@ <%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="security" - uri="http://www.springframework.org/security/tags" %> - + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="sec" + uri="http://www.springframework.org/security/tags"%> + + Home Page - + AUTHENTICATED - - + + ADMIN ROLE - + + +

principal.username:

+ +
+ + Text Field:
+ + \ No newline at end of file diff --git a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java index f13b23a10d..dfdfda6234 100644 --- a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java +++ b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java @@ -13,15 +13,30 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class HomeControllerTest { - + @Autowired private TestRestTemplate restTemplate; - @Test - public void home() throws Exception { - String body = this.restTemplate.withBasicAuth("ADMIN", SecurityConfig.DEFAULT_PASSWORD).getForEntity("/", String.class).getBody(); - System.out.println(body); - assertTrue(body.contains("AUTHENTICATED")); - assertTrue(body.contains("ADMIN ROLE")); - } + @Test + public void home() throws Exception { + String body = this.restTemplate.withBasicAuth("ADMIN", SecurityConfig.DEFAULT_PASSWORD) + .getForEntity("/", String.class) + .getBody(); + System.out.println(body); + + // test + assertTrue(body.contains("AUTHENTICATED")); + + // test + assertTrue(body.contains("ADMIN ROLE")); + + // test + assertTrue(body.contains("principal.username: ADMIN")); + + // test + assertTrue(body.contains(" + assertTrue(body.contains("")); + } } From 7b2dec656dfeb434881e1ad7205e23c18b7d7986 Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Sat, 11 Aug 2018 16:15:49 +0800 Subject: [PATCH 07/82] add more test --- .../org/baeldung/security/SecurityConfig.java | 35 +++++++++++-------- .../baeldung/security/HomeControllerTest.java | 4 +-- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/SecurityConfig.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/SecurityConfig.java index f6df516a0a..99c5f1e892 100644 --- a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/SecurityConfig.java +++ b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/SecurityConfig.java @@ -25,28 +25,29 @@ import org.springframework.security.crypto.password.PasswordEncoder; public class SecurityConfig extends WebSecurityConfigurerAdapter { private static final String ROLE_PREFIX = "ROLE_"; public static final String DEFAULT_PASSWORD = "password"; + @Bean static PasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(10); } - + @Bean UserDetailsService customUserDetailsService() { return new UserDetailsService() { - - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - //authenticate and return dummy user - Set authorities = new HashSet(); - authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + username)); - return new User(username, bCryptPasswordEncoder().encode(DEFAULT_PASSWORD), authorities); - } - }; + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + // authenticate, grant ADMIN role and return dummy user + Set authorities = new HashSet(); + authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + "ADMIN")); + return new User(username, bCryptPasswordEncoder().encode(DEFAULT_PASSWORD), authorities); + } + }; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(customUserDetailsService()).passwordEncoder(bCryptPasswordEncoder()); + auth.userDetailsService(customUserDetailsService()) + .passwordEncoder(bCryptPasswordEncoder()); } @@ -59,11 +60,15 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf(); - http.headers().frameOptions().sameOrigin(); - - http.antMatcher("/**").userDetailsService(customUserDetailsService()) + http.headers() + .frameOptions() + .sameOrigin(); + + http.antMatcher("/**") + .userDetailsService(customUserDetailsService()) .authorizeRequests() - .antMatchers("/**").permitAll() + .antMatchers("/**") + .permitAll() .and() .httpBasic(); } diff --git a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java index dfdfda6234..995d5fa3df 100644 --- a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java +++ b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java @@ -19,7 +19,7 @@ public class HomeControllerTest { @Test public void home() throws Exception { - String body = this.restTemplate.withBasicAuth("ADMIN", SecurityConfig.DEFAULT_PASSWORD) + String body = this.restTemplate.withBasicAuth("testUser", SecurityConfig.DEFAULT_PASSWORD) .getForEntity("/", String.class) .getBody(); System.out.println(body); @@ -31,7 +31,7 @@ public class HomeControllerTest { assertTrue(body.contains("ADMIN ROLE")); // test - assertTrue(body.contains("principal.username: ADMIN")); + assertTrue(body.contains("principal.username: testUser")); // test assertTrue(body.contains(" Date: Tue, 14 Aug 2018 14:41:06 +0800 Subject: [PATCH 08/82] refactor spring config --- .../org/baeldung/security/Application.java | 23 ------ .../baeldung/security/ApplicationConfig.java | 40 ++++++++++ .../org/baeldung/security/HomeController.java | 2 - .../org/baeldung/security/SecurityConfig.java | 75 ------------------- .../src/main/webapp/WEB-INF/views/home.jsp | 28 ++++--- .../baeldung/security/HomeControllerTest.java | 2 +- 6 files changed, 54 insertions(+), 116 deletions(-) delete mode 100644 spring-boot-security-taglibs/src/main/java/org/baeldung/security/Application.java create mode 100644 spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java delete mode 100644 spring-boot-security-taglibs/src/main/java/org/baeldung/security/SecurityConfig.java diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/Application.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/Application.java deleted file mode 100644 index eef41bd375..0000000000 --- a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/Application.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung.security; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; - -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - - public Application() { - super(); - } - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { - return builder.sources(Application.class); - } -} diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java new file mode 100644 index 0000000000..6283a102aa --- /dev/null +++ b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java @@ -0,0 +1,40 @@ +package org.baeldung.security; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +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.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; + +@SpringBootApplication +@Configuration +@EnableWebSecurity +public class ApplicationConfig extends WebSecurityConfigurerAdapter { + public static final String DEFAULT_PASSWORD = "password"; + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); + + auth.inMemoryAuthentication() + .passwordEncoder(encoder) + .withUser("testUser") + .password(encoder.encode(DEFAULT_PASSWORD)) + .roles("ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf(); + + http.authorizeRequests() + .antMatchers("/**") + .permitAll() + .and() + .httpBasic(); + } +} diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java index 0eb6ee242d..e697e7e301 100644 --- a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java +++ b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java @@ -9,10 +9,8 @@ import javax.servlet.http.HttpServletResponse; @Controller @RequestMapping("/") public class HomeController { - @RequestMapping("") public String home(HttpServletRequest request, HttpServletResponse response) { return "home"; } - } diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/SecurityConfig.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/SecurityConfig.java deleted file mode 100644 index 99c5f1e892..0000000000 --- a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/SecurityConfig.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.baeldung.security; - -import java.util.HashSet; -import java.util.Set; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.BeanIds; -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.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.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -@EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { - private static final String ROLE_PREFIX = "ROLE_"; - public static final String DEFAULT_PASSWORD = "password"; - - @Bean - static PasswordEncoder bCryptPasswordEncoder() { - return new BCryptPasswordEncoder(10); - } - - @Bean - UserDetailsService customUserDetailsService() { - return new UserDetailsService() { - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - // authenticate, grant ADMIN role and return dummy user - Set authorities = new HashSet(); - authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + "ADMIN")); - return new User(username, bCryptPasswordEncoder().encode(DEFAULT_PASSWORD), authorities); - } - }; - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(customUserDetailsService()) - .passwordEncoder(bCryptPasswordEncoder()); - - } - - @Bean(name = BeanIds.AUTHENTICATION_MANAGER) - @Override - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManager(); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf(); - http.headers() - .frameOptions() - .sameOrigin(); - - http.antMatcher("/**") - .userDetailsService(customUserDetailsService()) - .authorizeRequests() - .antMatchers("/**") - .permitAll() - .and() - .httpBasic(); - } -} diff --git a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp index 1117749ded..fff93186a0 100644 --- a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp +++ b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp @@ -1,8 +1,5 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="sec" - uri="http://www.springframework.org/security/tags"%> - +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%> @@ -11,19 +8,20 @@ Home Page - + AUTHENTICATED - + ADMIN ROLE - -

principal.username:

- -
- - Text Field:
- - +

+ principal.username: + +

+
+ + Text Field:
+ + \ No newline at end of file diff --git a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java index 995d5fa3df..c9c8698254 100644 --- a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java +++ b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java @@ -19,7 +19,7 @@ public class HomeControllerTest { @Test public void home() throws Exception { - String body = this.restTemplate.withBasicAuth("testUser", SecurityConfig.DEFAULT_PASSWORD) + String body = this.restTemplate.withBasicAuth("testUser", ApplicationConfig.DEFAULT_PASSWORD) .getForEntity("/", String.class) .getBody(); System.out.println(body); From d11fbc73adc2df6501ec9b8eb25d75cf6295d577 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 14 Aug 2018 14:46:35 +0800 Subject: [PATCH 09/82] refactor spring config --- spring-boot-security-taglibs/pom.xml | 132 +++++++++++++-------------- 1 file changed, 62 insertions(+), 70 deletions(-) diff --git a/spring-boot-security-taglibs/pom.xml b/spring-boot-security-taglibs/pom.xml index bd04ec3c0b..447f0c4be9 100644 --- a/spring-boot-security-taglibs/pom.xml +++ b/spring-boot-security-taglibs/pom.xml @@ -1,84 +1,76 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - spring-boot-security-taglibs - jar - spring-boot-security-taglibs - spring 5 security sample project + spring-boot-security-taglibs + jar + spring-boot-security-taglibs + spring 5 security sample project - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + - + - - org.springframework.boot - spring-boot-starter-security - + + org.springframework.boot + spring-boot-starter-security + - - org.springframework.boot - spring-boot-starter-web - + + org.springframework.boot + spring-boot-starter-web + - - - org.springframework.security - spring-security-taglibs - + + + org.springframework.security + spring-security-taglibs + - - - org.apache.tomcat.embed - tomcat-embed-jasper - provided - - - javax.servlet - jstl - - - - net.sourceforge.htmlunit - htmlunit - + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + javax.servlet + jstl + - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + - + - - spring-5-security-taglibs - - - src/main/resources - true - - + + spring-5-security-taglibs + + + src/main/resources + true + + + - - - - - - - UTF-8 - UTF-8 - 1.8 - + + UTF-8 + UTF-8 + 1.8 + \ No newline at end of file From bdad13227e25b4c76ce8ca8c70e9fef51795f195 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 14 Aug 2018 15:10:05 +0800 Subject: [PATCH 10/82] Update README.md --- spring-boot-security-taglibs/README.md | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/spring-boot-security-taglibs/README.md b/spring-boot-security-taglibs/README.md index f7eb314869..8b13789179 100644 --- a/spring-boot-security-taglibs/README.md +++ b/spring-boot-security-taglibs/README.md @@ -1,19 +1 @@ -========= -## Spring Security Login Example Project - -###The Course -The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - -### Relevant Articles: -- [Spring Security Form Login](http://www.baeldung.com/spring-security-login) -- [Spring Security Logout](http://www.baeldung.com/spring-security-logout) -- [Spring Security Expressions – hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) -- [Spring HTTP/HTTPS Channel Security](http://www.baeldung.com/spring-channel-security-https) -- [Spring Security - Customize the 403 Forbidden/Access Denied Page](http://www.baeldung.com/spring-security-custom-access-denied-page) -- [Spring Security – Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login) - -### Build the Project -``` -mvn clean install -``` From 4b1f9559808e42099f57d1272b0c6f11cb06bc72 Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Tue, 14 Aug 2018 22:57:17 +0800 Subject: [PATCH 11/82] fi alignment --- .../src/main/webapp/WEB-INF/views/home.jsp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp index fff93186a0..c13590a3df 100644 --- a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp +++ b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp @@ -10,7 +10,7 @@ AUTHENTICATED - +
ADMIN ROLE @@ -20,7 +20,8 @@
- Text Field:
+ Text Field: +
From 0d684eed97acea7aaf326d3b399c64c5b0c5090b Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Sat, 18 Aug 2018 17:23:07 +0800 Subject: [PATCH 12/82] fix requested comments --- .../baeldung/security/ApplicationConfig.java | 39 ++++++++++--------- .../org/baeldung/security/HomeController.java | 6 ++- .../src/main/resources/application.properties | 5 --- .../src/main/webapp/WEB-INF/views/home.jsp | 35 +++++++++-------- .../baeldung/security/HomeControllerTest.java | 23 +++++++++-- 5 files changed, 62 insertions(+), 46 deletions(-) diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java index 6283a102aa..763422e6df 100644 --- a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java +++ b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java @@ -1,40 +1,41 @@ package org.baeldung.security; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +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.crypto.factory.PasswordEncoderFactories; -import org.springframework.security.crypto.password.PasswordEncoder; +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.provisioning.InMemoryUserDetailsManager; @SpringBootApplication @Configuration @EnableWebSecurity public class ApplicationConfig extends WebSecurityConfigurerAdapter { - public static final String DEFAULT_PASSWORD = "password"; + // Using withDefaultPasswordEncoder and InMemoryUserDetailsManager for demonstration and testing purpose + @Bean @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); + public UserDetailsService userDetailsService() { + UserDetails user = User.withDefaultPasswordEncoder() + .username("testUser") + .password("password") + .roles("ADMIN") + .build(); - auth.inMemoryAuthentication() - .passwordEncoder(encoder) - .withUser("testUser") - .password(encoder.encode(DEFAULT_PASSWORD)) - .roles("ADMIN"); + return new InMemoryUserDetailsManager(user); } @Override protected void configure(HttpSecurity http) throws Exception { - http.csrf(); - - http.authorizeRequests() - .antMatchers("/**") - .permitAll() - .and() - .httpBasic(); + // @formatter:off + http.csrf() + .and() + .authorizeRequests() + .anyRequest().permitAll().and().httpBasic(); + // @formatter:on } } diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java index e697e7e301..cdd4c3f42b 100644 --- a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java +++ b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java @@ -1,6 +1,7 @@ package org.baeldung.security; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; @@ -9,8 +10,9 @@ import javax.servlet.http.HttpServletResponse; @Controller @RequestMapping("/") public class HomeController { - @RequestMapping("") - public String home(HttpServletRequest request, HttpServletResponse response) { + + @GetMapping + public String home() { return "home"; } } diff --git a/spring-boot-security-taglibs/src/main/resources/application.properties b/spring-boot-security-taglibs/src/main/resources/application.properties index 9c49bd2137..218868405f 100644 --- a/spring-boot-security-taglibs/src/main/resources/application.properties +++ b/spring-boot-security-taglibs/src/main/resources/application.properties @@ -1,8 +1,3 @@ #jsp config spring.mvc.view.prefix: /WEB-INF/views/ spring.mvc.view.suffix: .jsp -spring.http.encoding.charset=UTF-8 -# Enable http encoding support. -spring.http.encoding.enabled=true -# Force the encoding to the configured charset on HTTP requests and responses. -spring.http.encoding.force=true diff --git a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp index c13590a3df..7291608e3e 100644 --- a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp +++ b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp @@ -1,5 +1,7 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> -<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%> +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib prefix="sec" + uri="http://www.springframework.org/security/tags"%> @@ -8,21 +10,22 @@ Home Page + + ANONYMOUS + - AUTHENTICATED + AUTHENTICATED + + ADMIN ROLE + +

+ principal.username: + +

+
+ + Text Field:
+
- - ADMIN ROLE - -

- principal.username: - -

-
- - Text Field: -
- - \ No newline at end of file diff --git a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java index c9c8698254..c005185c92 100644 --- a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java +++ b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java @@ -1,5 +1,6 @@ package org.baeldung.security; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -18,11 +19,13 @@ public class HomeControllerTest { private TestRestTemplate restTemplate; @Test - public void home() throws Exception { - String body = this.restTemplate.withBasicAuth("testUser", ApplicationConfig.DEFAULT_PASSWORD) + public void whenUserIsAuthenticatedThenAuthenticatedSectionsShowOnSite() throws Exception { + String body = this.restTemplate.withBasicAuth("testUser", "password") .getForEntity("/", String.class) .getBody(); - System.out.println(body); + + // test + assertFalse(body.contains("ANONYMOUS")); // test assertTrue(body.contains("AUTHENTICATED")); @@ -31,7 +34,7 @@ public class HomeControllerTest { assertTrue(body.contains("ADMIN ROLE")); // test - assertTrue(body.contains("principal.username: testUser")); + assertTrue(body.contains("testUser")); // test assertTrue(body.contains(" assertTrue(body.contains("")); } + + @Test + public void whenUserIsNotAuthenticatedThenOnlyAnonymousSectionsShowOnSite() throws Exception { + String body = this.restTemplate.getForEntity("/", String.class) + .getBody(); + + // test + assertTrue(body.contains("ANONYMOUS")); + + // test + assertFalse(body.contains("AUTHENTICATED")); + } } From 3f8eddad332a4b7e3013e977ca9c57de12050ebc Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Sun, 19 Aug 2018 17:24:43 +0800 Subject: [PATCH 13/82] additional tests and content --- .../main/java/org/baeldung/security/ApplicationConfig.java | 1 + .../src/main/webapp/WEB-INF/views/home.jsp | 7 +++++-- .../java/org/baeldung/security/HomeControllerTest.java | 5 ++++- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java index 763422e6df..6419da3bdd 100644 --- a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java +++ b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java @@ -35,6 +35,7 @@ public class ApplicationConfig extends WebSecurityConfigurerAdapter { http.csrf() .and() .authorizeRequests() + .antMatchers("/adminOnlyURL").hasRole("ADMIN") .anyRequest().permitAll().and().httpBasic(); // @formatter:on } diff --git a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp index 7291608e3e..eed24182e2 100644 --- a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp +++ b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp @@ -14,9 +14,9 @@ ANONYMOUS - AUTHENTICATED + AUTHENTICATED Content - ADMIN ROLE + Content for users who have the "ADMIN" role.

principal.username: @@ -26,6 +26,9 @@ Text Field:
+ + Go to Admin Only URL + \ No newline at end of file diff --git a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java index c005185c92..78b3089fba 100644 --- a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java +++ b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java @@ -31,11 +31,14 @@ public class HomeControllerTest { assertTrue(body.contains("AUTHENTICATED")); // test - assertTrue(body.contains("ADMIN ROLE")); + assertTrue(body.contains("Content for users who have the \"ADMIN\" role.")); // test assertTrue(body.contains("testUser")); + // test + assertTrue(body.contains("")); + // test assertTrue(body.contains(" Date: Sun, 19 Aug 2018 17:34:29 +0800 Subject: [PATCH 14/82] additional tests and content --- .../src/main/webapp/WEB-INF/views/home.jsp | 5 ++--- .../test/java/org/baeldung/security/HomeControllerTest.java | 6 +++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp index eed24182e2..9bb96fe5fd 100644 --- a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp +++ b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp @@ -11,7 +11,7 @@ - ANONYMOUS + ANONYMOUS Content AUTHENTICATED Content @@ -19,8 +19,7 @@ Content for users who have the "ADMIN" role.

- principal.username: - + Welcome back,

diff --git a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java index 78b3089fba..189a691496 100644 --- a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java +++ b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java @@ -28,7 +28,7 @@ public class HomeControllerTest { assertFalse(body.contains("ANONYMOUS")); // test - assertTrue(body.contains("AUTHENTICATED")); + assertTrue(body.contains("AUTHENTICATED Content")); // test assertTrue(body.contains("Content for users who have the \"ADMIN\" role.")); @@ -52,9 +52,9 @@ public class HomeControllerTest { .getBody(); // test - assertTrue(body.contains("ANONYMOUS")); + assertTrue(body.contains("ANONYMOUS Content")); // test - assertFalse(body.contains("AUTHENTICATED")); + assertFalse(body.contains("AUTHENTICATED Content")); } } From 7263e223c5c2cfd5f8c81be494eb47710098dbd2 Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Tue, 21 Aug 2018 22:31:44 +0800 Subject: [PATCH 15/82] update examples --- .../baeldung/security/ApplicationConfig.java | 2 +- .../src/main/webapp/WEB-INF/views/home.jsp | 24 +++++++++++-------- .../baeldung/security/HomeControllerTest.java | 16 ++++++------- 3 files changed, 23 insertions(+), 19 deletions(-) diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java index 6419da3bdd..e8a95af5ce 100644 --- a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java +++ b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java @@ -35,7 +35,7 @@ public class ApplicationConfig extends WebSecurityConfigurerAdapter { http.csrf() .and() .authorizeRequests() - .antMatchers("/adminOnlyURL").hasRole("ADMIN") + .antMatchers("/userManagement").hasRole("ADMIN") .anyRequest().permitAll().and().httpBasic(); // @formatter:on } diff --git a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp index 9bb96fe5fd..70440e8dc9 100644 --- a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp +++ b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp @@ -9,24 +9,28 @@ Home Page - - - ANONYMOUS Content + + + Login + + + Logout + + - AUTHENTICATED Content - - Content for users who have the "ADMIN" role. -

Welcome back, -

+

+ + Manage Users + Text Field:
- -
Go to Admin Only URL + + Manage Users
diff --git a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java index 189a691496..e085fb4083 100644 --- a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java +++ b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java @@ -24,20 +24,20 @@ public class HomeControllerTest { .getForEntity("/", String.class) .getBody(); - // test - assertFalse(body.contains("ANONYMOUS")); + // test + assertFalse(body.contains("Login")); // test - assertTrue(body.contains("AUTHENTICATED Content")); + assertTrue(body.contains("Logout")); // test - assertTrue(body.contains("Content for users who have the \"ADMIN\" role.")); + assertTrue(body.contains("Manage Users")); // test assertTrue(body.contains("testUser")); // test - assertTrue(body.contains("")); + assertTrue(body.contains("")); // test assertTrue(body.contains(" - assertTrue(body.contains("ANONYMOUS Content")); + // test + assertTrue(body.contains("Login")); // test - assertFalse(body.contains("AUTHENTICATED Content")); + assertFalse(body.contains("Logout")); } } From 221ecbdae68b7e706e99236754b727d506e5943f Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Wed, 22 Aug 2018 22:07:20 +0800 Subject: [PATCH 16/82] Delete Readme file --- spring-boot-security-taglibs/README.md | 1 - 1 file changed, 1 deletion(-) delete mode 100644 spring-boot-security-taglibs/README.md diff --git a/spring-boot-security-taglibs/README.md b/spring-boot-security-taglibs/README.md deleted file mode 100644 index 8b13789179..0000000000 --- a/spring-boot-security-taglibs/README.md +++ /dev/null @@ -1 +0,0 @@ - From fe7b8bf4ba67ce520c764049da162af307837443 Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Wed, 22 Aug 2018 23:19:31 +0800 Subject: [PATCH 17/82] edit form example --- .../src/main/java/org/baeldung/security/HomeController.java | 6 +----- .../src/main/webapp/WEB-INF/views/home.jsp | 3 ++- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java index cdd4c3f42b..7e70c269cb 100644 --- a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java +++ b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java @@ -1,17 +1,13 @@ package org.baeldung.security; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Controller @RequestMapping("/") public class HomeController { - @GetMapping + @RequestMapping public String home() { return "home"; } diff --git a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp index 70440e8dc9..80ecd61cb5 100644 --- a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp +++ b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp @@ -25,9 +25,10 @@ Manage Users -
+ Text Field:
+
Manage Users From 8e5586ca48f7d12b2666a47d269dad9bc21d527d Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Fri, 24 Aug 2018 23:46:12 +0800 Subject: [PATCH 18/82] adding example for spring boot security tag libs --- spring-boot-security/pom.xml | 17 ++++++ .../springsecuritytaglibs/HomeController.java | 14 +++++ .../SpringBootSecurityTagLibsApplication.java | 9 +++ .../SpringBootSecurityTagLibsConfig.java | 31 ++++++++++ .../resources/application-taglibs.properties | 3 + .../src/main/resources/application.properties | 2 +- .../src/main/webapp/WEB-INF/views/home.jsp | 38 ++++++++++++ .../HomeControllerUnitTest.java | 60 +++++++++++++++++++ 8 files changed, 173 insertions(+), 1 deletion(-) create mode 100644 spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java create mode 100644 spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java create mode 100644 spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java create mode 100644 spring-boot-security/src/main/resources/application-taglibs.properties create mode 100644 spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp create mode 100644 spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java diff --git a/spring-boot-security/pom.xml b/spring-boot-security/pom.xml index 12f51eec94..b1673d383e 100644 --- a/spring-boot-security/pom.xml +++ b/spring-boot-security/pom.xml @@ -44,6 +44,23 @@ org.springframework.boot spring-boot-starter-web + + + + org.springframework.security + spring-security-taglibs + + + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + javax.servlet + jstl + org.springframework.boot diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java new file mode 100644 index 0000000000..eca093a76f --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/HomeController.java @@ -0,0 +1,14 @@ +package com.baeldung.springsecuritytaglibs; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/") +public class HomeController { + + @RequestMapping + public String home() { + return "home"; + } +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java new file mode 100644 index 0000000000..397ea47f96 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/SpringBootSecurityTagLibsApplication.java @@ -0,0 +1,9 @@ +package com.baeldung.springsecuritytaglibs; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +@PropertySource("classpath:application-taglibs.properties") +public class SpringBootSecurityTagLibsApplication { +} diff --git a/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java new file mode 100644 index 0000000000..665dd0bce9 --- /dev/null +++ b/spring-boot-security/src/main/java/com/baeldung/springsecuritytaglibs/config/SpringBootSecurityTagLibsConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.springsecuritytaglibs.config; + +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; + +@Configuration +@EnableWebSecurity +public class SpringBootSecurityTagLibsConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("testUser") + .password("password") + .roles("ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + // @formatter:off + http.csrf() + .and() + .authorizeRequests() + .antMatchers("/userManagement").hasRole("ADMIN") + .anyRequest().permitAll().and().httpBasic(); + // @formatter:on + } +} \ No newline at end of file diff --git a/spring-boot-security/src/main/resources/application-taglibs.properties b/spring-boot-security/src/main/resources/application-taglibs.properties new file mode 100644 index 0000000000..218868405f --- /dev/null +++ b/spring-boot-security/src/main/resources/application-taglibs.properties @@ -0,0 +1,3 @@ +#jsp config +spring.mvc.view.prefix: /WEB-INF/views/ +spring.mvc.view.suffix: .jsp diff --git a/spring-boot-security/src/main/resources/application.properties b/spring-boot-security/src/main/resources/application.properties index c2b8d70dc6..e776132359 100644 --- a/spring-boot-security/src/main/resources/application.properties +++ b/spring-boot-security/src/main/resources/application.properties @@ -1,4 +1,4 @@ #spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration #security.user.password=password #security.oauth2.client.client-id=client -#security.oauth2.client.client-secret=secret +#security.oauth2.client.client-secret=secret \ No newline at end of file diff --git a/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp new file mode 100644 index 0000000000..80ecd61cb5 --- /dev/null +++ b/spring-boot-security/src/main/webapp/WEB-INF/views/home.jsp @@ -0,0 +1,38 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib prefix="sec" + uri="http://www.springframework.org/security/tags"%> + + + + + +Home Page + + + + Login + + + + Logout + + + +

+ Welcome back, +

+ + Manage Users + +
+ + Text Field:
+ + + + Manage Users + +
+ + \ No newline at end of file diff --git a/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java new file mode 100644 index 0000000000..0585c06a59 --- /dev/null +++ b/spring-boot-security/src/test/java/com/baeldung/springsecuritytaglibs/HomeControllerUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.springsecuritytaglibs; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +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.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SpringBootSecurityTagLibsApplication.class) +public class HomeControllerUnitTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void whenUserIsAuthenticatedThenAuthenticatedSectionsShowOnSite() throws Exception { + String body = this.restTemplate.withBasicAuth("testUser", "password") + .getForEntity("/", String.class) + .getBody(); + + // test + assertFalse(body.contains("Login")); + + // test + assertTrue(body.contains("Logout")); + + // test + assertTrue(body.contains("Manage Users")); + + // test + assertTrue(body.contains("testUser")); + + // test + assertTrue(body.contains("")); + + // test + assertTrue(body.contains(" + assertTrue(body.contains("")); + } + + @Test + public void whenUserIsNotAuthenticatedThenOnlyAnonymousSectionsShowOnSite() throws Exception { + String body = this.restTemplate.getForEntity("/", String.class) + .getBody(); + + // test + assertTrue(body.contains("Login")); + + // test + assertFalse(body.contains("Logout")); + } +} From afdb37eb02b5f833a6278d2b8fdd651d8d0e436d Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Fri, 24 Aug 2018 23:48:20 +0800 Subject: [PATCH 19/82] Remove old tag libs module --- spring-boot-security-taglibs/.gitignore | 13 ---- spring-boot-security-taglibs/pom.xml | 76 ------------------- .../baeldung/security/ApplicationConfig.java | 42 ---------- .../org/baeldung/security/HomeController.java | 14 ---- .../src/main/resources/application.properties | 3 - .../src/main/webapp/WEB-INF/views/home.jsp | 38 ---------- .../baeldung/security/HomeControllerTest.java | 60 --------------- 7 files changed, 246 deletions(-) delete mode 100644 spring-boot-security-taglibs/.gitignore delete mode 100644 spring-boot-security-taglibs/pom.xml delete mode 100644 spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java delete mode 100644 spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java delete mode 100644 spring-boot-security-taglibs/src/main/resources/application.properties delete mode 100644 spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp delete mode 100644 spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java diff --git a/spring-boot-security-taglibs/.gitignore b/spring-boot-security-taglibs/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/spring-boot-security-taglibs/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.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-boot-security-taglibs/pom.xml b/spring-boot-security-taglibs/pom.xml deleted file mode 100644 index 447f0c4be9..0000000000 --- a/spring-boot-security-taglibs/pom.xml +++ /dev/null @@ -1,76 +0,0 @@ - - 4.0.0 - - spring-boot-security-taglibs - jar - spring-boot-security-taglibs - spring 5 security sample project - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - - org.springframework.boot - spring-boot-starter-security - - - - org.springframework.boot - spring-boot-starter-web - - - - - org.springframework.security - spring-security-taglibs - - - - - org.apache.tomcat.embed - tomcat-embed-jasper - provided - - - javax.servlet - jstl - - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - - - - - - spring-5-security-taglibs - - - src/main/resources - true - - - - - - UTF-8 - UTF-8 - 1.8 - - - \ No newline at end of file diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java deleted file mode 100644 index e8a95af5ce..0000000000 --- a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/ApplicationConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.security; - -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -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.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.provisioning.InMemoryUserDetailsManager; - -@SpringBootApplication -@Configuration -@EnableWebSecurity -public class ApplicationConfig extends WebSecurityConfigurerAdapter { - - // Using withDefaultPasswordEncoder and InMemoryUserDetailsManager for demonstration and testing purpose - @Bean - @Override - public UserDetailsService userDetailsService() { - UserDetails user = User.withDefaultPasswordEncoder() - .username("testUser") - .password("password") - .roles("ADMIN") - .build(); - - return new InMemoryUserDetailsManager(user); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - // @formatter:off - http.csrf() - .and() - .authorizeRequests() - .antMatchers("/userManagement").hasRole("ADMIN") - .anyRequest().permitAll().and().httpBasic(); - // @formatter:on - } -} diff --git a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java b/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java deleted file mode 100644 index 7e70c269cb..0000000000 --- a/spring-boot-security-taglibs/src/main/java/org/baeldung/security/HomeController.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.security; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping("/") -public class HomeController { - - @RequestMapping - public String home() { - return "home"; - } -} diff --git a/spring-boot-security-taglibs/src/main/resources/application.properties b/spring-boot-security-taglibs/src/main/resources/application.properties deleted file mode 100644 index 218868405f..0000000000 --- a/spring-boot-security-taglibs/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -#jsp config -spring.mvc.view.prefix: /WEB-INF/views/ -spring.mvc.view.suffix: .jsp diff --git a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp b/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp deleted file mode 100644 index 80ecd61cb5..0000000000 --- a/spring-boot-security-taglibs/src/main/webapp/WEB-INF/views/home.jsp +++ /dev/null @@ -1,38 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" - pageEncoding="UTF-8"%> -<%@ taglib prefix="sec" - uri="http://www.springframework.org/security/tags"%> - - - - - -Home Page - - - - Login - - - - Logout - - - -

- Welcome back, -

- - Manage Users - -
- - Text Field:
- - - -
Manage Users -
-
- - \ No newline at end of file diff --git a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java b/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java deleted file mode 100644 index e085fb4083..0000000000 --- a/spring-boot-security-taglibs/src/test/java/org/baeldung/security/HomeControllerTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.baeldung.security; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -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.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -public class HomeControllerTest { - - @Autowired - private TestRestTemplate restTemplate; - - @Test - public void whenUserIsAuthenticatedThenAuthenticatedSectionsShowOnSite() throws Exception { - String body = this.restTemplate.withBasicAuth("testUser", "password") - .getForEntity("/", String.class) - .getBody(); - - // test - assertFalse(body.contains("Login")); - - // test - assertTrue(body.contains("Logout")); - - // test - assertTrue(body.contains("Manage Users")); - - // test - assertTrue(body.contains("testUser")); - - // test - assertTrue(body.contains("")); - - // test - assertTrue(body.contains(" - assertTrue(body.contains("")); - } - - @Test - public void whenUserIsNotAuthenticatedThenOnlyAnonymousSectionsShowOnSite() throws Exception { - String body = this.restTemplate.getForEntity("/", String.class) - .getBody(); - - // test - assertTrue(body.contains("Login")); - - // test - assertFalse(body.contains("Logout")); - } -} From bd0e2c888ef220953a209b68f838be784f74518b Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Sat, 8 Sep 2018 08:04:42 +0200 Subject: [PATCH 20/82] added link --- spring-boot/README.MD | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 54382992d4..192c4f9fed 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -33,3 +33,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [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) From 2ee3d2ffd9c627f39e0cbcb0df0e5a23741a4be0 Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Mon, 10 Sep 2018 19:05:14 +0800 Subject: [PATCH 21/82] BAEL-2147 Add GsonTest --- .../com/baeldung/kotlin/gson/GsonUnitTest.kt | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt new file mode 100644 index 0000000000..fce3225ef8 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt @@ -0,0 +1,34 @@ +package com.baeldung.kotlin.gson + +import com.baeldung.datetime.UsePeriod +import com.google.gson.Gson +import com.google.gson.annotations.SerializedName +import java.time.LocalDate +import java.time.Period + +import org.junit.Assert +import org.junit.Test + +class GsonUnitTest { + + var gson = Gson() + + @Test + fun givenObject_thenGetJSONString() { + var jsonString = gson.toJson(TestModel(1,"Test")) + Assert.assertEquals(jsonString, "{\"id\":1,\"description\":\"Test\"}") + } + + @Test + fun givenJSONString_thenGetObject() { + var jsonString = "{\"id\":1,\"description\":\"Test\"}"; + var testModel = gson.fromJson(jsonString, TestModel::class.java) + Assert.assertEquals(testModel.id, 1) + Assert.assertEquals(testModel.description, "Test") + } + + data class TestModel( + val id: Int, + val description: String + ) +} \ No newline at end of file From 8962f0a3b6fc985712db3605b3520ff095076eb5 Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Mon, 10 Sep 2018 19:11:44 +0800 Subject: [PATCH 22/82] BAEL-2147 Remove unused import --- .../src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt | 4 ---- 1 file changed, 4 deletions(-) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt index fce3225ef8..bdf44d3b49 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/gson/GsonUnitTest.kt @@ -1,10 +1,6 @@ package com.baeldung.kotlin.gson -import com.baeldung.datetime.UsePeriod import com.google.gson.Gson -import com.google.gson.annotations.SerializedName -import java.time.LocalDate -import java.time.Period import org.junit.Assert import org.junit.Test From 5b78803c1fe11f524c3a776a93a60a13052c7ee1 Mon Sep 17 00:00:00 2001 From: Grigorios Dimopoulos Date: Sat, 22 Sep 2018 17:37:09 +0300 Subject: [PATCH 23/82] [BAEL2150] Code for the related article, about nth root in java. --- .../root/calculator/NthRootCalculator.java | 8 +++++ .../java/com/baeldung/nth/root/main/Main.java | 13 +++++++ .../calculator/NthRootCalculatorUnitTest.java | 21 ++++++++++++ .../baeldung/nth/root/main/MainUnitTest.java | 34 +++++++++++++++++++ 4 files changed, 76 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java create mode 100644 core-java/src/main/java/com/baeldung/nth/root/main/Main.java create mode 100644 core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java b/core-java/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java new file mode 100644 index 0000000000..217f1e06de --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nth/root/calculator/NthRootCalculator.java @@ -0,0 +1,8 @@ +package com.baeldung.nth.root.calculator; + +public class NthRootCalculator +{ + public Double calculate(Double base, Double n) { + return Math.pow(Math.E, Math.log(base)/n); + } +} diff --git a/core-java/src/main/java/com/baeldung/nth/root/main/Main.java b/core-java/src/main/java/com/baeldung/nth/root/main/Main.java new file mode 100644 index 0000000000..3fcd36812f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nth/root/main/Main.java @@ -0,0 +1,13 @@ +package com.baeldung.nth.root.main; + +import com.baeldung.nth.root.calculator.NthRootCalculator; + +public class Main { + public static void main(String[] args) { + NthRootCalculator calculator = new NthRootCalculator(); + Double base = Double.parseDouble(args[0]); + Double n = Double.parseDouble(args[1]); + Double result = calculator.calculate(base, n); + System.out.println("The " + n + " root of " + base + " equals to " + result + "."); + } +} diff --git a/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java new file mode 100644 index 0000000000..388bceef49 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.nth.root.calculator; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.junit.Assert.assertEquals; + +@RunWith(MockitoJUnitRunner.class) +public class NthRootCalculatorUnitTest { + + @InjectMocks + private NthRootCalculator nthRootCalculator; + + @Test + public void giventThatTheBaseIs125_andTheExpIs3_whenCalculateIsCalled_thenTheResultIsTheCorrectOne() { + Double result = nthRootCalculator.calculate(125.0, 3.0); + assertEquals(result, (Double) 5.0d); + } +} diff --git a/core-java/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java b/core-java/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java new file mode 100644 index 0000000000..a2fd839ba4 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nth/root/main/MainUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.nth.root.main; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import static org.junit.Assert.assertEquals; + +public class MainUnitTest { + @InjectMocks + private Main main; + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final PrintStream originalOut = System.out; + + @Before + public void setUpStreams() { + System.setOut(new PrintStream(outContent)); + } + + @After + public void restoreStreams() { + System.setOut(originalOut); + } + + @Test + public void givenThatTheBaseIs125_andTheExpIs3_whenMainIsCalled_thenTheCorrectResultIsPrinted() { + main.main(new String[]{"125.0", "3.0"}); + assertEquals("The 3.0 root of 125.0 equals to 5.0.\n", outContent.toString().replaceAll("\r", "")); + } +} From c1fce0bcd25144a1fb7e429aa7c6127cea49daa8 Mon Sep 17 00:00:00 2001 From: RoscoeLotriet Date: Mon, 24 Sep 2018 10:26:15 +0200 Subject: [PATCH 24/82] Implemented Stream if-else logic class --- .../conditional/StreamForEachIfElseLogic.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/stream/conditional/StreamForEachIfElseLogic.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/conditional/StreamForEachIfElseLogic.java b/core-java-8/src/main/java/com/baeldung/stream/conditional/StreamForEachIfElseLogic.java new file mode 100644 index 0000000000..e8800415dc --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/stream/conditional/StreamForEachIfElseLogic.java @@ -0,0 +1,30 @@ +package com.baeldung.stream.conditional; + +import java.util.stream.Stream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class StreamForEachIfElseLogic { + + private static final Logger LOG = LoggerFactory.getLogger(StreamForEachIfElseLogic.class); + + public static void main(String[] args) { + + ifElseLogic(); + + } + + private static void ifElseLogic() { + + Stream integers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + + integers.forEach(i -> { + if (i.intValue() % 2 == 0) { + LOG.info("{} is even", i); + } else { + LOG.info("{} is odd", i); + } + }); + } +} From af993076f16d079bf50f71ec005f2cefd1011dca Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Wed, 26 Sep 2018 23:24:26 +0800 Subject: [PATCH 25/82] LoopTest class --- .../kotlin/com/baeldung/kotlin/LoopTest.kt | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/kotlin/LoopTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LoopTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LoopTest.kt new file mode 100644 index 0000000000..e95592590b --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LoopTest.kt @@ -0,0 +1,79 @@ +package com.baeldung.kotlin + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse + +class LoopTest { + + @Test + fun givenLoop_whenBreak_thenComplete() { + var value = 0 + + for (i in 1..100) { + value = i + if (value == 30) + break; + } + + assertEquals(value, 30) + + outer_loop@ for (i in 1..10) { + for (j in 1..10) { + value = i * j + if (value == 30) + break@outer_loop; + } + } + + assertEquals(value, 30) + } + + @Test + fun givenLambda_whenReturn_thenComplete() { + listOf(1, 2, 3, 4, 5).forEach { + if (it == 3) return // non-local return directly to the caller + assert(it < 3) + } + //this point is unreachable + assert(false); + } + + @Test + fun givenLambda_whenReturnWithExplicitLabel_thenComplete() { + var result = mutableListOf(); + + listOf(1, 2, 3, 4, 5).forEach lit@{ + if (it == 3){ + // local return to the caller of the lambda, i.e. the forEach loop + return@lit + } + result.add(it) + } + + assert(1 in result + && 2 in result + && 4 in result + && 5 in result) + assertFalse(3 in result) + } + + @Test + fun givenLambda_whenReturnWithImplicitLabel_thenComplete() { + var result = mutableListOf(); + + listOf(1, 2, 3, 4, 5).forEach { + if (it == 3){ + // local return to the caller of the lambda, i.e. the forEach loop + return@forEach + } + result.add(it) + } + + assert(1 in result + && 2 in result + && 4 in result + && 5 in result) + assertFalse(3 in result) + } +} \ No newline at end of file From df99b29fb3756f5a01bda012553760666d84fed6 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Fri, 28 Sep 2018 10:00:44 +0800 Subject: [PATCH 26/82] test cases --- .../kotlin/com/baeldung/kotlin/LoopTest.kt | 72 +++++++++++++++---- 1 file changed, 57 insertions(+), 15 deletions(-) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LoopTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LoopTest.kt index e95592590b..3f1afb19c3 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LoopTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LoopTest.kt @@ -10,14 +10,16 @@ class LoopTest { fun givenLoop_whenBreak_thenComplete() { var value = 0 - for (i in 1..100) { + //break loop without label + for (i in 1..10) { value = i - if (value == 30) + if (value == 3) break; } - assertEquals(value, 30) + assertEquals(value, 3) + //break loop with label outer_loop@ for (i in 1..10) { for (j in 1..10) { value = i * j @@ -29,6 +31,31 @@ class LoopTest { assertEquals(value, 30) } + @Test + fun givenLoop_whenContinue_thenComplete() { + var processedList = mutableListOf() + //continue loop without label + for (i in 1..10) { + if (i == 3) + continue; + processedList.add(i) + } + + assert(processedList.all { it -> it != 3 }) + + //continue loop with label + processedList = mutableListOf() + outer_loop@ for (i in 1..10) { + for (j in 1..10) { + if (i == 3) + continue@outer_loop; + processedList.add(i*j) + } + } + + assertEquals(processedList.size, 90) + } + @Test fun givenLambda_whenReturn_thenComplete() { listOf(1, 2, 3, 4, 5).forEach { @@ -44,18 +71,14 @@ class LoopTest { var result = mutableListOf(); listOf(1, 2, 3, 4, 5).forEach lit@{ - if (it == 3){ + if (it == 3) { // local return to the caller of the lambda, i.e. the forEach loop return@lit } result.add(it) } - assert(1 in result - && 2 in result - && 4 in result - && 5 in result) - assertFalse(3 in result) + assert(result.all { it -> it != 3 }); } @Test @@ -63,17 +86,36 @@ class LoopTest { var result = mutableListOf(); listOf(1, 2, 3, 4, 5).forEach { - if (it == 3){ + if (it == 3) { // local return to the caller of the lambda, i.e. the forEach loop return@forEach } result.add(it) } - assert(1 in result - && 2 in result - && 4 in result - && 5 in result) - assertFalse(3 in result) + assert(result.all { it -> it != 3 }); + } + + @Test + fun givenAnonymousFunction_return_thenComplete() { + var result = mutableListOf(); + listOf(1, 2, 3, 4, 5).forEach(fun(element: Int) { + if (element == 3) return // local return to the caller of the anonymous fun, i.e. the forEach loop + result.add(element); + }) + + assert(result.all { it -> it != 3 }); + } + + @Test + fun givenAnonymousFunction_returnToLabel_thenComplete() { + var value = 0; + run loop@{ + listOf(1, 2, 3, 4, 5).forEach { + value = it; + if (it == 3) return@loop // non-local return from the lambda passed to run + } + } + assertEquals(value, 3) } } \ No newline at end of file From 6c0c94449d7e43eadd0406fa65dcc2897179da1b Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Fri, 28 Sep 2018 10:01:45 +0800 Subject: [PATCH 27/82] StructuralJumpTest --- .../com/baeldung/kotlin/{LoopTest.kt => StructuralJumpTest.kt} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename core-kotlin/src/test/kotlin/com/baeldung/kotlin/{LoopTest.kt => StructuralJumpTest.kt} (99%) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LoopTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt similarity index 99% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/LoopTest.kt rename to core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt index 3f1afb19c3..55b90deaa4 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/LoopTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt @@ -4,7 +4,7 @@ import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFalse -class LoopTest { +class StructuralJumpTest { @Test fun givenLoop_whenBreak_thenComplete() { From d3ad4dcfc2ad1fe818973fbca7d47da80f5e36be Mon Sep 17 00:00:00 2001 From: sachin29aug Date: Thu, 27 Sep 2018 22:52:50 -0400 Subject: [PATCH 28/82] BAEL-9051: Fix failing unit tests --- .../SpringContextIntegrationTest.java | 53 ++++++++++++++++++- .../SpringContextIntegrationTest.java | 18 +++++++ .../SpringContextIntegrationTest.java | 19 +++++++ .../SpringContextIntegrationTest.java | 17 ++++++ .../SpringContextIntegrationTest.java | 4 +- .../MySQLAutoconfiguration.java | 26 ++++++--- .../SpringContextIntegrationTest.java | 6 ++- .../SpringContextIntegrationTest.java | 5 ++ .../com/baeldung/spring/ClientWebConfig.java | 2 + .../SpringContextIntegrationTest.java | 14 ++--- .../SpringContextIntegrationTest.java | 8 +-- 11 files changed, 143 insertions(+), 29 deletions(-) create mode 100644 persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextIntegrationTest.java create mode 100644 persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextIntegrationTest.java create mode 100644 persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java diff --git a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextIntegrationTest.java index c5d8de1cc0..46ee3cd368 100644 --- a/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/persistence-modules/spring-data-cassandra/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,16 +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 SpringContextIntegrationTest { - @Test + 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-gemfire/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..2f0557ccc1 --- /dev/null +++ b/persistence-modules/spring-data-gemfire/src/test/java/org/baeldung/SpringContextIntegrationTest.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 SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..ea32ed324b --- /dev/null +++ b/persistence-modules/spring-data-neo4j/src/test/java/org/baeldung/SpringContextIntegrationTest.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 SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..e093892365 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/org/baeldung/SpringContextIntegrationTest.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 SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 2fb930b63f..4f595916f7 100644 --- a/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-boot-angular-ecommerce/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -5,10 +5,10 @@ import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.ecommerce.EcommerceApplicationIntegrationTest; +import com.baeldung.ecommerce.EcommerceApplication; @RunWith(SpringRunner.class) -@SpringBootTest(classes = EcommerceApplicationIntegrationTest.class) +@SpringBootTest(classes = EcommerceApplication.class) public class SpringContextIntegrationTest { @Test diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java index 4f4f6fb6af..d6fc1836c7 100644 --- a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java +++ b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/MySQLAutoconfiguration.java @@ -1,10 +1,27 @@ package com.baeldung.autoconfiguration; +import java.util.Arrays; +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureOrder; -import org.springframework.boot.autoconfigure.condition.*; +import org.springframework.boot.autoconfigure.condition.ConditionMessage; import org.springframework.boot.autoconfigure.condition.ConditionMessage.Style; -import org.springframework.context.annotation.*; +import org.springframework.boot.autoconfigure.condition.ConditionOutcome; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnResource; +import org.springframework.boot.autoconfigure.condition.SpringBootCondition; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import org.springframework.core.type.AnnotatedTypeMetadata; @@ -14,11 +31,6 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.util.ClassUtils; -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; -import java.util.Arrays; -import java.util.Properties; - @Configuration @ConditionalOnClass(DataSource.class) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) diff --git a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 35b231b5d8..b87ace74a4 100644 --- a/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-cloud-data-flow/batch-job/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,13 +1,15 @@ package org.baeldung; -import org.baeldung.spring.cloud.BatchJobApplication; +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(classes = BatchJobApplication.class) +@SpringBootTest +@ContextConfiguration(classes = JobConfiguration.class) public class SpringContextIntegrationTest { @Test diff --git a/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 7f906bdbcd..0a60412813 100644 --- a/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-data-jpa/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -2,12 +2,17 @@ package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.Application; +import com.baeldung.config.PersistenceConfiguration; +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.config.PersistenceUserConfiguration; @RunWith(SpringRunner.class) +@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class}) @SpringBootTest(classes = Application.class) public class SpringContextIntegrationTest { diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java index 9752526963..22260fca70 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/ClientWebConfig.java @@ -1,11 +1,13 @@ package com.baeldung.spring; +import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @ImportResource("classpath:webMvcConfig.xml") @Configuration +@ComponentScan public class ClientWebConfig implements WebMvcConfigurer { public ClientWebConfig() { diff --git a/spring-security-mvc-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 46bbc629c7..1d7f9ae497 100644 --- a/spring-security-mvc-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-security-mvc-login/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,9 +1,5 @@ package org.baeldung; -import org.baeldung.spring.ChannelSecSecurityConfig; -import org.baeldung.spring.MvcConfig; -import org.baeldung.spring.RedirectionSecurityConfig; -import org.baeldung.spring.SecSecurityConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; @@ -11,12 +7,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MvcConfig.class, ChannelSecSecurityConfig.class, RedirectionSecurityConfig.class, - SecSecurityConfig.class }) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) @WebAppConfiguration public class SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } } diff --git a/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java index e56f5d5031..6cf624c179 100644 --- a/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-security-rest-basic-auth/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,18 +1,12 @@ package org.baeldung; -import org.baeldung.client.spring.ClientConfig; -import org.baeldung.spring.SecSecurityConfig; -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.support.AnnotationConfigContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ClientConfig.class, SecSecurityConfig.class, - WebConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration({ "/WebSecurityConfig.xml" }) public class SpringContextIntegrationTest { @Test From 9b6a043cbb0378d75c385dfabf89dfc3fa675781 Mon Sep 17 00:00:00 2001 From: RoscoeLotriet Date: Fri, 28 Sep 2018 06:02:34 +0200 Subject: [PATCH 29/82] Updated if-else logic and added filter method examples --- .../conditional/StreamForEachIfElseLogic.java | 28 +++++++++++++------ 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/core-java-8/src/main/java/com/baeldung/stream/conditional/StreamForEachIfElseLogic.java b/core-java-8/src/main/java/com/baeldung/stream/conditional/StreamForEachIfElseLogic.java index e8800415dc..b8ef521b41 100644 --- a/core-java-8/src/main/java/com/baeldung/stream/conditional/StreamForEachIfElseLogic.java +++ b/core-java-8/src/main/java/com/baeldung/stream/conditional/StreamForEachIfElseLogic.java @@ -1,5 +1,7 @@ package com.baeldung.stream.conditional; +import java.util.Arrays; +import java.util.List; import java.util.stream.Stream; import org.slf4j.Logger; @@ -17,14 +19,24 @@ public class StreamForEachIfElseLogic { private static void ifElseLogic() { - Stream integers = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + List ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + + ints.stream() + .forEach(i -> { + if (i.intValue() % 2 == 0) { + LOG.info("{} is even", i); + } else { + LOG.info("{} is odd", i); + } + }); + + Stream evenIntegers = ints.stream() + .filter(i -> i.intValue() % 2 == 0); + Stream oddIntegers = ints.stream() + .filter(i -> i.intValue() % 2 != 0); + + evenIntegers.forEach(i -> LOG.info("{} is even", i)); + oddIntegers.forEach(i -> LOG.info("{} is odd", i)); - integers.forEach(i -> { - if (i.intValue() % 2 == 0) { - LOG.info("{} is even", i); - } else { - LOG.info("{} is odd", i); - } - }); } } From 33208b0be1c9b7cb8f1d9787a7cd58575a9f5b3e Mon Sep 17 00:00:00 2001 From: Kostiantyn Dobarskyi <29274427+KDobarskyi@users.noreply.github.com> Date: Fri, 28 Sep 2018 07:50:10 +0300 Subject: [PATCH 30/82] BAEL-2127 Chaining Completables in RxJava (#5323) --- rxjava-2/pom.xml | 3 +- .../baeldung/rxjava/CompletableUnitTest.java | 112 ++++++++++++++++++ 2 files changed, 113 insertions(+), 2 deletions(-) create mode 100644 rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java diff --git a/rxjava-2/pom.xml b/rxjava-2/pom.xml index 4c5ea014d7..a18b096b6d 100644 --- a/rxjava-2/pom.xml +++ b/rxjava-2/pom.xml @@ -38,9 +38,8 @@ 3.8.0 - 2.1.3 + 2.2.2 1.7.0 2.0.0 - \ No newline at end of file diff --git a/rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java b/rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java new file mode 100644 index 0000000000..6acda310a5 --- /dev/null +++ b/rxjava-2/src/test/java/com/baeldung/rxjava/CompletableUnitTest.java @@ -0,0 +1,112 @@ +package com.baeldung.rxjava; + +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Single; +import io.reactivex.observers.DisposableCompletableObserver; +import org.junit.Before; +import org.junit.Test; + +public class CompletableUnitTest { + + Completable first; + Completable second; + Completable error; + Throwable throwable = new RuntimeException(); + + @Before + public void setUpCompletables() { + first = Completable.fromSingle(Single.just(1)); + second = Completable.fromRunnable(() -> {}); + error = Single.error(throwable) + .ignoreElement(); + } + + @Test + public void whenCompletableConstructed_thenCompletedSuccessfully() { + Completable completed = Completable.complete(); + completed.subscribe(new DisposableCompletableObserver() { + @Override + public void onComplete() { + System.out.println("Completed!"); + } + + @Override + public void onError(Throwable e) { + e.printStackTrace(); + } + }); + Flowable flowable = Flowable.just("request received", "user logged in"); + Completable flowableCompletable = Completable.fromPublisher(flowable); + Completable singleCompletable = Single.just(1) + .ignoreElement(); + + completed.andThen(flowableCompletable) + .andThen(singleCompletable) + .test() + .assertComplete(); + } + + @Test + public void whenCombiningCompletables_thenCompletedSuccessfully() { + first.andThen(second) + .test() + .assertComplete(); + } + + @Test + public void whenCombinedWithError_thenCompletedWithError() { + first.andThen(second) + .andThen(error) + .test() + .assertError(throwable); + } + + @Test + public void whenCombinedWithNever_thenDoesNotComplete() { + first.andThen(second) + .andThen(Completable.never()) + .test() + .assertNotComplete(); + } + + @Test + public void whenMergedCompletables_thenCompletedSuccessfully() { + Completable.mergeArray(first, second) + .test() + .assertComplete(); + } + + @Test + public void whenMergedWithError_thenCompletedWithError() { + Completable.mergeArray(first, second, error) + .test() + .assertError(throwable); + } + + @Test + public void whenFlatMaped_thenCompletedSuccessfully() { + Completable allElementsCompletable = Flowable.just("request received", "user logged in") + .flatMapCompletable(message -> Completable + .fromRunnable(() -> System.out.println(message)) + ); + allElementsCompletable + .test() + .assertComplete(); + } + + @Test + public void whenAmbWithNever_thenCompletedSuccessfully() { + Completable.ambArray(first, Completable.never(), second) + .test() + .assertComplete(); + } + + @Test + public void whenAmbWithError_thenCompletedWithError() { + Completable.ambArray(error, first, second) + .test() + .assertError(throwable); + } + +} From 275adabbeed8ed3f1e477c3bddaa8baef0ca39d9 Mon Sep 17 00:00:00 2001 From: vizsoro Date: Fri, 28 Sep 2018 07:39:05 +0200 Subject: [PATCH 31/82] refactor of dependencies --- spring-boot-mvc/pom.xml | 24 ++++-------------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index 37d4698f0e..e4038f4c98 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -21,32 +21,16 @@ org.springframework.boot spring-boot-starter-web
- - - com.sun.faces - jsf-api - 2.2.18 - org.apache.tomcat.embed tomcat-embed-jasper + - javax.faces - javax.faces-api - 2.3 + org.glassfish + javax.faces + 2.2.8-30 - - javax.servlet - jstl - 1.2 - - - com.sun.faces - jsf-impl - 2.2.18 - - org.springframework.boot From 3ea0d3f8c904d16fb6b470976f1d6deb831aadda Mon Sep 17 00:00:00 2001 From: Nik Gorylenko Date: Fri, 28 Sep 2018 09:15:43 +0200 Subject: [PATCH 32/82] remove duplicate (#5073) --- testing-modules/junit-5/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 40c4e8cde9..836848282b 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -1,7 +1,6 @@ ### 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) -- [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [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 Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) From 17b4861863f14f35f57ffb3a85d7df68893d9138 Mon Sep 17 00:00:00 2001 From: Kostiantyn Dobarskyi <29274427+KDobarskyi@users.noreply.github.com> Date: Fri, 28 Sep 2018 10:27:47 +0300 Subject: [PATCH 33/82] BAEL-2127 added link to live article about Completable --- rxjava-2/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/rxjava-2/README.md b/rxjava-2/README.md index ccf575757f..78eb6e6428 100644 --- a/rxjava-2/README.md +++ b/rxjava-2/README.md @@ -2,5 +2,6 @@ - [RxJava and Error Handling](http://www.baeldung.com/rxjava-error-handling) - [RxJava 2 – Flowable](http://www.baeldung.com/rxjava-2-flowable) +- [RxJava 2 - Completable](http://www.baeldung.com/rxjava-completable) - [RxJava Maybe](http://www.baeldung.com/rxjava-maybe) -- [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) \ No newline at end of file +- [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) From 51914a01e198868037d75e76c6d2ebd359c21c8e Mon Sep 17 00:00:00 2001 From: Siben Nayak Date: Sat, 29 Sep 2018 01:17:10 +0530 Subject: [PATCH 34/82] [BAEL-2032] Operate on an item in a Stream then remove it (#5175) * [BAEL-2032] Operate on an item in a Stream then remove it * Remove the unit test from this package --- .../com/baeldung/stream}/StreamOperateAndRemoveUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename {core-java-collections/src/test/java/com/baeldung/collection => java-streams/src/test/java/com/baeldung/stream}/StreamOperateAndRemoveUnitTest.java (98%) diff --git a/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java similarity index 98% rename from core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java index 9f002c89a2..c5aa9a1651 100644 --- a/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/stream/StreamOperateAndRemoveUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.collection; +package com.baeldung.stream; import java.util.ArrayList; import java.util.List; From 75c258540e0a8ad55435f07407c54f744e677968 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 29 Sep 2018 09:32:36 +0300 Subject: [PATCH 35/82] remove extra vaadin project --- vaadin-spring/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 vaadin-spring/README.md diff --git a/vaadin-spring/README.md b/vaadin-spring/README.md deleted file mode 100644 index 347c92d7b5..0000000000 --- a/vaadin-spring/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [Sample Application with Spring Boot and Vaadin](https://www.baeldung.com/spring-boot-vaadin) From 56c2b9663e70876e8ecaeb62b3a223c9ccf75760 Mon Sep 17 00:00:00 2001 From: Patryk Date: Sat, 29 Sep 2018 10:52:02 +0200 Subject: [PATCH 36/82] BAEL-2165 (#5317) * BAEL-2165: Guide to Passay * BAEL-2165: Guide to Passay #2 * BAEL-2165: Guide to Passay #3 Fixed formatting. --- libraries-security/pom.xml | 10 ++ .../passay/NegativeMatchingRulesUnitTest.java | 149 ++++++++++++++++++ .../passay/PasswordGeneratorUnitTest.java | 50 ++++++ .../passay/PasswordValidatorUnitTest.java | 81 ++++++++++ .../passay/PositiveMatchingRulesUnitTest.java | 76 +++++++++ .../src/test/resources/messages.properties | 2 + 6 files changed, 368 insertions(+) create mode 100644 libraries-security/src/test/java/com/baeldung/passay/NegativeMatchingRulesUnitTest.java create mode 100644 libraries-security/src/test/java/com/baeldung/passay/PasswordGeneratorUnitTest.java create mode 100644 libraries-security/src/test/java/com/baeldung/passay/PasswordValidatorUnitTest.java create mode 100644 libraries-security/src/test/java/com/baeldung/passay/PositiveMatchingRulesUnitTest.java create mode 100644 libraries-security/src/test/resources/messages.properties diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index a57f029702..3077abc29c 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -38,6 +38,16 @@ ${junit.version} test + + org.passay + passay + 1.3.1 + + + org.cryptacular + cryptacular + 1.2.2 + diff --git a/libraries-security/src/test/java/com/baeldung/passay/NegativeMatchingRulesUnitTest.java b/libraries-security/src/test/java/com/baeldung/passay/NegativeMatchingRulesUnitTest.java new file mode 100644 index 0000000000..5054a5880e --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/passay/NegativeMatchingRulesUnitTest.java @@ -0,0 +1,149 @@ +package com.baeldung.passay; + +import org.cryptacular.bean.EncodingHashBean; +import org.cryptacular.spec.CodecSpec; +import org.cryptacular.spec.DigestSpec; +import org.junit.Assert; +import org.junit.Test; +import org.passay.DictionaryRule; +import org.passay.DictionarySubstringRule; +import org.passay.DigestHistoryRule; +import org.passay.EnglishSequenceData; +import org.passay.HistoryRule; +import org.passay.IllegalCharacterRule; +import org.passay.IllegalRegexRule; +import org.passay.IllegalSequenceRule; +import org.passay.NumberRangeRule; +import org.passay.PasswordData; +import org.passay.PasswordValidator; +import org.passay.RepeatCharacterRegexRule; +import org.passay.RuleResult; +import org.passay.SourceRule; +import org.passay.UsernameRule; +import org.passay.WhitespaceRule; +import org.passay.dictionary.ArrayWordList; +import org.passay.dictionary.WordListDictionary; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class NegativeMatchingRulesUnitTest { + + @Test + public void givenDictionaryRules_whenValidatePassword_thenFoundIllegalWordsFromDictionary() { + ArrayWordList arrayWordList = new ArrayWordList(new String[] { "bar", "foobar" }); + + WordListDictionary wordListDictionary = new WordListDictionary(arrayWordList); + + DictionaryRule dictionaryRule = new DictionaryRule(wordListDictionary); + DictionarySubstringRule dictionarySubstringRule = new DictionarySubstringRule(wordListDictionary); + + PasswordValidator passwordValidator = new PasswordValidator(dictionaryRule, dictionarySubstringRule); + RuleResult validate = passwordValidator.validate(new PasswordData("foobar")); + + assertFalse(validate.isValid()); + assertEquals("ILLEGAL_WORD:{matchingWord=foobar}", getDetail(validate, 0)); + assertEquals("ILLEGAL_WORD:{matchingWord=bar}", getDetail(validate, 1)); + } + + @Test + public void givenHistoryRule_whenValidatePassword_thenFoundIllegalWordsFromHistory() { + HistoryRule historyRule = new HistoryRule(); + + PasswordData passwordData = new PasswordData("123"); + passwordData.setPasswordReferences(new PasswordData.HistoricalReference("12345"), new PasswordData.HistoricalReference("1234"), new PasswordData.HistoricalReference("123")); + + PasswordValidator passwordValidator = new PasswordValidator(historyRule); + + RuleResult validate = passwordValidator.validate(passwordData); + + assertFalse(validate.isValid()); + assertEquals("HISTORY_VIOLATION:{historySize=3}", getDetail(validate, 0)); + } + + @Test + public void givenSeveralIllegalRules_whenValidatePassword_thenFoundSeveralIllegalPatterns() { + IllegalCharacterRule illegalCharacterRule = new IllegalCharacterRule(new char[] { 'a' }); + IllegalRegexRule illegalRegexRule = new IllegalRegexRule("\\w{2}\\d{2}"); + IllegalSequenceRule illegalSequenceRule = new IllegalSequenceRule(EnglishSequenceData.Alphabetical, 3, true); + NumberRangeRule numberRangeRule = new NumberRangeRule(1, 10); + WhitespaceRule whitespaceRule = new WhitespaceRule(); + + PasswordValidator passwordValidator = new PasswordValidator(illegalCharacterRule, illegalRegexRule, illegalSequenceRule, numberRangeRule, whitespaceRule); + + RuleResult validate = passwordValidator.validate(new PasswordData("abcd22 ")); + + assertFalse(validate.isValid()); + assertEquals("ILLEGAL_CHAR:{illegalCharacter=a, matchBehavior=contains}", getDetail(validate, 0)); + assertEquals("ILLEGAL_MATCH:{match=cd22, pattern=\\w{2}\\d{2}}", getDetail(validate, 1)); + assertEquals("ILLEGAL_ALPHABETICAL_SEQUENCE:{sequence=abc}", getDetail(validate, 2)); + assertEquals("ILLEGAL_ALPHABETICAL_SEQUENCE:{sequence=bcd}", getDetail(validate, 3)); + assertEquals("ILLEGAL_NUMBER_RANGE:{number=2, matchBehavior=contains}", getDetail(validate, 4)); + assertEquals("ILLEGAL_WHITESPACE:{whitespaceCharacter= , matchBehavior=contains}", getDetail(validate, 5)); + } + + @Test + public void givenSourceRule_whenValidatePassword_thenFoundIllegalWordsFromSource() { + SourceRule sourceRule = new SourceRule(); + + PasswordData passwordData = new PasswordData("password"); + passwordData.setPasswordReferences(new PasswordData.SourceReference("source", "password")); + + PasswordValidator passwordValidator = new PasswordValidator(sourceRule); + RuleResult validate = passwordValidator.validate(passwordData); + + assertFalse(validate.isValid()); + assertEquals("SOURCE_VIOLATION:{source=source}", getDetail(validate, 0)); + } + + @Test + public void givenRepeatCharacterRegexRuleRule_whenValidatePassword_thenFoundIllegalPatternMatches() { + RepeatCharacterRegexRule repeatCharacterRegexRule = new RepeatCharacterRegexRule(3); + + PasswordValidator passwordValidator = new PasswordValidator(repeatCharacterRegexRule); + + RuleResult validate = passwordValidator.validate(new PasswordData("aaabbb")); + + assertFalse(validate.isValid()); + assertEquals("ILLEGAL_MATCH:{match=aaa, pattern=([^\\x00-\\x1F])\\1{2}}", getDetail(validate, 0)); + assertEquals("ILLEGAL_MATCH:{match=bbb, pattern=([^\\x00-\\x1F])\\1{2}}", getDetail(validate, 1)); + } + + @Test + public void givenUserNameRule_whenValidatePassword_thenFoundUserNameInPassword() { + PasswordValidator passwordValidator = new PasswordValidator(new UsernameRule()); + + PasswordData passwordData = new PasswordData("testuser1234"); + passwordData.setUsername("testuser"); + + RuleResult validate = passwordValidator.validate(passwordData); + + assertFalse(validate.isValid()); + assertEquals("ILLEGAL_USERNAME:{username=testuser, matchBehavior=contains}", getDetail(validate, 0)); + } + + @Test + public void givenPasswordAndHashBeanAndEncryptedReferences_whenValidate_thenPasswordValidationShouldPass() { + List historicalReferences = Arrays.asList(new PasswordData.HistoricalReference("SHA256", "2e4551de804e27aacf20f9df5be3e8cd384ed64488b21ab079fb58e8c90068ab")); + PasswordData passwordData = new PasswordData("example!"); + passwordData.setPasswordReferences(historicalReferences); + + EncodingHashBean encodingHashBean = new EncodingHashBean(new CodecSpec("Base64"), new DigestSpec("SHA256"), 1, false); + + PasswordValidator passwordValidator = new PasswordValidator(new DigestHistoryRule(encodingHashBean)); + + RuleResult validate = passwordValidator.validate(passwordData); + + Assert.assertTrue(validate.isValid()); + } + + private String getDetail(RuleResult validate, int i) { + return validate.getDetails() + .get(i) + .toString(); + } + +} diff --git a/libraries-security/src/test/java/com/baeldung/passay/PasswordGeneratorUnitTest.java b/libraries-security/src/test/java/com/baeldung/passay/PasswordGeneratorUnitTest.java new file mode 100644 index 0000000000..ff279e9317 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/passay/PasswordGeneratorUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.passay; + +import org.junit.Assert; +import org.junit.Test; +import org.passay.CharacterData; +import org.passay.CharacterRule; +import org.passay.EnglishCharacterData; +import org.passay.PasswordGenerator; + +import java.util.stream.Stream; + +public class PasswordGeneratorUnitTest { + + @Test + public void givenDigitsGenerator_whenGeneratingPassword_thenPasswordContainsDigitsHasLength10() { + CharacterRule digits = new CharacterRule(EnglishCharacterData.Digit); + + PasswordGenerator passwordGenerator = new PasswordGenerator(); + String password = passwordGenerator.generatePassword(10, digits); + + Assert.assertTrue(password.length() == 10); + Assert.assertTrue(containsOnlyCharactersFromSet(password, "0123456789")); + } + + @Test + public void givenCustomizedRule_whenGenerating_thenGeneratedPasswordContainsCustomizedCharacters() { + CharacterRule specialCharacterRule = new CharacterRule(new CharacterData() { + @Override + public String getErrorCode() { + return "SAMPLE_ERROR_CODE"; + } + + @Override + public String getCharacters() { + return "ABCxyz123!@#"; + } + }); + + PasswordGenerator passwordGenerator = new PasswordGenerator(); + String password = passwordGenerator.generatePassword(10, specialCharacterRule); + + Assert.assertTrue(containsOnlyCharactersFromSet(password, "ABCxyz123!@#")); + } + + private boolean containsOnlyCharactersFromSet(String password, String setOfCharacters) { + return Stream.of(password.split("")) + .allMatch(it -> setOfCharacters.contains(it)); + } + +} diff --git a/libraries-security/src/test/java/com/baeldung/passay/PasswordValidatorUnitTest.java b/libraries-security/src/test/java/com/baeldung/passay/PasswordValidatorUnitTest.java new file mode 100644 index 0000000000..3fc59a82d5 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/passay/PasswordValidatorUnitTest.java @@ -0,0 +1,81 @@ +package com.baeldung.passay; + +import org.junit.Assert; +import org.junit.Test; +import org.passay.LengthRule; +import org.passay.MessageResolver; +import org.passay.PasswordData; +import org.passay.PasswordValidator; +import org.passay.PropertiesMessageResolver; +import org.passay.RuleResult; +import org.passay.RuleResultDetail; +import org.passay.RuleResultMetadata; +import org.passay.WhitespaceRule; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URL; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class PasswordValidatorUnitTest { + + @Test + public void givenPasswordValidatorWithLengthRule_whenValidation_thenTooShortPassword() { + PasswordData passwordData = new PasswordData("1234"); + + PasswordValidator passwordValidator = new PasswordValidator(new LengthRule(5)); + + RuleResult validate = passwordValidator.validate(passwordData); + assertEquals(false, validate.isValid()); + + RuleResultDetail ruleResultDetail = validate.getDetails() + .get(0); + assertEquals("TOO_SHORT", ruleResultDetail.getErrorCode()); + assertEquals(5, ruleResultDetail.getParameters() + .get("minimumLength")); + assertEquals(5, ruleResultDetail.getParameters() + .get("maximumLength")); + + Integer lengthCount = validate.getMetadata() + .getCounts() + .get(RuleResultMetadata.CountCategory.Length); + assertEquals(Integer.valueOf(4), lengthCount); + } + + @Test + public void givenPasswordValidatorWithLengthRule_whenValidation_thenTooLongPassword() { + PasswordData passwordData = new PasswordData("123456"); + + PasswordValidator passwordValidator = new PasswordValidator(new LengthRule(5)); + + RuleResult validate = passwordValidator.validate(passwordData); + assertFalse(validate.isValid()); + Assert.assertEquals("TOO_LONG", validate.getDetails() + .get(0) + .getErrorCode()); + } + + @Test + public void givenPasswordValidatorWithLengthRule_whenValidation_thenCustomizedMeesagesAvailable() throws IOException { + URL resource = this.getClass() + .getClassLoader() + .getResource("messages.properties"); + Properties props = new Properties(); + props.load(new FileInputStream(resource.getPath())); + + MessageResolver resolver = new PropertiesMessageResolver(props); + PasswordValidator validator = new PasswordValidator(resolver, new LengthRule(8, 16), new WhitespaceRule()); + + RuleResult tooShort = validator.validate(new PasswordData("XXXX")); + RuleResult tooLong = validator.validate(new PasswordData("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ")); + + assertEquals("Password must not contain less characters than 16.", validator.getMessages(tooShort) + .get(0)); + assertEquals("Password must not have more characters than 16.", validator.getMessages(tooLong) + .get(0)); + } + +} diff --git a/libraries-security/src/test/java/com/baeldung/passay/PositiveMatchingRulesUnitTest.java b/libraries-security/src/test/java/com/baeldung/passay/PositiveMatchingRulesUnitTest.java new file mode 100644 index 0000000000..0da1b43335 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/passay/PositiveMatchingRulesUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.passay; + +import org.junit.Test; +import org.passay.AllowedCharacterRule; +import org.passay.AllowedRegexRule; +import org.passay.CharacterCharacteristicsRule; +import org.passay.CharacterRule; +import org.passay.EnglishCharacterData; +import org.passay.LengthComplexityRule; +import org.passay.LengthRule; +import org.passay.PasswordData; +import org.passay.PasswordValidator; +import org.passay.RuleResult; + +import static org.junit.Assert.*; + +public class PositiveMatchingRulesUnitTest { + + @Test + public void givenPasswordValidationRules_whenValidatingPassword_thenPosswordIsNotValidWithSeveralErrors() { + PasswordValidator passwordValidator = new PasswordValidator(new AllowedCharacterRule(new char[] { 'a', 'b', 'c' }), new AllowedRegexRule("\\d{2}\\w{10}"), new CharacterRule(EnglishCharacterData.LowerCase, 5), new LengthRule(8, 10)); + + RuleResult validate = passwordValidator.validate(new PasswordData("12abc")); + + assertFalse(validate.isValid()); + assertEquals("ALLOWED_CHAR:{illegalCharacter=1, matchBehavior=contains}", getDetail(validate, 0)); + assertEquals("ALLOWED_CHAR:{illegalCharacter=2, matchBehavior=contains}", getDetail(validate, 1)); + assertEquals("ALLOWED_MATCH:{pattern=\\d{2}\\w{10}}", getDetail(validate, 2)); + assertEquals("INSUFFICIENT_LOWERCASE:{" + "minimumRequired=5, matchingCharacterCount=3, " + "validCharacters=abcdefghijklmnopqrstuvwxyz, " + "matchingCharacters=abc}", getDetail(validate, 3)); + assertEquals("TOO_SHORT:{minimumLength=8, maximumLength=10}", getDetail(validate, 4)); + } + + @Test + public void givenRulesForDifferentPasswordLength_whenValidatingTwoDifferentPassword_thenBothOfThemAreInvalid() { + PasswordData shortPassword = new PasswordData("12ab"); + PasswordData longPassword = new PasswordData("1234abcde"); + + LengthComplexityRule lengthComplexityRule = new LengthComplexityRule(); + lengthComplexityRule.addRules("[1,5]", new CharacterRule(EnglishCharacterData.LowerCase, 5)); + lengthComplexityRule.addRules("[6,10]", new AllowedCharacterRule(new char[] { 'a', 'b', 'c', 'd' })); + + PasswordValidator passwordValidator = new PasswordValidator(lengthComplexityRule); + + RuleResult validateShort = passwordValidator.validate(shortPassword); + RuleResult validateLong = passwordValidator.validate(longPassword); + + assertFalse(validateShort.isValid()); + assertFalse(validateLong.isValid()); + + assertEquals("INSUFFICIENT_LOWERCASE:{" + "minimumRequired=5, " + "matchingCharacterCount=2, " + "validCharacters=abcdefghijklmnopqrstuvwxyz, " + "matchingCharacters=ab}", getDetail(validateShort, 0)); + assertEquals("ALLOWED_CHAR:{illegalCharacter=1, matchBehavior=contains}", getDetail(validateLong, 0)); + } + + @Test + public void givenCharacterCharacteristicsRule_whenValidatingPassword_thenItIsInvalidAsItBreaksToManyRules() { + PasswordData shortPassword = new PasswordData(); + shortPassword.setPassword("12345abcde!"); + + CharacterCharacteristicsRule characterCharacteristicsRule = new CharacterCharacteristicsRule(4, new CharacterRule(EnglishCharacterData.LowerCase, 5), new CharacterRule(EnglishCharacterData.UpperCase, 5), new CharacterRule(EnglishCharacterData.Digit), + new CharacterRule(EnglishCharacterData.Special)); + + PasswordValidator passwordValidator = new PasswordValidator(characterCharacteristicsRule); + + RuleResult validate = passwordValidator.validate(shortPassword); + assertFalse(validate.isValid()); + + assertEquals("INSUFFICIENT_UPPERCASE:{" + "minimumRequired=5, " + "matchingCharacterCount=0, " + "validCharacters=ABCDEFGHIJKLMNOPQRSTUVWXYZ, " + "matchingCharacters=}", getDetail(validate, 0)); + assertEquals("INSUFFICIENT_CHARACTERISTICS:{" + "successCount=3, " + "minimumRequired=4, " + "ruleCount=4}", getDetail(validate, 1)); + } + + private String getDetail(RuleResult validate, int i) { + return validate.getDetails() + .get(i) + .toString(); + } +} diff --git a/libraries-security/src/test/resources/messages.properties b/libraries-security/src/test/resources/messages.properties new file mode 100644 index 0000000000..ad0039d71d --- /dev/null +++ b/libraries-security/src/test/resources/messages.properties @@ -0,0 +1,2 @@ +TOO_LONG=Password must not have more characters than %2$s. +TOO_SHORT=Password must not contain less characters than %2$s. \ No newline at end of file From 191b27a8c5d038b30b1febc17619183f352e80a7 Mon Sep 17 00:00:00 2001 From: Vaibhav Sahay Date: Sat, 29 Sep 2018 15:22:22 +0530 Subject: [PATCH 37/82] initial commit --- .../algorithms/mergesort/MergeSort.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java b/algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java new file mode 100644 index 0000000000..0deb48b6a0 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java @@ -0,0 +1,50 @@ +package com.baeldung.algorithms.mergesort; + +public class MergeSort { + + public static void main(String[] args) { + int[] a = { 5, 1, 6, 2, 3, 4 }; + mergeSort(a, a.length); + for (int i = 0; i < a.length; i++) + System.out.println(a[i]); + } + + public static void mergeSort(int[] a, int n) { + if (n < 2) + return; + int mid = n / 2; + int[] l = new int[mid]; + int[] r = new int[n - mid]; + + for (int i = 0; i < mid; i++) { + l[i] = a[i]; + } + for (int i = mid; i < n; i++) { + r[i - mid] = a[i]; + } + mergeSort(l, mid); + mergeSort(r, n - mid); + + merge(a, l, r, mid, n - mid); + } + + public static void merge(int[] a, int[] l, int[] r, int left, int right) { + + int i = 0, j = 0, k = 0; + + while (i < left && j < right) { + + if (l[i] < r[j]) + a[k++] = l[i++]; + else + a[k++] = r[j++]; + + } + + while (i < left) + a[k++] = l[i++]; + + while (j < right) + a[k++] = r[j++]; + } +} From 5db1d97f8f0c8d0f72eced10d672bf77a095ce6a Mon Sep 17 00:00:00 2001 From: Vaibhav Sahay Date: Sat, 29 Sep 2018 15:24:09 +0530 Subject: [PATCH 38/82] initial commit --- .../algorithms/mergesort/MergeSortTest.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java new file mode 100644 index 0000000000..64916fdc08 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java @@ -0,0 +1,26 @@ +package com.baeldung.algorithms.mergesort; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + + +class MergeSortTest { + + @Test + void positiveTest() { + int[] input = { 5, 1, 6, 2, 3, 4 }; + int[] expected = { 1, 2, 3, 4, 5, 6 }; + MergeSort.mergeSort(input, input.length); + assertArrayEquals(expected, input); + } + + @Test + void negativeTest() { + int[] input = { 5, 1, 6, 2, 3, 4 }; + int[] expected = { 1, 2, 3, 4, 6 ,5}; + MergeSort.mergeSort(input, input.length); + assertArrayEquals(expected, input); + } + +} From d01ab8e3eb3969a3165063467ff008f98c7d2028 Mon Sep 17 00:00:00 2001 From: Vaibhav Sahay Date: Sat, 29 Sep 2018 15:37:34 +0530 Subject: [PATCH 39/82] removed negative test --- .../com/baeldung/algorithms/mergesort/MergeSortTest.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java index 64916fdc08..a367c8eeee 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java @@ -15,12 +15,4 @@ class MergeSortTest { assertArrayEquals(expected, input); } - @Test - void negativeTest() { - int[] input = { 5, 1, 6, 2, 3, 4 }; - int[] expected = { 1, 2, 3, 4, 6 ,5}; - MergeSort.mergeSort(input, input.length); - assertArrayEquals(expected, input); - } - } From 681815d97f4051ec7467d570c8d3cbd4742d6e6b Mon Sep 17 00:00:00 2001 From: Vaibhav Sahay Date: Sat, 29 Sep 2018 15:44:14 +0530 Subject: [PATCH 40/82] Deleted MergeSortTest.java --- .../algorithms/mergesort/MergeSortTest.java | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java deleted file mode 100644 index a367c8eeee..0000000000 --- a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.algorithms.mergesort; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.Test; - - -class MergeSortTest { - - @Test - void positiveTest() { - int[] input = { 5, 1, 6, 2, 3, 4 }; - int[] expected = { 1, 2, 3, 4, 5, 6 }; - MergeSort.mergeSort(input, input.length); - assertArrayEquals(expected, input); - } - -} From 6a3eec15e55541876a951543a0e6584f18eb83cc Mon Sep 17 00:00:00 2001 From: Vaibhav Sahay Date: Sat, 29 Sep 2018 16:06:30 +0530 Subject: [PATCH 41/82] Unit test for MergeSort --- .../algorithms/mergesort/MergeSortTest.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java new file mode 100644 index 0000000000..5c304ba7fe --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java @@ -0,0 +1,25 @@ +package com.baeldung.algorithms.mergesort; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class MergeSortTest { + + @Test + void positiveTest() { + int[] input = { 5, 1, 6, 2, 3, 4 }; + int[] expected = { 1, 2, 3, 4, 5, 6 }; + MergeSort.mergeSort(input, input.length); + assertArrayEquals(expected, input); + } + + @Test + void negativeTest() { + int[] input = { 5, 1, 6, 2, 3, 4 }; + int[] expected = { 1, 2, 3, 4, 6, 5 }; + MergeSort.mergeSort(input, input.length); + assertArrayEquals(expected, input); + } + +} From 575dcc38409110819d7af51a8189d8bab475c506 Mon Sep 17 00:00:00 2001 From: Vaibhav Sahay Date: Sat, 29 Sep 2018 16:15:54 +0530 Subject: [PATCH 42/82] Updated the imports --- .../algorithms/mergesort/MergeSortTest.java | 25 ------------------ .../mergesort/MergeSortUnitTest.java | 26 +++++++++++++++++++ 2 files changed, 26 insertions(+), 25 deletions(-) delete mode 100644 algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java deleted file mode 100644 index 5c304ba7fe..0000000000 --- a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.algorithms.mergesort; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.Test; - -class MergeSortTest { - - @Test - void positiveTest() { - int[] input = { 5, 1, 6, 2, 3, 4 }; - int[] expected = { 1, 2, 3, 4, 5, 6 }; - MergeSort.mergeSort(input, input.length); - assertArrayEquals(expected, input); - } - - @Test - void negativeTest() { - int[] input = { 5, 1, 6, 2, 3, 4 }; - int[] expected = { 1, 2, 3, 4, 6, 5 }; - MergeSort.mergeSort(input, input.length); - assertArrayEquals(expected, input); - } - -} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java new file mode 100644 index 0000000000..c46bac041f --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.algorithms.mergesort; + +import org.junit.Assert; + +import org.junit.Test; + +public class MergeSortUnitTest { + + @Test + public void positiveTest() { + int[] actual = { 5, 1, 6, 2, 3, 4 }; + int[] expected = { 1, 2, 3, 4, 5, 6 }; + MergeSort.mergeSort(actual, actual.length); + Assert.assertArrayEquals(expected, actual); + } + + @Test + public void negativeTest() { + int[] actual = { 5, 1, 6, 2, 3, 4 }; + int[] expected = { 1, 2, 3, 4, 6, 5 }; + MergeSort.mergeSort(actual, actual.length); + Assert.assertArrayEquals(expected, actual); + + } + +} From ea4b5c8636e58a3960d25107dec22b4b0c2fbd92 Mon Sep 17 00:00:00 2001 From: Vaibhav Sahay Date: Sat, 29 Sep 2018 16:19:45 +0530 Subject: [PATCH 43/82] removed negative test --- .../baeldung/algorithms/mergesort/MergeSortUnitTest.java | 9 --------- 1 file changed, 9 deletions(-) diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java index c46bac041f..5cd14b7bd0 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java @@ -14,13 +14,4 @@ public class MergeSortUnitTest { Assert.assertArrayEquals(expected, actual); } - @Test - public void negativeTest() { - int[] actual = { 5, 1, 6, 2, 3, 4 }; - int[] expected = { 1, 2, 3, 4, 6, 5 }; - MergeSort.mergeSort(actual, actual.length); - Assert.assertArrayEquals(expected, actual); - - } - } From 33ca802287284180b4ea21bc5a8526c618d940b4 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 29 Sep 2018 14:38:45 +0300 Subject: [PATCH 44/82] update jsf --- spring-boot-mvc/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index 169c9509b5..65d23ebfc6 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -27,7 +27,7 @@ org.glassfish javax.faces - 2.2.8-30 + 2.3.7 From 258532c40fb06a81ed754b4591ff619472377e8d Mon Sep 17 00:00:00 2001 From: Alejandro Gervasio Date: Sat, 29 Sep 2018 11:04:18 -0300 Subject: [PATCH 45/82] BAEL-2253 - Difference Between @NotNull, @NotEmpty and @NotBlank Constraints in Bean Validation (#5310) * Initial Commit * Update UserNotBlankUnitTest.java * Update UserNotEmptyUnitTest.java * Update UserNotNullUnitTest.java --- javaxval/pom.xml | 126 ++++++++++-------- .../appplication/Application.java | 14 ++ .../entities/UserNotBlank.java | 22 +++ .../entities/UserNotEmpty.java | 22 +++ .../entities/UserNotNull.java | 22 +++ .../test/UserNotBlankUnitTest.java | 63 +++++++++ .../test/UserNotEmptyUnitTest.java | 54 ++++++++ .../test/UserNotNullUnitTest.java | 54 ++++++++ 8 files changed, 323 insertions(+), 54 deletions(-) create mode 100644 javaxval/src/main/java/org/baeldung/javabeanconstraints/appplication/Application.java create mode 100644 javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotBlank.java create mode 100644 javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotEmpty.java create mode 100644 javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotNull.java create mode 100644 javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotBlankUnitTest.java create mode 100644 javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotEmptyUnitTest.java create mode 100644 javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotNullUnitTest.java diff --git a/javaxval/pom.xml b/javaxval/pom.xml index 7af766261b..63cb4c1d1d 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -1,55 +1,73 @@ - - 4.0.0 - com.baeldung - javaxval - 0.1-SNAPSHOT - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - - org.hibernate - hibernate-validator-annotation-processor - ${hibernate-validator.version} - - - javax.el - javax.el-api - ${javax.el-api.version} - - - org.glassfish.web - javax.el - ${javax.el.version} - - - org.springframework - spring-context - ${org.springframework.version} - - - org.springframework - spring-test - ${org.springframework.version} - - - - - 2.0.1.Final - 6.0.7.Final - 3.0.0 - 2.2.6 - 5.0.2.RELEASE - - + + 4.0.0 + com.baeldung + javaxval + 0.1-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + javax.validation + validation-api + ${validation-api.version} + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + org.hibernate + hibernate-validator-annotation-processor + ${hibernate-validator.version} + + + javax.el + javax.el-api + ${javax.el-api.version} + + + org.glassfish.web + javax.el + ${javax.el.version} + + + org.springframework + spring-context + ${org.springframework.version} + + + org.springframework + spring-test + ${org.springframework.version} + + + junit + junit + ${junit.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 2.0.1.Final + 6.0.7.Final + 3.0.0 + 2.2.6 + 5.0.2.RELEASE + 4.12 + 3.11.1 + \ No newline at end of file diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/appplication/Application.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/appplication/Application.java new file mode 100644 index 0000000000..c9f2ab6f98 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/appplication/Application.java @@ -0,0 +1,14 @@ +package org.baeldung.javabeanconstraints.appplication; + +import javax.validation.Validation; +import javax.validation.Validator; +import org.baeldung.javabeanconstraints.entities.UserNotBlank; + +public class Application { + + public static void main(String[] args) throws Exception { + Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); + UserNotBlank user = new UserNotBlank(" "); + validator.validate(user).stream().forEach(violation -> System.out.println(violation.getMessage())); + } +} diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotBlank.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotBlank.java new file mode 100644 index 0000000000..2ea6a3af56 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotBlank.java @@ -0,0 +1,22 @@ +package org.baeldung.javabeanconstraints.entities; + +import javax.validation.constraints.NotBlank; + +public class UserNotBlank { + + @NotBlank(message = "Name is mandatory") + private final String name; + + public UserNotBlank(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "User{" + "name=" + name + "}"; + } +} diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotEmpty.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotEmpty.java new file mode 100644 index 0000000000..39e34b63d3 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotEmpty.java @@ -0,0 +1,22 @@ +package org.baeldung.javabeanconstraints.entities; + +import javax.validation.constraints.NotEmpty; + +public class UserNotEmpty { + + @NotEmpty(message = "Name is mandatory") + private final String name; + + public UserNotEmpty(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "User{" + "name=" + name + "}"; + } +} diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotNull.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotNull.java new file mode 100644 index 0000000000..598c9ba9f9 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/entities/UserNotNull.java @@ -0,0 +1,22 @@ +package org.baeldung.javabeanconstraints.entities; + +import javax.validation.constraints.NotNull; + +public class UserNotNull { + + @NotNull(message = "Name is mandatory") + private final String name; + + public UserNotNull(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return "User{" + "name=" + name + "}"; + } +} diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotBlankUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotBlankUnitTest.java new file mode 100644 index 0000000000..954833fef1 --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotBlankUnitTest.java @@ -0,0 +1,63 @@ +package org.baeldung.javabeanconstraints.test; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import static org.assertj.core.api.Assertions.assertThat; +import org.baeldung.javabeanconstraints.entities.UserNotBlank; +import org.junit.BeforeClass; +import org.junit.Test; + +public class UserNotBlankUnitTest { + + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenNotBlankName_thenNoConstraintViolations() { + UserNotBlank user = new UserNotBlank("John"); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenBlankName_thenOneConstraintViolation() { + UserNotBlank user = new UserNotBlank(" "); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenEmptyName_thenOneConstraintViolation() { + UserNotBlank user = new UserNotBlank(""); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenNullName_thenOneConstraintViolation() { + UserNotBlank user = new UserNotBlank(null); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenToString_thenCorrect() { + UserNotBlank user = new UserNotBlank("John"); + + assertThat(user.toString()).isEqualTo("User{name=John}"); + } +} diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotEmptyUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotEmptyUnitTest.java new file mode 100644 index 0000000000..c2675ed8b6 --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotEmptyUnitTest.java @@ -0,0 +1,54 @@ +package org.baeldung.javabeanconstraints.test; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import static org.assertj.core.api.Assertions.assertThat; +import org.baeldung.javabeanconstraints.entities.UserNotEmpty; +import org.junit.BeforeClass; +import org.junit.Test; + +public class UserNotEmptyUnitTest { + + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenNotEmptyName_thenNoConstraintViolations() { + UserNotEmpty user = new UserNotEmpty("John"); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenEmptyName_thenOneConstraintViolation() { + UserNotEmpty user = new UserNotEmpty(""); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenNullName_thenOneConstraintViolation() { + UserNotEmpty user = new UserNotEmpty(null); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenToString_thenCorrect() { + UserNotEmpty user = new UserNotEmpty("John"); + + assertThat(user.toString()).isEqualTo("User{name=John}"); + } +} diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotNullUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotNullUnitTest.java new file mode 100644 index 0000000000..3dd1811947 --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/test/UserNotNullUnitTest.java @@ -0,0 +1,54 @@ +package org.baeldung.javabeanconstraints.test; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import static org.assertj.core.api.Assertions.assertThat; +import org.baeldung.javabeanconstraints.entities.UserNotNull; +import org.junit.BeforeClass; +import org.junit.Test; + +public class UserNotNullUnitTest { + + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenNotNullName_thenNoConstraintViolations() { + UserNotNull user = new UserNotNull("John"); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenNullName_thenOneConstraintViolation() { + UserNotNull user = new UserNotNull(null); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(1); + } + + @Test + public void whenEmptyName_thenNoConstraintViolations() { + UserNotNull user = new UserNotNull(""); + + Set> violations = validator.validate(user); + + assertThat(violations.size()).isEqualTo(0); + } + + @Test + public void whenToString_thenCorrect() { + UserNotNull user = new UserNotNull("John"); + + assertThat(user.toString()).isEqualTo("User{name=John}"); + } +} From 2af9eb89f18557e566c2b9cdd0218b5a01745b99 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 29 Sep 2018 21:12:21 +0530 Subject: [PATCH 46/82] [BAEL-9017] - Fixed conflicts --- .../{AppTest.java => AppUnitTest.java} | 6 +++--- ...erviceTest.java => MyServiceUnitTest.java} | 4 ++-- ...Test.java => EmployeeServiceUnitTest.java} | 2 +- ...viceTest.java => UserServiceLiveTest.java} | 2 +- ...ateDiffTest.java => DateDiffUnitTest.java} | 2 +- pom.xml | 20 +++++++++---------- .../{AppTest.java => AppLiveTest.java} | 6 +++--- ....java => GroovyConfigurationUnitTest.java} | 2 +- ...st.java => JavaConfigurationUnitTest.java} | 2 +- ...est.java => XmlConfigurationUnitTest.java} | 2 +- .../{AppTest.java => AppUnitTest.java} | 6 +++--- .../pmd/{CntTest.java => CntUnitTest.java} | 2 +- 12 files changed, 28 insertions(+), 28 deletions(-) rename animal-sniffer-mvn-plugin/src/test/java/com/baeldung/{AppTest.java => AppUnitTest.java} (81%) rename guest/log4j2-example/src/test/java/com/stackify/services/{MyServiceTest.java => MyServiceUnitTest.java} (98%) rename guest/logback-example/src/test/java/com/stackify/services/{EmployeeServiceTest.java => EmployeeServiceUnitTest.java} (98%) rename guest/webservices/rest-server/src/test/java/com/stackify/services/{UserServiceTest.java => UserServiceLiveTest.java} (95%) rename java-difference-date/src/test/java/com/baeldung/{DateDiffTest.java => DateDiffUnitTest.java} (98%) rename rest-with-spark-java/src/test/java/com/baeldung/{AppTest.java => AppLiveTest.java} (96%) rename spring-groovy/src/test/java/com/baeldug/groovyconfig/{GroovyConfigurationTest.java => GroovyConfigurationUnitTest.java} (97%) rename spring-groovy/src/test/java/com/baeldug/groovyconfig/{JavaConfigurationTest.java => JavaConfigurationUnitTest.java} (93%) rename spring-groovy/src/test/java/com/baeldug/groovyconfig/{XmlConfigurationTest.java => XmlConfigurationUnitTest.java} (94%) rename spring-groovy/src/test/java/com/baeldug/spring_groovy/{AppTest.java => AppUnitTest.java} (82%) rename static-analysis/src/test/java/com/baeldung/pmd/{CntTest.java => CntUnitTest.java} (92%) diff --git a/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java b/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java similarity index 81% rename from animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java rename to animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java index 8ecb1bc629..dcfd22ff87 100644 --- a/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java +++ b/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java @@ -7,7 +7,7 @@ import junit.framework.TestSuite; /** * Unit test for simple App. */ -public class AppTest +public class AppUnitTest extends TestCase { /** @@ -15,7 +15,7 @@ public class AppTest * * @param testName name of the test case */ - public AppTest( String testName ) + public AppUnitTest( String testName ) { super( testName ); } @@ -25,7 +25,7 @@ public class AppTest */ public static Test suite() { - return new TestSuite( AppTest.class ); + return new TestSuite( AppUnitTest.class ); } /** diff --git a/guest/log4j2-example/src/test/java/com/stackify/services/MyServiceTest.java b/guest/log4j2-example/src/test/java/com/stackify/services/MyServiceUnitTest.java similarity index 98% rename from guest/log4j2-example/src/test/java/com/stackify/services/MyServiceTest.java rename to guest/log4j2-example/src/test/java/com/stackify/services/MyServiceUnitTest.java index 49e367e45b..bd08225be4 100644 --- a/guest/log4j2-example/src/test/java/com/stackify/services/MyServiceTest.java +++ b/guest/log4j2-example/src/test/java/com/stackify/services/MyServiceUnitTest.java @@ -18,9 +18,9 @@ import org.junit.Test; import com.stackify.models.User; import com.stackify.services.MyService; -public class MyServiceTest { +public class MyServiceUnitTest { - private static final Logger logger = LogManager.getLogger(MyServiceTest.class); + private static final Logger logger = LogManager.getLogger(MyServiceUnitTest.class); @Test public void testService() { diff --git a/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java b/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceUnitTest.java similarity index 98% rename from guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java rename to guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceUnitTest.java index 187b27e1df..a3051f7087 100644 --- a/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceTest.java +++ b/guest/logback-example/src/test/java/com/stackify/services/EmployeeServiceUnitTest.java @@ -9,7 +9,7 @@ import com.stackify.models.Employee; import ch.qos.logback.classic.Level; -public class EmployeeServiceTest { +public class EmployeeServiceUnitTest { private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); private EmployeeService employeeService = new EmployeeService(); diff --git a/guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceTest.java b/guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceLiveTest.java similarity index 95% rename from guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceTest.java rename to guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceLiveTest.java index 064951fbbe..be3992b7f7 100644 --- a/guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceTest.java +++ b/guest/webservices/rest-server/src/test/java/com/stackify/services/UserServiceLiveTest.java @@ -6,7 +6,7 @@ import io.restassured.RestAssured; import static io.restassured.RestAssured.*; import static org.hamcrest.CoreMatchers.*; -public class UserServiceTest { +public class UserServiceLiveTest { @Test public void whenAddUser_thenGetUserOk() { RestAssured.baseURI = "http://localhost:8080/rest-server"; diff --git a/java-difference-date/src/test/java/com/baeldung/DateDiffTest.java b/java-difference-date/src/test/java/com/baeldung/DateDiffUnitTest.java similarity index 98% rename from java-difference-date/src/test/java/com/baeldung/DateDiffTest.java rename to java-difference-date/src/test/java/com/baeldung/DateDiffUnitTest.java index 4203f7ef38..2c5323be6f 100644 --- a/java-difference-date/src/test/java/com/baeldung/DateDiffTest.java +++ b/java-difference-date/src/test/java/com/baeldung/DateDiffUnitTest.java @@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; -public class DateDiffTest { +public class DateDiffUnitTest { @Test public void givenTwoDatesBeforeJava8_whenDifferentiating_thenWeGetSix() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); diff --git a/pom.xml b/pom.xml index 495aeb434b..d99832db52 100644 --- a/pom.xml +++ b/pom.xml @@ -1081,8 +1081,8 @@ java-websocket - - + activejdbc + animal-sniffer-mvn-plugin apache-bval apache-shiro @@ -1098,7 +1098,7 @@ dubbo - + java-difference-date jni jooby @@ -1106,13 +1106,13 @@ ratpack - + rest-with-spark-java spring-boot-autoconfiguration spring-boot-custom-starter - + spring-boot-jasypt spring-data-rest-querydsl - + spring-groovy spring-mobile spring-mustache spring-mvc-simple @@ -1123,7 +1123,7 @@ spring-roo spring-security-stormpath sse-jaxrs - + static-analysis stripe @@ -1134,8 +1134,8 @@ - - + + @@ -1151,7 +1151,7 @@ spring-boot-h2/spring-boot-h2-database - + diff --git a/rest-with-spark-java/src/test/java/com/baeldung/AppTest.java b/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java similarity index 96% rename from rest-with-spark-java/src/test/java/com/baeldung/AppTest.java rename to rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java index c7b88dd6d1..9e24879767 100644 --- a/rest-with-spark-java/src/test/java/com/baeldung/AppTest.java +++ b/rest-with-spark-java/src/test/java/com/baeldung/AppLiveTest.java @@ -16,16 +16,16 @@ import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; -public class AppTest extends TestCase { +public class AppLiveTest extends TestCase { ObjectMapper mapper = new ObjectMapper(); - public AppTest( String testName ) { + public AppLiveTest( String testName ) { super( testName ); } public static Test suite() { - return new TestSuite( AppTest.class ); + return new TestSuite( AppLiveTest.class ); } public void testApp() throws IOException, ClassNotFoundException { diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationTest.java b/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java similarity index 97% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationTest.java rename to spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java index 91ca6dbfe9..dbefba5ba5 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationTest.java +++ b/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java @@ -7,7 +7,7 @@ import java.io.File; import org.junit.Test; import org.springframework.context.support.GenericGroovyApplicationContext; -public class GroovyConfigurationTest { +public class GroovyConfigurationUnitTest { private static final String FILE_NAME = "GroovyBeanConfig.groovy"; private static final String FILE_PATH = "src/main/java/com/baeldug/groovyconfig/"; diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationTest.java b/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java similarity index 93% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationTest.java rename to spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java index 2d9b1000ff..c1e16f1b62 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationTest.java +++ b/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java @@ -5,7 +5,7 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -public class JavaConfigurationTest { +public class JavaConfigurationUnitTest { @Test public void whenJavaConfig_thenCorrectPerson() { diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationTest.java b/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java similarity index 94% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationTest.java rename to spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java index 3ee724207c..b8d341ee39 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationTest.java +++ b/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class XmlConfigurationTest { +public class XmlConfigurationUnitTest { @Test public void whenXmlConfig_thenCorrectPerson() { diff --git a/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppTest.java b/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java similarity index 82% rename from spring-groovy/src/test/java/com/baeldug/spring_groovy/AppTest.java rename to spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java index 19eefb6c0f..3d8fa3e2d8 100644 --- a/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppTest.java +++ b/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java @@ -7,7 +7,7 @@ import junit.framework.TestSuite; /** * Unit test for simple App. */ -public class AppTest +public class AppUnitTest extends TestCase { /** @@ -15,7 +15,7 @@ public class AppTest * * @param testName name of the test case */ - public AppTest( String testName ) + public AppUnitTest( String testName ) { super( testName ); } @@ -25,7 +25,7 @@ public class AppTest */ public static Test suite() { - return new TestSuite( AppTest.class ); + return new TestSuite( AppUnitTest.class ); } /** diff --git a/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java b/static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java similarity index 92% rename from static-analysis/src/test/java/com/baeldung/pmd/CntTest.java rename to static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java index ed72602f99..cdbf9f6f5e 100644 --- a/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java +++ b/static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java @@ -4,7 +4,7 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; -public class CntTest { +public class CntUnitTest { private Cnt service; From aeb17113973b9d216a9cf9c0eb40fb79bc48d957 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 29 Sep 2018 23:22:40 +0530 Subject: [PATCH 47/82] [BAEL-9018] - Fixed malformed POMs and remaining PMD problems --- apache-avro/pom.xml | 2 +- ...> AvroSerealizerDeSerealizerUnitTest.java} | 2 +- flyway/pom.xml | 1 + ...st.java => FlywayApplicationUnitTest.java} | 2 +- guest/spring-mvc/pom.xml | 2 +- guest/spring-security/pom.xml | 2 +- pom.xml | 32 +++++++++---------- spring-custom-aop/pom.xml | 1 + 8 files changed, 23 insertions(+), 21 deletions(-) rename apache-avro/src/test/java/com/baeldung/avro/util/serealization/{AvroSerealizerDeSerealizerTest.java => AvroSerealizerDeSerealizerUnitTest.java} (98%) rename flyway/src/test/java/com/baeldung/flywaycallbacks/{FlywayApplicationTest.java => FlywayApplicationUnitTest.java} (98%) diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml index 3e3234ff96..ddf5844271 100644 --- a/apache-avro/pom.xml +++ b/apache-avro/pom.xml @@ -6,7 +6,7 @@ com.baeldung apache-avro 0.0.1-SNAPSHOT - Apache Avro + Apache Avro UTF-8 diff --git a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java similarity index 98% rename from apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java rename to apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java index ecd15ccbbc..992ea806c3 100644 --- a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java +++ b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java @@ -13,7 +13,7 @@ import java.util.Objects; import static org.junit.Assert.*; -public class AvroSerealizerDeSerealizerTest { +public class AvroSerealizerDeSerealizerUnitTest { AvroSerealizer serealizer; AvroDeSerealizer deSerealizer; diff --git a/flyway/pom.xml b/flyway/pom.xml index b1cc58af3d..353bbfb1ec 100644 --- a/flyway/pom.xml +++ b/flyway/pom.xml @@ -65,6 +65,7 @@ 5.0.2 5.0.2 + 1.4.195 diff --git a/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java b/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java similarity index 98% rename from flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java rename to flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java index 5e96fff64d..bf30ce604d 100644 --- a/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationTest.java +++ b/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java @@ -16,7 +16,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) @ContextConfiguration(classes = FlywayCallbackTestConfig.class) -public class FlywayApplicationTest { +public class FlywayApplicationUnitTest { private Log log = LogFactory.getLog(getClass()); diff --git a/guest/spring-mvc/pom.xml b/guest/spring-mvc/pom.xml index 42543b5be0..c0ef451605 100644 --- a/guest/spring-mvc/pom.xml +++ b/guest/spring-mvc/pom.xml @@ -12,7 +12,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.M5 + 2.0.0.RELEASE diff --git a/guest/spring-security/pom.xml b/guest/spring-security/pom.xml index baca3bce85..8be42ba32b 100644 --- a/guest/spring-security/pom.xml +++ b/guest/spring-security/pom.xml @@ -11,7 +11,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.M6 + 2.0.0.RELEASE diff --git a/pom.xml b/pom.xml index 495aeb434b..d322b71343 100644 --- a/pom.xml +++ b/pom.xml @@ -611,11 +611,11 @@ java-websocket activejdbc - + apache-avro apache-bval apache-shiro apache-spark - + asciidoctor checker-plugin @@ -624,7 +624,7 @@ dagger data-structures dubbo - + flyway @@ -638,7 +638,7 @@ spring-boot-autoconfiguration spring-boot-custom-starter spring-boot-jasypt - + spring-custom-aop spring-data-rest-querydsl spring-mobile @@ -667,8 +667,8 @@ - - + + jenkins/hello-world @@ -1096,9 +1096,9 @@ dagger data-structures dubbo - + flyway - + java-difference-date jni jooby @@ -1106,13 +1106,13 @@ ratpack - + rest-with-spark-java spring-boot-autoconfiguration spring-boot-custom-starter - - + spring-boot-jasypt + spring-custom-aop spring-data-rest-querydsl - + spring-groovy spring-mobile spring-mustache spring-mvc-simple @@ -1123,7 +1123,7 @@ spring-roo spring-security-stormpath sse-jaxrs - + static-analysis stripe @@ -1139,8 +1139,8 @@ - - + + jenkins/hello-world @@ -1151,7 +1151,7 @@ spring-boot-h2/spring-boot-h2-database - + diff --git a/spring-custom-aop/pom.xml b/spring-custom-aop/pom.xml index fd5f87a476..f0b1dbb5ac 100644 --- a/spring-custom-aop/pom.xml +++ b/spring-custom-aop/pom.xml @@ -149,6 +149,7 @@ 3.1.7 8.5.11 18.0 + 8.0.43 From fb34ecb351d966768e14c821adf010952aed6e29 Mon Sep 17 00:00:00 2001 From: hardik-r-shah Date: Sun, 30 Sep 2018 10:14:49 +0530 Subject: [PATCH 48/82] BAEL-2149 initial commit (#5186) * BAEL-2149 initial commit * BAEL-2149 calculate percentage --- .../percentage/PercentageCalculator.java | 21 ++++++++++++ .../PercentageCalculatorUnitTest.java | 33 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 java-numbers/src/main/java/com/baeldung/percentage/PercentageCalculator.java create mode 100644 java-numbers/src/test/java/com/baeldung/percentage/PercentageCalculatorUnitTest.java diff --git a/java-numbers/src/main/java/com/baeldung/percentage/PercentageCalculator.java b/java-numbers/src/main/java/com/baeldung/percentage/PercentageCalculator.java new file mode 100644 index 0000000000..e74de2cc67 --- /dev/null +++ b/java-numbers/src/main/java/com/baeldung/percentage/PercentageCalculator.java @@ -0,0 +1,21 @@ +package com.baeldung.percentage; + +import java.util.Scanner; + +public class PercentageCalculator { + + public double calculatePercentage(double obtained,double total){ + return obtained*100/total; + } + + public static void main(String[] args) { + PercentageCalculator pc = new PercentageCalculator(); + Scanner in = new Scanner(System.in); + System.out.println("Enter obtained marks:"); + double obtained = in.nextDouble(); + System.out.println("Enter total marks:"); + double total =in.nextDouble(); + System.out.println("Percentage obtained :"+pc.calculatePercentage(obtained,total)); + } + +} diff --git a/java-numbers/src/test/java/com/baeldung/percentage/PercentageCalculatorUnitTest.java b/java-numbers/src/test/java/com/baeldung/percentage/PercentageCalculatorUnitTest.java new file mode 100644 index 0000000000..202d4f8112 --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/percentage/PercentageCalculatorUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.percentage; + +import org.junit.Assert; +import org.junit.Test; + +public class PercentageCalculatorUnitTest { + private PercentageCalculator pc = new PercentageCalculator(); + + @Test + public void whenPass2Integers_thenShouldCalculatePercentage(){ + Assert.assertEquals("Result not as expected", + 50.0,pc.calculatePercentage(50,100),0.1); + } + + @Test + public void whenPassObtainedMarksAsDouble_thenShouldCalculatePercentage(){ + Assert.assertEquals("Result not as expected",5.05, + pc.calculatePercentage(50.5,1000),0.1); + } + + @Test + public void whenPassTotalMarksAsDouble_thenShouldCalculatePercentage(){ + Assert.assertEquals("Result not as expected",19.6, + pc.calculatePercentage(5,25.5),0.1); + } + + @Test + public void whenPass2DoubleNumbers_thenShouldCalculatePercentage(){ + Assert.assertEquals("Result not as expected",20, + pc.calculatePercentage(5.5,27.5),0.1); + } + +} From ac15191bf624c7a51454edbd4ff55d7a94692ffe Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 30 Sep 2018 10:42:59 +0530 Subject: [PATCH 49/82] [BAEL-9017] - Uncommented PMD violations from default profile --- pom.xml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pom.xml b/pom.xml index d99832db52..9076867362 100644 --- a/pom.xml +++ b/pom.xml @@ -610,7 +610,7 @@ java-websocket activejdbc - + animal-sniffer-mvn-plugin apache-bval apache-shiro @@ -626,7 +626,7 @@ dubbo - + java-difference-date jni jooby @@ -634,13 +634,13 @@ ratpack - + rest-with-spark-java spring-boot-autoconfiguration spring-boot-custom-starter spring-boot-jasypt spring-data-rest-querydsl - + spring-groovy spring-mobile spring-mustache spring-mvc-simple @@ -651,7 +651,7 @@ spring-roo spring-security-stormpath sse-jaxrs - + static-analysis stripe Twitter4J @@ -662,8 +662,8 @@ - - + + @@ -679,7 +679,7 @@ spring-boot-h2/spring-boot-h2-database - + From d475578d3b68d35ae26c90bbb2ede77b71b1874a Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 30 Sep 2018 08:45:49 +0300 Subject: [PATCH 50/82] Update pom.xml --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 97d1b1dff5..8fb43ead16 100644 --- a/pom.xml +++ b/pom.xml @@ -1083,11 +1083,11 @@ java-websocket activejdbc animal-sniffer-mvn-plugin - + apache-avro apache-bval apache-shiro apache-spark - + asciidoctor checker-plugin From 8cff5212f90d44ebc88c999cb235304399012e49 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 30 Sep 2018 11:13:35 +0300 Subject: [PATCH 51/82] update read file test --- .../com/baeldung/file/FileOperationsManualTest.java | 11 ++++++----- core-java-io/src/test/resources/fileTest.txt | 1 + 2 files changed, 7 insertions(+), 5 deletions(-) create mode 100644 core-java-io/src/test/resources/fileTest.txt diff --git a/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java index 6a020f5eae..faa6b0ae8d 100644 --- a/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java +++ b/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java @@ -15,9 +15,11 @@ import java.io.InputStreamReader; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; +import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; @@ -50,7 +52,7 @@ public class FileOperationsManualTest { @Test public void givenFileName_whenUsingJarFile_thenFileData() throws IOException { - String expectedData = "BSD License"; + String expectedData = "MIT License"; Class clazz = Matchers.class; InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt"); @@ -79,7 +81,7 @@ public class FileOperationsManualTest { ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("fileTest.txt").getFile()); - String data = FileUtils.readFileToString(file); + String data = FileUtils.readFileToString(file, "UTF-8"); assertEquals(expectedData, data.trim()); } @@ -102,12 +104,11 @@ public class FileOperationsManualTest { Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); - StringBuilder data = new StringBuilder(); Stream lines = Files.lines(path); - lines.forEach(line -> data.append(line).append("\n")); + String data = lines.collect(Collectors.joining("\n")); lines.close(); - assertEquals(expectedData, data.toString().trim()); + assertEquals(expectedData, data.trim()); } private String readFromInputStream(InputStream inputStream) throws IOException { diff --git a/core-java-io/src/test/resources/fileTest.txt b/core-java-io/src/test/resources/fileTest.txt new file mode 100644 index 0000000000..ce4bea208b --- /dev/null +++ b/core-java-io/src/test/resources/fileTest.txt @@ -0,0 +1 @@ +Hello World from fileTest.txt!!! \ No newline at end of file From dcf5a40c3fa2f4972b9e119de51a54463e417703 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 30 Sep 2018 11:14:54 +0300 Subject: [PATCH 52/82] remove import --- .../test/java/com/baeldung/file/FileOperationsManualTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java index faa6b0ae8d..e781489808 100644 --- a/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java +++ b/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java @@ -15,7 +15,6 @@ import java.io.InputStreamReader; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; -import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; From 75430b99f2680f71b52e3d339910617c23c9cee1 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 30 Sep 2018 13:37:09 +0300 Subject: [PATCH 53/82] add calc age test --- .../java/com/baeldung/date/AgeCalculator.java | 32 +++++++++++++++++++ .../baeldung/date/AgeCalculatorUnitTest.java | 31 ++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 java-dates/src/main/java/com/baeldung/date/AgeCalculator.java create mode 100644 java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java diff --git a/java-dates/src/main/java/com/baeldung/date/AgeCalculator.java b/java-dates/src/main/java/com/baeldung/date/AgeCalculator.java new file mode 100644 index 0000000000..c031c97dec --- /dev/null +++ b/java-dates/src/main/java/com/baeldung/date/AgeCalculator.java @@ -0,0 +1,32 @@ +package com.baeldung.date; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.Period; +import java.util.Date; +import org.joda.time.Years; + +public class AgeCalculator { + + public int calculateAge(LocalDate birthDate, LocalDate currentDate) { + // validate inputs ... + return Period.between(birthDate, currentDate) + .getYears(); + } + + public int calculateAgeWithJodaTime(org.joda.time.LocalDate birthDate, org.joda.time.LocalDate currentDate) { + // validate inputs ... + Years age = Years.yearsBetween(birthDate, currentDate); + return age.getYears(); + } + + public int calculateAgeWithJava7(Date birthDate, Date currentDate) { + // validate inputs ... + DateFormat formatter = new SimpleDateFormat("yyyyMMdd"); + int d1 = Integer.parseInt(formatter.format(birthDate)); + int d2 = Integer.parseInt(formatter.format(currentDate)); + int age = (d2 - d1) / 10000; + return age; + } +} \ No newline at end of file diff --git a/java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java b/java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java new file mode 100644 index 0000000000..dcd261337c --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/date/AgeCalculatorUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.date; + +import static org.junit.Assert.assertEquals; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.Date; +import org.junit.jupiter.api.Test; + +public class AgeCalculatorUnitTest { + AgeCalculator ageCalculator = new AgeCalculator(); + + @Test + public void givenLocalDate_whenCalculateAge_thenOk() { + assertEquals(10, ageCalculator.calculateAge(LocalDate.of(2008, 5, 20), LocalDate.of(2018, 9, 20))); + } + + @Test + public void givenJodaTime_whenCalculateAge_thenOk() { + assertEquals(10, ageCalculator.calculateAgeWithJodaTime(new org.joda.time.LocalDate(2008, 5, 20), new org.joda.time.LocalDate(2018, 9, 20))); + } + + @Test + public void givenDate_whenCalculateAge_thenOk() throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); + Date birthDate = sdf.parse("2008-05-20"); + Date currentDate = sdf.parse("2018-09-20"); + assertEquals(10, ageCalculator.calculateAgeWithJava7(birthDate, currentDate)); + } + +} \ No newline at end of file From 5c36405c1ff8fb8a89ceb25cc66f8edb83cd537a Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sun, 30 Sep 2018 19:31:56 +0530 Subject: [PATCH 54/82] BAEL-9148 Fix Java EE Annotations Project - Removed JavaEEAnnotationsSample project from inside src/main/java/com/baeldung/javaeeannotations folder of jee-7 module - Moved sources and jsps to jee-7 main module --- jee-7/README.md | 1 + jee-7/pom.xml | 2 +- .../AccountServlet.java | 2 +- .../BankAppServletContextListener.java | 2 +- .../JavaEEAnnotationsSample/README.txt | 76 ------------------- .../JavaEEAnnotationsSample/pom.xml | 52 ------------- .../src/main/webapp/WEB-INF/web.xml | 10 --- .../src/main/webapp/login.jsp | 12 --- .../javaeeannotations => }/LogInFilter.java | 2 +- .../UploadCustomerDocumentsServlet.java | 2 +- .../webapp/index.jsp => webapp/account.jsp} | 0 .../src/main => }/webapp/upload.jsp | 0 12 files changed, 6 insertions(+), 155 deletions(-) rename jee-7/src/main/java/com/baeldung/javaeeannotations/{JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations => }/AccountServlet.java (94%) rename jee-7/src/main/java/com/baeldung/javaeeannotations/{JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations => }/BankAppServletContextListener.java (82%) delete mode 100644 jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt delete mode 100644 jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml delete mode 100644 jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml delete mode 100644 jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp rename jee-7/src/main/java/com/baeldung/javaeeannotations/{JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations => }/LogInFilter.java (90%) rename jee-7/src/main/java/com/baeldung/javaeeannotations/{JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations => }/UploadCustomerDocumentsServlet.java (90%) rename jee-7/src/main/{java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp => webapp/account.jsp} (100%) rename jee-7/src/main/{java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main => }/webapp/upload.jsp (100%) diff --git a/jee-7/README.md b/jee-7/README.md index 08a180cfa3..f0bd65fdf2 100644 --- a/jee-7/README.md +++ b/jee-7/README.md @@ -6,3 +6,4 @@ - [A Guide to Java EE Web-Related Annotations](http://www.baeldung.com/javaee-web-annotations) - [Introduction to Testing with Arquillian](http://www.baeldung.com/arquillian) - [Securing Java EE with Spring Security](http://www.baeldung.com/java-ee-spring-security) +- [A Guide to Java EE Web-Related Annotations](https://www.baeldung.com/javaee-web-annotations) \ No newline at end of file diff --git a/jee-7/pom.xml b/jee-7/pom.xml index 242fa778c0..4f6e6a20fb 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -130,7 +130,7 @@ maven-war-plugin ${maven-war-plugin.version} - webapp + src/main/webapp false diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java similarity index 94% rename from jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java rename to jee-7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java index a487d4c3b1..30dc82aa58 100644 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java +++ b/jee-7/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java @@ -1,4 +1,4 @@ -package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations; +package com.baeldung.javaeeannotations; import java.io.IOException; import java.io.PrintWriter; diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java similarity index 82% rename from jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java rename to jee-7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java index dc9a91d059..ee1b624cd1 100644 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java +++ b/jee-7/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java @@ -1,4 +1,4 @@ -package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations; +package com.baeldung.javaeeannotations; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt deleted file mode 100644 index 0f95e588b8..0000000000 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt +++ /dev/null @@ -1,76 +0,0 @@ -About the application ---------------------- -This application demonstrates the usage of JavaEE Web Annotations. - - -Contents of the application ---------------------------- -1. AccountServlet.java - Demonstrates the @WebServlet and @ServletSecurity annotation. - -NOTES: @WebServlet annotation designates the AccountServlet class as a Servlet component. - The usage of its parameters 'urlPatterns' & 'initParams' can be observed. - An initialization parameter 'type' is being set to denote the type of the bank account. - - @ServletSecurity annotation imposes security constraints on the AccountServlet based on - the tomcat-users.xml. -   - This code assumes that your tomcat-users.xml looks as follows: - - - - - - - -   -N.B : To see @ServletSecurity annotation in action, please uncomment the annotation code - for @ServletSecurity. - - -2. BankAppServletContextListener.java - Demonstrates the @WebListener annotation for denoting a class as a ServletContextListener. - -NOTES: Sets a Servlet context attribute ATTR_DEFAULT_LANGUAGE to 'english' on web application start up, - which can then be used throughout the application. - - -3. LogInFilter.java - Demonstrates the @WebFilter annotation. - -NOTES: @WebFilter annotation designates the LogInFilter class as a Filter component. - It filters all requests to the bank account servlet and redirects them to - the login page. - -N.B : To see @WebFilter annotation in action, please uncomment the annotation code for @WebFilter. - - -4. UploadCustomerDocumentsServlet.java - Demonstrates the @MultipartConfig annotation. - -NOTES: @MultipartConfig anotation designates the UploadCustomerDocumentsServlet Servlet component, - to handle multipart/form-data requests. - To see it in action, deploy the web application an access the url: http://:/JavaEEAnnotationsSample/upload.jsp - Once you upload a file from here, it will get uploaded to D:/custDocs (assuming such a folder exists). - - -5. index.jsp - This is the welcome page. - -NOTES: You can enter a deposit amount here and click on the 'Deposit' button to see the AccountServlet in action. - -6. login.jsp - All requests to the AccountServlet are redirected to this page, if the LogInFilter is imposed. - -7. upload.jsp - Demonstrates the usage of handling multipart/form-data requests by the UploadCustomerDocumentsServlet. - - -Building and Running the application ------------------------------------- -To build the application: - -1. Open the project in eclipse -2. Right click on it in eclispe and choose Run As > Maven build -3. Give 'clean install' under Goals -4. This should build the WAR file of the application - -To run the application: - -1. Right click on the project -2. Run as > Run on Server -3. This will start you Tomcat server and deploy the application (Provided that you have configured Tomcat in your eclipse) -4. You should now be able to access the url : http://:/JavaEEAnnotationsSample diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml deleted file mode 100644 index 6a0dd05180..0000000000 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - 4.0.0 - com.baeldung.javaeeannotations - JavaEEAnnotationsSample - 0.0.1-SNAPSHOT - war - JavaEEAnnotationsSample - JavaEEAnnotationsSample - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - javax.annotation - javax.annotation-api - 1.3 - - - - javax.servlet - javax.servlet-api - 3.1.0 - - - - javax.servlet.jsp - jsp-api - 2.1 - - - - - - - - org.apache.maven.plugins - maven-war-plugin - 2.4 - - src/main/webapp - SpringFieldConstructorInjection - false - - - - - JavaEEAnnotationsSample - - \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index a92885ec11..0000000000 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - BASIC - default - - diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp deleted file mode 100644 index 6892cb0420..0000000000 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp +++ /dev/null @@ -1,12 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Login - - -Login Here... - - \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java similarity index 90% rename from jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java rename to jee-7/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java index bfe1a39377..5ee420f6a2 100644 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java +++ b/jee-7/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java @@ -1,4 +1,4 @@ -package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations; +package com.baeldung.javaeeannotations; import java.io.IOException; diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java similarity index 90% rename from jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java rename to jee-7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java index 6945f663bb..28922dba46 100644 --- a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java +++ b/jee-7/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java @@ -1,4 +1,4 @@ -package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations; +package com.baeldung.javaeeannotations; import java.io.IOException; import java.io.PrintWriter; diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp b/jee-7/src/main/webapp/account.jsp similarity index 100% rename from jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp rename to jee-7/src/main/webapp/account.jsp diff --git a/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp b/jee-7/src/main/webapp/upload.jsp similarity index 100% rename from jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp rename to jee-7/src/main/webapp/upload.jsp From 91efa72938f10da095eb4d7ab477020889a947df Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 30 Sep 2018 20:58:06 +0530 Subject: [PATCH 55/82] [BAEL-9460] - Added code examples of Add section in 'Comparison with Lambdas' article --- .../com/baeldung/java8/Java8SortUnitTest.java | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java index f371c0d7da..71ec5b147f 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java @@ -1,16 +1,18 @@ package com.baeldung.java8; -import com.baeldung.java8.entity.Human; -import com.google.common.collect.Lists; -import com.google.common.primitives.Ints; -import org.junit.Assert; -import org.junit.Test; +import static org.hamcrest.Matchers.equalTo; import java.util.Collections; import java.util.Comparator; import java.util.List; +import java.util.stream.Collectors; -import static org.hamcrest.Matchers.equalTo; +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.java8.entity.Human; +import com.google.common.collect.Lists; +import com.google.common.primitives.Ints; public class Java8SortUnitTest { @@ -111,5 +113,22 @@ public class Java8SortUnitTest { humans.sort(Comparator.comparing(Human::getName)); Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12))); } + + @Test + public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { + final List letters = Lists.newArrayList("B", "A", "C"); + + final List sortedLetters = letters.stream().sorted().collect(Collectors.toList()); + Assert.assertThat(sortedLetters.get(0), equalTo("A")); + } + @Test + public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { + + final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); + final Comparator nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName()); + + final List sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList()); + Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12))); + } } From 3b4e23cedf14ce23de22b56d8346d64f8afada2b Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Sun, 30 Sep 2018 23:40:19 +0800 Subject: [PATCH 56/82] refactor some code --- .../com/baeldung/kotlin/StructuralJumpTest.kt | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt index 55b90deaa4..076adfb94e 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt @@ -14,7 +14,7 @@ class StructuralJumpTest { for (i in 1..10) { value = i if (value == 3) - break; + break } assertEquals(value, 3) @@ -24,7 +24,7 @@ class StructuralJumpTest { for (j in 1..10) { value = i * j if (value == 30) - break@outer_loop; + break@outer_loop } } @@ -37,7 +37,7 @@ class StructuralJumpTest { //continue loop without label for (i in 1..10) { if (i == 3) - continue; + continue processedList.add(i) } @@ -48,7 +48,7 @@ class StructuralJumpTest { outer_loop@ for (i in 1..10) { for (j in 1..10) { if (i == 3) - continue@outer_loop; + continue@outer_loop processedList.add(i*j) } } @@ -63,12 +63,12 @@ class StructuralJumpTest { assert(it < 3) } //this point is unreachable - assert(false); + assert(false) } @Test fun givenLambda_whenReturnWithExplicitLabel_thenComplete() { - var result = mutableListOf(); + var result = mutableListOf() listOf(1, 2, 3, 4, 5).forEach lit@{ if (it == 3) { @@ -78,12 +78,12 @@ class StructuralJumpTest { result.add(it) } - assert(result.all { it -> it != 3 }); + assert(result.all { it -> it != 3 }) } @Test fun givenLambda_whenReturnWithImplicitLabel_thenComplete() { - var result = mutableListOf(); + var result = mutableListOf() listOf(1, 2, 3, 4, 5).forEach { if (it == 3) { @@ -93,26 +93,26 @@ class StructuralJumpTest { result.add(it) } - assert(result.all { it -> it != 3 }); + assert(result.all { it -> it != 3 }) } @Test fun givenAnonymousFunction_return_thenComplete() { - var result = mutableListOf(); + var result = mutableListOf() listOf(1, 2, 3, 4, 5).forEach(fun(element: Int) { if (element == 3) return // local return to the caller of the anonymous fun, i.e. the forEach loop - result.add(element); + result.add(element) }) - assert(result.all { it -> it != 3 }); + assert(result.all { it -> it != 3 }) } @Test fun givenAnonymousFunction_returnToLabel_thenComplete() { - var value = 0; + var value = 0 run loop@{ listOf(1, 2, 3, 4, 5).forEach { - value = it; + value = it if (it == 3) return@loop // non-local return from the lambda passed to run } } From 05b75713ab5536930d99166d01e760c47f7c5de9 Mon Sep 17 00:00:00 2001 From: eelhazati Date: Sun, 30 Sep 2018 20:04:22 +0100 Subject: [PATCH 57/82] cdi portable extension --- flyway-cdi-extension/pom.xml | 51 +++++++++++++ .../cdi/extension/FlywayExtension.java | 74 +++++++++++++++++++ .../baeldung/cdi/extension/FlywayType.java | 14 ++++ .../com/baeldung/cdi/extension/MainApp.java | 16 ++++ .../src/main/resources/META-INF/beans.xml | 6 ++ .../javax.enterprise.inject.spi.Extension | 2 + .../db/migration/V1__Create_person_table.sql | 4 + .../resources/db/migration/V2__Add_people.sql | 3 + pom.xml | 1 + 9 files changed, 171 insertions(+) create mode 100644 flyway-cdi-extension/pom.xml create mode 100644 flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java create mode 100644 flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayType.java create mode 100644 flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/MainApp.java create mode 100644 flyway-cdi-extension/src/main/resources/META-INF/beans.xml create mode 100644 flyway-cdi-extension/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension create mode 100644 flyway-cdi-extension/src/main/resources/db/migration/V1__Create_person_table.sql create mode 100644 flyway-cdi-extension/src/main/resources/db/migration/V2__Add_people.sql diff --git a/flyway-cdi-extension/pom.xml b/flyway-cdi-extension/pom.xml new file mode 100644 index 0000000000..c6ee26f783 --- /dev/null +++ b/flyway-cdi-extension/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + + com.baeldung + flyway-cdi-extension + 1.0-SNAPSHOT + + + 1.8 + 1.8 + + + + + javax.enterprise + cdi-api + 2.0.SP1 + + + org.jboss.weld.se + weld-se-core + 3.0.5.Final + runtime + + + org.flywaydb + flyway-core + 5.1.4 + + + org.apache.tomcat + tomcat-jdbc + 8.5.33 + + + javax.annotation + javax.annotation-api + 1.3.2 + + + com.h2database + h2 + 1.4.197 + runtime + + + + diff --git a/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java b/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java new file mode 100644 index 0000000000..a5019b82c1 --- /dev/null +++ b/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java @@ -0,0 +1,74 @@ +package com.baeldung.cdi.extension; + +import org.apache.tomcat.jdbc.pool.DataSource; +import org.flywaydb.core.Flyway; + +import javax.annotation.sql.DataSourceDefinition; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; +import javax.enterprise.inject.Any; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.literal.InjectLiteral; +import javax.enterprise.inject.spi.*; +import javax.enterprise.util.AnnotationLiteral; + + +/** + * Flyway is now under CDI container like: + * + * @ApplicationScoped + * @FlywayType public class Flyway{ + * @Inject setDataSource(DataSource dataSource){ + * //... + * } + * } + */ + +public class FlywayExtension implements Extension { + + DataSourceDefinition dataSourceDefinition = null; + + public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) { + bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName()); + } + + public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType patEvent) { + AnnotatedType at = patEvent.getAnnotatedType(); + dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class); + } + + public void processAnnotatedType(@Observes ProcessAnnotatedType patEvent) { + patEvent.configureAnnotatedType() + //Add Scope + .add(ApplicationScoped.Literal.INSTANCE) + //Add Qualifier + .add(new AnnotationLiteral() { + }) + //Decorate setDataSource(DataSource dataSource){} with @Inject + .filterMethods(annotatedMethod -> { + return annotatedMethod.getParameters().size() == 1 && + annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class); + }) + .findFirst().get().add(InjectLiteral.INSTANCE); + } + + void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) { + abdEvent.addBean() + .types(javax.sql.DataSource.class, DataSource.class) + .qualifiers(new AnnotationLiteral() {}, new AnnotationLiteral() {}) + .scope(ApplicationScoped.class) + .name(DataSource.class.getName()) + .beanClass(DataSource.class) + .createWith(creationalContext -> { + DataSource instance = new DataSource(); + instance.setUrl(dataSourceDefinition.url()); + instance.setDriverClassName(dataSourceDefinition.className()); + return instance; + }); + } + + void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) { + Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral() {}).get(); + flyway.migrate(); + } +} diff --git a/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayType.java b/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayType.java new file mode 100644 index 0000000000..7c3a5affa6 --- /dev/null +++ b/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/FlywayType.java @@ -0,0 +1,14 @@ +package com.baeldung.cdi.extension; + +import javax.inject.Qualifier; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; + +@Retention(RetentionPolicy.RUNTIME) +@Target({FIELD, METHOD, PARAMETER, TYPE}) +@Qualifier +public @interface FlywayType { +} \ No newline at end of file diff --git a/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/MainApp.java b/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/MainApp.java new file mode 100644 index 0000000000..1f6c5b43ba --- /dev/null +++ b/flyway-cdi-extension/src/main/java/com/baeldung/cdi/extension/MainApp.java @@ -0,0 +1,16 @@ +package com.baeldung.cdi.extension; + +import javax.annotation.sql.DataSourceDefinition; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.se.SeContainer; +import javax.enterprise.inject.se.SeContainerInitializer; + +@ApplicationScoped +@DataSourceDefinition(name = "ds", className = "org.h2.Driver", url = "jdbc:h2:mem:testdb") +public class MainApp { + public static void main(String[] args) { + SeContainerInitializer initializer = SeContainerInitializer.newInstance(); + try (SeContainer container = initializer.initialize()) { + } + } +} \ No newline at end of file diff --git a/flyway-cdi-extension/src/main/resources/META-INF/beans.xml b/flyway-cdi-extension/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..44959bfa99 --- /dev/null +++ b/flyway-cdi-extension/src/main/resources/META-INF/beans.xml @@ -0,0 +1,6 @@ + + \ No newline at end of file diff --git a/flyway-cdi-extension/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/flyway-cdi-extension/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension new file mode 100644 index 0000000000..a82dc47714 --- /dev/null +++ b/flyway-cdi-extension/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension @@ -0,0 +1,2 @@ +com.baeldung.cdi.extension.FlywayExtension + diff --git a/flyway-cdi-extension/src/main/resources/db/migration/V1__Create_person_table.sql b/flyway-cdi-extension/src/main/resources/db/migration/V1__Create_person_table.sql new file mode 100644 index 0000000000..6bddc7689e --- /dev/null +++ b/flyway-cdi-extension/src/main/resources/db/migration/V1__Create_person_table.sql @@ -0,0 +1,4 @@ +create table PERSON ( + ID int not null, + NAME varchar(100) not null +); diff --git a/flyway-cdi-extension/src/main/resources/db/migration/V2__Add_people.sql b/flyway-cdi-extension/src/main/resources/db/migration/V2__Add_people.sql new file mode 100644 index 0000000000..d8f1d62667 --- /dev/null +++ b/flyway-cdi-extension/src/main/resources/db/migration/V2__Add_people.sql @@ -0,0 +1,3 @@ +insert into PERSON (ID, NAME) values (1, 'Axel'); +insert into PERSON (ID, NAME) values (2, 'Mr. Foo'); +insert into PERSON (ID, NAME) values (3, 'Ms. Bar'); diff --git a/pom.xml b/pom.xml index bda69bfd42..7ece14150c 100644 --- a/pom.xml +++ b/pom.xml @@ -681,6 +681,7 @@ + flyway-cdi-extension From b4aa279eaa46d627ee8a787d299e7dd9579f0738 Mon Sep 17 00:00:00 2001 From: Shubhra Srivastava Date: Mon, 1 Oct 2018 03:22:49 +0530 Subject: [PATCH 58/82] BALE-2224 Ternary Operator In Java (#5362) --- .../TernaryOperatorUnitTest.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java b/core-java/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java new file mode 100644 index 0000000000..6b292ad8ab --- /dev/null +++ b/core-java/src/test/java/com/baeldung/ternaryoperator/TernaryOperatorUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.ternaryoperator; + +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class TernaryOperatorUnitTest { + + @Test + public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue() { + int number = 10; + String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10"; + + assertThat(msg).isEqualTo("Number is less than or equal to 10"); + } + + @Test + public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated() { + int exp1 = 0, exp2 = 0; + int result = 12 > 10 ? ++exp1 : ++exp2; + + assertThat(exp1).isEqualTo(1); + assertThat(exp2).isEqualTo(0); + assertThat(result).isEqualTo(1); + } + + @Test + public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated() { + int exp1 = 0, exp2 = 0; + int result = 8 > 10 ? ++exp1 : ++exp2; + + assertThat(exp1).isEqualTo(0); + assertThat(exp2).isEqualTo(1); + assertThat(result).isEqualTo(1); + } + + @Test + public void givenANestedCondition_whenUsingTernaryOperator_thenCorrectValueIsReturned() { + int number = 6; + String msg = number > 10 ? "Number is greater than 10" : number > 5 ? "Number is greater than 5" : "Number is less than or equal to 5"; + + assertThat(msg).isEqualTo("Number is greater than 5"); + } +} From 317ed150a1f47501b73fff6355244982ce0ab19e Mon Sep 17 00:00:00 2001 From: ramansahasi Date: Mon, 1 Oct 2018 07:29:53 +0530 Subject: [PATCH 59/82] BAEL-2015 Memory leaks in Java (#5295) * BAEL-2015_Memory_leaks_in_Java * Ignored tests * Update NonStaticFieldsDemo.java * Corrected class name * converted tabspaces to whitespaces --- .../memoryleaks/equalshashcode/Person.java | 9 +++++ .../equalshashcode/PersonOptimized.java | 25 ++++++++++++++ .../memoryleaks/finalize/BulkyObject.java | 32 +++++++++++++++++ .../finalize/BulkyObjectOptimized.java | 22 ++++++++++++ .../memoryleaks/innerclass/BulkyObject.java | 22 ++++++++++++ .../innerclass/InnerClassDriver.java | 17 ++++++++++ .../innerclass/InnerClassWrapper.java | 10 ++++++ .../innerclass/StaticNestedClassWrapper.java | 10 ++++++ .../internedstrings/InternedString.java | 17 ++++++++++ .../ReadStringFromFileUtil.java | 34 +++++++++++++++++++ .../internedstrings/StringObject.java | 17 ++++++++++ .../staticfields/NonStaticFieldsDemo.java | 21 ++++++++++++ .../staticfields/StaticFieldsDemo.java | 21 ++++++++++++ .../PersonMemoryLeakUnitTest.java | 33 ++++++++++++++++++ .../finalize/FinalizeMemoryLeakUnitTest.java | 28 +++++++++++++++ .../StaticInnerClassMemoryLeakUnitTest.java | 20 +++++++++++ .../StringInternMemoryLeakUnitTest.java | 20 +++++++++++ .../NonStaticFieldsMemoryLeakUnitTest.java | 26 ++++++++++++++ .../StaticFieldsMemoryLeakUnitTest.java | 26 ++++++++++++++ 19 files changed, 410 insertions(+) create mode 100755 core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java create mode 100755 core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java create mode 100755 core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java create mode 100644 core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java create mode 100755 core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java create mode 100755 core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java create mode 100755 core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java create mode 100755 core-java/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java create mode 100644 core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java create mode 100644 core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java create mode 100644 core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java create mode 100644 core-java/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java create mode 100644 core-java/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java create mode 100644 core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java b/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java new file mode 100755 index 0000000000..e16d1ae6da --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/Person.java @@ -0,0 +1,9 @@ +package com.baeldung.memoryleaks.equalshashcode; + +public class Person { + public String name; + + public Person(String name) { + this.name = name; + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java b/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java new file mode 100755 index 0000000000..3af70dd1eb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/equalshashcode/PersonOptimized.java @@ -0,0 +1,25 @@ +package com.baeldung.memoryleaks.equalshashcode; + +public class PersonOptimized { + public String name; + + public PersonOptimized(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof PersonOptimized)) { + return false; + } + PersonOptimized person = (PersonOptimized) o; + return person.name.equals(name); + } + + @Override + public int hashCode() { + int result = 17; + result = 31 * result + name.hashCode(); + return result; + }} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java b/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java new file mode 100755 index 0000000000..ce77d883f6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObject.java @@ -0,0 +1,32 @@ +package com.baeldung.memoryleaks.finalize; + +import java.nio.charset.Charset; +import java.util.Random; + +public class BulkyObject { + private String data[]; + + public BulkyObject() { + data = new String[1000000]; + + for(int i=0; i<1000000; i++) { + data[i] = getRandomString(); + } + } + + private String getRandomString() { + byte[] array = new byte[1000]; + new Random().nextBytes(array); + return new String(array, Charset.forName("UTF-8")); + } + + @Override + public void finalize() { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Finalizer called"); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java b/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java new file mode 100644 index 0000000000..dc1302432e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/finalize/BulkyObjectOptimized.java @@ -0,0 +1,22 @@ +package com.baeldung.memoryleaks.finalize; + +import java.nio.charset.Charset; +import java.util.Random; + +public class BulkyObjectOptimized { + private String data[]; + + public BulkyObjectOptimized() { + data = new String[1000000]; + + for(int i=0; i<1000000; i++) { + data[i] = getRandomString(); + } + } + + private String getRandomString() { + byte[] array = new byte[1000]; + new Random().nextBytes(array); + return new String(array, Charset.forName("UTF-8")); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java new file mode 100755 index 0000000000..bbd5310182 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/BulkyObject.java @@ -0,0 +1,22 @@ +package com.baeldung.memoryleaks.innerclass; + +import java.nio.charset.Charset; +import java.util.Random; + +public class BulkyObject { + private String data[]; + + public BulkyObject() { + data = new String[1000000]; + + for(int i=0; i<1000000; i++) { + data[i] = getRandomString(); + } + } + + private String getRandomString() { + byte[] array = new byte[1000]; + new Random().nextBytes(array); + return new String(array, Charset.forName("UTF-8")); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java new file mode 100755 index 0000000000..06f928bc4a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassDriver.java @@ -0,0 +1,17 @@ +package com.baeldung.memoryleaks.innerclass; + +public class InnerClassDriver { + public static InnerClassWrapper.SimpleInnerClass getSimpleInnerClassObj() { + return new InnerClassWrapper().new SimpleInnerClass(); + } + + public static void main2(String[] args) { + InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = getSimpleInnerClassObj(); + System.out.println("Debug point"); + } + + public static void main(String[] args) { + StaticNestedClassWrapper.StaticNestedClass simpleInnerClassObj = new StaticNestedClassWrapper.StaticNestedClass(); + System.out.println("Debug point"); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java new file mode 100755 index 0000000000..25fecf9bb3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/InnerClassWrapper.java @@ -0,0 +1,10 @@ +package com.baeldung.memoryleaks.innerclass; + + +public class InnerClassWrapper { + private BulkyObject bulkyObject = new BulkyObject(); + + public class SimpleInnerClass { + + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java new file mode 100755 index 0000000000..d1729d78a3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/innerclass/StaticNestedClassWrapper.java @@ -0,0 +1,10 @@ +package com.baeldung.memoryleaks.innerclass; + + +public class StaticNestedClassWrapper { + private BulkyObject bulkyObject = new BulkyObject(); + + public static class StaticNestedClass { + + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java new file mode 100644 index 0000000000..cbba8f849d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/InternedString.java @@ -0,0 +1,17 @@ +package com.baeldung.memoryleaks.internedstrings; + +public class InternedString { + private static final String FILEPATH = "C:\\bigstring.txt"; + + public void readString() { + String s1 = ReadStringFromFileUtil.read(FILEPATH).intern(); + String s2 = ReadStringFromFileUtil.read(FILEPATH).intern(); + + if (s1 == s2) { + System.out.println("Both the strings objects are same"); + } + else { + System.out.println("Both the strings objects are different"); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java new file mode 100644 index 0000000000..2b7d72accc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/ReadStringFromFileUtil.java @@ -0,0 +1,34 @@ +package com.baeldung.memoryleaks.internedstrings; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class ReadStringFromFileUtil { + + public static String read(String fileName) { + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(fileName)); + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + return sb.toString(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } + +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java new file mode 100644 index 0000000000..e48e448d18 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/internedstrings/StringObject.java @@ -0,0 +1,17 @@ +package com.baeldung.memoryleaks.internedstrings; + +public class StringObject { + private static final String FILEPATH = "C:\\bigstring.txt"; + + public void readString() { + String s1 = ReadStringFromFileUtil.read(FILEPATH); + String s2 = ReadStringFromFileUtil.read(FILEPATH); + + if (s1 == s2) { + System.out.println("Both the strings objects are same"); + } + else { + System.out.println("Both the strings objects are different"); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java b/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java new file mode 100644 index 0000000000..f2b220e76d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsDemo.java @@ -0,0 +1,21 @@ +package com.baeldung.memoryleaks.staticfields; + +import java.util.ArrayList; +import java.util.List; + +public class NonStaticFieldsDemo { + public List list = new ArrayList<>(); + + public void populateList() { + for (int i = 0; i < 10000000; i++) { + list.add(Math.random()); + } + System.out.println("Debug Point 2"); + } + + public static void main(String[] args) { + System.out.println("Debug Point 1"); + new NonStaticFieldsDemo().populateList(); + System.out.println("Debug Point 3"); + } +} diff --git a/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java b/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java new file mode 100644 index 0000000000..17cebc2843 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/memoryleaks/staticfields/StaticFieldsDemo.java @@ -0,0 +1,21 @@ +package com.baeldung.memoryleaks.staticfields; + +import java.util.ArrayList; +import java.util.List; + +public class StaticFieldsDemo { + public static List list = new ArrayList<>(); + + public void populateList() { + for (int i = 0; i < 10000000; i++) { + list.add(Math.random()); + } + System.out.println("Debug Point 2"); + } + + public static void main(String[] args) { + System.out.println("Debug Point 1"); + new StaticFieldsDemo().populateList(); + System.out.println("Debug Point 3"); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java new file mode 100644 index 0000000000..3fa1db18d2 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/equalshashcode/PersonMemoryLeakUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.memoryleaks.equalshashcode; + +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Ignore; +import org.junit.Test; + +public class PersonMemoryLeakUnitTest { + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenMap_whenEqualsAndHashCodeNotOverridden_thenMemoryLeak() { + Map map = new HashMap(); + for(int i=0; i<10000000; i++) { + map.put(new Person("jon"), 1); + } + assertTrue(map.size() > 1); + System.out.print("Debug Point - VisuaLVM"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenMap_whenEqualsAndHashCodeOverridden_thenNoMemoryLeak() { + Map map = new HashMap(); + for(int i=0; i<10000; i++) { + map.put(new PersonOptimized("jon"), 1); + } + assertTrue(map.size() == 1); + System.out.print("Debug Point - VisuaLVM"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java new file mode 100644 index 0000000000..b6d81a8968 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/finalize/FinalizeMemoryLeakUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.memoryleaks.finalize; + +import org.junit.Ignore; +import org.junit.Test; + +public class FinalizeMemoryLeakUnitTest { + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenObjectWithFinalizer_whenCreatingAndDestroyingThisObject_thenMemoryLeak() { + BulkyObject[] stock = new BulkyObject[100000]; + + for(int i=0; i<100000; i++) { + stock[i] = new BulkyObject(); + } + System.out.print("Debug Point - VisuaLVM"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenObjectWithoutFinalizer_whenCreatingAndDestroyingThisObject_thenNoMemoryLeak() { + BulkyObjectOptimized[] stock = new BulkyObjectOptimized[100000]; + + for(int i=0; i<100000; i++) { + stock[i] = new BulkyObjectOptimized(); + } + System.out.print("Debug Point - VisuaLVM"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java new file mode 100644 index 0000000000..0854e4a38a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/innerclass/StaticInnerClassMemoryLeakUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.memoryleaks.innerclass; + +import org.junit.Ignore; +import org.junit.Test; + +public class StaticInnerClassMemoryLeakUnitTest { + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenUsingInnerClass_whenInitializingInnerClass_thenInnerClassHoldsReferenceOfOuterObject() { + InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = new InnerClassWrapper().new SimpleInnerClass(); + System.out.print("Debug Point - VisuaLVM"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenUsingStaticNestedClass_whenInitializingInnerClass_thenStaticNestedClassDoesntReferenceOuterObject() { + StaticNestedClassWrapper.StaticNestedClass staticNestedClassObj = new StaticNestedClassWrapper.StaticNestedClass(); + System.out.print("Debug Point - VisuaLVM"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java new file mode 100644 index 0000000000..6d363e0bdc --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/internedstrings/StringInternMemoryLeakUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.memoryleaks.internedstrings; + +import org.junit.Ignore; +import org.junit.Test; + +public class StringInternMemoryLeakUnitTest { + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenJava6OrBelow_whenInterningLargeStrings_thenPermgenIncreases() { + new InternedString().readString(); + System.out.print("Debug Point - VisuaLVM"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenJava6OrBelow_whenNotInterningLargeStrings_thenPermgenDoesntIncrease() { + new StringObject().readString(); + System.out.print("Debug Point - VisuaLVM"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java new file mode 100644 index 0000000000..e64fdb73e0 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/NonStaticFieldsMemoryLeakUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.memoryleaks.staticfields; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +public class NonStaticFieldsMemoryLeakUnitTest { + public List list = new ArrayList<>(); + + public void populateList() { + for (int i = 0; i < 10000000; i++) { + list.add(Math.random()); + } + System.out.println("Debug Point 2"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenNonStaticLargeList_whenPopulatingList_thenListGarbageCollected() { + System.out.println("Debug Point 1"); + new NonStaticFieldsMemoryLeakUnitTest().populateList(); + System.out.println("Debug Point 3"); + } +} diff --git a/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java new file mode 100644 index 0000000000..1765f0cf0d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/memoryleaks/staticfields/StaticFieldsMemoryLeakUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.memoryleaks.staticfields; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; + +public class StaticFieldsMemoryLeakUnitTest { + public static List list = new ArrayList<>(); + + public void populateList() { + for (int i = 0; i < 10000000; i++) { + list.add(Math.random()); + } + System.out.println("Debug Point 2"); + } + + @Test + @Ignore // Test deliberately ignored as memory leak tests consume lots of resources + public void givenStaticLargeList_whenPopulatingList_thenListIsNotGarbageCollected() { + System.out.println("Debug Point 1"); + new StaticFieldsDemo().populateList(); + System.out.println("Debug Point 3"); + } +} From b343e82095bc9ecd7b966549d2e570493871a1a2 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Sun, 30 Sep 2018 21:57:59 -0600 Subject: [PATCH 60/82] Initial graylog + spring boot demo (#5299) * Initial graylog + spring boot demo * Move Graylog demo into existing spring-boot module --- spring-boot/pom.xml | 16 ++++++++++++- .../graylog/GraylogDemoApplication.java | 17 +++++++++++++ spring-boot/src/main/resources/log4j.xml | 24 +++++++++++++++++++ 3 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 spring-boot/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java create mode 100644 spring-boot/src/main/resources/log4j.xml diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 50859f674c..0ea6b6156f 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -145,6 +145,20 @@ chaos-monkey-spring-boot ${chaos.monkey.version} + + + + + org.springframework.boot + spring-boot-starter-log4j + 1.3.8.RELEASE + + + org.graylog2 + gelfj + 1.1.16 + compile + @@ -224,4 +238,4 @@ 2.2.4 - \ No newline at end of file + diff --git a/spring-boot/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java b/spring-boot/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java new file mode 100644 index 0000000000..be49a0e927 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.graylog; + +import org.apache.log4j.Logger; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class GraylogDemoApplication { + + private final static Logger LOG = + Logger.getLogger(GraylogDemoApplication.class); + + public static void main(String[] args) { + SpringApplication.run(GraylogDemoApplication.class, args); + LOG.info("Hello from Spring Boot"); + } +} diff --git a/spring-boot/src/main/resources/log4j.xml b/spring-boot/src/main/resources/log4j.xml new file mode 100644 index 0000000000..61c1b7b229 --- /dev/null +++ b/spring-boot/src/main/resources/log4j.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 037c3f4cc4edc96a67187f2e5099fbfedc0f5b80 Mon Sep 17 00:00:00 2001 From: sandy03934 Date: Mon, 1 Oct 2018 12:20:49 +0530 Subject: [PATCH 61/82] apache-geode code samples Issue: BAEL-1466 --- apache-geode/pom.xml | 46 ++++++++ .../java/com/baeldung/geode/Customer.java | 78 +++++++++++++ .../java/com/baeldung/geode/CustomerKey.java | 57 +++++++++ .../geode/functions/UpperCaseNames.java | 34 ++++++ .../geode/GeodeSamplesIntegrationTest.java | 110 ++++++++++++++++++ 5 files changed, 325 insertions(+) create mode 100644 apache-geode/pom.xml create mode 100644 apache-geode/src/main/java/com/baeldung/geode/Customer.java create mode 100644 apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java create mode 100644 apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java create mode 100644 apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java diff --git a/apache-geode/pom.xml b/apache-geode/pom.xml new file mode 100644 index 0000000000..a3f6604ac4 --- /dev/null +++ b/apache-geode/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + com.baeldung + apache-geode + 1.0-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 1.6.0 + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + org.apache.geode + geode-core + ${geode.core} + + + junit + junit + RELEASE + + + + \ No newline at end of file diff --git a/apache-geode/src/main/java/com/baeldung/geode/Customer.java b/apache-geode/src/main/java/com/baeldung/geode/Customer.java new file mode 100644 index 0000000000..82ee5ecaeb --- /dev/null +++ b/apache-geode/src/main/java/com/baeldung/geode/Customer.java @@ -0,0 +1,78 @@ +package com.baeldung.geode; + +import java.io.Serializable; +import java.util.Objects; + +public class Customer implements Serializable { + + private static final long serialVersionUID = -7482516011038799900L; + + private CustomerKey key; + private String firstName; + private String lastName; + private Integer age; + + public Customer() { + } + + public Customer(String firstName, String lastName, int age) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + } + + public Customer(CustomerKey key, String firstName, String lastName, int age) { + this(firstName, lastName, age); + this.key = key; + } + + // setters and getters + + public static long getSerialVersionUID() { + return serialVersionUID; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + @Override + public String toString() { + return "Customer{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Customer customer = (Customer) o; + return Objects.equals(firstName, customer.firstName) && Objects.equals(lastName, customer.lastName) && Objects.equals(age, customer.age); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName, age); + } +} diff --git a/apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java b/apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java new file mode 100644 index 0000000000..bfa64870c0 --- /dev/null +++ b/apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java @@ -0,0 +1,57 @@ +package com.baeldung.geode; + +import java.io.Serializable; + +public class CustomerKey implements Serializable { + + private static final long serialVersionUID = -3529253035303792458L; + private long id; + private String country; + + public CustomerKey(long id) { + this.id = id; + this.country = "USA"; + } + + public CustomerKey(long id, String country) { + this.id = id; + this.country = country; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + CustomerKey that = (CustomerKey) o; + + if (id != that.id) + return false; + return country != null ? country.equals(that.country) : that.country == null; + } + + @Override + public int hashCode() { + int result = (int) (id ^ (id >>> 32)); + result = 31 * result + (country != null ? country.hashCode() : 0); + return result; + } +} diff --git a/apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java b/apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java new file mode 100644 index 0000000000..5ff8e53da8 --- /dev/null +++ b/apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java @@ -0,0 +1,34 @@ +package com.baeldung.geode.functions; + +import com.baeldung.geode.Customer; +import com.baeldung.geode.CustomerKey; +import org.apache.geode.cache.Region; +import org.apache.geode.cache.execute.Function; +import org.apache.geode.cache.execute.FunctionContext; +import org.apache.geode.cache.execute.RegionFunctionContext; + +import java.util.Map; + +public class UpperCaseNames implements Function { + private static final long serialVersionUID = -8946294032165677602L; + + @Override + public void execute(FunctionContext context) { + RegionFunctionContext regionContext = (RegionFunctionContext) context; + Region region = regionContext.getDataSet(); + + for (Map.Entry entry : region.entrySet()) { + Customer customer = entry.getValue(); + customer.setFirstName(customer.getFirstName() + .toUpperCase()); + } + + context.getResultSender() + .lastResult(true); + } + + @Override + public String getId() { + return getClass().getName(); + } +} diff --git a/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java new file mode 100644 index 0000000000..b96d2c9b6a --- /dev/null +++ b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java @@ -0,0 +1,110 @@ +package com.baeldung.geode; + +import com.baeldung.geode.functions.UpperCaseNames; +import org.apache.geode.cache.Region; +import org.apache.geode.cache.client.ClientCache; +import org.apache.geode.cache.client.ClientCacheFactory; +import org.apache.geode.cache.client.ClientRegionShortcut; +import org.apache.geode.cache.execute.Execution; +import org.apache.geode.cache.execute.FunctionService; +import org.apache.geode.cache.query.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; + +public class GeodeSamplesIntegrationTest { + + ClientCache cache = null; + Region region = null; + Region queryRegion = null; + Region customerRegion = null; + + @Before + public void connect() { + this.cache = new ClientCacheFactory().addPoolLocator("localhost", 10334) + .create(); + this.region = this.cache. createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY) + .create("baeldung"); + this.customerRegion = this.cache. createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY) + .create("baeldung-customers"); + } + + @After + public void cleanup() { + this.cache.close(); + } + + @Test + public void whenSendMessageToRegion_thenMessageSavedSuccessfully() { + + this.region.put("1", "Hello"); + this.region.put("2", "Baeldung"); + + assertEquals("Hello", region.get("1")); + assertEquals("Baeldung", region.get("2")); + + } + + @Test + public void whenPutMultipleValuesAtOnce_thenValuesSavedSuccessfully() { + + Supplier> keys = () -> Stream.of("A", "B", "C", "D", "E"); + Map values = keys.get() + .collect(Collectors.toMap(Function.identity(), String::toLowerCase)); + + this.region.putAll(values); + + keys.get() + .forEach(k -> assertEquals(k.toLowerCase(), this.region.get(k))); + + } + + @Test + public void whenPutCustomKey_thenValuesSavedSuccessfully() { + CustomerKey key = new CustomerKey(123); + Customer customer = new Customer(key, "William", "Russell", 35); + + Map customerInfo = new HashMap<>(); + customerInfo.put(key, customer); + + this.customerRegion.putAll(customerInfo); + + Customer storedCustomer = this.customerRegion.get(key); + assertEquals("William", storedCustomer.getFirstName()); + assertEquals("Russell", storedCustomer.getLastName()); + + } + + @Test + public void whenFindACustomerUsingOQL_thenCorrectCustomerObject() throws NameResolutionException, TypeMismatchException, QueryInvocationTargetException, FunctionDomainException { + + Map data = new HashMap<>(); + data.put(new CustomerKey(1), new Customer("Gheorge", "Manuc", 36)); + data.put(new CustomerKey(2), new Customer("Allan", "McDowell", 43)); + this.customerRegion.putAll(data); + + QueryService queryService = this.cache.getQueryService(); + String query = "select * from /baeldung-customers c where c.firstName = 'Allan'"; + SelectResults queryResults = (SelectResults) queryService.newQuery(query) + .execute(); + assertEquals(1, queryResults.size()); + + } + + @Test + public void whenExecuteUppercaseNames_thenCustomerNamesAreUppercased() { + Execution execution = FunctionService.onRegion(this.customerRegion); + execution.execute(UpperCaseNames.class.getName()); + Customer customer = this.customerRegion.get(new CustomerKey(1)); + assertEquals("GHEORGE", customer.getFirstName()); + } +} From 379eab82d6d2e26280b006808fa41b08f666d2e9 Mon Sep 17 00:00:00 2001 From: RoscoeLotriet Date: Mon, 1 Oct 2018 14:18:24 +0200 Subject: [PATCH 62/82] Implemented Stream forEach if/else unit test --- .../conditional/StreamForEachIfElseLogic.java | 42 ------------------- .../StreamForEachIfElseUnitTest.java | 41 ++++++++++++++++++ 2 files changed, 41 insertions(+), 42 deletions(-) delete mode 100644 core-java-8/src/main/java/com/baeldung/stream/conditional/StreamForEachIfElseLogic.java create mode 100644 core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/conditional/StreamForEachIfElseLogic.java b/core-java-8/src/main/java/com/baeldung/stream/conditional/StreamForEachIfElseLogic.java deleted file mode 100644 index b8ef521b41..0000000000 --- a/core-java-8/src/main/java/com/baeldung/stream/conditional/StreamForEachIfElseLogic.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.stream.conditional; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Stream; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class StreamForEachIfElseLogic { - - private static final Logger LOG = LoggerFactory.getLogger(StreamForEachIfElseLogic.class); - - public static void main(String[] args) { - - ifElseLogic(); - - } - - private static void ifElseLogic() { - - List ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - - ints.stream() - .forEach(i -> { - if (i.intValue() % 2 == 0) { - LOG.info("{} is even", i); - } else { - LOG.info("{} is odd", i); - } - }); - - Stream evenIntegers = ints.stream() - .filter(i -> i.intValue() % 2 == 0); - Stream oddIntegers = ints.stream() - .filter(i -> i.intValue() % 2 != 0); - - evenIntegers.forEach(i -> LOG.info("{} is even", i)); - oddIntegers.forEach(i -> LOG.info("{} is odd", i)); - - } -} diff --git a/core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java b/core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java new file mode 100644 index 0000000000..b5d26eb6a8 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.stream.conditional; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; + +import org.junit.Assert; +import org.junit.Test; + +public class StreamForEachIfElseUnitTest { + + @Test + public final void givenIntegerStream_whenCheckingIntegerParityWithIfElse_thenEnsureCorrectParity() { + List ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + + ints.stream() + .forEach(i -> { + if (i.intValue() % 2 == 0) { + Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0); + } else { + Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0); + } + }); + + } + + @Test + public final void givenIntegerStream_whenCheckingIntegerParityWithStreamFilter_thenEnsureCorrectParity() { + List ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + + Stream evenIntegers = ints.stream() + .filter(i -> i.intValue() % 2 == 0); + Stream oddIntegers = ints.stream() + .filter(i -> i.intValue() % 2 != 0); + + evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0)); + oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0)); + + } + +} From 59a5313d9605c23e0e041a8b3d5279a1760a0a7b Mon Sep 17 00:00:00 2001 From: Swapan Pramanick Date: Tue, 2 Oct 2018 07:58:53 +0530 Subject: [PATCH 63/82] Changes for BAEL-2176 (#5305) * Evaluation Article - Spring web-flux * Evaluation Article - Spring web-flux * Evaluation Article - Spring web-flux * Evaluation Article - Spring web-flux * core-scala: initial commit * adding core-scala to pom * Revert "core-scala: initial commit" This reverts commit d46873405a67addfaa69aa7855b37af9c4a3df14. * BAEL-2176 * inserting new lines between given, when and then parts * Formatted using formatter * indentation changed further * Suggested changes in coding --- gson/pom.xml | 130 +++++++++--------- .../org/baeldung/gson/entities/Employee.java | 36 +++++ .../serialization/HashMapDeserializer.java | 66 +++++++++ gson/src/main/resources/logback.xml | 8 +- .../HashMapDeserializationUnitTest.java | 86 ++++++++++++ gson/src/test/resources/logback-test.xml | 19 +++ 6 files changed, 276 insertions(+), 69 deletions(-) create mode 100644 gson/src/main/java/org/baeldung/gson/entities/Employee.java create mode 100644 gson/src/main/java/org/baeldung/gson/serialization/HashMapDeserializer.java create mode 100644 gson/src/test/java/org/baeldung/gson/deserialization/HashMapDeserializationUnitTest.java create mode 100644 gson/src/test/resources/logback-test.xml diff --git a/gson/pom.xml b/gson/pom.xml index 6e7779d26a..8222cb50e1 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -1,73 +1,73 @@ - 4.0.0 - com.baeldung - gson - 0.1-SNAPSHOT - gson + 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 + gson + 0.1-SNAPSHOT + gson - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + - - - - org.projectlombok - lombok - ${lombok.version} - provided - - - joda-time - joda-time - ${joda-time.version} - - - commons-io - commons-io - ${commons-io.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - com.google.code.gson - gson - ${gson.version} - - + + + + org.projectlombok + lombok + ${lombok.version} + provided + + + joda-time + joda-time + ${joda-time.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + com.google.code.gson + gson + ${gson.version} + + - - gson - - - src/main/resources - true - - - + + gson + + + src/main/resources + true + + + - - - 2.8.0 - - 3.5 - 4.1 - 2.9.6 + + + 2.8.0 + + 3.5 + 4.1 + 2.9.6 1.16.10 - + \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/entities/Employee.java b/gson/src/main/java/org/baeldung/gson/entities/Employee.java new file mode 100644 index 0000000000..cedcd6572e --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/entities/Employee.java @@ -0,0 +1,36 @@ +package org.baeldung.gson.entities; + +public class Employee { + private int id; + private String name; + private String address; + + public Employee(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} diff --git a/gson/src/main/java/org/baeldung/gson/serialization/HashMapDeserializer.java b/gson/src/main/java/org/baeldung/gson/serialization/HashMapDeserializer.java new file mode 100644 index 0000000000..bb73e32559 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serialization/HashMapDeserializer.java @@ -0,0 +1,66 @@ +package org.baeldung.gson.serialization; + +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.Map; + +import org.baeldung.gson.entities.Employee; + +import com.google.gson.*; + +public class HashMapDeserializer implements JsonDeserializer> { + + @Override + public HashMap deserialize(JsonElement elem, Type type, JsonDeserializationContext context) throws JsonParseException { + HashMap map = new HashMap<>(); + for (Map.Entry entry : elem.getAsJsonObject().entrySet()) { + JsonElement jsonValue = entry.getValue(); + Object value = null; + if (jsonValue.isJsonPrimitive()) { + value = toPrimitive(jsonValue.getAsJsonPrimitive(), context); + } else { + value = context.deserialize(jsonValue, Employee.class); + } + map.put(entry.getKey(), value); + } + return map; + + } + + private Object toPrimitive(JsonPrimitive jsonValue, JsonDeserializationContext context) { + if (jsonValue.isBoolean()) + return jsonValue.getAsBoolean(); + else if (jsonValue.isString()) + return jsonValue.getAsString(); + else { + BigDecimal bigDec = jsonValue.getAsBigDecimal(); + Long l; + Integer i; + if ((i = toInteger(bigDec)) != null) { + return i; + } else if ((l = toLong(bigDec)) != null) { + return l; + } else { + return bigDec.doubleValue(); + } + } + } + + private Long toLong(BigDecimal val) { + try { + return val.toBigIntegerExact().longValue(); + } catch (ArithmeticException e) { + return null; + } + } + + private Integer toInteger(BigDecimal val) { + try { + return val.intValueExact(); + } catch (ArithmeticException e) { + return null; + } + } + +} diff --git a/gson/src/main/resources/logback.xml b/gson/src/main/resources/logback.xml index 56af2d397e..7bd5154680 100644 --- a/gson/src/main/resources/logback.xml +++ b/gson/src/main/resources/logback.xml @@ -7,13 +7,13 @@ - - + + - + - + \ No newline at end of file diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/HashMapDeserializationUnitTest.java b/gson/src/test/java/org/baeldung/gson/deserialization/HashMapDeserializationUnitTest.java new file mode 100644 index 0000000000..6905ade0da --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/deserialization/HashMapDeserializationUnitTest.java @@ -0,0 +1,86 @@ +package org.baeldung.gson.deserialization; + +import java.lang.reflect.Type; +import java.util.HashMap; + +import org.baeldung.gson.entities.Employee; +import org.baeldung.gson.serialization.HashMapDeserializer; +import org.junit.Assert; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonSyntaxException; +import com.google.gson.internal.LinkedTreeMap; +import com.google.gson.reflect.TypeToken; + +public class HashMapDeserializationUnitTest { + + private static final Logger logger = LoggerFactory.getLogger(HashMapDeserializationUnitTest.class); + + @Test + public void whenUsingHashMapClass_thenShouldReturnMapWithDefaultClasses() { + + String jsonString = "{'employee.name':'Bob','employee.salary':10000, 'employee.active':true, " + + "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}"; + + Gson gson = new Gson(); + HashMap map = gson.fromJson(jsonString, HashMap.class); + + logger.info("The converted map: {}", map); + Assert.assertEquals(4, map.size()); + Assert.assertEquals(Double.class, map.get("employee.salary").getClass()); + Assert.assertEquals(LinkedTreeMap.class, map.get("employee").getClass()); + + } + + @Test(expected = JsonSyntaxException.class) + public void whenUsingJsonStringWithDuplicateKey_thenShouldThrowJsonSyntaxException() { + + String jsonString = "{'employee.name':'Bob', 'employee.name':'Jenny','employee.salary':10000, " + + "'employee.active':true, " + "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}"; + + Gson gson = new Gson(); + HashMap map = gson.fromJson(jsonString, HashMap.class); + + logger.info("The converted map: {}", map); + } + + @Test + public void whenUsingTypeToken_thenShouldReturnMapWithProperClass() { + + String jsonString = "{'Bob':{'id':10, 'name': 'Bob Willis', 'address':'UK'}," + + "'Jenny':{'id':10, 'name': 'Jenny McCarthy', 'address':'USA'}, " + + "'Steve':{'id':10, 'name': 'Steven Waugh', 'address':'Australia'}}"; + + Gson gson = new Gson(); + Type empMapType = new TypeToken>(){}.getType(); + HashMap nameEmployeeMap = gson.fromJson(jsonString, empMapType); + + logger.info("The converted map: {}", nameEmployeeMap); + Assert.assertEquals(3, nameEmployeeMap.size()); + Assert.assertEquals(Employee.class, nameEmployeeMap.get("Bob").getClass()); + } + + @Test + public void whenUsingCustomDeserializer_thenShouldReturnMapWithProperClass() { + + String jsonString = "{'employee.name':'Bob','employee.salary':10000, 'employee.active':true, " + + "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}"; + + Type type = new TypeToken>(){}.getType(); + Gson gson = new GsonBuilder() + .registerTypeAdapter(type, new HashMapDeserializer()) + .create(); + HashMap blendedMap = gson.fromJson(jsonString, type); + + logger.info("The converted map: {}", blendedMap); + Assert.assertEquals(4, blendedMap.size()); + Assert.assertEquals(Integer.class, blendedMap.get("employee.salary").getClass()); + Assert.assertEquals(Employee.class, blendedMap.get("employee").getClass()); + + } + +} diff --git a/gson/src/test/resources/logback-test.xml b/gson/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..7bd5154680 --- /dev/null +++ b/gson/src/test/resources/logback-test.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file From ea225590646c84892c9b439788c6fa80dcf43698 Mon Sep 17 00:00:00 2001 From: dionisPrifti Date: Tue, 2 Oct 2018 04:41:18 +0200 Subject: [PATCH 64/82] BAEL-2209 : Quicksort Dionis Prifti (#5365) * Merged changes from the original repository. * Added event streaming example with WebFlux. * Deleted auto-generated code. * Deleted auto-generated code. * BAEL-2209 : Added java class and JUnit test for QuickSort implementation. * Revert "Added event streaming example with WebFlux." This reverts commit 21527b34643bbb0d1437a0ab3ef392024a391107. * BAEL-2209: Removed main method from Quicksort class. * BAEL-2209 : Added the implementation and unit test for 3-Way Quicksort. --- .../algorithms/quicksort/QuickSort.java | 39 +++++++++++++++++++ .../quicksort/ThreeWayQuickSort.java | 38 ++++++++++++++++++ .../quicksort/QuickSortUnitTest.java | 17 ++++++++ .../quicksort/ThreeWayQuickSortUnitTest.java | 15 +++++++ 4 files changed, 109 insertions(+) create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSort.java create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java b/algorithms/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java new file mode 100644 index 0000000000..e113cc3242 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java @@ -0,0 +1,39 @@ +package com.baeldung.algorithms.quicksort; + +public class QuickSort { + + public static void quickSort(int arr[], int begin, int end) + { + if (begin < end) { + int partitionIndex = partition(arr, begin, end); + + // Recursively sort elements of the 2 sub-arrays + quickSort(arr, begin, partitionIndex-1); + quickSort(arr, partitionIndex+1, end); + } + } + + private static int partition(int arr[], int begin, int end) + { + int pivot = arr[end]; + int i = (begin-1); + + for (int j=begin; j Date: Mon, 1 Oct 2018 23:42:46 -0300 Subject: [PATCH 65/82] Class Refactor (#5374) New tests in Hibernate with proxy --- .../hibernate/proxy/BatchEmployee.java | 56 ------------- .../proxy/{Boss.java => Company.java} | 25 +++--- .../baeldung/hibernate/proxy/Employee.java | 49 +++++++---- .../hibernate/proxy/HibernateUtil.java | 2 +- .../proxy/HibernateProxyUnitTest.java | 81 +++++++++++++------ 5 files changed, 105 insertions(+), 108 deletions(-) delete mode 100644 hibernate5/src/main/java/com/baeldung/hibernate/proxy/BatchEmployee.java rename hibernate5/src/main/java/com/baeldung/hibernate/proxy/{Boss.java => Company.java} (51%) diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/BatchEmployee.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/BatchEmployee.java deleted file mode 100644 index 00643ab3dd..0000000000 --- a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/BatchEmployee.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.hibernate.proxy; - -import org.hibernate.annotations.BatchSize; - -import javax.persistence.*; -import java.io.Serializable; - -@Entity -@BatchSize(size = 5) -public class BatchEmployee implements Serializable { - - @Id - @GeneratedValue (strategy = GenerationType.SEQUENCE) - private Long id; - - @ManyToOne(fetch = FetchType.LAZY) - private Boss boss; - - @Column(name = "name") - private String name; - - @Column(name = "surname") - private String surname; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Boss getBoss() { - return boss; - } - - public void setBoss(Boss boss) { - this.boss = boss; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getSurname() { - return surname; - } - - public void setSurname(String surname) { - this.surname = surname; - } -} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Boss.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java similarity index 51% rename from hibernate5/src/main/java/com/baeldung/hibernate/proxy/Boss.java rename to hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java index b6e01814d0..b21078dfeb 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Boss.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java @@ -2,9 +2,10 @@ package com.baeldung.hibernate.proxy; import javax.persistence.*; import java.io.Serializable; +import java.util.Objects; @Entity -public class Boss implements Serializable { +public class Company implements Serializable { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) @@ -13,14 +14,10 @@ public class Boss implements Serializable { @Column(name = "name") private String name; - @Column(name = "surname") - private String surname; + public Company() { } - public Boss() { } - - public Boss(String name, String surname) { + public Company(String name) { this.name = name; - this.surname = surname; } public Long getId() { @@ -39,11 +36,17 @@ public class Boss implements Serializable { this.name = name; } - public String getSurname() { - return surname; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Company company = (Company) o; + return Objects.equals(id, company.id) && + Objects.equals(name, company.name); } - public void setSurname(String surname) { - this.surname = surname; + @Override + public int hashCode() { + return Objects.hash(id, name); } } diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java index 6bc64c35ef..2c2aa7956d 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java @@ -1,9 +1,13 @@ package com.baeldung.hibernate.proxy; +import org.hibernate.annotations.BatchSize; + import javax.persistence.*; import java.io.Serializable; +import java.util.Objects; @Entity +@BatchSize(size = 5) public class Employee implements Serializable { @Id @@ -11,13 +15,17 @@ public class Employee implements Serializable { private Long id; @ManyToOne(fetch = FetchType.LAZY) - private Boss boss; + private Company workplace; - @Column(name = "name") - private String name; + @Column(name = "first_name") + private String firstName; - @Column(name = "surname") - private String surname; + public Employee() { } + + public Employee(Company workplace, String firstName) { + this.workplace = workplace; + this.firstName = firstName; + } public Long getId() { return id; @@ -27,27 +35,34 @@ public class Employee implements Serializable { this.id = id; } - public Boss getBoss() { - return boss; + public Company getWorkplace() { + return workplace; } - public void setBoss(Boss boss) { - this.boss = boss; + public void setWorkplace(Company workplace) { + this.workplace = workplace; } - public String getName() { - return name; + public String getFirstName() { + return firstName; } - public void setName(String name) { - this.name = name; + public void setFirstName(String firstName) { + this.firstName = firstName; } - public String getSurname() { - return surname; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Employee employee = (Employee) o; + return Objects.equals(id, employee.id) && + Objects.equals(workplace, employee.workplace) && + Objects.equals(firstName, employee.firstName); } - public void setSurname(String surname) { - this.surname = surname; + @Override + public int hashCode() { + return Objects.hash(id, workplace, firstName); } } diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java index e6ad0432bd..37c083049f 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java @@ -30,7 +30,7 @@ public class HibernateUtil { private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.proxy"); - metadataSources.addAnnotatedClass(Boss.class); + metadataSources.addAnnotatedClass(Company.class); metadataSources.addAnnotatedClass(Employee.class); Metadata metadata = metadataSources.buildMetadata(); diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java index fa41797dd2..242e6b41d7 100644 --- a/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java +++ b/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.hibernate.proxy; import org.hibernate.*; +import org.hibernate.proxy.HibernateProxy; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -8,25 +9,31 @@ import org.junit.Test; import static org.junit.Assert.*; import java.io.IOException; -import java.util.List; import static org.junit.Assert.fail; public class HibernateProxyUnitTest { + private SessionFactory factory; + private Session session; + private Company workplace; + + private Employee albert; + + private Employee bob; + + private Employee charlotte; + @Before public void init(){ try { - session = HibernateUtil.getSessionFactory("hibernate.properties") - .openSession(); + factory = HibernateUtil.getSessionFactory("hibernate.properties"); + session = factory.openSession(); } catch (HibernateException | IOException e) { fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); } - - Boss boss = new Boss("Eduard", "Freud"); - session.save(boss); } @After @@ -36,40 +43,68 @@ public class HibernateProxyUnitTest { } } - @Test(expected = NullPointerException.class) + @Test public void givenAnInexistentEmployeeId_whenUseGetMethod_thenReturnNull() { - Employee employee = session.get(Employee.class, new Long(14)); + Employee employee = session.get(Employee.class, 14L); + assertNull(employee); + } + + @Test(expected = ObjectNotFoundException.class) + public void givenAnInexistentEmployeeId_whenUseLoadMethod_thenThrowObjectNotFoundException() { + Employee employee = session.load(Employee.class, 999L); assertNull(employee); employee.getId(); } @Test public void givenAnInexistentEmployeeId_whenUseLoadMethod_thenReturnAProxy() { - Employee employee = session.load(Employee.class, new Long(14)); + Employee employee = session.load(Employee.class, 14L); assertNotNull(employee); + assertTrue(employee instanceof HibernateProxy); } @Test - public void givenABatchEmployeeList_whenSaveOne_thenSaveTheWholeBatch() { - Transaction transaction = session.beginTransaction(); + public void givenThreeEmployees_whenLoadThemWithBatch_thenReturnAllOfThemWithOneQuery() { + Transaction tx = session.beginTransaction(); - for (long i = 1; i <= 5; i++) { - Employee employee = new Employee(); - employee.setName("Employee " + i); - session.save(employee); - } + //We are saving 3 entities with one flush + + this.workplace = new Company("Bizco"); + session.save(workplace); + + this.albert = new Employee(workplace, "Albert"); + session.save(albert); + + this.bob = new Employee(workplace, "Bob"); + session.save(bob); + + this.charlotte = new Employee(workplace, "Charlotte"); + session.save(charlotte); - //After this line is possible to see all the insertions in the logs session.flush(); session.clear(); - transaction.commit(); - transaction = session.beginTransaction(); + tx.commit(); + session = factory.openSession(); - List employeeList = session.createQuery("from Employee") - .setCacheMode(CacheMode.IGNORE).getResultList(); + Employee proxyAlbert = session.load(Employee.class, this.albert.getId()); + assertNotNull(proxyAlbert); + assertTrue(proxyAlbert instanceof HibernateProxy); - assertEquals(employeeList.size(), 5); - transaction.commit(); + Employee proxyBob = session.load(Employee.class, this.bob.getId()); + assertNotNull(proxyBob); + assertTrue(proxyBob instanceof HibernateProxy); + + Employee proxyCharlotte = session.load(Employee.class, this.charlotte.getId()); + assertNotNull(proxyCharlotte); + assertTrue(proxyCharlotte instanceof HibernateProxy); + + //Fetching from database 3 entities with one call + //Select from log: where employee0_.id in (?, ?, ?) + proxyAlbert.getFirstName(); + + assertEquals(proxyAlbert, this.albert); + assertEquals(proxyBob, this.bob); + assertEquals(proxyCharlotte, this.charlotte); } } From 2c6a3a69b09ed2d901a452304030d21f5d3ca58a Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 2 Oct 2018 10:43:04 +0800 Subject: [PATCH 66/82] change example --- .../com/baeldung/kotlin/StructuralJumpTest.kt | 126 +++++++++--------- 1 file changed, 63 insertions(+), 63 deletions(-) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt index 076adfb94e..6866816517 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt @@ -4,118 +4,118 @@ import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFalse -class StructuralJumpTest { +class StructuralJumpTest { @Test fun givenLoop_whenBreak_thenComplete() { - var value = 0 - - //break loop without label - for (i in 1..10) { - value = i - if (value == 3) + var value = "" + for (i in 'a'..'e') { + value += i.toString() + if (i == 'c') break } - - assertEquals(value, 3) - - //break loop with label - outer_loop@ for (i in 1..10) { - for (j in 1..10) { - value = i * j - if (value == 30) + assertEquals("abc", value) + } + @Test + fun givenLoop_whenBreakWithLabel_thenComplete() { + var value = "" + outer_loop@ for (i in 'a'..'d') { + for (j in 1..3) { + value += "" + i + j + if (i == 'b' && j == 1) break@outer_loop } } - - assertEquals(value, 30) + assertEquals("a1a2a3b1", value) } @Test fun givenLoop_whenContinue_thenComplete() { - var processedList = mutableListOf() - //continue loop without label - for (i in 1..10) { - if (i == 3) + var result = "" + for (i in 'a'..'d') { + if (i == 'b') continue - processedList.add(i) + result += i } - - assert(processedList.all { it -> it != 3 }) - - //continue loop with label - processedList = mutableListOf() - outer_loop@ for (i in 1..10) { - for (j in 1..10) { - if (i == 3) + assertEquals("acd", result) + } + @Test + fun givenLoop_whenContinueWithLabel_thenComplete() { + var result = "" + outer_loop@ for (i in 'a'..'c') { + for (j in 1..3) { + if (i == 'b') continue@outer_loop - processedList.add(i*j) + result += "" + i + j } } - - assertEquals(processedList.size, 90) + assertEquals("a1a2a3c1c2c3", result) } @Test fun givenLambda_whenReturn_thenComplete() { - listOf(1, 2, 3, 4, 5).forEach { - if (it == 3) return // non-local return directly to the caller - assert(it < 3) + var result = returnInLambda(); + assertEquals("hello", result) + } + + private fun returnInLambda(): String { + var result = "" + "hello_world".forEach { + // non-local return directly to the caller + if (it == '_') return result + result += it.toString() } - //this point is unreachable - assert(false) + //this line won't be reached + return result; } @Test fun givenLambda_whenReturnWithExplicitLabel_thenComplete() { - var result = mutableListOf() - - listOf(1, 2, 3, 4, 5).forEach lit@{ - if (it == 3) { + var result = "" + "hello_world".forEach lit@{ + if (it == 'o') { // local return to the caller of the lambda, i.e. the forEach loop return@lit } - result.add(it) + result += it.toString() } - - assert(result.all { it -> it != 3 }) + assertEquals("hell_wrld", result) } @Test fun givenLambda_whenReturnWithImplicitLabel_thenComplete() { - var result = mutableListOf() - - listOf(1, 2, 3, 4, 5).forEach { - if (it == 3) { + var result = "" + "hello_world".forEach { + if (it == 'o') { // local return to the caller of the lambda, i.e. the forEach loop return@forEach } - result.add(it) + result += it.toString() } - - assert(result.all { it -> it != 3 }) + assertEquals("hell_wrld", result) } @Test fun givenAnonymousFunction_return_thenComplete() { - var result = mutableListOf() - listOf(1, 2, 3, 4, 5).forEach(fun(element: Int) { - if (element == 3) return // local return to the caller of the anonymous fun, i.e. the forEach loop - result.add(element) + var result = "" + "hello_world".forEach(fun(element) { + // local return to the caller of the anonymous fun, i.e. the forEach loop + if (element == 'o') return + result += element.toString() }) - - assert(result.all { it -> it != 3 }) + assertEquals("hell_wrld", result) } @Test fun givenAnonymousFunction_returnToLabel_thenComplete() { - var value = 0 + var result = "" run loop@{ - listOf(1, 2, 3, 4, 5).forEach { - value = it - if (it == 3) return@loop // non-local return from the lambda passed to run + "hello_world".forEach { + // non-local return from the lambda passed to run + if (it == '_') return@loop + result += it.toString() } } - assertEquals(value, 3) + assertEquals("hello", result) } } \ No newline at end of file From 9eb81e705999bf44e0ec5fdffe6cc8d1aa9d1d57 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 2 Oct 2018 10:45:31 +0800 Subject: [PATCH 67/82] change example --- .../com/baeldung/kotlin/StructuralJumpTest.kt | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt index 6866816517..b5183d3568 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt @@ -9,12 +9,12 @@ class StructuralJumpTest { @Test fun givenLoop_whenBreak_thenComplete() { var value = "" - for (i in 'a'..'e') { - value += i.toString() - if (i == 'c') + for (i in "hello_world") { + if (i == '_') break + value += i.toString() } - assertEquals("abc", value) + assertEquals("hello", value) } @Test fun givenLoop_whenBreakWithLabel_thenComplete() { @@ -32,12 +32,12 @@ class StructuralJumpTest { @Test fun givenLoop_whenContinue_thenComplete() { var result = "" - for (i in 'a'..'d') { - if (i == 'b') + for (i in "hello_world") { + if (i == '_') continue result += i } - assertEquals("acd", result) + assertEquals("helloworld", result) } @Test fun givenLoop_whenContinueWithLabel_thenComplete() { @@ -73,26 +73,26 @@ class StructuralJumpTest { fun givenLambda_whenReturnWithExplicitLabel_thenComplete() { var result = "" "hello_world".forEach lit@{ - if (it == 'o') { + if (it == '_') { // local return to the caller of the lambda, i.e. the forEach loop return@lit } result += it.toString() } - assertEquals("hell_wrld", result) + assertEquals("helloworld", result) } @Test fun givenLambda_whenReturnWithImplicitLabel_thenComplete() { var result = "" "hello_world".forEach { - if (it == 'o') { + if (it == '_') { // local return to the caller of the lambda, i.e. the forEach loop return@forEach } result += it.toString() } - assertEquals("hell_wrld", result) + assertEquals("helloworld", result) } @Test @@ -100,10 +100,10 @@ class StructuralJumpTest { var result = "" "hello_world".forEach(fun(element) { // local return to the caller of the anonymous fun, i.e. the forEach loop - if (element == 'o') return + if (element == '_') return result += element.toString() }) - assertEquals("hell_wrld", result) + assertEquals("helloworld", result) } @Test From acd7aa9852d8f26c4aca727d191f54545e477fe9 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Tue, 2 Oct 2018 12:21:22 +0300 Subject: [PATCH 68/82] disabling the jenkins hello workd module in the default profile --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7ece14150c..61a22b0b33 100644 --- a/pom.xml +++ b/pom.xml @@ -671,7 +671,7 @@ - jenkins/hello-world + From d663b472f27320a563db456ee885ca0e22735cfa Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Tue, 2 Oct 2018 13:45:48 +0300 Subject: [PATCH 69/82] temporarily disabling two modules --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 61a22b0b33..255fd46dc8 100644 --- a/pom.xml +++ b/pom.xml @@ -522,9 +522,9 @@ spring-rest-angular spring-rest-full spring-rest-query-language - spring-rest + + spring-resttemplate - spring-rest-simple spring-security-acl spring-security-cache-control spring-security-client/spring-security-jsp-authentication From 27cb74d30ecc5faae86b0b5f238385cd6c59f23d Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Tue, 2 Oct 2018 13:51:01 +0300 Subject: [PATCH 70/82] trying out a profile split --- pom.xml | 282 ++++++++++++++++++++++++++++++++------------------------ 1 file changed, 160 insertions(+), 122 deletions(-) diff --git a/pom.xml b/pom.xml index 255fd46dc8..385a8dfc6d 100644 --- a/pom.xml +++ b/pom.xml @@ -290,7 +290,7 @@ - default + default-first @@ -562,130 +562,168 @@ spring-reactor spring-vertx spring-jinq - spring-rest-embedded-tomcat - testing-modules/testing - testing-modules/testng - video-tutorials - xml - xmlunit-2 - struts-2 - apache-velocity - apache-solrj - rabbitmq - vertx - persistence-modules/spring-data-gemfire - mybatis - spring-drools - drools - persistence-modules/liquibase - spring-boot-property-exp - testing-modules/mockserver - testing-modules/test-containers - undertow - vaadin - vertx-and-rxjava - saas - deeplearning4j - lucene - vraptor - persistence-modules/java-cockroachdb - spring-security-thymeleaf - persistence-modules/java-jdbi - jersey - java-spi - performance-tests - twilio - spring-boot-ctx-fluent - java-ee-8-security-api - spring-webflux-amqp - antlr - maven-archetype - optaplanner - apache-meecrowave - spring-reactive-kotlin - jnosql - spring-boot-angular-ecommerce - cdi-portable-extension - jta - - java-websocket - activejdbc - animal-sniffer-mvn-plugin - apache-avro - apache-bval - apache-shiro - apache-spark - asciidoctor - checker-plugin - - - core-java-sun - custom-pmd - dagger - data-structures - dubbo - flyway - - java-difference-date - - jni - jooby - - - - ratpack - rest-with-spark-java - spring-boot-autoconfiguration - spring-boot-custom-starter - spring-boot-jasypt - spring-custom-aop - spring-data-rest-querydsl - spring-groovy - spring-mobile - spring-mustache - spring-mvc-simple - spring-mybatis - spring-rest-hal-browser - spring-rest-shell - spring-rest-template - spring-roo - spring-security-stormpath - sse-jaxrs - static-analysis - stripe - - Twitter4J - wicket - xstream - cas/cas-secured-app - cas/cas-server - - - - - - - - - - - - - - - - - spring-boot-custom-starter/greeter - spring-boot-h2/spring-boot-h2-database - - - - - flyway-cdi-extension + + 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 + + + + + + + + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + parent-kotlin + + spring-rest-embedded-tomcat + testing-modules/testing + testing-modules/testng + video-tutorials + xml + xmlunit-2 + struts-2 + apache-velocity + apache-solrj + rabbitmq + vertx + persistence-modules/spring-data-gemfire + mybatis + spring-drools + drools + persistence-modules/liquibase + spring-boot-property-exp + testing-modules/mockserver + testing-modules/test-containers + undertow + vaadin + vertx-and-rxjava + saas + deeplearning4j + lucene + vraptor + persistence-modules/java-cockroachdb + spring-security-thymeleaf + persistence-modules/java-jdbi + jersey + java-spi + performance-tests + twilio + spring-boot-ctx-fluent + java-ee-8-security-api + spring-webflux-amqp + antlr + maven-archetype + optaplanner + apache-meecrowave + spring-reactive-kotlin + jnosql + spring-boot-angular-ecommerce + cdi-portable-extension + jta + + java-websocket + activejdbc + animal-sniffer-mvn-plugin + apache-avro + apache-bval + apache-shiro + apache-spark + asciidoctor + checker-plugin + + + core-java-sun + custom-pmd + dagger + data-structures + dubbo + flyway + + java-difference-date + + jni + jooby + + + + ratpack + rest-with-spark-java + spring-boot-autoconfiguration + spring-boot-custom-starter + spring-boot-jasypt + spring-custom-aop + spring-data-rest-querydsl + spring-groovy + spring-mobile + spring-mustache + spring-mvc-simple + spring-mybatis + spring-rest-hal-browser + spring-rest-shell + spring-rest-template + spring-roo + spring-security-stormpath + sse-jaxrs + static-analysis + stripe + + Twitter4J + wicket + xstream + cas/cas-secured-app + cas/cas-server + + + + + + + + + + + + + + + + + spring-boot-custom-starter/greeter + spring-boot-h2/spring-boot-h2-database + + + + + flyway-cdi-extension + + + + spring-context @@ -1034,7 +1072,7 @@ spring-rest spring-resttemplate spring-rest-simple - spring-reactive-kotlin + spring-reactive-kotlin From adbace2aaad0f8f86e30a59f699f9b4f1a875860 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Tue, 2 Oct 2018 13:54:35 +0300 Subject: [PATCH 71/82] profile fix --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index 385a8dfc6d..79438cac84 100644 --- a/pom.xml +++ b/pom.xml @@ -1486,7 +1486,6 @@ spring-security-thymeleaf persistence-modules/java-jdbi jersey - jersey-client-rx java-spi performance-tests twilio From 52c2ce4ede9980b37ed1d36491f8217b40117df9 Mon Sep 17 00:00:00 2001 From: Josh Cummings Date: Tue, 2 Oct 2018 07:11:43 -0600 Subject: [PATCH 72/82] Adding apache-geode module to build (#5367) --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 79438cac84..ef34881cef 100644 --- a/pom.xml +++ b/pom.xml @@ -332,6 +332,7 @@ annotations apache-cxf apache-fop + apache-geode apache-poi apache-tika apache-thrift From 9a085b0e8f1ac6892dca4eff4ca9e6edeb476547 Mon Sep 17 00:00:00 2001 From: Josh Cummings Date: Tue, 2 Oct 2018 07:22:12 -0600 Subject: [PATCH 73/82] Polish Session.load Tests (#5378) Cleaned up some confusing wording and a confusing test. Added two more tests for demonstrating how session.load works with associations. Issue: BAEL-2126 --- .../com/baeldung/hibernate/proxy/Company.java | 10 ++++ .../baeldung/hibernate/proxy/Employee.java | 1 + .../proxy/HibernateProxyUnitTest.java | 54 +++++++++++++++++-- 3 files changed, 61 insertions(+), 4 deletions(-) diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java index b21078dfeb..f146a8674e 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java @@ -2,7 +2,9 @@ package com.baeldung.hibernate.proxy; import javax.persistence.*; import java.io.Serializable; +import java.util.HashSet; import java.util.Objects; +import java.util.Set; @Entity public class Company implements Serializable { @@ -14,6 +16,10 @@ public class Company implements Serializable { @Column(name = "name") private String name; + @OneToMany + @JoinColumn(name = "workplace_id") + private Set employees = new HashSet<>(); + public Company() { } public Company(String name) { @@ -36,6 +42,10 @@ public class Company implements Serializable { this.name = name; } + public Set getEmployees() { + return this.employees; + } + @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java index 2c2aa7956d..4bc0b8f25c 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java @@ -15,6 +15,7 @@ public class Employee implements Serializable { private Long id; @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "workplace_id") private Company workplace; @Column(name = "first_name") diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java index 242e6b41d7..0a4caf032b 100644 --- a/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java +++ b/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java @@ -50,19 +50,65 @@ public class HibernateProxyUnitTest { } @Test(expected = ObjectNotFoundException.class) - public void givenAnInexistentEmployeeId_whenUseLoadMethod_thenThrowObjectNotFoundException() { + public void givenAnNonExistentEmployeeId_whenUseLoadMethod_thenThrowObjectNotFoundException() { Employee employee = session.load(Employee.class, 999L); - assertNull(employee); - employee.getId(); + assertNotNull(employee); + employee.getFirstName(); } @Test - public void givenAnInexistentEmployeeId_whenUseLoadMethod_thenReturnAProxy() { + public void givenAnNonExistentEmployeeId_whenUseLoadMethod_thenReturnAProxy() { Employee employee = session.load(Employee.class, 14L); assertNotNull(employee); assertTrue(employee instanceof HibernateProxy); } + @Test + public void givenAnEmployeeFromACompany_whenUseLoadMethod_thenCompanyIsAProxy() { + Transaction tx = session.beginTransaction(); + + this.workplace = new Company("Bizco"); + session.save(workplace); + + this.albert = new Employee(workplace, "Albert"); + session.save(albert); + + session.flush(); + session.clear(); + + tx.commit(); + this.session = factory.openSession(); + + Employee proxyAlbert = session.load(Employee.class, albert.getId()); + assertTrue(proxyAlbert instanceof HibernateProxy); + + // with many-to-one lazy-loading, associations remain proxies + assertTrue(proxyAlbert.getWorkplace() instanceof HibernateProxy); + } + + @Test + public void givenACompanyWithEmployees_whenUseLoadMethod_thenEmployeesAreProxies() { + Transaction tx = session.beginTransaction(); + + this.workplace = new Company("Bizco"); + session.save(workplace); + + this.albert = new Employee(workplace, "Albert"); + session.save(albert); + + session.flush(); + session.clear(); + + tx.commit(); + this.session = factory.openSession(); + + Company proxyBizco = session.load(Company.class, workplace.getId()); + assertTrue(proxyBizco instanceof HibernateProxy); + + // with one-to-many, associations aren't proxies + assertFalse(proxyBizco.getEmployees().iterator().next() instanceof HibernateProxy); + } + @Test public void givenThreeEmployees_whenLoadThemWithBatch_thenReturnAllOfThemWithOneQuery() { Transaction tx = session.beginTransaction(); From 5f2b7d5fef2f068eae525145ab52480e4513912c Mon Sep 17 00:00:00 2001 From: eelhazati Date: Tue, 2 Oct 2018 21:35:45 +0100 Subject: [PATCH 74/82] Maven polyglot --- .../.mvn/extensions.xml | 8 ++ .../maven-polyglot-json-app/pom.json | 34 ++++++ .../polyglot/MavenPolyglotApplication.java | 19 +++ .../src/main/resources/model.json | 109 ++++++++++++++++++ .../maven-polyglot-json-extension/pom.xml | 47 ++++++++ .../demo/polyglot/CustomModelProcessor.java | 62 ++++++++++ .../.mvn/extensions.xml | 8 ++ maven-polyglot/maven-polyglot-yml-app/pom.yml | 7 ++ .../maven/polyglot/YamlDemoApplication.java | 7 ++ .../src/main/resources/model.json | 109 ++++++++++++++++++ 10 files changed, 410 insertions(+) create mode 100644 maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml create mode 100644 maven-polyglot/maven-polyglot-json-app/pom.json create mode 100644 maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java create mode 100644 maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json create mode 100644 maven-polyglot/maven-polyglot-json-extension/pom.xml create mode 100644 maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java create mode 100644 maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml create mode 100644 maven-polyglot/maven-polyglot-yml-app/pom.yml create mode 100644 maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java create mode 100644 maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json diff --git a/maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml b/maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml new file mode 100644 index 0000000000..c06b76e1b2 --- /dev/null +++ b/maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml @@ -0,0 +1,8 @@ + + + + com.baeldung.maven.polyglot + maven-polyglot-json-extension + 1.0-SNAPSHOT + + \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-json-app/pom.json b/maven-polyglot/maven-polyglot-json-app/pom.json new file mode 100644 index 0000000000..abd58f3127 --- /dev/null +++ b/maven-polyglot/maven-polyglot-json-app/pom.json @@ -0,0 +1,34 @@ +{ + "modelVersion": "4.0.0", + "groupId": "com.baeldung.maven.polyglot", + "artifactId": "maven-polyglot-json-app", + "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 + }, + "properties": { + "project.build.sourceEncoding": "UTF-8", + "project.reporting.outputEncoding": "UTF-8", + "maven.compiler.source": "1.8", + "maven.compiler.target": "1.8", + "java.version": "1.8" + }, + "dependencies": [ + { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-starter-web" + } + ], + "build": { + "plugins": [ + { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-maven-plugin" + } + ] + } +} \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java b/maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java new file mode 100644 index 0000000000..d03116889f --- /dev/null +++ b/maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.maven.polyglot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.GetMapping; + +@RestController +@SpringBootApplication +public class MavenPolyglotApplication { + public static void main(String[] args) { + SpringApplication.run(MavenPolyglotApplication.class, args); + } + + @GetMapping("/") + public String home(){ + return "Hello JSON Maven Model !"; + } +} diff --git a/maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json b/maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json new file mode 100644 index 0000000000..f006582c12 --- /dev/null +++ b/maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json @@ -0,0 +1,109 @@ +{ + "modules": [], + "distributionManagement": null, + "properties": { + "project.reporting.outputEncoding": "UTF-8", + "java.version": "1.8", + "maven.compiler.source": "1.8", + "project.build.sourceEncoding": "UTF-8", + "maven.compiler.target": "1.8" + }, + "dependencyManagement": null, + "dependencies": [ + { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-starter-web", + "version": null, + "type": "jar", + "classifier": null, + "scope": null, + "systemPath": null, + "exclusions": [], + "optional": null, + "managementKey": "org.springframework.boot:spring-boot-starter-web:jar" + } + ], + "repositories": [], + "pluginRepositories": [], + "reports": null, + "reporting": null, + "modelVersion": "4.0.0", + "parent": { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-starter-parent", + "version": "2.0.5.RELEASE", + "relativePath": "", + "id": "org.springframework.boot:spring-boot-starter-parent:pom:2.0.5.RELEASE" + }, + "groupId": "com.demo.polyglot", + "artifactId": "maven-polyglot-app", + "version": "1.0.1", + "packaging": "jar", + "name": "Json Maven Polyglot", + "description": null, + "url": null, + "inceptionYear": null, + "organization": null, + "licenses": [], + "developers": [], + "contributors": [], + "mailingLists": [], + "prerequisites": null, + "scm": null, + "issueManagement": null, + "ciManagement": null, + "build": { + "plugins": [ + { + "inherited": null, + "configuration": null, + "inheritanceApplied": true, + "groupId": "org.liquibase", + "artifactId": "liquibase-maven-plugin", + "version": "3.0.5", + "extensions": null, + "executions": [], + "dependencies": [], + "goals": null, + "key": "org.liquibase:liquibase-maven-plugin", + "id": "org.liquibase:liquibase-maven-plugin:3.0.5", + "executionsAsMap": {} + } + ], + "pluginManagement": null, + "defaultGoal": null, + "resources": [], + "testResources": [], + "directory": null, + "finalName": null, + "filters": [], + "sourceDirectory": null, + "scriptSourceDirectory": null, + "testSourceDirectory": null, + "outputDirectory": null, + "testOutputDirectory": null, + "extensions": [], + "pluginsAsMap": { + "org.liquibase:liquibase-maven-plugin": { + "inherited": null, + "configuration": null, + "inheritanceApplied": true, + "groupId": "org.liquibase", + "artifactId": "liquibase-maven-plugin", + "version": "3.0.5", + "extensions": null, + "executions": [], + "dependencies": [], + "goals": null, + "key": "org.liquibase:liquibase-maven-plugin", + "id": "org.liquibase:liquibase-maven-plugin:3.0.5", + "executionsAsMap": {} + } + } + }, + "profiles": [], + "modelEncoding": "UTF-8", + "pomFile": null, + "id": "com.demo.polyglot:maven-polyglot-app:jar:1.0.1", + "projectDirectory": null +} diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-polyglot/maven-polyglot-json-extension/pom.xml new file mode 100644 index 0000000000..d5c5b7ab55 --- /dev/null +++ b/maven-polyglot/maven-polyglot-json-extension/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + + com.baeldung.maven.polyglot + maven-polyglot-json-extension + 1.0-SNAPSHOT + + + 1.8 + 1.8 + + + + + org.apache.maven + maven-core + 3.5.4 + provided + + + com.fasterxml.jackson.core + jackson-databind + 2.9.6 + + + + + + + org.codehaus.plexus + plexus-component-metadata + 1.7.1 + + + + generate-metadata + + + + + + + + \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java b/maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java new file mode 100644 index 0000000000..a1756192e9 --- /dev/null +++ b/maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java @@ -0,0 +1,62 @@ +package com.demo.polyglot; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.maven.model.Model; +import org.apache.maven.model.building.FileModelSource; +import org.apache.maven.model.building.ModelProcessor; +import org.apache.maven.model.io.ModelParseException; +import org.apache.maven.model.io.ModelReader; +import org.codehaus.plexus.component.annotations.Component; +import org.codehaus.plexus.component.annotations.Requirement; +import org.codehaus.plexus.util.ReaderFactory; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.util.Map; + +@Component(role = ModelProcessor.class) +public class CustomModelProcessor implements ModelProcessor { + + private static final String XML_POM = "pom.xml"; + private static final String JSON_POM = "pom.json"; + private static final String JSON_EXT = ".json"; + + ObjectMapper objectMapper = new ObjectMapper(); + + @Requirement + private ModelReader modelReader; + + @Override + public File locatePom(File projectDirectory) { + File pomFile = new File(projectDirectory, JSON_POM); + if (!pomFile.exists()) { + pomFile = new File(projectDirectory, XML_POM); + } + return pomFile; + } + + @Override + public Model read(InputStream input, Map options) throws IOException, ModelParseException { + try (final Reader in = ReaderFactory.newPlatformReader(input)) { + return read(in, options); + } + } + + @Override + public Model read(Reader reader, Map options) throws IOException, ModelParseException { + FileModelSource source = (options != null) ? (FileModelSource) options.get(SOURCE) : null; + if (source != null && source.getLocation().endsWith(JSON_EXT)) { + Model model = objectMapper.readValue(reader, Model.class); + return model; + } + //It's a normal maven project with a pom.xml file + return modelReader.read(reader, options); + } + + @Override + public Model read(File input, Map options) throws IOException, ModelParseException { + return null; + } +} \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml b/maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml new file mode 100644 index 0000000000..cfc6275681 --- /dev/null +++ b/maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml @@ -0,0 +1,8 @@ + + + + io.takari.polyglot + polyglot-yaml + 0.3.1 + + \ 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 new file mode 100644 index 0000000000..445e2eec3b --- /dev/null +++ b/maven-polyglot/maven-polyglot-yml-app/pom.yml @@ -0,0 +1,7 @@ +modelVersion: 4.0.0 +groupId: com.baeldung.maven.polyglot +artifactId: maven-polyglot-yml-app +version: 1.0-SNAPSHOT +name: 'YAML Demo' + +properties: {maven.compiler.source: 1.8, maven.compiler.target: 1.8} \ No newline at end of file diff --git a/maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java b/maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java new file mode 100644 index 0000000000..2142c7f9b8 --- /dev/null +++ b/maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java @@ -0,0 +1,7 @@ +package com.baeldung.maven.polyglot; + +public class YamlDemoApplication { + public static void main(String[] args) { + System.out.println("Hello Maven Polyglot YAML !"); + } +} diff --git a/maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json b/maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json new file mode 100644 index 0000000000..f006582c12 --- /dev/null +++ b/maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json @@ -0,0 +1,109 @@ +{ + "modules": [], + "distributionManagement": null, + "properties": { + "project.reporting.outputEncoding": "UTF-8", + "java.version": "1.8", + "maven.compiler.source": "1.8", + "project.build.sourceEncoding": "UTF-8", + "maven.compiler.target": "1.8" + }, + "dependencyManagement": null, + "dependencies": [ + { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-starter-web", + "version": null, + "type": "jar", + "classifier": null, + "scope": null, + "systemPath": null, + "exclusions": [], + "optional": null, + "managementKey": "org.springframework.boot:spring-boot-starter-web:jar" + } + ], + "repositories": [], + "pluginRepositories": [], + "reports": null, + "reporting": null, + "modelVersion": "4.0.0", + "parent": { + "groupId": "org.springframework.boot", + "artifactId": "spring-boot-starter-parent", + "version": "2.0.5.RELEASE", + "relativePath": "", + "id": "org.springframework.boot:spring-boot-starter-parent:pom:2.0.5.RELEASE" + }, + "groupId": "com.demo.polyglot", + "artifactId": "maven-polyglot-app", + "version": "1.0.1", + "packaging": "jar", + "name": "Json Maven Polyglot", + "description": null, + "url": null, + "inceptionYear": null, + "organization": null, + "licenses": [], + "developers": [], + "contributors": [], + "mailingLists": [], + "prerequisites": null, + "scm": null, + "issueManagement": null, + "ciManagement": null, + "build": { + "plugins": [ + { + "inherited": null, + "configuration": null, + "inheritanceApplied": true, + "groupId": "org.liquibase", + "artifactId": "liquibase-maven-plugin", + "version": "3.0.5", + "extensions": null, + "executions": [], + "dependencies": [], + "goals": null, + "key": "org.liquibase:liquibase-maven-plugin", + "id": "org.liquibase:liquibase-maven-plugin:3.0.5", + "executionsAsMap": {} + } + ], + "pluginManagement": null, + "defaultGoal": null, + "resources": [], + "testResources": [], + "directory": null, + "finalName": null, + "filters": [], + "sourceDirectory": null, + "scriptSourceDirectory": null, + "testSourceDirectory": null, + "outputDirectory": null, + "testOutputDirectory": null, + "extensions": [], + "pluginsAsMap": { + "org.liquibase:liquibase-maven-plugin": { + "inherited": null, + "configuration": null, + "inheritanceApplied": true, + "groupId": "org.liquibase", + "artifactId": "liquibase-maven-plugin", + "version": "3.0.5", + "extensions": null, + "executions": [], + "dependencies": [], + "goals": null, + "key": "org.liquibase:liquibase-maven-plugin", + "id": "org.liquibase:liquibase-maven-plugin:3.0.5", + "executionsAsMap": {} + } + } + }, + "profiles": [], + "modelEncoding": "UTF-8", + "pomFile": null, + "id": "com.demo.polyglot:maven-polyglot-app:jar:1.0.1", + "projectDirectory": null +} From 450709d13b47e05d675ce8239cd5336319ffda42 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Wed, 3 Oct 2018 16:59:44 +0000 Subject: [PATCH 75/82] Using Math.sin with Degrees Issue: BAEL-2157 --- .../com/baeldung/maths/MathSinUnitTest.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 java-numbers/src/test/java/com/baeldung/maths/MathSinUnitTest.java diff --git a/java-numbers/src/test/java/com/baeldung/maths/MathSinUnitTest.java b/java-numbers/src/test/java/com/baeldung/maths/MathSinUnitTest.java new file mode 100644 index 0000000000..111b2f4465 --- /dev/null +++ b/java-numbers/src/test/java/com/baeldung/maths/MathSinUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.maths; + +import static org.junit.Assert.assertTrue; + +import org.junit.jupiter.api.Test; + +public class MathSinUnitTest { + + @Test + public void givenAnAngleInDegrees_whenUsingToRadians_thenResultIsInRadians() { + double angleInDegrees = 30; + double sinForDegrees = Math.sin(Math.toRadians(angleInDegrees)); // 0.5 + + double thirtyDegreesInRadians = 1/6 * Math.PI; + double sinForRadians = Math.sin(thirtyDegreesInRadians); // 0.5 + + assertTrue(sinForDegrees == sinForRadians); + } + +} From 0b792c58f21e55904e53600ab577b2cdefb92b3b Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 3 Oct 2018 21:29:42 +0300 Subject: [PATCH 76/82] Update and rename StructuralJumpTest.kt to StructuralJumpUnitTest.kt --- .../{StructuralJumpTest.kt => StructuralJumpUnitTest.kt} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename core-kotlin/src/test/kotlin/com/baeldung/kotlin/{StructuralJumpTest.kt => StructuralJumpUnitTest.kt} (98%) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt similarity index 98% rename from core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt rename to core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt index b5183d3568..436dc9e2ba 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/StructuralJumpUnitTest.kt @@ -4,7 +4,7 @@ import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFalse -class StructuralJumpTest { +class StructuralJumpUnitTest { @Test fun givenLoop_whenBreak_thenComplete() { @@ -118,4 +118,4 @@ class StructuralJumpTest { } assertEquals("hello", result) } -} \ No newline at end of file +} From 0093ee4c3a388eea91f32ed450a9ce20be38cb15 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 3 Oct 2018 22:13:41 +0300 Subject: [PATCH 77/82] Create README.md --- maven-polyglot/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 maven-polyglot/README.md diff --git a/maven-polyglot/README.md b/maven-polyglot/README.md new file mode 100644 index 0000000000..589315efd1 --- /dev/null +++ b/maven-polyglot/README.md @@ -0,0 +1,3 @@ +To run the maven-polyglot-json-app successfully, you first have to build the maven-polyglot-json-extension module using: mvn clean install. + +Related Articles: From 75f1d41340bb409c5a01676d52371ce4b9e8e3be Mon Sep 17 00:00:00 2001 From: Eugen Date: Thu, 4 Oct 2018 18:51:37 +0100 Subject: [PATCH 78/82] Update README.md --- README.md | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index d20968b455..ac52f72f5e 100644 --- a/README.md +++ b/README.md @@ -10,13 +10,14 @@ And here's the Master Class of Learn Spring Security:
-Spring Tutorials +Java and Spring Tutorials ================ -This project is **a collection of small and focused tutorials** each covering a single and well defined area of development. -Most of the tutorial projects are focused on the `Spring Framework` (and `Spring Security`). +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 Securiyt. In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`. + Building the project ==================== To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false` @@ -28,15 +29,3 @@ Any IDE can be used to work with the projects, but if you're using Eclipse, cons - import the included **formatter** in Eclipse: `https://github.com/eugenp/tutorials/tree/master/eclipse` - - -CI - Jenkins -================================ -This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)** - -### Relevant Articles: -================================ - -- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure) -- [Apache Maven Tutorial](http://www.baeldung.com/maven) -- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library) From 950631923c649f8f3c35d2ee55157cc6d36338f9 Mon Sep 17 00:00:00 2001 From: Eugen Date: Thu, 4 Oct 2018 18:52:03 +0100 Subject: [PATCH 79/82] Update README.md --- README.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/README.md b/README.md index ac52f72f5e..06363da79d 100644 --- a/README.md +++ b/README.md @@ -21,11 +21,3 @@ In additional to Spring, the following technologies are in focus: `core Java`, ` Building the project ==================== To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false` - - -Working with the code in Eclipse -================================ -Any IDE can be used to work with the projects, but if you're using Eclipse, consider the following. - -- import the included **formatter** in Eclipse: -`https://github.com/eugenp/tutorials/tree/master/eclipse` From c63187b581108587668dbacc0fa704605e5ca2ac Mon Sep 17 00:00:00 2001 From: Eugen Date: Thu, 4 Oct 2018 19:01:20 +0100 Subject: [PATCH 80/82] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 06363da79d..ea6f4c2243 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ The "REST with Spring" Classes ============================== -Here's the Master Class of REST With Spring (price changes permanently next Friday):
+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:
From 01a38b89b90f1f792190fe0831861b5da363a589 Mon Sep 17 00:00:00 2001 From: Eugen Date: Thu, 4 Oct 2018 19:01:50 +0100 Subject: [PATCH 81/82] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ea6f4c2243..adb17ca7e5 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,10 @@ The "REST with Spring" Classes ============================== 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)** +**[>> 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)** +**[>> 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)** From bfe1429851f91d8439530d2fdaef2bc9cdc54e44 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Thu, 4 Oct 2018 19:19:33 +0100 Subject: [PATCH 82/82] moving modules between profiles --- pom.xml | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/pom.xml b/pom.xml index ef34881cef..a499aac7ee 100644 --- a/pom.xml +++ b/pom.xml @@ -551,18 +551,6 @@ spring-security-rest spring-security-sso spring-security-x509 - spring-session - spring-sleuth - spring-social-login - spring-spel - spring-state-machine - spring-thymeleaf - spring-userservice - spring-zuul - spring-remoting - spring-reactor - spring-vertx - spring-jinq
@@ -601,6 +589,18 @@ parent-java parent-kotlin + spring-session + spring-sleuth + spring-social-login + spring-spel + spring-state-machine + spring-thymeleaf + spring-userservice + spring-zuul + spring-remoting + spring-reactor + spring-vertx + spring-jinq spring-rest-embedded-tomcat testing-modules/testing testing-modules/testng