diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..40f5c88746 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Eugen Paraschiv + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/algorithms/README.md b/algorithms/README.md index b0c5ee9d77..5f101c296c 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -14,3 +14,4 @@ - [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort) - [Introduction to JGraphT](http://www.baeldung.com/jgrapht) - [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm) +- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance) diff --git a/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java b/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java new file mode 100644 index 0000000000..48d51a8848 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/prime/PrimeGenerator.java @@ -0,0 +1,59 @@ +package com.baeldung.algorithms.prime; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class PrimeGenerator { + public static List sieveOfEratosthenes(int n) { + final boolean prime[] = new boolean[n + 1]; + Arrays.fill(prime, true); + + for (int p = 2; p * p <= n; p++) { + if (prime[p]) { + for (int i = p * 2; i <= n; i += p) + prime[i] = false; + } + } + + final List primes = new LinkedList<>(); + for (int i = 2; i <= n; i++) { + if (prime[i]) + primes.add(i); + } + return primes; + } + + public static List primeNumbersBruteForce(int max) { + final List primeNumbers = new LinkedList(); + for (int i = 2; i <= max; i++) { + if (isPrimeBruteForce(i)) { + primeNumbers.add(i); + } + } + return primeNumbers; + } + + private static boolean isPrimeBruteForce(int x) { + for (int i = 2; i < x; i++) { + if (x % i == 0) { + return false; + } + } + return true; + } + + public static List primeNumbersTill(int max) { + return IntStream.rangeClosed(2, max) + .filter(x -> isPrime(x)) + .boxed() + .collect(Collectors.toList()); + } + + private static boolean isPrime(int x) { + return IntStream.rangeClosed(2, (int) (Math.sqrt(x))) + .allMatch(n -> x % n != 0); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java new file mode 100644 index 0000000000..4995e938b7 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java @@ -0,0 +1,28 @@ +package com.baeldung.algorithms.prime; + +import static com.baeldung.algorithms.prime.PrimeGenerator.*; + +import java.util.Arrays; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +public class PrimeGeneratorTest { + @Test + public void whenBruteForced_returnsSuccessfully() { + final List primeNumbers = primeNumbersBruteForce(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenOptimized_returnsSuccessfully() { + final List primeNumbers = primeNumbersTill(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenSieveOfEratosthenes_returnsSuccessfully() { + final List primeNumbers = sieveOfEratosthenes(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } +} diff --git a/apache-poi/src/main/java/com/baeldung/poi/powerpoint/PowerPointHelper.java b/apache-poi/src/main/java/com/baeldung/poi/powerpoint/PowerPointHelper.java new file mode 100644 index 0000000000..e2af4f8808 --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/poi/powerpoint/PowerPointHelper.java @@ -0,0 +1,224 @@ +package com.baeldung.poi.powerpoint; + +import org.apache.poi.sl.usermodel.AutoNumberingScheme; +import org.apache.poi.sl.usermodel.PictureData; +import org.apache.poi.sl.usermodel.TableCell; +import org.apache.poi.sl.usermodel.TextParagraph; +import org.apache.poi.util.IOUtils; +import org.apache.poi.xslf.usermodel.*; + +import java.awt.*; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Helper class for the PowerPoint presentation creation + */ +public class PowerPointHelper { + + /** + * Read an existing presentation + * + * @param fileLocation + * File location of the presentation + * @return instance of {@link XMLSlideShow} + * @throws IOException + */ + public XMLSlideShow readingExistingSlideShow(String fileLocation) throws IOException { + return new XMLSlideShow(new FileInputStream(fileLocation)); + } + + /** + * Create a sample presentation + * + * @param fileLocation + * File location of the presentation + * @throws IOException + */ + public void createPresentation(String fileLocation) throws IOException { + // Create presentation + XMLSlideShow ppt = new XMLSlideShow(); + + XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0); + + // Retriving the slide layout + XSLFSlideLayout layout = defaultMaster.getLayout(SlideLayout.TITLE_ONLY); + + // Creating the 1st slide + XSLFSlide slide1 = ppt.createSlide(layout); + XSLFTextShape title = slide1.getPlaceholder(0); + // Clearing text to remove the predefined one in the template + title.clearText(); + XSLFTextParagraph p = title.addNewTextParagraph(); + + XSLFTextRun r1 = p.addNewTextRun(); + r1.setText("Baeldung"); + r1.setFontColor(new Color(78, 147, 89)); + r1.setFontSize(48.); + + // Add Image + ClassLoader classLoader = getClass().getClassLoader(); + byte[] pictureData = IOUtils.toByteArray(new FileInputStream(classLoader.getResource("logo-leaf.png").getFile())); + + XSLFPictureData pd = ppt.addPicture(pictureData, PictureData.PictureType.PNG); + XSLFPictureShape picture = slide1.createPicture(pd); + picture.setAnchor(new Rectangle(320, 230, 100, 92)); + + // Creating 2nd slide + layout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT); + XSLFSlide slide2 = ppt.createSlide(layout); + + // setting the tile + title = slide2.getPlaceholder(0); + title.clearText(); + XSLFTextRun r = title.addNewTextParagraph().addNewTextRun(); + r.setText("Baeldung"); + + // Adding the link + XSLFHyperlink link = r.createHyperlink(); + link.setAddress("http://www.baeldung.com"); + + // setting the content + XSLFTextShape content = slide2.getPlaceholder(1); + content.clearText(); // unset any existing text + content.addNewTextParagraph().addNewTextRun().setText("First paragraph"); + content.addNewTextParagraph().addNewTextRun().setText("Second paragraph"); + content.addNewTextParagraph().addNewTextRun().setText("Third paragraph"); + + // Creating 3rd slide - List + layout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT); + XSLFSlide slide3 = ppt.createSlide(layout); + title = slide3.getPlaceholder(0); + title.clearText(); + r = title.addNewTextParagraph().addNewTextRun(); + r.setText("Lists"); + + content = slide3.getPlaceholder(1); + content.clearText(); + XSLFTextParagraph p1 = content.addNewTextParagraph(); + p1.setIndentLevel(0); + p1.setBullet(true); + r1 = p1.addNewTextRun(); + r1.setText("Bullet"); + + // the next three paragraphs form an auto-numbered list + XSLFTextParagraph p2 = content.addNewTextParagraph(); + p2.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1); + p2.setIndentLevel(1); + XSLFTextRun r2 = p2.addNewTextRun(); + r2.setText("Numbered List Item - 1"); + + // Creating 4th slide + XSLFSlide slide4 = ppt.createSlide(); + createTable(slide4); + + // Save presentation + FileOutputStream out = new FileOutputStream(fileLocation); + ppt.write(out); + out.close(); + + // Closing presentation + ppt.close(); + } + + /** + * Delete a slide from the presentation + * + * @param ppt + * The presentation + * @param slideNumber + * The number of the slide to be deleted (0-based) + */ + public void deleteSlide(XMLSlideShow ppt, int slideNumber) { + ppt.removeSlide(slideNumber); + } + + /** + * Re-order the slides inside a presentation + * + * @param ppt + * The presentation + * @param slideNumber + * The number of the slide to move + * @param newSlideNumber + * The new position of the slide (0-base) + */ + public void reorderSlide(XMLSlideShow ppt, int slideNumber, int newSlideNumber) { + List slides = ppt.getSlides(); + + XSLFSlide secondSlide = slides.get(slideNumber); + ppt.setSlideOrder(secondSlide, newSlideNumber); + } + + /** + * Retrieve the placeholder inside a slide + * + * @param slide + * The slide + * @return List of placeholder inside a slide + */ + public List retrieveTemplatePlaceholders(XSLFSlide slide) { + List placeholders = new ArrayList<>(); + + for (XSLFShape shape : slide.getShapes()) { + if (shape instanceof XSLFAutoShape) { + placeholders.add(shape); + } + } + return placeholders; + } + + /** + * Create a table + * + * @param slide + * Slide + */ + private void createTable(XSLFSlide slide) { + + XSLFTable tbl = slide.createTable(); + tbl.setAnchor(new Rectangle(50, 50, 450, 300)); + + int numColumns = 3; + int numRows = 5; + + // header + XSLFTableRow headerRow = tbl.addRow(); + headerRow.setHeight(50); + for (int i = 0; i < numColumns; i++) { + XSLFTableCell th = headerRow.addCell(); + XSLFTextParagraph p = th.addNewTextParagraph(); + p.setTextAlign(TextParagraph.TextAlign.CENTER); + XSLFTextRun r = p.addNewTextRun(); + r.setText("Header " + (i + 1)); + r.setBold(true); + r.setFontColor(Color.white); + th.setFillColor(new Color(79, 129, 189)); + th.setBorderWidth(TableCell.BorderEdge.bottom, 2.0); + th.setBorderColor(TableCell.BorderEdge.bottom, Color.white); + // all columns are equally sized + tbl.setColumnWidth(i, 150); + } + + // data + for (int rownum = 0; rownum < numRows; rownum++) { + XSLFTableRow tr = tbl.addRow(); + tr.setHeight(50); + for (int i = 0; i < numColumns; i++) { + XSLFTableCell cell = tr.addCell(); + XSLFTextParagraph p = cell.addNewTextParagraph(); + XSLFTextRun r = p.addNewTextRun(); + + r.setText("Cell " + (i * rownum + 1)); + if (rownum % 2 == 0) { + cell.setFillColor(new Color(208, 216, 232)); + } else { + cell.setFillColor(new Color(233, 247, 244)); + } + } + } + } +} diff --git a/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java new file mode 100644 index 0000000000..5319208e85 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java @@ -0,0 +1,77 @@ +package com.baeldung.poi.powerpoint; + +import org.apache.poi.xslf.usermodel.XMLSlideShow; +import org.apache.poi.xslf.usermodel.XSLFShape; +import org.apache.poi.xslf.usermodel.XSLFSlide; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.util.List; + +public class PowerPointIntegrationTest { + + private PowerPointHelper pph; + private String fileLocation; + private static final String FILE_NAME = "presentation.pptx"; + + @Before + public void setUp() throws Exception { + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; + + pph = new PowerPointHelper(); + pph.createPresentation(fileLocation); + } + + @Test + public void whenReadingAPresentation_thenOK() throws Exception { + XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation); + + Assert.assertNotNull(xmlSlideShow); + Assert.assertEquals(4, xmlSlideShow.getSlides().size()); + } + + @Test + public void whenRetrievingThePlaceholdersForEachSlide_thenOK() throws Exception { + XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation); + + List onlyTitleSlidePlaceholders = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(0)); + List titleAndBodySlidePlaceholders = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(1)); + List emptySlidePlaceholdes = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(3)); + + Assert.assertEquals(1, onlyTitleSlidePlaceholders.size()); + Assert.assertEquals(2, titleAndBodySlidePlaceholders.size()); + Assert.assertEquals(0, emptySlidePlaceholdes.size()); + + } + + @Test + public void whenSortingSlides_thenOK() throws Exception { + XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation); + XSLFSlide slide4 = xmlSlideShow.getSlides().get(3); + pph.reorderSlide(xmlSlideShow, 3, 1); + + Assert.assertEquals(slide4, xmlSlideShow.getSlides().get(1)); + } + + @Test + public void givenPresentation_whenDeletingASlide_thenOK() throws Exception { + XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation); + pph.deleteSlide(xmlSlideShow, 3); + + Assert.assertEquals(3, xmlSlideShow.getSlides().size()); + } + + @After + public void tearDown() throws Exception { + File testFile = new File(fileLocation); + if (testFile.exists()) { + testFile.delete(); + } + pph = null; + } +} diff --git a/apache-spark/README.md b/apache-spark/README.md new file mode 100644 index 0000000000..fb8059eb27 --- /dev/null +++ b/apache-spark/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [Introduction to Apache Spark](http://www.baeldung.com/apache-spark) diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index f66d54ae67..543354e8b3 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -65,6 +65,24 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + @@ -107,4 +125,5 @@ + diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java index fc05e3b38f..25cbb9bc9b 100644 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java @@ -40,14 +40,14 @@ public class CasSecuredAppApplication { @Primary public AuthenticationEntryPoint authenticationEntryPoint(ServiceProperties sP) { CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint(); - entryPoint.setLoginUrl("https://localhost:8443/cas/login"); + entryPoint.setLoginUrl("https://localhost:6443/cas/login"); entryPoint.setServiceProperties(sP); return entryPoint; } @Bean public TicketValidator ticketValidator() { - return new Cas30ServiceTicketValidator("https://localhost:8443/cas"); + return new Cas30ServiceTicketValidator("https://localhost:6443/cas"); } @Bean @@ -71,7 +71,7 @@ public class CasSecuredAppApplication { @Bean public LogoutFilter logoutFilter() { LogoutFilter logoutFilter = new LogoutFilter( - "https://localhost:8443/cas/logout", securityContextLogoutHandler()); + "https://localhost:6443/cas/logout", securityContextLogoutHandler()); logoutFilter.setFilterProcessesUrl("/logout/cas"); return logoutFilter; } @@ -79,7 +79,7 @@ public class CasSecuredAppApplication { @Bean public SingleSignOutFilter singleSignOutFilter() { SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); - singleSignOutFilter.setCasServerUrlPrefix("https://localhost:8443/cas"); + singleSignOutFilter.setCasServerUrlPrefix("https://localhost:6443/cas"); singleSignOutFilter.setIgnoreInitConfiguration(true); return singleSignOutFilter; } diff --git a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java similarity index 84% rename from cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java rename to cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java index 09dbaf0c61..2f2644e2ea 100644 --- a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationTests.java +++ b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class CasSecuredAppApplicationTests { +public class CasSecuredAppApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/cas/cas-server/etc/cas/thekeystore b/cas/cas-server/etc/cas/thekeystore deleted file mode 100644 index 15f9af2dae..0000000000 Binary files a/cas/cas-server/etc/cas/thekeystore and /dev/null differ diff --git a/cas/cas-server/etc/cas/thekeystore.crt b/cas/cas-server/etc/cas/thekeystore.crt deleted file mode 100644 index 5c7543f0c6..0000000000 Binary files a/cas/cas-server/etc/cas/thekeystore.crt and /dev/null differ diff --git a/cas/cas-server/src/main/resources/application.properties b/cas/cas-server/src/main/resources/application.properties index 2d5e9a7277..018fd351ff 100644 --- a/cas/cas-server/src/main/resources/application.properties +++ b/cas/cas-server/src/main/resources/application.properties @@ -2,9 +2,9 @@ # CAS Server Context Configuration # server.context-path=/cas -server.port=8443 +server.port=6443 -server.ssl.key-store=file:/etc/cas/thekeystore +server.ssl.key-store=classpath:/etc/cas/thekeystore server.ssl.key-store-password=changeit server.ssl.key-password=changeit # server.ssl.ciphers= @@ -40,6 +40,12 @@ spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true +## +#CAS CONFIG LOCATION +# +cas.standalone.config=classpath:/etc/cas/config + + ## # CAS Cloud Bus Configuration # @@ -82,6 +88,7 @@ spring.thymeleaf.mode=HTML # CAS Log4j Configuration # # logging.config=file:/etc/cas/log4j2.xml + server.context-parameters.isLog4jAutoInitializationDisabled=true ## @@ -102,11 +109,12 @@ cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ? cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect cas.authn.jdbc.query[0].user=root -cas.authn.jdbc.query[0].password= +cas.authn.jdbc.query[0].password=root cas.authn.jdbc.query[0].ddlAuto=none -cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver +#cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver +cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver cas.authn.jdbc.query[0].fieldPassword=password -cas.authn.jdbc.query[0].passwordEncoder.type=BCRYPT +cas.authn.jdbc.query[0].passwordEncoder.type=NONE ## diff --git a/cas/cas-server/src/main/resources/cas.properties b/cas/cas-server/src/main/resources/cas.properties index be2babcd14..f80f22fc11 100644 --- a/cas/cas-server/src/main/resources/cas.properties +++ b/cas/cas-server/src/main/resources/cas.properties @@ -1,16 +1,15 @@ -cas.server.name: https://localhost:8443 -cas.server.prefix: https://localhost:8443/cas +cas.server.name: https://localhost:6443 +cas.server.prefix: https://localhost:643/cas cas.adminPagesSecurity.ip=127\.0\.0\.1 -logging.config: file:/etc/cas/config/log4j2.xml - cas.serviceRegistry.initFromJson=true cas.serviceRegistry.config.location=classpath:/services cas.authn.accept.users= cas.authn.accept.name= + #CAS Database Authentication Property # cas.authn.jdbc.query[0].healthQuery= diff --git a/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql b/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql new file mode 100644 index 0000000000..79a4a48a82 --- /dev/null +++ b/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql @@ -0,0 +1,16 @@ +-- Dumping database structure for test +CREATE DATABASE IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET latin1 */; +USE `test`; + +-- Dumping structure for table test.users +CREATE TABLE IF NOT EXISTS `users` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `email` varchar(50) DEFAULT NULL, + `password` text DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; + +/*!40000 ALTER TABLE `users` DISABLE KEYS */; +INSERT INTO `users` (`id`, `email`, `password`) VALUES + (1, 'test@test.com', 'Mellon'); +/*!40000 ALTER TABLE `users` ENABLE KEYS */; \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/application.yml b/cas/cas-server/src/main/resources/etc/cas/config/application.yml new file mode 100644 index 0000000000..be1f7c3edd --- /dev/null +++ b/cas/cas-server/src/main/resources/etc/cas/config/application.yml @@ -0,0 +1,2 @@ +info: + description: CAS Configuration \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/cas.properties b/cas/cas-server/src/main/resources/etc/cas/config/cas.properties new file mode 100644 index 0000000000..47a1477308 --- /dev/null +++ b/cas/cas-server/src/main/resources/etc/cas/config/cas.properties @@ -0,0 +1,7 @@ +cas.server.name: https://cas.example.org:8443 +cas.server.prefix: https://cas.example.org:8443/cas + +cas.adminPagesSecurity.ip=127\.0\.0\.1 + +logging.config: file:/etc/cas/config/log4j2.xml +# cas.serviceRegistry.config.location: classpath:/services diff --git a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml new file mode 100644 index 0000000000..53b30b4228 --- /dev/null +++ b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml @@ -0,0 +1,117 @@ + + + + + + . + + warn + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore b/cas/cas-server/src/main/resources/etc/cas/thekeystore new file mode 100644 index 0000000000..86170dff16 Binary files /dev/null and b/cas/cas-server/src/main/resources/etc/cas/thekeystore differ diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt b/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt new file mode 100644 index 0000000000..5bd9d5baba Binary files /dev/null and b/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt differ diff --git a/core-java-8/README.md b/core-java-8/README.md index 690bd48ed5..540a32b0ba 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -30,3 +30,5 @@ - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) - [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) - [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception) +- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) +- [Copy a File with Java](http://www.baeldung.com/java-copy-file) diff --git a/core-java-8/src/main/java/com/baeldung/annotations/ClassWithAnnotation.java b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithAnnotation.java new file mode 100644 index 0000000000..034e6785a4 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithAnnotation.java @@ -0,0 +1,5 @@ +package com.baeldung.annotations; + +@Deprecated +class ClassWithAnnotation { +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/ClassWithDeprecatedMethod.java b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithDeprecatedMethod.java new file mode 100644 index 0000000000..6f5da03b74 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithDeprecatedMethod.java @@ -0,0 +1,9 @@ +package com.baeldung.annotations; + +class ClassWithDeprecatedMethod { + + @Deprecated + static void deprecatedMethod() { + + } +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSafeVarargs.java b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSafeVarargs.java new file mode 100644 index 0000000000..cfa91f5951 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSafeVarargs.java @@ -0,0 +1,11 @@ +package com.baeldung.annotations; + +class ClassWithSafeVarargs { + + @SafeVarargs + final void iterateOverVarargs(T... args) { + for (T x : args) { + // do stuff with x + } + } +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSuppressWarnings.java b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSuppressWarnings.java new file mode 100644 index 0000000000..fe22ec1c24 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSuppressWarnings.java @@ -0,0 +1,9 @@ +package com.baeldung.annotations; + +class ClassWithSuppressWarnings { + + @SuppressWarnings("deprecation") + void useDeprecatedMethod() { + ClassWithDeprecatedMethod.deprecatedMethod(); // no warning is generated here + } +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/IntConsumer.java b/core-java-8/src/main/java/com/baeldung/annotations/IntConsumer.java new file mode 100644 index 0000000000..4f16b27281 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/IntConsumer.java @@ -0,0 +1,8 @@ +package com.baeldung.annotations; + +@FunctionalInterface +interface IntConsumer { + + void accept(Integer number); + +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/Interval.java b/core-java-8/src/main/java/com/baeldung/annotations/Interval.java new file mode 100644 index 0000000000..f73e6e5b14 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/Interval.java @@ -0,0 +1,8 @@ +package com.baeldung.annotations; + +import java.lang.annotation.Repeatable; + +@Repeatable(Intervals.class) +@interface Interval { + int hour() default 1; +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/IntervalUsage.java b/core-java-8/src/main/java/com/baeldung/annotations/IntervalUsage.java new file mode 100644 index 0000000000..2e11de8215 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/IntervalUsage.java @@ -0,0 +1,9 @@ +package com.baeldung.annotations; + +public class IntervalUsage { + + @Interval(hour = 17) + @Interval(hour = 13) + void doPeriodicCleanup() { + } +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/Intervals.java b/core-java-8/src/main/java/com/baeldung/annotations/Intervals.java new file mode 100644 index 0000000000..af469f18cc --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/Intervals.java @@ -0,0 +1,5 @@ +package com.baeldung.annotations; + +@interface Intervals { + Interval[] value(); +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotation.java b/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotation.java new file mode 100644 index 0000000000..6e71f446b0 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotation.java @@ -0,0 +1,11 @@ +package com.baeldung.annotations; + +import java.lang.annotation.*; + +@Inherited +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD}) +@interface MyAnnotation { + +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotationTarget.java b/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotationTarget.java new file mode 100644 index 0000000000..37f40a624e --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotationTarget.java @@ -0,0 +1,16 @@ +package com.baeldung.annotations; + +class MyAnnotationTarget { + + // this is OK + @MyAnnotation + String someField; + + // @MyAnnotation <- this is invalid usage! + void doSomething() { + + // this also works + @MyAnnotation + String localVariable; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/annotations/MyOperation.java b/core-java-8/src/main/java/com/baeldung/annotations/MyOperation.java new file mode 100644 index 0000000000..a4385bc786 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/MyOperation.java @@ -0,0 +1,6 @@ +package com.baeldung.annotations; + +interface MyOperation { + + void perform(); +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/annotations/MyOperationImpl.java b/core-java-8/src/main/java/com/baeldung/annotations/MyOperationImpl.java new file mode 100644 index 0000000000..e6a8ce76d3 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/annotations/MyOperationImpl.java @@ -0,0 +1,9 @@ +package com.baeldung.annotations; + +class MyOperationImpl implements MyOperation { + + @Override + public void perform() { + + } +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/prime/PrimeGenerator.java b/core-java-8/src/main/java/com/baeldung/prime/PrimeGenerator.java new file mode 100644 index 0000000000..750807ce77 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/prime/PrimeGenerator.java @@ -0,0 +1,59 @@ +package com.baeldung.prime; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class PrimeGenerator { + public static List sieveOfEratosthenes(int n) { + final boolean prime[] = new boolean[n + 1]; + Arrays.fill(prime, true); + + for (int p = 2; p * p <= n; p++) { + if (prime[p]) { + for (int i = p * 2; i <= n; i += p) + prime[i] = false; + } + } + + final List primes = new LinkedList<>(); + for (int i = 2; i <= n; i++) { + if (prime[i]) + primes.add(i); + } + return primes; + } + + public static List primeNumbersBruteForce(int max) { + final List primeNumbers = new LinkedList(); + for (int i = 2; i <= max; i++) { + if (isPrimeBruteForce(i)) { + primeNumbers.add(i); + } + } + return primeNumbers; + } + + private static boolean isPrimeBruteForce(int x) { + for (int i = 2; i < x; i++) { + if (x % i == 0) { + return false; + } + } + return true; + } + + public static List primeNumbersTill(int max) { + return IntStream.rangeClosed(2, max) + .filter(x -> isPrime(x)) + .boxed() + .collect(Collectors.toList()); + } + + private static boolean isPrime(int x) { + return IntStream.rangeClosed(2, (int) (Math.sqrt(x))) + .allMatch(n -> x % n != 0); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java b/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java new file mode 100644 index 0000000000..3a1016c63b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplay.java @@ -0,0 +1,55 @@ +package com.baeldung.timezonedisplay; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +public class TimezoneDisplay { + + public enum OffsetBase { + GMT, UTC + } + + public List getTimeZoneList(OffsetBase base) { + Set availableZoneIds = ZoneId.getAvailableZoneIds(); + + LocalDateTime now = LocalDateTime.now(); + return availableZoneIds + .stream() + .map(ZoneId::of) + .sorted(new ZoneComparator()) + .map(id -> String.format("(%s%s) %s", base, getOffset(now, id), id.getId())) + .collect(Collectors.toList()); + } + + private String getOffset(LocalDateTime dateTime, ZoneId id) { + return dateTime + .atZone(id) + .getOffset() + .getId() + .replace("Z", "+00:00"); + } + + private class ZoneComparator implements Comparator { + + @Override + public int compare(ZoneId zoneId1, ZoneId zoneId2) { + LocalDateTime now = LocalDateTime.now(); + + ZoneOffset offset1 = now + .atZone(zoneId1) + .getOffset(); + + ZoneOffset offset2 = now + .atZone(zoneId2) + .getOffset(); + + return offset1.compareTo(offset2); + } + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java b/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java new file mode 100644 index 0000000000..aa9f84e21a --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayApp.java @@ -0,0 +1,18 @@ +package com.baeldung.timezonedisplay; + +import java.util.List; + +public class TimezoneDisplayApp { + + public static void main(String... args) { + TimezoneDisplay display = new TimezoneDisplay(); + + System.out.println("Time zones in UTC:"); + List utc = display.getTimeZoneList(TimezoneDisplay.OffsetBase.UTC); + utc.forEach(System.out::println); + + System.out.println("Time zones in GMT:"); + List gmt = display.getTimeZoneList(TimezoneDisplay.OffsetBase.GMT); + gmt.forEach(System.out::println); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java b/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java new file mode 100644 index 0000000000..e53e1c183e --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java @@ -0,0 +1,28 @@ +package com.baeldung.prime; + +import static com.baeldung.prime.PrimeGenerator.*; + +import java.util.Arrays; +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +public class PrimeGeneratorTest { + @Test + public void whenBruteForced_returnsSuccessfully() { + final List primeNumbers = primeNumbersBruteForce(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenOptimized_returnsSuccessfully() { + final List primeNumbers = primeNumbersTill(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } + + @Test + public void whenSieveOfEratosthenes_returnsSuccessfully() { + final List primeNumbers = sieveOfEratosthenes(20); + assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers); + } +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java new file mode 100644 index 0000000000..c794c57e87 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java @@ -0,0 +1,39 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows a way to convert java.util.Date into java.time.LocalDate. + * + * @author abialas + * + */ +public class DateToLocalDateConverter { + + public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) { + return dateToConvert.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + } + + public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) { + return new java.sql.Date(dateToConvert.getTime()).toLocalDate(); + } + + public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) { + return Instant.ofEpochMilli(dateToConvert.getTime()) + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + } + + public static LocalDate convertToLocalDate(Date dateToConvert) { + return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault()); + } + +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java new file mode 100644 index 0000000000..17ca5b1122 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java @@ -0,0 +1,39 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows a way to convert java.util.Date into java.time.LocalDateTime. + * + * @author abialas + * + */ +public class DateToLocalDateTimeConverter { + + public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) { + return dateToConvert.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + } + + public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) { + return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime(); + } + + public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) { + return Instant.ofEpochMilli(dateToConvert.getTime()) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + } + + public static LocalDateTime convertToLocalDateTime(Date dateToConvert) { + return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault()); + } + +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java new file mode 100644 index 0000000000..f219dcf038 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java @@ -0,0 +1,27 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows different ways of converting java.time.LocalDateTime into java.util.Date. + * + * @author abialas + * + */ +public class LocalDateTimeToDateConverter { + + public static Date convertToDateViaSqlTimestamp(LocalDateTime dateToConvert) { + return java.sql.Timestamp.valueOf(dateToConvert); + } + + public static Date convertToDateViaInstant(LocalDateTime dateToConvert) { + return java.util.Date.from(dateToConvert.atZone(ZoneId.systemDefault()) + .toInstant()); + } + +} diff --git a/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java b/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java new file mode 100644 index 0000000000..f9893da5d0 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java @@ -0,0 +1,28 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.Date; + +/** + * Class which shows different ways of converting java.time.LocalDate into java.util.Date. + * + * @author abialas + * + */ +public class LocalDateToDateConverter { + + public static Date convertToDateViaSqlDate(LocalDate dateToConvert) { + return java.sql.Date.valueOf(dateToConvert); + } + + public static Date convertToDateViaInstant(LocalDate dateToConvert) { + return java.util.Date.from(dateToConvert.atStartOfDay() + .atZone(ZoneId.systemDefault()) + .toInstant()); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java new file mode 100644 index 0000000000..ab69bba359 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterTest.java @@ -0,0 +1,89 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +import com.baeldung.java9.datetime.DateToLocalDateConverter; + +/** + * JUnits for {@link DateToLocalDateConverter} class. + * + * @author abialas + * + */ +public class DateToLocalDateConverterTest { + + @Test + public void shouldReturn10thNovember2010WhenConvertViaInstant() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert); + + // then + assertEquals(2010, localDate.get(ChronoField.YEAR)); + assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertToLocalDate() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10); + Date dateToConvert = calendar.getTime(); + + // when + LocalDate localDateTime = DateToLocalDateConverter.convertToLocalDate(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java new file mode 100644 index 0000000000..97c70ee5ac --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterTest.java @@ -0,0 +1,97 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoField; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +import com.baeldung.java9.datetime.DateToLocalDateTimeConverter; + +/** + * JUnits for {@link DateToLocalDateTimeConverter} class. + * + * @author abialas + * + */ +public class DateToLocalDateTimeConverterTest { + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertToLocalDateTime() { + // given + Calendar calendar = Calendar.getInstance(); + calendar.set(2010, 10, 10, 8, 20); + Date dateToConvert = calendar.getTime(); + + // when + LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert); + + // then + assertEquals(2010, localDateTime.get(ChronoField.YEAR)); + assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH)); + assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY)); + assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR)); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java new file mode 100644 index 0000000000..2c6898381f --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterTest.java @@ -0,0 +1,61 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDateTime; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +/** + * + * JUnits for {@link LocalDateTimeToDateConverter} class. + * + * @author abialas + * + */ +public class LocalDateTimeToDateConverterTest { + + @Test + public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() { + // given + LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20); + + // when + Date date = LocalDateTimeToDateConverter.convertToDateViaInstant(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(8, calendar.get(Calendar.HOUR)); + assertEquals(20, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlTimestamp() { + // given + LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20); + + // when + Date date = LocalDateTimeToDateConverter.convertToDateViaSqlTimestamp(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals(8, calendar.get(Calendar.HOUR)); + assertEquals(20, calendar.get(Calendar.MINUTE)); + assertEquals(0, calendar.get(Calendar.SECOND)); + } + +} diff --git a/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java new file mode 100644 index 0000000000..7f20d5d2d2 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterTest.java @@ -0,0 +1,55 @@ +/** + * + */ +package com.baeldung.java9.datetime; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Date; + +import org.junit.Test; + +/** + * + * JUnits for {@link LocalDateToDateConverter} class. + * + * @author abialas + * + */ +public class LocalDateToDateConverterTest { + + @Test + public void shouldReturn10thNovember2010WhenConvertViaInstant() { + // given + LocalDate dateToConvert = LocalDate.of(2010, 11, 10); + + // when + Date date = LocalDateToDateConverter.convertToDateViaInstant(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + } + + @Test + public void shouldReturn10thNovember2010WhenConvertViaSqlDate() { + // given + LocalDate dateToConvert = LocalDate.of(2010, 11, 10); + + // when + Date date = LocalDateToDateConverter.convertToDateViaSqlDate(dateToConvert); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + // then + assertEquals(2010, calendar.get(Calendar.YEAR)); + assertEquals(10, calendar.get(Calendar.MONTH)); + assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH)); + } + +} diff --git a/core-java-concurrency/README.md b/core-java-concurrency/README.md index f1d95482d4..48c5f2a50c 100644 --- a/core-java-concurrency/README.md +++ b/core-java-concurrency/README.md @@ -30,3 +30,4 @@ - [Guide to Volatile Keyword in Java](http://www.baeldung.com/java-volatile) - [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent) - [Semaphores in Java](http://www.baeldung.com/java-semaphore) +- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread) diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java index d742d3a55f..4d87978070 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java @@ -3,7 +3,6 @@ package com.baeldung.concurrent.daemon; public class NewThread extends Thread { public void run() { - long startTime = System.currentTimeMillis(); while (true) { for (int i = 0; i < 10; i++) { diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java new file mode 100644 index 0000000000..0e72821a88 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/stopping/ControlSubThread.java @@ -0,0 +1,52 @@ +package com.baeldung.concurrent.stopping; + +import java.util.concurrent.atomic.AtomicBoolean; + +public class ControlSubThread implements Runnable { + + private Thread worker; + private int interval = 100; + private AtomicBoolean running = new AtomicBoolean(false); + private AtomicBoolean stopped = new AtomicBoolean(true); + + + public ControlSubThread(int sleepInterval) { + interval = sleepInterval; + } + + public void start() { + worker = new Thread(this); + worker.start(); + } + + public void stop() { + running.set(false); + } + + public void interrupt() { + running.set(false); + worker.interrupt(); + } + + boolean isRunning() { + return running.get(); + } + + boolean isStopped() { + return stopped.get(); + } + + public void run() { + running.set(true); + stopped.set(false); + while (running.get()) { + try { + Thread.sleep(interval); + } catch (InterruptedException e) { + // no-op, just loop again + } + // do something + } + stopped.set(true); + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadLiveTest.java similarity index 87% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadLiveTest.java index 4bd4848905..2a51f83e2b 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/runnable/RunnableVsThreadLiveTest.java @@ -1,24 +1,21 @@ package com.baeldung.concurrent.runnable; import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.lang3.RandomUtils; -import org.junit.After; import org.junit.AfterClass; -import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class RunnableVsThreadTest { +public class RunnableVsThreadLiveTest { private static Logger log = - LoggerFactory.getLogger(RunnableVsThreadTest.class); + LoggerFactory.getLogger(RunnableVsThreadLiveTest.class); private static ExecutorService executorService; @@ -77,9 +74,7 @@ public class RunnableVsThreadTest { public void givenACallableAsLambda_whenSubmitToES_thenResult() throws Exception { - Future future = executorService.submit(() -> { - return RandomUtils.nextInt(0, 100); - }); + Future future = executorService.submit(() -> RandomUtils.nextInt(0, 100)); log.info("Result from callable: {}", future.get()); } @@ -99,7 +94,7 @@ class SimpleThread extends Thread{ private String message; - public SimpleThread(String message) { + SimpleThread(String message) { this.message = message; } @@ -116,7 +111,7 @@ class SimpleRunnable implements Runnable { private String message; - public SimpleRunnable(String message) { + SimpleRunnable(String message) { this.message = message; } diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java new file mode 100644 index 0000000000..70854f013f --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java @@ -0,0 +1,54 @@ +package com.baeldung.concurrent.stopping; + +import com.jayway.awaitility.Awaitility; +import org.junit.Test; + +import java.util.concurrent.TimeUnit; + +import static com.jayway.awaitility.Awaitility.await; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class StopThreadTest { + + @Test + public void whenStoppedThreadIsStopped() throws InterruptedException { + + int interval = 100; + + ControlSubThread controlSubThread = new ControlSubThread(interval); + controlSubThread.start(); + + // Give things a chance to get set up + Thread.sleep(interval); + assertTrue(controlSubThread.isRunning()); + assertFalse(controlSubThread.isStopped()); + + // Stop it and make sure the flags have been reversed + controlSubThread.stop(); + await() + .until(() -> assertTrue(controlSubThread.isStopped())); + } + + @Test + public void whenInterruptedThreadIsStopped() throws InterruptedException { + + int interval = 5000; + + ControlSubThread controlSubThread = new ControlSubThread(interval); + controlSubThread.start(); + + // Give things a chance to get set up + Thread.sleep(100); + assertTrue(controlSubThread.isRunning()); + assertFalse(controlSubThread.isStopped()); + + // Stop it and make sure the flags have been reversed + controlSubThread.interrupt(); + + // Wait less than the time we would normally sleep, and make sure we exited. + Awaitility.await() + .atMost(interval/ 10, TimeUnit.MILLISECONDS) + .until(controlSubThread::isStopped); + } +} diff --git a/core-java-sun/.gitignore b/core-java-sun/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/core-java-sun/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-sun/README.md b/core-java-sun/README.md new file mode 100644 index 0000000000..9cf8b26f1b --- /dev/null +++ b/core-java-sun/README.md @@ -0,0 +1,6 @@ +========= + +## Core Java Cookbooks and Examples + +### Relevant Articles: +- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) diff --git a/core-java-sun/pom.xml b/core-java-sun/pom.xml new file mode 100644 index 0000000000..3997f47d19 --- /dev/null +++ b/core-java-sun/pom.xml @@ -0,0 +1,489 @@ + + 4.0.0 + com.baeldung + core-java-sun + 0.1.0-SNAPSHOT + jar + + core-java-sun + + + + + + net.sourceforge.collections + collections-generic + ${collections-generic.version} + + + com.google.guava + guava + ${guava.version} + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + + commons-io + commons-io + ${commons-io.version} + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + + org.decimal4j + decimal4j + ${decimal4j.version} + + + + org.bouncycastle + bcprov-jdk15on + ${bouncycastle.version} + + + + org.unix4j + unix4j-command + ${unix4j.version} + + + + com.googlecode.grep4j + grep4j + ${grep4j.version} + + + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + + log4j + log4j + 1.2.17 + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + + + org.hamcrest + hamcrest-all + 1.3 + test + + + + junit + junit + ${junit.version} + test + + + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + + commons-codec + commons-codec + ${commons-codec.version} + + + + org.javamoney + moneta + 1.1 + + + + org.owasp.esapi + esapi + 2.1.0.1 + + + + com.sun.messaging.mq + fscontext + ${fscontext.version} + + + com.codepoetics + protonpack + ${protonpack.version} + + + one.util + streamex + ${streamex.version} + + + io.vavr + vavr + ${vavr.version} + + + org.openjdk.jmh + jmh-core + 1.19 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.19 + + + org.springframework + spring-web + 4.3.4.RELEASE + + + com.sun + tools + 1.8.0 + system + ${java.home}/../lib/tools.jar + + + + + core-java + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + libs/ + org.baeldung.executable.ExecutableMavenJar + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + package + + single + + + ${project.basedir} + + + org.baeldung.executable.ExecutableMavenJar + + + + jar-with-dependencies + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + shade + + + true + + + org.baeldung.executable.ExecutableMavenJar + + + + + + + + + com.jolira + onejar-maven-plugin + + + + org.baeldung.executable.ExecutableMavenJar + true + ${project.build.finalName}-onejar.${project.packaging} + + + one-jar + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + spring-boot + org.baeldung.executable.ExecutableMavenJar + + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + java + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed + + -Xmx300m + -XX:+UseParallelGC + -classpath + + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed + + + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + org.codehaus.mojo + exec-maven-plugin + + + + run-benchmarks + + none + + exec + + + test + java + + -classpath + + org.openjdk.jmh.Main + .* + + + + + + + + + + + + + 2.8.5 + + + 1.7.21 + 1.1.7 + + + 23.0 + 3.5 + 1.55 + 1.10 + 3.6.1 + 1.0.3 + 2.5 + 4.1 + 4.01 + 0.4 + 1.8.7 + 1.16.12 + 4.6-b01 + 1.13 + 0.6.5 + 0.9.0 + + + 1.3 + 4.12 + 2.8.9 + 3.6.1 + 1.7.0 + + + 3.6.0 + 2.19.1 + + \ No newline at end of file diff --git a/mockito/.gitignore b/core-java-sun/src/main/java/com/baeldung/.gitignore similarity index 100% rename from mockito/.gitignore rename to core-java-sun/src/main/java/com/baeldung/.gitignore diff --git a/core-java-sun/src/main/java/com/baeldung/README.md b/core-java-sun/src/main/java/com/baeldung/README.md new file mode 100644 index 0000000000..51809b2882 --- /dev/null +++ b/core-java-sun/src/main/java/com/baeldung/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java) diff --git a/core-java-sun/src/main/java/com/baeldung/javac/Positive.java b/core-java-sun/src/main/java/com/baeldung/javac/Positive.java new file mode 100644 index 0000000000..443b866fea --- /dev/null +++ b/core-java-sun/src/main/java/com/baeldung/javac/Positive.java @@ -0,0 +1,9 @@ +package com.baeldung.javac; + +import java.lang.annotation.*; + +@Documented +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.PARAMETER}) +public @interface Positive { +} diff --git a/core-java-sun/src/main/java/com/baeldung/javac/SampleJavacPlugin.java b/core-java-sun/src/main/java/com/baeldung/javac/SampleJavacPlugin.java new file mode 100644 index 0000000000..eb48d6a216 --- /dev/null +++ b/core-java-sun/src/main/java/com/baeldung/javac/SampleJavacPlugin.java @@ -0,0 +1,123 @@ +package com.baeldung.javac; + +import com.sun.source.tree.MethodTree; +import com.sun.source.tree.VariableTree; +import com.sun.source.util.*; +import com.sun.tools.javac.api.BasicJavacTask; +import com.sun.tools.javac.code.TypeTag; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.TreeMaker; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.Name; +import com.sun.tools.javac.util.Names; + +import javax.tools.JavaCompiler; +import java.util.*; +import java.util.stream.Collectors; + +import static com.sun.tools.javac.util.List.nil; + +/** + * A {@link JavaCompiler javac} plugin which inserts {@code >= 0} checks into resulting {@code *.class} files + * for numeric method parameters marked by {@link Positive} + */ +public class SampleJavacPlugin implements Plugin { + + public static final String NAME = "MyPlugin"; + + private static Set TARGET_TYPES = new HashSet<>(Arrays.asList( + // Use only primitive types for simplicity + byte.class.getName(), short.class.getName(), char.class.getName(), + int.class.getName(), long.class.getName(), float.class.getName(), double.class.getName())); + + @Override + public String getName() { + return NAME; + } + + @Override + public void init(JavacTask task, String... args) { + Context context = ((BasicJavacTask) task).getContext(); + task.addTaskListener(new TaskListener() { + @Override + public void started(TaskEvent e) { + } + + @Override + public void finished(TaskEvent e) { + if (e.getKind() != TaskEvent.Kind.PARSE) { + return; + } + e.getCompilationUnit() + .accept(new TreeScanner() { + @Override + public Void visitMethod(MethodTree method, Void v) { + List parametersToInstrument = method.getParameters() + .stream() + .filter(SampleJavacPlugin.this::shouldInstrument) + .collect(Collectors.toList()); + if (!parametersToInstrument.isEmpty()) { + // There is a possible case that more than one argument is marked by @Positive, + // as the checks are added to the method's body beginning, we process parameters RTL + // to ensure correct order. + Collections.reverse(parametersToInstrument); + parametersToInstrument.forEach(p -> addCheck(method, p, context)); + } + // There is a possible case that there is a nested class declared in a method's body, + // hence, we want to proceed with method body AST as well. + return super.visitMethod(method, v); + } + }, null); + } + }); + } + + private boolean shouldInstrument(VariableTree parameter) { + return TARGET_TYPES.contains(parameter.getType().toString()) + && parameter.getModifiers().getAnnotations() + .stream() + .anyMatch(a -> Positive.class.getSimpleName().equals(a.getAnnotationType().toString())); + } + + private void addCheck(MethodTree method, VariableTree parameter, Context context) { + JCTree.JCIf check = createCheck(parameter, context); + JCTree.JCBlock body = (JCTree.JCBlock) method.getBody(); + body.stats = body.stats.prepend(check); + } + + private static JCTree.JCIf createCheck(VariableTree parameter, Context context) { + TreeMaker factory = TreeMaker.instance(context); + Names symbolsTable = Names.instance(context); + + return factory.at(((JCTree) parameter).pos) + .If(factory.Parens(createIfCondition(factory, symbolsTable, parameter)), + createIfBlock(factory, symbolsTable, parameter), + null); + } + + private static JCTree.JCBinary createIfCondition(TreeMaker factory, Names symbolsTable, VariableTree parameter) { + Name parameterId = symbolsTable.fromString(parameter.getName().toString()); + return factory.Binary(JCTree.Tag.LE, + factory.Ident(parameterId), + factory.Literal(TypeTag.INT, 0)); + } + + private static JCTree.JCBlock createIfBlock(TreeMaker factory, Names symbolsTable, VariableTree parameter) { + String parameterName = parameter.getName().toString(); + Name parameterId = symbolsTable.fromString(parameterName); + + String errorMessagePrefix = String.format("Argument '%s' of type %s is marked by @%s but got '", + parameterName, parameter.getType(), Positive.class.getSimpleName()); + String errorMessageSuffix = "' for it"; + + return factory.Block(0, com.sun.tools.javac.util.List.of( + factory.Throw( + factory.NewClass(null, nil(), + factory.Ident(symbolsTable.fromString(IllegalArgumentException.class.getSimpleName())), + com.sun.tools.javac.util.List.of(factory.Binary(JCTree.Tag.PLUS, + factory.Binary(JCTree.Tag.PLUS, factory.Literal(TypeTag.CLASS, errorMessagePrefix), + factory.Ident(parameterId)), + factory.Literal(TypeTag.CLASS, errorMessageSuffix))), null)))); + } + +} diff --git a/core-java-sun/src/main/resources/log4j.properties b/core-java-sun/src/main/resources/log4j.properties new file mode 100644 index 0000000000..621cf01735 --- /dev/null +++ b/core-java-sun/src/main/resources/log4j.properties @@ -0,0 +1,6 @@ +log4j.rootLogger=DEBUG, A1 + +log4j.appender.A1=org.apache.log4j.ConsoleAppender + +log4j.appender.A1.layout=org.apache.log4j.PatternLayout +log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n \ No newline at end of file diff --git a/mockito/src/main/resources/logback.xml b/core-java-sun/src/main/resources/logback.xml similarity index 100% rename from mockito/src/main/resources/logback.xml rename to core-java-sun/src/main/resources/logback.xml diff --git a/core-java-sun/src/test/java/com/baeldung/javac/SampleJavacPluginIntegrationTest.java b/core-java-sun/src/test/java/com/baeldung/javac/SampleJavacPluginIntegrationTest.java new file mode 100644 index 0000000000..b877038add --- /dev/null +++ b/core-java-sun/src/test/java/com/baeldung/javac/SampleJavacPluginIntegrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.javac; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class SampleJavacPluginIntegrationTest { + + private static final String CLASS_TEMPLATE = + "package com.baeldung.javac;\n" + + "\n" + + "public class Test {\n" + + " public static %1$s service(@Positive %1$s i) {\n" + + " return i;\n" + + " }\n" + + "}\n" + + ""; + + private TestCompiler compiler = new TestCompiler(); + private TestRunner runner = new TestRunner(); + + @Test(expected = IllegalArgumentException.class) + public void givenInt_whenNegative_thenThrowsException() throws Throwable { + compileAndRun(double.class,-1); + } + + @Test(expected = IllegalArgumentException.class) + public void givenInt_whenZero_thenThrowsException() throws Throwable { + compileAndRun(int.class,0); + } + + @Test + public void givenInt_whenPositive_thenSuccess() throws Throwable { + assertEquals(1, compileAndRun(int.class, 1)); + } + + private Object compileAndRun(Class argumentType, Object argument) throws Throwable { + String qualifiedClassName = "com.baeldung.javac.Test"; + byte[] byteCode = compiler.compile(qualifiedClassName, String.format(CLASS_TEMPLATE, argumentType.getName())); + return runner.run(byteCode, qualifiedClassName, "service", new Class[] {argumentType}, argument); + } +} diff --git a/core-java-sun/src/test/java/com/baeldung/javac/SimpleClassFile.java b/core-java-sun/src/test/java/com/baeldung/javac/SimpleClassFile.java new file mode 100644 index 0000000000..2c8e66e6e3 --- /dev/null +++ b/core-java-sun/src/test/java/com/baeldung/javac/SimpleClassFile.java @@ -0,0 +1,26 @@ +package com.baeldung.javac; + +import javax.tools.SimpleJavaFileObject; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; + +/** Holds compiled byte code in a byte array */ +public class SimpleClassFile extends SimpleJavaFileObject { + + private ByteArrayOutputStream out; + + public SimpleClassFile(URI uri) { + super(uri, Kind.CLASS); + } + + @Override + public OutputStream openOutputStream() throws IOException { + return out = new ByteArrayOutputStream(); + } + + public byte[] getCompiledBinaries() { + return out.toByteArray(); + } +} \ No newline at end of file diff --git a/core-java-sun/src/test/java/com/baeldung/javac/SimpleFileManager.java b/core-java-sun/src/test/java/com/baeldung/javac/SimpleFileManager.java new file mode 100644 index 0000000000..346f240754 --- /dev/null +++ b/core-java-sun/src/test/java/com/baeldung/javac/SimpleFileManager.java @@ -0,0 +1,34 @@ +package com.baeldung.javac; + +import javax.tools.*; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +/** Adapts {@link SimpleClassFile} to the {@link JavaCompiler} */ +public class SimpleFileManager extends ForwardingJavaFileManager { + + private final List compiled = new ArrayList<>(); + + public SimpleFileManager(StandardJavaFileManager delegate) { + super(delegate); + } + + @Override + public JavaFileObject getJavaFileForOutput(Location location, + String className, + JavaFileObject.Kind kind, + FileObject sibling) + { + SimpleClassFile result = new SimpleClassFile(URI.create("string://" + className)); + compiled.add(result); + return result; + } + + /** + * @return compiled binaries processed by the current class + */ + public List getCompiled() { + return compiled; + } +} \ No newline at end of file diff --git a/core-java-sun/src/test/java/com/baeldung/javac/SimpleSourceFile.java b/core-java-sun/src/test/java/com/baeldung/javac/SimpleSourceFile.java new file mode 100644 index 0000000000..9287b1a0dd --- /dev/null +++ b/core-java-sun/src/test/java/com/baeldung/javac/SimpleSourceFile.java @@ -0,0 +1,23 @@ +package com.baeldung.javac; + +import javax.tools.SimpleJavaFileObject; +import java.net.URI; + +/** Exposes given test source to the compiler. */ +public class SimpleSourceFile extends SimpleJavaFileObject { + + private final String content; + + public SimpleSourceFile(String qualifiedClassName, String testSource) { + super(URI.create(String.format("file://%s%s", + qualifiedClassName.replaceAll("\\.", "/"), + Kind.SOURCE.extension)), + Kind.SOURCE); + content = testSource; + } + + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return content; + } +} \ No newline at end of file diff --git a/core-java-sun/src/test/java/com/baeldung/javac/TestCompiler.java b/core-java-sun/src/test/java/com/baeldung/javac/TestCompiler.java new file mode 100644 index 0000000000..ee40e563a3 --- /dev/null +++ b/core-java-sun/src/test/java/com/baeldung/javac/TestCompiler.java @@ -0,0 +1,35 @@ +package com.baeldung.javac; + +import javax.tools.JavaCompiler; +import javax.tools.ToolProvider; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; + +public class TestCompiler { + public byte[] compile(String qualifiedClassName, String testSource) { + StringWriter output = new StringWriter(); + + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + SimpleFileManager fileManager = new SimpleFileManager(compiler.getStandardFileManager( + null, + null, + null + )); + List compilationUnits = singletonList(new SimpleSourceFile(qualifiedClassName, testSource)); + List arguments = new ArrayList<>(); + arguments.addAll(asList("-classpath", System.getProperty("java.class.path"), + "-Xplugin:" + SampleJavacPlugin.NAME)); + JavaCompiler.CompilationTask task = compiler.getTask(output, + fileManager, + null, + arguments, + null, + compilationUnits); + task.call(); + return fileManager.getCompiled().iterator().next().getCompiledBinaries(); + } +} diff --git a/core-java-sun/src/test/java/com/baeldung/javac/TestRunner.java b/core-java-sun/src/test/java/com/baeldung/javac/TestRunner.java new file mode 100644 index 0000000000..6a03ad4918 --- /dev/null +++ b/core-java-sun/src/test/java/com/baeldung/javac/TestRunner.java @@ -0,0 +1,41 @@ +package com.baeldung.javac; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class TestRunner { + + public Object run(byte[] byteCode, + String qualifiedClassName, + String methodName, + Class[] argumentTypes, + Object... args) + throws Throwable + { + ClassLoader classLoader = new ClassLoader() { + @Override + protected Class findClass(String name) throws ClassNotFoundException { + return defineClass(name, byteCode, 0, byteCode.length); + } + }; + Class clazz; + try { + clazz = classLoader.loadClass(qualifiedClassName); + } catch (ClassNotFoundException e) { + throw new RuntimeException("Can't load compiled test class", e); + } + + Method method; + try { + method = clazz.getMethod(methodName, argumentTypes); + } catch (NoSuchMethodException e) { + throw new RuntimeException("Can't find the 'main()' method in the compiled test class", e); + } + + try { + return method.invoke(null, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } +} diff --git a/spring-jpa/.gitignore b/core-java-sun/src/test/resources/.gitignore similarity index 100% rename from spring-jpa/.gitignore rename to core-java-sun/src/test/resources/.gitignore diff --git a/core-java/README.md b/core-java/README.md index b4b8d9062e..1feee4126e 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -114,4 +114,10 @@ - [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) - [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int) - [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns) +- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) +- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static) +- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array) +- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) +- [Copy a File with Java](http://www.baeldung.com/java-copy-file) +- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns) diff --git a/core-java/pom.xml b/core-java/pom.xml index bb3958f36c..2c4cbfc37b 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -181,11 +181,6 @@ 2.1.0.1 - - com.sun.messaging.mq - fscontext - ${fscontext.version} - com.codepoetics protonpack @@ -249,7 +244,7 @@ **/*LongRunningUnitTest.java **/*ManualTest.java - true + @@ -453,7 +448,7 @@ 1.1.7 - 22.0 + 23.0 3.5 1.55 1.10 diff --git a/core-java/src/main/java/com/baeldung/breakcontinue/BreakContinue.java b/core-java/src/main/java/com/baeldung/breakcontinue/BreakContinue.java new file mode 100644 index 0000000000..ce85b487c1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/breakcontinue/BreakContinue.java @@ -0,0 +1,138 @@ +package com.baeldung.breakcontinue; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +/** + * @author Santosh + * + */ +public class BreakContinue { + + public static int unlabeledBreak() { + String searchName = "Wilson"; + int counter = 0; + List names = Arrays.asList("John", "Peter", "Robert", "Wilson", "Anthony", "Donald", "Richard"); + + for (String name : names) { + counter++; + if (name.equalsIgnoreCase(searchName)) { + break; + } + } + + return counter; + } + + public static int unlabeledBreakNestedLoops() { + String searchName = "Wilson"; + int counter = 0; + Map> nameMap = new HashMap<>(); + nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson")); + nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold")); + nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan")); + + Iterator>> iterator = nameMap.entrySet() + .iterator(); + Entry> entry = null; + List names = null; + while (iterator.hasNext()) { + entry = iterator.next(); + names = entry.getValue(); + for (String name : names) { + if (name.equalsIgnoreCase(searchName)) { + counter++; + break; + } + } + } + + return counter; + } + + public static int labeledBreak() { + String searchName = "Wilson"; + int counter = 0; + Map> nameMap = new HashMap<>(); + nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson")); + nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold")); + nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan")); + + Iterator>> iterator = nameMap.entrySet() + .iterator(); + Entry> entry = null; + List names = null; + compare: + while (iterator.hasNext()) { + entry = iterator.next(); + names = entry.getValue(); + for (String name : names) { + if (name.equalsIgnoreCase(searchName)) { + counter++; + break compare; + } + } + } + + return counter; + } + + public static int unlabeledContinue() { + String searchName = "Wilson"; + int counter = 0; + Map> nameMap = new HashMap<>(); + nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson")); + nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold")); + nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan")); + + Iterator>> iterator = nameMap.entrySet() + .iterator(); + Entry> entry = null; + List names = null; + while (iterator.hasNext()) { + entry = iterator.next(); + names = entry.getValue(); + for (String name : names) { + if (!name.equalsIgnoreCase(searchName)) { + continue; + } + + counter++; + } + } + + return counter; + } + + public static int labeledContinue() { + String searchName = "Wilson"; + int counter = 0; + Map> nameMap = new HashMap<>(); + nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson")); + nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold")); + nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan")); + + Iterator>> iterator = nameMap.entrySet() + .iterator(); + Entry> entry = null; + List names = null; + compare: + while (iterator.hasNext()) { + entry = iterator.next(); + names = entry.getValue(); + for (String name : names) { + if (name.equalsIgnoreCase(searchName)) { + counter++; + continue compare; + } + } + } + + return counter; + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparable/Player.java b/core-java/src/main/java/com/baeldung/comparable/Player.java new file mode 100644 index 0000000000..68a78980f3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparable/Player.java @@ -0,0 +1,51 @@ +package com.baeldung.comparable; + +public class Player implements Comparable { + + private int ranking; + + private String name; + + private int age; + + public Player(int ranking, String name, int age) { + this.ranking = ranking; + this.name = name; + this.age = age; + } + + public int getRanking() { + return ranking; + } + + public void setRanking(int ranking) { + this.ranking = ranking; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return this.name; + } + + @Override + public int compareTo(Player otherPlayer) { + return (this.getRanking() - otherPlayer.getRanking()); + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparable/PlayerSorter.java b/core-java/src/main/java/com/baeldung/comparable/PlayerSorter.java new file mode 100644 index 0000000000..a9b883f579 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparable/PlayerSorter.java @@ -0,0 +1,25 @@ +package com.baeldung.comparable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class PlayerSorter { + + public static void main(String[] args) { + + List footballTeam = new ArrayList(); + Player player1 = new Player(59, "John", 20); + Player player2 = new Player(67, "Roger", 22); + Player player3 = new Player(45, "Steven", 24); + footballTeam.add(player1); + footballTeam.add(player2); + footballTeam.add(player3); + + System.out.println("Before Sorting : " + footballTeam); + Collections.sort(footballTeam); + System.out.println("After Sorting : " + footballTeam); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparator/Player.java b/core-java/src/main/java/com/baeldung/comparator/Player.java new file mode 100644 index 0000000000..e6e9ee0db6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparator/Player.java @@ -0,0 +1,46 @@ +package com.baeldung.comparator; + +public class Player { + + private int ranking; + + private String name; + + private int age; + + public Player(int ranking, String name, int age) { + this.ranking = ranking; + this.name = name; + this.age = age; + } + + public int getRanking() { + return ranking; + } + + public void setRanking(int ranking) { + this.ranking = ranking; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return this.name; + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparator/PlayerAgeComparator.java b/core-java/src/main/java/com/baeldung/comparator/PlayerAgeComparator.java new file mode 100644 index 0000000000..d2e7ca1f42 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparator/PlayerAgeComparator.java @@ -0,0 +1,12 @@ +package com.baeldung.comparator; + +import java.util.Comparator; + +public class PlayerAgeComparator implements Comparator { + + @Override + public int compare(Player firstPlayer, Player secondPlayer) { + return (firstPlayer.getAge() - secondPlayer.getAge()); + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparator/PlayerAgeSorter.java b/core-java/src/main/java/com/baeldung/comparator/PlayerAgeSorter.java new file mode 100644 index 0000000000..3bbbcddb80 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparator/PlayerAgeSorter.java @@ -0,0 +1,27 @@ +package com.baeldung.comparator; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class PlayerAgeSorter { + + public static void main(String[] args) { + + List footballTeam = new ArrayList(); + Player player1 = new Player(59, "John", 22); + Player player2 = new Player(67, "Roger", 20); + Player player3 = new Player(45, "Steven", 24); + footballTeam.add(player1); + footballTeam.add(player2); + footballTeam.add(player3); + + System.out.println("Before Sorting : " + footballTeam); + //Instance of PlayerAgeComparator + PlayerAgeComparator playerComparator = new PlayerAgeComparator(); + Collections.sort(footballTeam, playerComparator); + System.out.println("After Sorting by age : " + footballTeam); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparator/PlayerRankingComparator.java b/core-java/src/main/java/com/baeldung/comparator/PlayerRankingComparator.java new file mode 100644 index 0000000000..2d42698843 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparator/PlayerRankingComparator.java @@ -0,0 +1,12 @@ +package com.baeldung.comparator; + +import java.util.Comparator; + +public class PlayerRankingComparator implements Comparator { + + @Override + public int compare(Player firstPlayer, Player secondPlayer) { + return (firstPlayer.getRanking() - secondPlayer.getRanking()); + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparator/PlayerRankingSorter.java b/core-java/src/main/java/com/baeldung/comparator/PlayerRankingSorter.java new file mode 100644 index 0000000000..581585fb7e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparator/PlayerRankingSorter.java @@ -0,0 +1,27 @@ +package com.baeldung.comparator; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class PlayerRankingSorter { + + public static void main(String[] args) { + + List footballTeam = new ArrayList(); + Player player1 = new Player(59, "John", 22); + Player player2 = new Player(67, "Roger", 20); + Player player3 = new Player(45, "Steven", 40); + footballTeam.add(player1); + footballTeam.add(player2); + footballTeam.add(player3); + + System.out.println("Before Sorting : " + footballTeam); + //Instance of PlayerRankingComparator + PlayerRankingComparator playerComparator = new PlayerRankingComparator(); + Collections.sort(footballTeam, playerComparator); + System.out.println("After Sorting by ranking : " + footballTeam); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractFactory.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractFactory.java new file mode 100644 index 0000000000..46d97d1a15 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractFactory.java @@ -0,0 +1,6 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public interface AbstractFactory { + Animal getAnimal(String toyType) ; + Color getColor(String colorType); +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractPatternDriver.java new file mode 100644 index 0000000000..7ab166e16a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractPatternDriver.java @@ -0,0 +1,18 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class AbstractPatternDriver { + public static void main(String[] args) { + AbstractFactory abstractFactory; + + //creating a brown toy dog + abstractFactory = FactoryProvider.getFactory("Toy"); + Animal toy = abstractFactory.getAnimal("Dog"); + + abstractFactory = FactoryProvider.getFactory("Color"); + Color color = abstractFactory.getColor("Brown"); + + String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound(); + + System.out.println(result); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Animal.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Animal.java new file mode 100644 index 0000000000..59c1336053 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Animal.java @@ -0,0 +1,6 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public interface Animal { + String getType(); + String makeSound(); +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AnimalFactory.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AnimalFactory.java new file mode 100644 index 0000000000..49583c3a98 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/AnimalFactory.java @@ -0,0 +1,21 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class AnimalFactory implements AbstractFactory { + + @Override + public Animal getAnimal(String animalType) { + if ("Dog".equalsIgnoreCase(animalType)) { + return new Dog(); + } else if ("Duck".equalsIgnoreCase(animalType)) { + return new Duck(); + } + + return null; + } + + @Override + public Color getColor(String color) { + throw new UnsupportedOperationException(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Brown.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Brown.java new file mode 100644 index 0000000000..f251285ebf --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Brown.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class Brown implements Color { + + @Override + public String getColor() { + return "brown"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Color.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Color.java new file mode 100644 index 0000000000..897bb71f38 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Color.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public interface Color { + String getColor(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/ColorFactory.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/ColorFactory.java new file mode 100644 index 0000000000..8f7559ff27 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/ColorFactory.java @@ -0,0 +1,21 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class ColorFactory implements AbstractFactory { + + @Override + public Color getColor(String colorType) { + if ("Brown".equalsIgnoreCase(colorType)) { + return new Brown(); + } else if ("White".equalsIgnoreCase(colorType)) { + return new White(); + } + + return null; + } + + @Override + public Animal getAnimal(String toyType) { + throw new UnsupportedOperationException(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Dog.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Dog.java new file mode 100644 index 0000000000..002b5665d3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Dog.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class Dog implements Animal { + + @Override + public String getType() { + return "Dog"; + } + + @Override + public String makeSound() { + return "Barks"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Duck.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Duck.java new file mode 100644 index 0000000000..5603ad6eee --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/Duck.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class Duck implements Animal { + + @Override + public String getType() { + return "Duck"; + } + + @Override + public String makeSound() { + return "Squeks"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/FactoryProvider.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/FactoryProvider.java new file mode 100644 index 0000000000..fcbee1e6de --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/FactoryProvider.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class FactoryProvider { + public static AbstractFactory getFactory(String choice){ + + if("Toy".equalsIgnoreCase(choice)){ + return new AnimalFactory(); + } + else if("Color".equalsIgnoreCase(choice)){ + return new ColorFactory(); + } + + return null; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/White.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/White.java new file mode 100644 index 0000000000..62ef8048ea --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/abstractfactory/White.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +public class White implements Color { + + @Override + public String getColor() { + return "White"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/builder/BankAccount.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/builder/BankAccount.java new file mode 100644 index 0000000000..355fa74895 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/builder/BankAccount.java @@ -0,0 +1,64 @@ +package com.baeldung.designpatterns.creational.builder; + +public class BankAccount { + private String name; + private String accountNumber; + private String email; + private boolean newsletter; + + //The constructor that takes a builder from which it will create object + //the access to this is only provided to builder + private BankAccount(BankAccountBuilder builder) { + this.name = builder.name; + this.accountNumber = builder.accountNumber; + this.email = builder.email; + this.newsletter = builder.newsletter; + } + + public static class BankAccountBuilder { + private String name; + private String accountNumber; + private String email; + private boolean newsletter; + + //All Mandatory parameters goes with this constructor + public BankAccountBuilder(String name, String accountNumber) { + this.name = name; + this.accountNumber = accountNumber; + } + + //setters for optional parameters which returns this same builder + //to support fluent design + public BankAccountBuilder withEmail(String email) { + this.email = email; + return this; + } + + public BankAccountBuilder wantNewsletter(boolean newsletter) { + this.newsletter = newsletter; + return this; + } + + //the actual build method that prepares and returns a BankAccount object + public BankAccount build() { + return new BankAccount(this); + } + } + + //getters + public String getName() { + return name; + } + + public String getAccountNumber() { + return accountNumber; + } + + public String getEmail() { + return email; + } + + public boolean isNewsletter() { + return newsletter; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/builder/BuilderPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/builder/BuilderPatternDriver.java new file mode 100644 index 0000000000..d92a70e664 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/builder/BuilderPatternDriver.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.creational.builder; + +public class BuilderPatternDriver { + public static void main(String[] args) { + BankAccount newAccount = new BankAccount + .BankAccountBuilder("Jon", "22738022275") + .withEmail("jon@example.com") + .wantNewsletter(true) + .build(); + + System.out.println("Name: " + newAccount.getName()); + System.out.println("AccountNumber:" + newAccount.getAccountNumber()); + System.out.println("Email: " + newAccount.getEmail()); + System.out.println("Want News letter?: " + newAccount.isNewsletter()); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/FactoryDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/FactoryDriver.java new file mode 100644 index 0000000000..64ee307bb8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/FactoryDriver.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.creational.factory; + +public class FactoryDriver { + public static void main(String[] args) { + Polygon p; + PolygonFactory factory = new PolygonFactory(); + + //get the shape which has 4 sides + p = factory.getPolygon(4); + System.out.println("The shape with 4 sides is a " + p.getType()); + + //get the shape which has 4 sides + p = factory.getPolygon(8); + System.out.println("The shape with 8 sides is a " + p.getType()); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Heptagon.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Heptagon.java new file mode 100644 index 0000000000..935fc2f04c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Heptagon.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.factory; + +public class Heptagon implements Polygon { + + @Override + public String getType() { + return "Heptagon"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Octagon.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Octagon.java new file mode 100644 index 0000000000..fc62302dc8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Octagon.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.factory; + +public class Octagon implements Polygon { + + @Override + public String getType() { + return "Octagon"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Pentagon.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Pentagon.java new file mode 100644 index 0000000000..65d109b10b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Pentagon.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.factory; + +public class Pentagon implements Polygon { + + @Override + public String getType() { + return "Pentagon"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Polygon.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Polygon.java new file mode 100644 index 0000000000..8364e546b0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Polygon.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.creational.factory; + +public interface Polygon { + String getType(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/PolygonFactory.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/PolygonFactory.java new file mode 100644 index 0000000000..9f34fe77b9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/PolygonFactory.java @@ -0,0 +1,22 @@ +package com.baeldung.designpatterns.creational.factory; + +public class PolygonFactory { + public Polygon getPolygon(int numberOfSides) { + if(numberOfSides == 3) { + return new Triangle(); + } + if(numberOfSides == 4) { + return new Square(); + } + if(numberOfSides == 5) { + return new Pentagon(); + } + if(numberOfSides == 7) { + return new Heptagon(); + } + else if(numberOfSides == 8) { + return new Octagon(); + } + return null; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Square.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Square.java new file mode 100644 index 0000000000..805c1c9ae3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Square.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.factory; + +public class Square implements Polygon { + + @Override + public String getType() { + return "Square"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Triangle.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Triangle.java new file mode 100644 index 0000000000..8a8832d8a1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/Triangle.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.creational.factory; + +public class Triangle implements Polygon { + + @Override + public String getType() { + return "Triangle"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/singleton/Singleton.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/singleton/Singleton.java new file mode 100644 index 0000000000..1a5ac82c89 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/singleton/Singleton.java @@ -0,0 +1,13 @@ +package com.baeldung.designpatterns.creational.singleton; + +public class Singleton { + private Singleton() {} + + private static class SingletonHolder { + public static final Singleton instance = new Singleton(); + } + + public static Singleton getInstance() { + return SingletonHolder.instance; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/singleton/SingletonDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/singleton/SingletonDriver.java new file mode 100644 index 0000000000..1955008d3e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/singleton/SingletonDriver.java @@ -0,0 +1,8 @@ +package com.baeldung.designpatterns.creational.singleton; + +public class SingletonDriver { + public static void main(String[] args) { + Singleton instance = Singleton.getInstance(); + System.out.println(instance.toString()); + } +} diff --git a/core-java/src/main/java/com/baeldung/loops/LoopsInJava.java b/core-java/src/main/java/com/baeldung/loops/LoopsInJava.java new file mode 100644 index 0000000000..1b2e621b52 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/loops/LoopsInJava.java @@ -0,0 +1,43 @@ +package com.baeldung.loops; + +public class LoopsInJava { + + public int[] simple_for_loop() { + int[] arr = new int[5]; + for (int i = 0; i < 5; i++) { + arr[i] = i; + System.out.println("Simple for loop: i - " + i); + } + return arr; + } + + public int[] enhanced_for_each_loop() { + int[] intArr = { 0, 1, 2, 3, 4 }; + int[] arr = new int[5]; + for (int num : intArr) { + arr[num] = num; + System.out.println("Enhanced for-each loop: i - " + num); + } + return arr; + } + + public int[] while_loop() { + int i = 0; + int[] arr = new int[5]; + while (i < 5) { + arr[i] = i; + System.out.println("While loop: i - " + i++); + } + return arr; + } + + public int[] do_while_loop() { + int i = 0; + int[] arr = new int[5]; + do { + arr[i] = i; + System.out.println("Do-While loop: i - " + i++); + } while (i < 5); + return arr; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/nestedclass/Enclosing.java b/core-java/src/main/java/com/baeldung/nestedclass/Enclosing.java new file mode 100644 index 0000000000..a9911538b0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nestedclass/Enclosing.java @@ -0,0 +1,11 @@ +package com.baeldung.nestedclass; + +public class Enclosing { + + public static class Nested { + + public void test() { + System.out.println("Calling test..."); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/nestedclass/NewEnclosing.java b/core-java/src/main/java/com/baeldung/nestedclass/NewEnclosing.java new file mode 100644 index 0000000000..c7e04e8600 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nestedclass/NewEnclosing.java @@ -0,0 +1,15 @@ +package com.baeldung.nestedclass; + +public class NewEnclosing { + + void run() { + class Local { + + void run() { + System.out.println("Welcome to Baeldung!"); + } + } + Local local = new Local(); + local.run(); + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/nestedclass/Outer.java b/core-java/src/main/java/com/baeldung/nestedclass/Outer.java new file mode 100644 index 0000000000..ebd6d27293 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nestedclass/Outer.java @@ -0,0 +1,11 @@ +package com.baeldung.nestedclass; + +public class Outer { + + public class Inner { + + public void test() { + System.out.println("Calling test..."); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/nestedclass/SimpleAbstractClass.java b/core-java/src/main/java/com/baeldung/nestedclass/SimpleAbstractClass.java new file mode 100644 index 0000000000..586e2d12b4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nestedclass/SimpleAbstractClass.java @@ -0,0 +1,5 @@ +package com.baeldung.nestedclass; + +abstract class SimpleAbstractClass { + abstract void run(); +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java b/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java new file mode 100644 index 0000000000..4882ebe175 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7.java @@ -0,0 +1,43 @@ +package com.baeldung.timezonedisplay; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.TimeZone; +import java.util.concurrent.TimeUnit; + +public class TimezoneDisplayJava7 { + + public enum OffsetBase { + GMT, UTC + } + + public List getTimeZoneList(TimezoneDisplayJava7.OffsetBase base) { + String[] availableZoneIds = TimeZone.getAvailableIDs(); + List result = new ArrayList<>(availableZoneIds.length); + + for (String zoneId : availableZoneIds) { + TimeZone curTimeZone = TimeZone.getTimeZone(zoneId); + + String offset = calculateOffset(curTimeZone.getRawOffset()); + + result.add(String.format("(%s%s) %s", base, offset, zoneId)); + } + + Collections.sort(result); + + return result; + } + + private String calculateOffset(int rawOffset) { + if (rawOffset == 0) { + return "+00:00"; + } + long hours = TimeUnit.MILLISECONDS.toHours(rawOffset); + long minutes = TimeUnit.MILLISECONDS.toMinutes(rawOffset); + minutes = Math.abs(minutes - TimeUnit.HOURS.toMinutes(hours)); + + return String.format("%+03d:%02d", hours, Math.abs(minutes)); + } + +} diff --git a/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java b/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java new file mode 100644 index 0000000000..9f20667660 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/timezonedisplay/TimezoneDisplayJava7App.java @@ -0,0 +1,23 @@ +package com.baeldung.timezonedisplay; + +import java.util.List; + +public class TimezoneDisplayJava7App { + + public static void main(String... args) { + TimezoneDisplayJava7 display = new TimezoneDisplayJava7(); + + System.out.println("Time zones in UTC:"); + List utc = display.getTimeZoneList(TimezoneDisplayJava7.OffsetBase.UTC); + for (String timeZone : utc) { + System.out.println(timeZone); + } + + System.out.println("Time zones in GMT:"); + List gmt = display.getTimeZoneList(TimezoneDisplayJava7.OffsetBase.GMT); + for (String timeZone : gmt) { + System.out.println(timeZone); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/util/StreamUtils.java b/core-java/src/main/java/com/baeldung/util/StreamUtils.java new file mode 100644 index 0000000000..42f438732f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/util/StreamUtils.java @@ -0,0 +1,16 @@ +package com.baeldung.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import org.apache.commons.io.IOUtils; + +public class StreamUtils { + + public static String getStringFromInputStream(InputStream input) throws IOException { + StringWriter writer = new StringWriter(); + IOUtils.copy(input, writer, "UTF-8"); + return writer.toString(); + } +} diff --git a/core-java/src/main/resources/META-INF/services/com.sun.source.util.Plugin b/core-java/src/main/resources/META-INF/services/com.sun.source.util.Plugin new file mode 100644 index 0000000000..91fb6eb3b0 --- /dev/null +++ b/core-java/src/main/resources/META-INF/services/com.sun.source.util.Plugin @@ -0,0 +1 @@ +com.baeldung.javac.SampleJavacPlugin \ No newline at end of file diff --git a/core-java/src/main/resources/countries.properties b/core-java/src/main/resources/countries.properties new file mode 100644 index 0000000000..3c1f53aded --- /dev/null +++ b/core-java/src/main/resources/countries.properties @@ -0,0 +1,3 @@ +UK +US +Germany diff --git a/core-java/src/test/java/com/baeldung/arraydeque/ArrayDequeTest.java b/core-java/src/test/java/com/baeldung/arraydeque/ArrayDequeTest.java new file mode 100644 index 0000000000..50813a8601 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/arraydeque/ArrayDequeTest.java @@ -0,0 +1,50 @@ +package com.baeldung.arraydeque; + +import java.util.ArrayDeque; +import java.util.Deque; + +import static org.junit.Assert.*; +import org.junit.Test; + +public class ArrayDequeTest { + + @Test + public void whenOffer_addsAtLast() { + final Deque deque = new ArrayDeque<>(); + + deque.offer("first"); + deque.offer("second"); + + assertEquals("second", deque.getLast()); + } + + @Test + public void whenPoll_removesFirst() { + final Deque deque = new ArrayDeque<>(); + + deque.offer("first"); + deque.offer("second"); + + assertEquals("first", deque.poll()); + } + + @Test + public void whenPush_addsAtFirst() { + final Deque deque = new ArrayDeque<>(); + + deque.push("first"); + deque.push("second"); + + assertEquals("second", deque.getFirst()); + } + + @Test + public void whenPop_removesLast() { + final Deque deque = new ArrayDeque<>(); + + deque.push("first"); + deque.push("second"); + + assertEquals("second", deque.pop()); + } +} diff --git a/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java new file mode 100644 index 0000000000..1980497cd3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java @@ -0,0 +1,39 @@ +package com.baeldung.breakcontinue; + +import static com.baeldung.breakcontinue.BreakContinue.labeledBreak; +import static com.baeldung.breakcontinue.BreakContinue.labeledContinue; +import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreak; +import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreakNestedLoops; +import static com.baeldung.breakcontinue.BreakContinue.unlabeledContinue; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class BreakContinueTest { + + @Test + public void whenUnlabeledBreak_ThenEqual() { + assertEquals(4, unlabeledBreak()); + } + + @Test + public void whenUnlabeledBreakNestedLoops_ThenEqual() { + assertEquals(2, unlabeledBreakNestedLoops()); + } + + @Test + public void whenLabeledBreak_ThenEqual() { + assertEquals(1, labeledBreak()); + } + + @Test + public void whenUnlabeledContinue_ThenEqual() { + assertEquals(5, unlabeledContinue()); + } + + @Test + public void whenLabeledContinue_ThenEqual() { + assertEquals(3, labeledContinue()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/comparable/ComparableUnitTest.java b/core-java/src/test/java/com/baeldung/comparable/ComparableUnitTest.java new file mode 100644 index 0000000000..e8745884b8 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/comparable/ComparableUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.comparable; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.Test; + +public class ComparableUnitTest { + + @Test + public void whenUsingComparable_thenSortedList() { + List footballTeam = new ArrayList(); + Player player1 = new Player(59, "John", 20); + Player player2 = new Player(67, "Roger", 22); + Player player3 = new Player(45, "Steven", 24); + footballTeam.add(player1); + footballTeam.add(player2); + footballTeam.add(player3); + Collections.sort(footballTeam); + assertEquals(footballTeam.get(0) + .getName(), "Steven"); + assertEquals(footballTeam.get(2) + .getRanking(), 67); + } + +} diff --git a/core-java/src/test/java/com/baeldung/comparator/ComparatorUnitTest.java b/core-java/src/test/java/com/baeldung/comparator/ComparatorUnitTest.java new file mode 100644 index 0000000000..5b7ec3bfe4 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/comparator/ComparatorUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.comparator; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class ComparatorUnitTest { + + List footballTeam; + + @Before + public void setUp() { + footballTeam = new ArrayList(); + Player player1 = new Player(59, "John", 20); + Player player2 = new Player(67, "Roger", 22); + Player player3 = new Player(45, "Steven", 24); + footballTeam.add(player1); + footballTeam.add(player2); + footballTeam.add(player3); + } + + @Test + public void whenUsingRankingComparator_thenSortedList() { + PlayerRankingComparator playerComparator = new PlayerRankingComparator(); + Collections.sort(footballTeam, playerComparator); + assertEquals(footballTeam.get(0) + .getName(), "Steven"); + assertEquals(footballTeam.get(2) + .getRanking(), 67); + } + + @Test + public void whenUsingAgeComparator_thenSortedList() { + PlayerAgeComparator playerComparator = new PlayerAgeComparator(); + Collections.sort(footballTeam, playerComparator); + assertEquals(footballTeam.get(0) + .getName(), "John"); + assertEquals(footballTeam.get(2) + .getRanking(), 45); + } + +} diff --git a/core-java/src/test/java/com/baeldung/comparator/Java8ComparatorUnitTest.java b/core-java/src/test/java/com/baeldung/comparator/Java8ComparatorUnitTest.java new file mode 100644 index 0000000000..49c8749309 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/comparator/Java8ComparatorUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.comparator; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class Java8ComparatorUnitTest { + + List footballTeam; + + @Before + public void setUp() { + footballTeam = new ArrayList(); + Player player1 = new Player(59, "John", 22); + Player player2 = new Player(67, "Roger", 20); + Player player3 = new Player(45, "Steven", 24); + footballTeam.add(player1); + footballTeam.add(player2); + footballTeam.add(player3); + } + + @Test + public void whenComparing_UsingLambda_thenSorted() { + System.out.println("************** Java 8 Comaparator **************"); + Comparator byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking(); + + System.out.println("Before Sorting : " + footballTeam); + Collections.sort(footballTeam, byRanking); + System.out.println("After Sorting : " + footballTeam); + assertEquals(footballTeam.get(0) + .getName(), "Steven"); + assertEquals(footballTeam.get(2) + .getRanking(), 67); + } + + @Test + public void whenComparing_UsingComparatorComparing_thenSorted() { + System.out.println("********* Comaparator.comparing method *********"); + System.out.println("********* byRanking *********"); + Comparator byRanking = Comparator.comparing(Player::getRanking); + + System.out.println("Before Sorting : " + footballTeam); + Collections.sort(footballTeam, byRanking); + System.out.println("After Sorting : " + footballTeam); + assertEquals(footballTeam.get(0) + .getName(), "Steven"); + assertEquals(footballTeam.get(2) + .getRanking(), 67); + + System.out.println("********* byAge *********"); + Comparator byAge = Comparator.comparing(Player::getAge); + + System.out.println("Before Sorting : " + footballTeam); + Collections.sort(footballTeam, byAge); + System.out.println("After Sorting : " + footballTeam); + assertEquals(footballTeam.get(0) + .getName(), "Roger"); + assertEquals(footballTeam.get(2) + .getRanking(), 45); + } + +} diff --git a/core-java/src/test/java/com/baeldung/copyfiles/FileCopierTest.java b/core-java/src/test/java/com/baeldung/copyfiles/FileCopierTest.java new file mode 100644 index 0000000000..973436a26a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/copyfiles/FileCopierTest.java @@ -0,0 +1,70 @@ +package com.baeldung.copyfiles; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; + +import org.apache.commons.io.FileUtils; +import org.junit.Before; +import org.junit.Test; +import static org.assertj.core.api.Assertions.*; + +public class FileCopierTest { + File original = new File("src/test/resources/original.txt"); + + @Before + public void init() throws IOException { + if (!original.exists()) + Files.createFile(original.toPath()); + } + + @Test + public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { + File copied = new File("src/test/resources/copiedWithIo.txt"); + try (InputStream in = new BufferedInputStream(new FileInputStream(original)); + OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) { + byte[] buffer = new byte[1024]; + int lengthRead; + while ((lengthRead = in.read(buffer)) > 0) { + out.write(buffer, 0, lengthRead); + out.flush(); + } + } + assertThat(copied).exists(); + assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); + } + + @Test + public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException { + File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); + FileUtils.copyFile(original, copied); + assertThat(copied).exists(); + assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); + } + + @Test + public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException { + Path copied = Paths.get("src/test/resources/copiedWithNio.txt"); + Path originalPath = original.toPath(); + Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING); + assertThat(copied).exists(); + assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied))); + } + + @Test + public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException { + File copied = new File("src/test/resources/copiedWithApacheCommons.txt"); + com.google.common.io.Files.copy(original, copied); + assertThat(copied).exists(); + assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath()))); + } +} diff --git a/core-java/src/test/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractPatternIntegrationTest.java new file mode 100644 index 0000000000..dc02b976a0 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/creational/abstractfactory/AbstractPatternIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung.designpatterns.creational.abstractfactory; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class AbstractPatternIntegrationTest { + @Test + public void givenAbstractFactory_whenGettingObjects_thenSuccessful() { + AbstractFactory abstractFactory; + + //creating a brown toy dog + abstractFactory = FactoryProvider.getFactory("Toy"); + Animal toy = abstractFactory.getAnimal("Dog"); + + abstractFactory = FactoryProvider.getFactory("Color"); + Color color = abstractFactory.getColor("Brown"); + + String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound(); + assertEquals("A Dog with brown color Barks", result); + } + +} diff --git a/core-java/src/test/java/com/baeldung/designpatterns/creational/builder/BuilderPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/creational/builder/BuilderPatternIntegrationTest.java new file mode 100644 index 0000000000..898330b26e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/creational/builder/BuilderPatternIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.designpatterns.creational.builder; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class BuilderPatternIntegrationTest { + @Test + public void whenCreatingObjectThroughBuilder_thenObjectValid() { + BankAccount newAccount = new BankAccount + .BankAccountBuilder("Jon", "22738022275") + .withEmail("jon@example.com") + .wantNewsletter(true) + .build(); + + assertEquals(newAccount.getName(), "Jon"); + assertEquals(newAccount.getAccountNumber(), "22738022275"); + assertEquals(newAccount.getEmail(), "jon@example.com"); + assertEquals(newAccount.isNewsletter(), true); + } + + @Test + public void whenSkippingOptionalParameters_thenObjectValid() { + BankAccount newAccount = new BankAccount + .BankAccountBuilder("Jon", "22738022275") + .build(); + + assertEquals(newAccount.getName(), "Jon"); + assertEquals(newAccount.getAccountNumber(), "22738022275"); + assertEquals(newAccount.getEmail(), null); + assertEquals(newAccount.isNewsletter(), false); + } +} diff --git a/core-java/src/test/java/com/baeldung/designpatterns/creational/factory/FactoryIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/creational/factory/FactoryIntegrationTest.java new file mode 100644 index 0000000000..ed0419c16d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/creational/factory/FactoryIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.designpatterns.creational.factory; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class FactoryIntegrationTest { + + @Test + public void whenUsingFactoryForSquare_thenCorrectObjectReturned() { + Polygon p; + PolygonFactory factory = new PolygonFactory(); + + //get the shape which has 4 sides + p = factory.getPolygon(4); + String result = "The shape with 4 sides is a " + p.getType(); + + assertEquals("The shape with 4 sides is a Square", result); + } + + @Test + public void whenUsingFactoryForOctagon_thenCorrectObjectReturned() { + Polygon p; + PolygonFactory factory = new PolygonFactory(); + + //get the shape which has 4 sides + p = factory.getPolygon(8); + String result = "The shape with 8 sides is a " + p.getType(); + + assertEquals("The shape with 8 sides is a Octagon", result); + } +} diff --git a/core-java/src/test/java/com/baeldung/designpatterns/creational/singleton/SingletonIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/creational/singleton/SingletonIntegrationTest.java new file mode 100644 index 0000000000..a3d5b7a14d --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/creational/singleton/SingletonIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.designpatterns.creational.singleton; + +import org.junit.Test; +import static org.junit.Assert.*; + +public class SingletonIntegrationTest { + + @Test + /** + * Although there is absolutely no way to determine whether + * a class is Singleton, in this test case, we will just + * check for two objects if they point to same instance or + * not. We will also check for their hashcode. + */ + public void whenGettingMultipleObjects_thenAllPointToSame() { + //first object + Singleton obj1 = Singleton.getInstance(); + + //Second object + Singleton obj2 = Singleton.getInstance(); + + assertTrue(obj1 == obj2); + assertEquals(obj1.hashCode(), obj2.hashCode()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/file/FilesTest.java b/core-java/src/test/java/com/baeldung/file/FilesTest.java new file mode 100644 index 0000000000..e17e8580aa --- /dev/null +++ b/core-java/src/test/java/com/baeldung/file/FilesTest.java @@ -0,0 +1,94 @@ +package com.baeldung.file; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; + +import com.google.common.base.Charsets; +import com.google.common.io.CharSink; +import com.google.common.io.FileWriteMode; +import org.apache.commons.io.FileUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.util.StreamUtils; + +public class FilesTest { + + public static final String fileName = "src/main/resources/countries.properties"; + + @Before + @After + public void setup() throws Exception { + PrintWriter writer = new PrintWriter(fileName); + writer.print("UK\r\n" + "US\r\n" + "Germany\r\n"); + writer.close(); + } + + @Test + public void whenAppendToFileUsingGuava_thenCorrect() throws IOException { + File file = new File(fileName); + CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND); + chs.write("Spain\r\n"); + + assertThat(StreamUtils.getStringFromInputStream( + new FileInputStream(fileName))) + .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + } + + + @Test + public void whenAppendToFileUsingFiles_thenCorrect() throws IOException { + Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND); + + assertThat(StreamUtils.getStringFromInputStream( + new FileInputStream(fileName))) + .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + } + + @Test + public void whenAppendToFileUsingFileUtils_thenCorrect() throws IOException { + File file = new File(fileName); + FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true); + + assertThat(StreamUtils.getStringFromInputStream( + new FileInputStream(fileName))) + .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + } + + @Test + public void whenAppendToFileUsingFileOutputStream_thenCorrect() throws Exception { + FileOutputStream fos = new FileOutputStream(fileName, true); + fos.write("Spain\r\n".getBytes()); + fos.close(); + + assertThat(StreamUtils.getStringFromInputStream( + new FileInputStream(fileName))) + .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + } + + @Test + public void whenAppendToFileUsingFileWriter_thenCorrect() throws IOException { + FileWriter fw = new FileWriter(fileName, true); + BufferedWriter bw = new BufferedWriter(fw); + bw.write("Spain"); + bw.newLine(); + bw.close(); + + assertThat( + StreamUtils.getStringFromInputStream( + new FileInputStream(fileName))) + .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n"); + } +} diff --git a/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java b/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java new file mode 100644 index 0000000000..9590eabfef --- /dev/null +++ b/core-java/src/test/java/com/baeldung/loops/WhenUsingLoops.java @@ -0,0 +1,37 @@ +package com.baeldung.loops; + +import org.junit.Assert; +import org.junit.Test; + +public class WhenUsingLoops { + + private LoopsInJava loops = new LoopsInJava(); + + @Test + public void shouldRunForLoop() { + int[] expected = { 0, 1, 2, 3, 4 }; + int[] actual = loops.simple_for_loop(); + Assert.assertArrayEquals(expected, actual); + } + + @Test + public void shouldRunEnhancedForeachLoop() { + int[] expected = { 0, 1, 2, 3, 4 }; + int[] actual = loops.enhanced_for_each_loop(); + Assert.assertArrayEquals(expected, actual); + } + + @Test + public void shouldRunWhileLoop() { + int[] expected = { 0, 1, 2, 3, 4 }; + int[] actual = loops.while_loop(); + Assert.assertArrayEquals(expected, actual); + } + + @Test + public void shouldRunDoWhileLoop() { + int[] expected = { 0, 1, 2, 3, 4 }; + int[] actual = loops.do_while_loop(); + Assert.assertArrayEquals(expected, actual); + } +} diff --git a/core-java/src/test/java/com/baeldung/nestedclass/AnonymousInnerTest.java b/core-java/src/test/java/com/baeldung/nestedclass/AnonymousInnerTest.java new file mode 100644 index 0000000000..394c0bb57a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nestedclass/AnonymousInnerTest.java @@ -0,0 +1,16 @@ +package com.baeldung.nestedclass; + +import org.junit.Test; + +public class AnonymousInnerTest { + + @Test + public void whenRunAnonymousClass_thenCorrect() { + SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() { + void run() { + System.out.println("Running Anonymous Class..."); + } + }; + simpleAbstractClass.run(); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/nestedclass/InnerClassTest.java b/core-java/src/test/java/com/baeldung/nestedclass/InnerClassTest.java new file mode 100644 index 0000000000..e9cb119ac2 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nestedclass/InnerClassTest.java @@ -0,0 +1,13 @@ +package com.baeldung.nestedclass; + +import org.junit.Test; + +public class InnerClassTest { + + @Test + public void givenInnerClassWhenInstantiating_thenCorrect() { + Outer outer = new Outer(); + Outer.Inner inner = outer.new Inner(); + inner.test(); + } +} diff --git a/core-java/src/test/java/com/baeldung/nestedclass/LocalClassTest.java b/core-java/src/test/java/com/baeldung/nestedclass/LocalClassTest.java new file mode 100644 index 0000000000..dad19161ad --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nestedclass/LocalClassTest.java @@ -0,0 +1,12 @@ +package com.baeldung.nestedclass; + +import org.junit.Test; + +public class LocalClassTest { + + @Test + public void whenTestingLocalClass_thenCorrect() { + NewEnclosing newEnclosing = new NewEnclosing(); + newEnclosing.run(); + } +} diff --git a/core-java/src/test/java/com/baeldung/nestedclass/NestedClassTest.java b/core-java/src/test/java/com/baeldung/nestedclass/NestedClassTest.java new file mode 100644 index 0000000000..16c883689a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nestedclass/NestedClassTest.java @@ -0,0 +1,12 @@ +package com.baeldung.nestedclass; + +import org.junit.Test; + +public class NestedClassTest { + + @Test + public void whenInstantiatingStaticNestedClass_thenCorrect() { + Enclosing.Nested nested = new Enclosing.Nested(); + nested.test(); + } +} diff --git a/core-java/src/test/java/com/baeldung/nestedclass/NewOuterTest.java b/core-java/src/test/java/com/baeldung/nestedclass/NewOuterTest.java new file mode 100644 index 0000000000..e883687d33 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/nestedclass/NewOuterTest.java @@ -0,0 +1,32 @@ +package com.baeldung.nestedclass; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +public class NewOuterTest { + + int a = 1; + static int b = 2; + + public class InnerClass { + int a = 3; + static final int b = 4; + + @Test + public void whenShadowing_thenCorrect() { + assertEquals(3, a); + assertEquals(4, b); + assertEquals(1, NewOuterTest.this.a); + assertEquals(2, NewOuterTest.b); + assertEquals(2, NewOuterTest.this.b); + } + } + + @Test + public void shadowingTest() { + NewOuterTest outer = new NewOuterTest(); + NewOuterTest.InnerClass inner = outer.new InnerClass(); + inner.whenShadowing_thenCorrect(); + + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java b/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java new file mode 100644 index 0000000000..2b04617f36 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stack/StackUnitTest.java @@ -0,0 +1,137 @@ +package com.baeldung.stack; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.*; + +import java.util.Arrays; +import java.util.List; +import java.util.ListIterator; +import java.util.Stack; + +import org.junit.Test; +public class StackUnitTest { + + @Test + public void whenStackIsCreated_thenItHasSize0() { + Stack intStack = new Stack(); + assertEquals(0, intStack.size()); + } + + @Test + public void givenEmptyStack_whenElementIsPushed_thenStackSizeisIncreased() { + Stack intStack = new Stack(); + intStack.push(1); + assertEquals(1, intStack.size()); + } + + @Test + public void givenEmptyStack_whenMultipleElementsArePushed_thenStackSizeisIncreased() { + Stack intStack = new Stack(); + List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + boolean result = intStack.addAll(intList); + assertTrue(result); + assertEquals(7, intList.size()); + } + + @Test + public void whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.pop(); + assertTrue(intStack.isEmpty()); + } + + @Test + public void whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.peek(); + assertEquals(1, intStack.search(5)); + assertEquals(1, intStack.size()); + } + + @Test + public void whenElementIsOnStack_thenSearchReturnsItsDistanceFromTheTop() { + Stack intStack = new Stack(); + intStack.push(5); + assertEquals(1, intStack.search(5)); + } + + @Test + public void whenElementIsOnStack_thenIndexOfReturnsItsIndex() { + Stack intStack = new Stack(); + intStack.push(5); + int indexOf = intStack.indexOf(5); + assertEquals(0, indexOf); + } + + @Test + public void whenMultipleElementsAreOnStack_thenIndexOfReturnsLastElementIndex() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.push(5); + intStack.push(5); + int lastIndexOf = intStack.lastIndexOf(5); + assertEquals(2, lastIndexOf); + } + + @Test + public void givenElementOnStack_whenRemoveElementIsInvoked_thenElementIsRemoved() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.push(5); + intStack.removeElement(5); + assertEquals(1, intStack.size()); + } + + @Test + public void givenElementOnStack_whenRemoveElementAtIsInvoked_thenElementIsRemoved() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.push(7); + intStack.removeElementAt(1); + assertEquals(-1, intStack.search(7)); + } + + @Test + public void givenElementsOnStack_whenRemoveAllElementsIsInvoked_thenAllElementsAreRemoved() { + Stack intStack = new Stack(); + intStack.push(5); + intStack.push(7); + intStack.removeAllElements(); + assertTrue(intStack.isEmpty()); + } + + @Test + public void givenElementsOnStack_whenRemoveAllIsInvoked_thenAllElementsFromCollectionAreRemoved() { + Stack intStack = new Stack(); + List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + intStack.addAll(intList); + intStack.add(500); + intStack.removeAll(intList); + assertEquals(1, intStack.size()); + } + + @Test + public void givenElementsOnStack_whenRemoveIfIsInvoked_thenAllElementsSatysfyingConditionAreRemoved() { + Stack intStack = new Stack(); + List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + intStack.addAll(intList); + intStack.removeIf(element -> element < 6); + assertEquals(2, intStack.size()); + } + + @Test + public void whenAnotherStackCreatedWhileTraversingStack_thenStacksAreEqual() { + Stack intStack = new Stack<>(); + List intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + intStack.addAll(intList); + ListIterator it = intStack.listIterator(); + Stack result = new Stack(); + while(it.hasNext()) { + result.push(it.next()); + } + + assertThat(result, equalTo(intStack)); + } +} diff --git a/core-java/src/test/java/com/baeldung/string/StringTest.java b/core-java/src/test/java/com/baeldung/string/StringTest.java index fe1a69aa23..e88b2d7c2c 100644 --- a/core-java/src/test/java/com/baeldung/string/StringTest.java +++ b/core-java/src/test/java/com/baeldung/string/StringTest.java @@ -223,4 +223,4 @@ public class StringTest { assertEquals("200", String.valueOf(l)); } -} +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java new file mode 100644 index 0000000000..ad4f5dce7e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java @@ -0,0 +1,141 @@ +package com.baeldung.string.formatter; + +import java.util.Calendar; +import java.util.Formatter; +import java.util.GregorianCalendar; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class StringFormatterExampleTests { + + @Test + public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() { + //Syntax of Format Specifiers for Date/Time Representation + Calendar c = new GregorianCalendar(2017, 11, 10); + String s = String.format("The date is: %tm %1$te,%1$tY", c); + + + assertEquals("The date is: 12 10,2017", s); + } + + @Test + public void givenString_whenGeneralConversion_thenConvertedString() { + //General Conversions + String s = String.format("The correct answer is %s", false); + assertEquals("The correct answer is false", s); + + s = String.format("The correct answer is %b", null); + assertEquals("The correct answer is false", s); + + s = String.format("The correct answer is %B", true); + assertEquals("The correct answer is TRUE", s); + } + + @Test + public void givenString_whenCharConversion_thenConvertedString() { + //Character Conversions + String s = String.format("The correct answer is %c", 'a'); + assertEquals("The correct answer is a", s); + + s = String.format("The correct answer is %c", null); + assertEquals("The correct answer is null", s); + + s = String.format("The correct answer is %C", 'b'); + assertEquals("The correct answer is B", s); + + s = String.format("The valid unicode character: %c", 0x0400); + assertTrue(Character.isValidCodePoint(0x0400)); + assertEquals("The valid unicode character: Ѐ", s); + } + + @Test(expected = java.util.IllegalFormatCodePointException.class) + public void givenString_whenIllegalCodePointForConversion_thenError() { + String s = String.format("The valid unicode character: %c", 0x11FFFF); + assertFalse(Character.isValidCodePoint(0x11FFFF)); + assertEquals("The valid unicode character: Ā", s); + } + + @Test + public void givenString_whenNumericIntegralConversion_thenConvertedString() { + //Numeric Integral Conversions + String s = String.format("The number 25 in decimal = %d", 25); + assertEquals("The number 25 in decimal = 25", s); + + s = String.format("The number 25 in octal = %o", 25); + assertEquals("The number 25 in octal = 31", s); + + s = String.format("The number 25 in hexadecimal = %x", 25); + assertEquals("The number 25 in hexadecimal = 19", s); + } + + @Test + public void givenString_whenNumericFloatingConversion_thenConvertedString() { + //Numeric Floating-point Conversions + String s = String.format("The computerized scientific format of 10000.00 " + + "= %e", 10000.00); + assertEquals("The computerized scientific format of 10000.00 = 1.000000e+04", s); + + s = String.format("The decimal format of 10.019 = %f", 10.019); + assertEquals("The decimal format of 10.019 = 10.019000", s); + } + + @Test + public void givenString_whenLineSeparatorConversion_thenConvertedString() { + //Line Separator Conversion + String s = String.format("First Line %nSecond Line"); + assertEquals("First Line " + System.getProperty("line.separator") + + "Second Line", s); + } + + @Test + public void givenString_whenSpecifyFlag_thenGotFormattedString() { + //Without left-justified flag + String s = String.format("Without left justified flag: %5d", 25); + assertEquals("Without left justified flag: 25", s); + + //Using left-justified flag + s = String.format("With left justified flag: %-5d", 25); + assertEquals("With left justified flag: 25 ", s); + } + + @Test + public void givenString_whenSpecifyPrecision_thenGotExpected() { + + //Precision + String s = String.format("Output of 25.09878 with Precision 2: %.2f", 25.09878); + assertEquals("Output of 25.09878 with Precision 2: 25.10", s); + + s = String.format("Output of general conversion type with Precision 2: %.2b", true); + assertEquals("Output of general conversion type with Precision 2: tr", s); + } + + @Test + public void givenString_whenSpecifyArgumentIndex_thenGotExpected() { + Calendar c = new GregorianCalendar(2017, 11, 10); + //Argument_Index + String s = String.format("The date is: %tm %1$te,%1$tY", c); + assertEquals("The date is: 12 10,2017", s); + + s = String.format("The date is: %tm % - - - 4.0.0 - - drools-backward-chaining - 1.0 - drools-backward-chaining - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - 6.4.0.Final - - - - - org.kie - kie-api - ${runtime.version} - - - org.drools - drools-core - ${runtime.version} - - - org.drools - drools-decisiontables - ${runtime.version} - - - diff --git a/drools/backward-chaining/src/main/java/com/baeldung/BackwardChainingBeatles.java b/drools/backward-chaining/src/main/java/com/baeldung/BackwardChainingBeatles.java deleted file mode 100644 index 7fc5bd3685..0000000000 --- a/drools/backward-chaining/src/main/java/com/baeldung/BackwardChainingBeatles.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung; - -import org.kie.api.KieServices; -import org.kie.api.runtime.KieContainer; -import org.kie.api.runtime.KieSession; - -import com.baeldung.model.Beatle; - -public class BackwardChainingBeatles { - public static void main(String[] args) { - - KieServices ks = KieServices.Factory.get(); - KieContainer kContainer = ks.getKieClasspathContainer(); - KieSession kSession = kContainer.newKieSession("ksession-backward-chaining"); - // drools session base on the xml configuration (kmodule.xml) - - // graph population - kSession.insert(new Beatle("Starr", "drums")); - kSession.insert(new Beatle("McCartney", "bass")); - kSession.insert(new Beatle("Lennon", "guitar")); - kSession.insert(new Beatle("Harrison", "guitar")); - - kSession.insert("Ringo"); // invoke the rule that calls the query implentation of backward chaining - kSession.fireAllRules(); // invoke all the rules - - } - -} \ No newline at end of file diff --git a/drools/backward-chaining/src/main/java/com/baeldung/model/Beatle.java b/drools/backward-chaining/src/main/java/com/baeldung/model/Beatle.java deleted file mode 100644 index 4b219b3a69..0000000000 --- a/drools/backward-chaining/src/main/java/com/baeldung/model/Beatle.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.model; - -import org.kie.api.definition.type.Position; - -public class Beatle { - - @Position(0) - private String lastName; - @Position(1) - private String instrument; - - public Beatle(String lastName, String instrument) { - this.lastName = lastName; - this.instrument = instrument; - } - - public String getInstrument() { - return instrument; - } - - public void setInstrument(String instrument) { - this.instrument = instrument; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - -} \ No newline at end of file diff --git a/drools/backward-chaining/src/main/resources/META-INF/kmodule.xml b/drools/backward-chaining/src/main/resources/META-INF/kmodule.xml deleted file mode 100644 index 6498e26343..0000000000 --- a/drools/backward-chaining/src/main/resources/META-INF/kmodule.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/drools/backward-chaining/src/main/resources/META-INF/maven/pom.properties b/drools/backward-chaining/src/main/resources/META-INF/maven/pom.properties deleted file mode 100644 index 26d8331732..0000000000 --- a/drools/backward-chaining/src/main/resources/META-INF/maven/pom.properties +++ /dev/null @@ -1,3 +0,0 @@ -groupId=com.baeldung.drools -artifactId=DroosBackwardChaining -version=1.0.0-SNAPSHOT diff --git a/drools/backward-chaining/src/main/resources/backward_chaining/Beatles.drl b/drools/backward-chaining/src/main/resources/backward_chaining/Beatles.drl deleted file mode 100644 index 8d0d06a79e..0000000000 --- a/drools/backward-chaining/src/main/resources/backward_chaining/Beatles.drl +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung - -import com.baeldung.model.Beatle; - - -query whichBeatle(String lastName, String instrument) - Beatle(lastName, instrument;) - or - (Beatle(lastName, null;) - and - whichBeatle(null, instrument;)) //recursive call to the function that allows to search in a derivation tree structure -end - -rule "Ringo" - when - String(this == "Ringo") - whichBeatle("Starr", "drums";) - then - System.out.println("The beatle is Ringo Starr"); -end - -rule "Paul" - when - String(this == "Paul") - whichBeatle("McCartney", "bass";) - then - System.out.println("The beatle is Paul McCartney"); -end - -rule "John" - when - String(this == "John") - whichBeatle("Lennon", "guitar";) - then - System.out.println("The beatle is John Lennon"); -end - -rule "George" - when - String(this == "George") - whichBeatle("Harrison", "guitar";) - then - System.out.println("The beatle is George Harrison"); -end diff --git a/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java b/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java deleted file mode 100644 index 676e941950..0000000000 --- a/drools/backward-chaining/src/test/java/com/baeldung/test/BackwardChainingTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.test; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.kie.api.KieServices; -import org.kie.api.runtime.KieContainer; -import org.kie.api.runtime.KieSession; - -import com.baeldung.drools.model.Fact; -import com.baeldung.drools.model.Result; - -import static junit.framework.TestCase.assertEquals; - -@RunWith(value = JUnit4.class) -public class BackwardChainingTest { - private Result result; - private KieServices ks; - private KieContainer kContainer; - private KieSession ksession; - - @Before - public void before() { - result = new Result(); - ks = KieServices.Factory.get(); - kContainer = ks.getKieClasspathContainer(); - ksession = kContainer.newKieSession("ksession-backward-chaining"); - ksession.setGlobal("result", result); - } - - @Test - public void whenWallOfChinaIsGiven_ThenItBelongsToPlanetEarth() { - - ksession.setGlobal("result", result); - ksession.insert(new Fact("Asia", "Planet Earth")); - ksession.insert(new Fact("China", "Asia")); - ksession.insert(new Fact("Great Wall of China", "China")); - - ksession.fireAllRules(); - - // Assert Decision one - assertEquals(result.getValue(), "Decision one taken: Great Wall of China BELONGS TO Planet Earth"); - } - - @Test - public void whenChinaIsNotGiven_ThenWallOfChinaDoesNotBelongToPlanetEarth() { - ksession.insert(new Fact("Asia", "Planet Earth")); - // ksession.insert(new Location("China", "Asia")); // not provided to force Decision two - ksession.insert(new Fact("Great Wall of China", "China")); - - ksession.fireAllRules(); - - // Assert Decision two - assertEquals(result.getValue(), "Decision two taken: Great Wall of China DOES NOT BELONG TO Planet Earth"); - } -} diff --git a/drools/pom.xml b/drools/pom.xml index 29231f150c..5f228802fa 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -1,24 +1,19 @@ - 4.0.0 - com.baeldung drools - 1.0.0-SNAPSHOT - com.baeldung parent-modules 1.0.0-SNAPSHOT - - - 4.4.6 - 7.1.0.Beta2 - 3.13 - + + 4.4.6 + 7.4.1.Final + 3.13 + @@ -68,4 +63,25 @@ - \ No newline at end of file + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + + + + + + diff --git a/drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java b/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java similarity index 59% rename from drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java rename to drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java index 1c1d258b47..6f15ee510b 100644 --- a/drools/backward-chaining/src/main/java/com/baeldung/drools/BackwardChaining.java +++ b/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java @@ -1,9 +1,8 @@ -package com.baeldung.drools; +package com.baeldung.drools.backward_chaining; -import org.kie.api.KieServices; -import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; +import com.baeldung.drools.config.DroolsBeanFactory; import com.baeldung.drools.model.Fact; import com.baeldung.drools.model.Result; @@ -11,23 +10,21 @@ public class BackwardChaining { public static void main(String[] args) { Result result = new BackwardChaining().backwardChaining(); System.out.println(result.getValue()); - result.getFacts().stream().forEach(System.out::println); + result.getFacts() + .stream() + .forEach(System.out::println); } public Result backwardChaining() { Result result = new Result(); - KieServices ks = KieServices.Factory.get(); - KieContainer kContainer = ks.getKieClasspathContainer(); - KieSession ksession = kContainer.newKieSession("ksession-backward-chaining"); + KieSession ksession = new DroolsBeanFactory().getKieSession(); ksession.setGlobal("result", result); ksession.insert(new Fact("Asia", "Planet Earth")); -// ksession.insert(new Fact("China", "Asia")); + ksession.insert(new Fact("China", "Asia")); ksession.insert(new Fact("Great Wall of China", "China")); ksession.fireAllRules(); return result; - } - } \ No newline at end of file diff --git a/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java b/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java index e8841b05e2..cf5d56f246 100644 --- a/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java +++ b/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java @@ -3,7 +3,6 @@ package com.baeldung.drools.config; import org.drools.decisiontable.DecisionTableProviderImpl; import org.kie.api.KieServices; import org.kie.api.builder.*; -import org.kie.api.io.KieResources; import org.kie.api.io.Resource; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; @@ -22,7 +21,7 @@ public class DroolsBeanFactory { private KieFileSystem getKieFileSystem() throws IOException{ KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); - List rules=Arrays.asList("SuggestApplicant.drl","Product_rules.xls"); + List rules=Arrays.asList("BackwardChaining.drl","SuggestApplicant.drl","Product_rules.xls"); for(String rule:rules){ kieFileSystem.write(ResourceFactory.newClassPathResource(rule)); } @@ -56,9 +55,11 @@ public class DroolsBeanFactory { getKieRepository(); KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); + kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/BackwardChaining.drl")); kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/SuggestApplicant.drl")); kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Product_rules.xls")); - + + KieBuilder kb = kieServices.newKieBuilder(kieFileSystem); kb.buildAll(); KieModule kieModule = kb.getKieModule(); diff --git a/drools/backward-chaining/src/main/java/com/baeldung/drools/model/Fact.java b/drools/src/main/java/com/baeldung/drools/model/Fact.java similarity index 100% rename from drools/backward-chaining/src/main/java/com/baeldung/drools/model/Fact.java rename to drools/src/main/java/com/baeldung/drools/model/Fact.java diff --git a/drools/backward-chaining/src/main/java/com/baeldung/drools/model/Result.java b/drools/src/main/java/com/baeldung/drools/model/Result.java similarity index 100% rename from drools/backward-chaining/src/main/java/com/baeldung/drools/model/Result.java rename to drools/src/main/java/com/baeldung/drools/model/Result.java diff --git a/drools/backward-chaining/src/main/resources/backward_chaining/rules.drl b/drools/src/main/resources/com/baeldung/drools/rules/BackwardChaining.drl similarity index 67% rename from drools/backward-chaining/src/main/resources/backward_chaining/rules.drl rename to drools/src/main/resources/com/baeldung/drools/rules/BackwardChaining.drl index abcf95b9f1..975be84fb4 100644 --- a/drools/backward-chaining/src/main/resources/backward_chaining/rules.drl +++ b/drools/src/main/resources/com/baeldung/drools/rules/BackwardChaining.drl @@ -1,4 +1,4 @@ -package com.baeldung +package com.baeldung.drools.rules import com.baeldung.drools.model.Fact; @@ -19,13 +19,6 @@ then result.setValue("Decision one taken: Great Wall of China BELONGS TO Planet Earth"); end -rule "Great Wall of China DOES NOT BELONG TO of Planet Earth" -when - not belongsTo("Great Wall of China", "Planet Earth";) -then - result.setValue("Decision two taken: Great Wall of China DOES NOT BELONG TO Planet Earth"); -end - rule "print all facts" when belongsTo(element, place;) diff --git a/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java new file mode 100644 index 0000000000..f49d0b82de --- /dev/null +++ b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java @@ -0,0 +1,36 @@ +package com.baeldung.drools.backward_chaining; + +import org.junit.Before; +import org.junit.Test; +import org.kie.api.runtime.KieSession; + +import com.baeldung.drools.config.DroolsBeanFactory; +import com.baeldung.drools.model.Fact; +import com.baeldung.drools.model.Result; + +import static junit.framework.TestCase.assertEquals; + +public class BackwardChainingTest { + private Result result; + private KieSession ksession; + + @Before + public void before() { + result = new Result(); + ksession = new DroolsBeanFactory().getKieSession(); + } + + @Test + public void whenWallOfChinaIsGiven_ThenItBelongsToPlanetEarth() { + + ksession.setGlobal("result", result); + ksession.insert(new Fact("Asia", "Planet Earth")); + ksession.insert(new Fact("China", "Asia")); + ksession.insert(new Fact("Great Wall of China", "China")); + + ksession.fireAllRules(); + + // Assert Decision one + assertEquals(result.getValue(), "Decision one taken: Great Wall of China BELONGS TO Planet Earth"); + } +} diff --git a/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java b/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java index e86f52ff56..57376e9c4a 100644 --- a/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java +++ b/ejb/wildfly/widlfly-web/src/main/java/TestEJBServlet.java @@ -16,32 +16,26 @@ import wildfly.beans.UserBeanLocal; * Servlet implementation class TestEJBServlet */ public class TestEJBServlet extends HttpServlet { - private static final long serialVersionUID = 1L; - @EJB - private UserBeanLocal userBean; + @EJB + private UserBeanLocal userBean; - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - List users = userBean.getUsers(); + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + List users = userBean.getUsers(); - PrintWriter out = response.getWriter(); + PrintWriter out = response.getWriter(); - out.println(""); - out.println("Users"); - out.println(""); - out.println("

List of users:

"); - out.println(""); - for (User user : users) { - out.println(""); - out.print(""); - out.print(""); - out.println(""); - } - } + out.println(""); + out.println(""); + for (User user : users) { + out.print(user.getUsername()); + out.print(" " + user.getEmail() + "
"); + } + out.println(""); + out.println(""); + } - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - doGet(request, response); - } + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doGet(request, response); + } } diff --git a/gradle/.gitignore b/gradle/.gitignore new file mode 100644 index 0000000000..da88288c09 --- /dev/null +++ b/gradle/.gitignore @@ -0,0 +1 @@ +/.gradle/ diff --git a/gradle/.travis.yml b/gradle/.travis.yml new file mode 100644 index 0000000000..b2b534799b --- /dev/null +++ b/gradle/.travis.yml @@ -0,0 +1,27 @@ +# More details on how to configure the Travis build +# https://docs.travis-ci.com/user/customizing-the-build/ + +# Speed up build with travis caches +cache: + directories: + - $HOME/.gradle/caches/ + - $HOME/.gradle/wrapper/ + +language: java + +jdk: + - oraclejdk8 + +#Skipping install step to avoid having Travis run arbitrary './gradlew assemble' task +# https://docs.travis-ci.com/user/customizing-the-build/#Skipping-the-Installation-Step +install: + - true + +#Don't build tags +branches: + except: + - /^v\d/ + +#Build and perform release (if needed) +script: + - ./gradlew build -s && ./gradlew ciPerformRelease \ No newline at end of file diff --git a/gradle/build.gradle b/gradle/build.gradle index fc561987f7..dcc592a2b4 100644 --- a/gradle/build.gradle +++ b/gradle/build.gradle @@ -1,25 +1,35 @@ -apply plugin: 'java' -apply plugin: 'maven' - -repositories{ - mavenCentral() +allprojects { + repositories { + jcenter() + } } -dependencies{ - compile 'org.springframework:spring-context:4.3.5.RELEASE' -} -task hello { - println "this Baeldung's tutorial is ${awesomeness}" +subprojects { + + version = '1.0' } -uploadArchives { - repositories { - mavenDeployer { - repository(url: 'http://yourmavenrepo/repository') { - authentication(userName: 'user', password: 'password'); - } - - } - } +apply plugin: 'eclipse' + +println 'This will be executed during the configuration phase.' + +task configured { + println 'This will also be executed during the configuration phase.' +} + +task execFirstTest { + doLast { + println 'This will be executed during the execution phase.' + } +} + +task execSecondTest { + doFirst { + println 'This will be executed first during the execution phase.' + } + doLast { + println 'This will be executed last during the execution phase.' + } + println 'This will be executed during the configuration phase as well.' } diff --git a/gradle/gradle.properties b/gradle/gradle.properties deleted file mode 100644 index 41701e5a19..0000000000 --- a/gradle/gradle.properties +++ /dev/null @@ -1,3 +0,0 @@ -awesomeness=awesome -group=com.baeldung.tutorial -version=1.0.1 diff --git a/gradle/gradle/shipkit.gradle b/gradle/gradle/shipkit.gradle new file mode 100644 index 0000000000..144c01dc05 --- /dev/null +++ b/gradle/gradle/shipkit.gradle @@ -0,0 +1,41 @@ +//This default Shipkit configuration file was created automatically and is intended to be checked-in. +//Default configuration is sufficient for local testing and trying out Shipkit. +//To leverage Shipkit fully, please fix the TODO items, refer to our Getting Started Guide for help: +// +// https://github.com/mockito/shipkit/blob/master/docs/getting-started.md +// +shipkit { + //TODO is the repository correct? + gitHub.repository = "unspecified-user/unspecified-repo" + + //TODO generate and use your own read-only GitHub personal access token + gitHub.readOnlyAuthToken = "76826c9ec886612f504d12fd4268b16721c4f85d" + + //TODO generate GitHub write token, and ensure your Travis CI has this env variable exported + gitHub.writeAuthToken = System.getenv("GH_WRITE_TOKEN") +} + +allprojects { + plugins.withId("com.jfrog.bintray") { + + //Bintray configuration is handled by JFrog Bintray Gradle Plugin + //For reference see the official documentation: https://github.com/bintray/gradle-bintray-plugin + bintray { + + //TODO sign up for free open source account with https://bintray.com, then look up your API key on your profile page in Bintray + key = '7ea297848ca948adb7d3ee92a83292112d7ae989' + //TODO don't check in the key, remove above line and use env variable exported on CI: + //key = System.getenv("BINTRAY_API_KEY") + + pkg { + //TODO configure Bintray settings per your project (https://github.com/bintray/gradle-bintray-plugin) + repo = 'bootstrap' + user = 'shipkit-bootstrap-bot' + userOrg = 'shipkit-bootstrap' + name = 'maven' + licenses = ['MIT'] + labels = ['continuous delivery', 'release automation', 'shipkit'] + } + } + } +} diff --git a/gradle/gradle/wrapper/gradle-wrapper.jar b/gradle/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 3391a4cdf6..0000000000 Binary files a/gradle/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/gradle/wrapper/gradle-wrapper.properties b/gradle/gradle/wrapper/gradle-wrapper.properties index b601d97764..ebf7ae9184 100644 --- a/gradle/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Sat Dec 31 15:46:08 BRT 2016 +#Thu Oct 12 16:43:02 BDT 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.2.1-bin.zip diff --git a/gradle/gradletaskdemo/aplugin.gradle b/gradle/gradletaskdemo/aplugin.gradle new file mode 100644 index 0000000000..ca96c50b54 --- /dev/null +++ b/gradle/gradletaskdemo/aplugin.gradle @@ -0,0 +1,5 @@ +task fromPlugin { + doLast { + println "I'm from plugin" + } +} \ No newline at end of file diff --git a/gradle/gradletaskdemo/build.gradle b/gradle/gradletaskdemo/build.gradle new file mode 100644 index 0000000000..58dadd7460 --- /dev/null +++ b/gradle/gradletaskdemo/build.gradle @@ -0,0 +1,110 @@ +buildscript { + repositories { + maven { + url "https://plugins.gradle.org/m2/" + } + } + dependencies { + classpath "org.shipkit:shipkit:0.9.117" + } +} + + +plugins { + id 'java' +} + + +apply from: 'aplugin.gradle' +apply plugin: 'org.shipkit.bintray-release' + + +//hello task +task hello { + doLast { + println 'Baeldung' + } +} + +//Groovy in gradle task +task toLower { + doLast { + String someString = 'HELLO FROM BAELDUNG' + println "Original: " + someString + println "Lower case: " + someString.toLowerCase() + } +} + + +// Task dependencies +task helloGradle { + doLast { + println 'Hello Gradle!' + } +} + +task fromBaeldung(dependsOn: helloGradle) { + doLast { + println "I'm from Baeldung" + } +} + + +//Adding behavior to a task via api +task helloBaeldung { + doLast { + println 'I will be executed second' + } +} + +helloBaeldung.doFirst { + println 'I will be executed first' +} + +helloBaeldung.doLast { + println 'I will be executed third' +} + +helloBaeldung { + doLast { + println 'I will be executed fourth' + } +} + + + + +//Adding extra task properties +task ourTask { + ext.theProperty = "theValue" +} + +task printTaskProperty { + doLast { + println ourTask.theProperty + } +} + + + +//Declaring dependencies +dependencies { + compile group: + 'org.springframework', name: 'spring-core', version: '4.3.5.RELEASE' + compile 'org.springframework:spring-core:4.3.5.RELEASE', + 'org.springframework:spring-aop:4.3.5.RELEASE' + compile( + [group: 'org.springframework', name: 'spring-core', version: '4.3.5.RELEASE'], + [group: 'org.springframework', name: 'spring-aop', version: '4.3.5.RELEASE'] + ) + testCompile('org.hibernate:hibernate-core:5.2.12.Final') { + transitive = true + } + runtime(group: 'org.hibernate', name: 'hibernate-core', version: '5.2.12.Final') { + transitive = false + } + runtime "org.codehaus.groovy:groovy-all:2.4.11@jar" + runtime group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.4.11', ext: 'jar' + + compile fileTree(dir: 'libs', include: '*.jar') +} diff --git a/gradle/gradletaskdemo/build/tmp/jar/MANIFEST.MF b/gradle/gradletaskdemo/build/tmp/jar/MANIFEST.MF new file mode 100644 index 0000000000..59499bce4a --- /dev/null +++ b/gradle/gradletaskdemo/build/tmp/jar/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 + diff --git a/gradle/gradlew b/gradle/gradlew index 9d82f78915..27309d9231 100644 --- a/gradle/gradlew +++ b/gradle/gradlew @@ -6,12 +6,30 @@ ## ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" @@ -30,6 +48,7 @@ die ( ) { cygwin=false msys=false darwin=false +nonstop=false case "`uname`" in CYGWIN* ) cygwin=true @@ -40,26 +59,11 @@ case "`uname`" in MINGW* ) msys=true ;; + NONSTOP* ) + nonstop=true + ;; esac -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -85,7 +89,7 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then diff --git a/gradle/gradlew.bat b/gradle/gradlew.bat index 8a0b282aa6..832fdb6079 100644 --- a/gradle/gradlew.bat +++ b/gradle/gradlew.bat @@ -8,14 +8,14 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome @@ -46,7 +46,7 @@ echo location of your Java installation. goto fail :init -@rem Get command-line arguments, handling Windowz variants +@rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args diff --git a/gradle/greeter/.gitignore b/gradle/greeter/.gitignore new file mode 100644 index 0000000000..e93e09f86e --- /dev/null +++ b/gradle/greeter/.gitignore @@ -0,0 +1,3 @@ +/.gradle +/build +/bin diff --git a/gradle/greeter/build.gradle b/gradle/greeter/build.gradle new file mode 100644 index 0000000000..6f43f23494 --- /dev/null +++ b/gradle/greeter/build.gradle @@ -0,0 +1,18 @@ +apply plugin : 'java' +apply plugin : 'application' + + + +dependencies { + compile project(':greeting-library') + compile project(':greeting-library-java') +} + +mainClassName = 'greeter.Greeter' +run { + if (project.hasProperty("appArgs")) { + args Eval.me(appArgs) + } + else + args = ["Baeldung"]; +} diff --git a/gradle/greeter/src/main/java/greeter/Greeter.java b/gradle/greeter/src/main/java/greeter/Greeter.java new file mode 100644 index 0000000000..7b59f0c4bc --- /dev/null +++ b/gradle/greeter/src/main/java/greeter/Greeter.java @@ -0,0 +1,13 @@ +package greeter; + +import baeldunggreeter.Formatter; + +public class Greeter { + public static void main(String[] args) { + final String output = GreetingFormatter + .greeting(args[0]); + String date = Formatter.getFormattedDate(); + System.out.println(output); + System.out.println("Today is :" + date); + } +} diff --git a/gradle/greeter/src/test/java/greetertest/TestGreeting.java b/gradle/greeter/src/test/java/greetertest/TestGreeting.java new file mode 100644 index 0000000000..0ae5fab631 --- /dev/null +++ b/gradle/greeter/src/test/java/greetertest/TestGreeting.java @@ -0,0 +1,11 @@ + + + + +public class TestGreeting{ + + + + + +} \ No newline at end of file diff --git a/gradle/greeting-library-java/.gitignore b/gradle/greeting-library-java/.gitignore new file mode 100644 index 0000000000..348c102afc --- /dev/null +++ b/gradle/greeting-library-java/.gitignore @@ -0,0 +1,2 @@ +/build +/bin diff --git a/gradle/greeting-library-java/build.gradle b/gradle/greeting-library-java/build.gradle new file mode 100644 index 0000000000..34931bd0cd --- /dev/null +++ b/gradle/greeting-library-java/build.gradle @@ -0,0 +1,9 @@ +apply plugin :'java' +//apply plugin : 'application' + + + +dependencies{ + compile group: 'joda-time', name: 'joda-time', version: '2.9.9' + testCompile group: 'junit', name: 'junit', version: '4.12' +} diff --git a/gradle/greeting-library-java/src/main/java/baeldunggreeter/Formatter.java b/gradle/greeting-library-java/src/main/java/baeldunggreeter/Formatter.java new file mode 100644 index 0000000000..367e992c1b --- /dev/null +++ b/gradle/greeting-library-java/src/main/java/baeldunggreeter/Formatter.java @@ -0,0 +1,14 @@ +package baeldunggreeter; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +public class Formatter { + public static String getFormattedDate() { + DateFormat dateFormat = new SimpleDateFormat( + "yyyy-MM-dd HH:mm:ss"); + Date date = new Date(); + return dateFormat.format(date); + } +} diff --git a/gradle/greeting-library-java/src/test/java/baeldunggreetertest/FormatterTest.java b/gradle/greeting-library-java/src/test/java/baeldunggreetertest/FormatterTest.java new file mode 100644 index 0000000000..49efc934a5 --- /dev/null +++ b/gradle/greeting-library-java/src/test/java/baeldunggreetertest/FormatterTest.java @@ -0,0 +1,23 @@ +package baeldunggreetertest; + +import static org.junit.Assert.assertTrue; + +import java.util.Date; +import java.util.regex.Pattern; + +import org.junit.Test; + +import baeldunggreeter.Formatter; + +public class FormatterTest { + + @Test + public void testFormatter() { + + String dateRegex1 = "^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) ([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])$"; + String dateString = Formatter.getFormattedDate(); + assertTrue(Pattern + .matches(dateRegex1, dateString)); + + } +} \ No newline at end of file diff --git a/gradle/greeting-library/.gitignore b/gradle/greeting-library/.gitignore new file mode 100644 index 0000000000..84c048a73c --- /dev/null +++ b/gradle/greeting-library/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/gradle/greeting-library/bin/greeter/GreetingFormatter.groovy b/gradle/greeting-library/bin/greeter/GreetingFormatter.groovy new file mode 100644 index 0000000000..94c863e294 --- /dev/null +++ b/gradle/greeting-library/bin/greeter/GreetingFormatter.groovy @@ -0,0 +1,10 @@ +package greeter + +import groovy.transform.CompileStatic + +@CompileStatic +class GreetingFormatter{ + static String greeting(final String name) { + "Hello, ${name.capitalize()}" + } +} diff --git a/gradle/greeting-library/bin/greeter/GreetingFormatterSpec.groovy b/gradle/greeting-library/bin/greeter/GreetingFormatterSpec.groovy new file mode 100644 index 0000000000..f1c1211552 --- /dev/null +++ b/gradle/greeting-library/bin/greeter/GreetingFormatterSpec.groovy @@ -0,0 +1,13 @@ +package greeter + +import spock.lang.Specification + +class GreetingFormatterSpec extends Specification { + + def 'Creating a greeting'() { + + expect: 'The greeeting to be correctly capitalized' + GreetingFormatter.greeting('gradlephant') == 'Hello, Gradlephant' + + } +} diff --git a/gradle/greeting-library/build.gradle b/gradle/greeting-library/build.gradle new file mode 100644 index 0000000000..eb526b3b03 --- /dev/null +++ b/gradle/greeting-library/build.gradle @@ -0,0 +1,9 @@ +apply plugin : 'groovy' + +dependencies { + compile 'org.codehaus.groovy:groovy:2.4.12' + + testCompile 'org.spockframework:spock-core:1.0-groovy-2.4', { + exclude module : 'groovy-all' + } +} diff --git a/gradle/greeting-library/src/main/groovy/greeter/GreetingFormatter.groovy b/gradle/greeting-library/src/main/groovy/greeter/GreetingFormatter.groovy new file mode 100644 index 0000000000..db8a035b67 --- /dev/null +++ b/gradle/greeting-library/src/main/groovy/greeter/GreetingFormatter.groovy @@ -0,0 +1,10 @@ +package greeter + +import groovy.transform.CompileStatic + +@CompileStatic +class GreetingFormatter{ + static String greeting(final String name) { + "Hello, ${name.capitalize()}" + } +} \ No newline at end of file diff --git a/gradle/greeting-library/src/test/groovy/greeter/GreetingFormatterSpec.groovy b/gradle/greeting-library/src/test/groovy/greeter/GreetingFormatterSpec.groovy new file mode 100644 index 0000000000..f1c1211552 --- /dev/null +++ b/gradle/greeting-library/src/test/groovy/greeter/GreetingFormatterSpec.groovy @@ -0,0 +1,13 @@ +package greeter + +import spock.lang.Specification + +class GreetingFormatterSpec extends Specification { + + def 'Creating a greeting'() { + + expect: 'The greeeting to be correctly capitalized' + GreetingFormatter.greeting('gradlephant') == 'Hello, Gradlephant' + + } +} diff --git a/gradle/settings.gradle b/gradle/settings.gradle new file mode 100644 index 0000000000..38704681bd --- /dev/null +++ b/gradle/settings.gradle @@ -0,0 +1,10 @@ +rootProject.name = 'gradletutorial' + + +include 'greeting-library' +include 'greeting-library-java' +include 'greeter' +include 'gradletaskdemo' + + +println 'This will be executed during the initialization phase.' diff --git a/gradle/src/main/java/Main.java b/gradle/src/main/java/Main.java deleted file mode 100644 index 10edd1840b..0000000000 --- a/gradle/src/main/java/Main.java +++ /dev/null @@ -1,5 +0,0 @@ -public class Main{ - public static void main(String[] args){ - System.out.println("Baeldung Rocks"); - } -} diff --git a/gradle/version.properties b/gradle/version.properties new file mode 100644 index 0000000000..565e9213ae --- /dev/null +++ b/gradle/version.properties @@ -0,0 +1,3 @@ +#Version of the produced binaries. This file is intended to be checked-in. +#It will be automatically bumped by release automation. +version=0.0.1 diff --git a/guava-modules/README.md b/guava-modules/README.md new file mode 100644 index 0000000000..79e45a89e7 --- /dev/null +++ b/guava-modules/README.md @@ -0,0 +1,3 @@ + +## Guava Modules + diff --git a/guava18/README.md b/guava-modules/guava-18/README.md similarity index 100% rename from guava18/README.md rename to guava-modules/guava-18/README.md diff --git a/guava18/pom.xml b/guava-modules/guava-18/pom.xml similarity index 90% rename from guava18/pom.xml rename to guava-modules/guava-18/pom.xml index 0b96918171..a9aba47f12 100644 --- a/guava18/pom.xml +++ b/guava-modules/guava-18/pom.xml @@ -4,13 +4,14 @@ 4.0.0com.baeldung - guava18 + guava-180.1.0-SNAPSHOT com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/guava18/src/main/java/com/baeldung/guava/entity/Administrator.java b/guava-modules/guava-18/src/main/java/com/baeldung/guava/entity/Administrator.java similarity index 100% rename from guava18/src/main/java/com/baeldung/guava/entity/Administrator.java rename to guava-modules/guava-18/src/main/java/com/baeldung/guava/entity/Administrator.java diff --git a/guava18/src/main/java/com/baeldung/guava/entity/Player.java b/guava-modules/guava-18/src/main/java/com/baeldung/guava/entity/Player.java similarity index 100% rename from guava18/src/main/java/com/baeldung/guava/entity/Player.java rename to guava-modules/guava-18/src/main/java/com/baeldung/guava/entity/Player.java diff --git a/guava18/src/main/java/com/baeldung/guava/entity/User.java b/guava-modules/guava-18/src/main/java/com/baeldung/guava/entity/User.java similarity index 100% rename from guava18/src/main/java/com/baeldung/guava/entity/User.java rename to guava-modules/guava-18/src/main/java/com/baeldung/guava/entity/User.java diff --git a/guava18/src/test/java/com/baeldung/guava/FluentIterableUnitTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/FluentIterableUnitTest.java similarity index 100% rename from guava18/src/test/java/com/baeldung/guava/FluentIterableUnitTest.java rename to guava-modules/guava-18/src/test/java/com/baeldung/guava/FluentIterableUnitTest.java diff --git a/guava18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java similarity index 100% rename from guava18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java rename to guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java diff --git a/guava18/src/test/java/com/baeldung/guava/MoreExecutorsUnitTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/MoreExecutorsUnitTest.java similarity index 100% rename from guava18/src/test/java/com/baeldung/guava/MoreExecutorsUnitTest.java rename to guava-modules/guava-18/src/test/java/com/baeldung/guava/MoreExecutorsUnitTest.java diff --git a/guava18/src/test/java/com/baeldung/guava/MoreObjectsUnitTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/MoreObjectsUnitTest.java similarity index 100% rename from guava18/src/test/java/com/baeldung/guava/MoreObjectsUnitTest.java rename to guava-modules/guava-18/src/test/java/com/baeldung/guava/MoreObjectsUnitTest.java diff --git a/guava19/README.md b/guava-modules/guava-19/README.md similarity index 100% rename from guava19/README.md rename to guava-modules/guava-19/README.md diff --git a/guava19/pom.xml b/guava-modules/guava-19/pom.xml similarity index 91% rename from guava19/pom.xml rename to guava-modules/guava-19/pom.xml index af9bc51eb9..2345212eba 100644 --- a/guava19/pom.xml +++ b/guava-modules/guava-19/pom.xml @@ -4,13 +4,14 @@ 4.0.0 com.baeldung - guava19 + guava-19 0.1.0-SNAPSHOT com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/guava19/src/main/java/com/baeldung/guava/entity/User.java b/guava-modules/guava-19/src/main/java/com/baeldung/guava/entity/User.java similarity index 100% rename from guava19/src/main/java/com/baeldung/guava/entity/User.java rename to guava-modules/guava-19/src/main/java/com/baeldung/guava/entity/User.java diff --git a/guava19/src/test/java/com/baeldung/guava/CharMatcherUnitTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/CharMatcherUnitTest.java similarity index 100% rename from guava19/src/test/java/com/baeldung/guava/CharMatcherUnitTest.java rename to guava-modules/guava-19/src/test/java/com/baeldung/guava/CharMatcherUnitTest.java diff --git a/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java similarity index 100% rename from guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java rename to guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java diff --git a/guava19/src/test/java/com/baeldung/guava/HashingUnitTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/HashingUnitTest.java similarity index 100% rename from guava19/src/test/java/com/baeldung/guava/HashingUnitTest.java rename to guava-modules/guava-19/src/test/java/com/baeldung/guava/HashingUnitTest.java diff --git a/guava19/src/test/java/com/baeldung/guava/TypeTokenUnitTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/TypeTokenUnitTest.java similarity index 100% rename from guava19/src/test/java/com/baeldung/guava/TypeTokenUnitTest.java rename to guava-modules/guava-19/src/test/java/com/baeldung/guava/TypeTokenUnitTest.java diff --git a/guava21/README.md b/guava-modules/guava-21/README.md similarity index 100% rename from guava21/README.md rename to guava-modules/guava-21/README.md diff --git a/guava21/pom.xml b/guava-modules/guava-21/pom.xml similarity index 91% rename from guava21/pom.xml rename to guava-modules/guava-21/pom.xml index 930def2a67..94bb66e76a 100644 --- a/guava21/pom.xml +++ b/guava-modules/guava-21/pom.xml @@ -4,13 +4,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - guava21 + guava-21 1.0-SNAPSHOT com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/AtomicLongMapTutorials.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/AtomicLongMapTutorials.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/AtomicLongMapTutorials.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/AtomicLongMapTutorials.java diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/ComparatorsExamples.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/ComparatorsExamples.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/ComparatorsExamples.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/ComparatorsExamples.java diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/ConcatStreams.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/ConcatStreams.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/ConcatStreams.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/ConcatStreams.java diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/InternerBuilderExample.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/InternerBuilderExample.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/InternerBuilderExample.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/InternerBuilderExample.java diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/MonitorExample.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/MonitorExample.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/MonitorExample.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/MonitorExample.java diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/MoreCollectorsExample.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/MoreCollectorsExample.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/MoreCollectorsExample.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/MoreCollectorsExample.java diff --git a/guava21/src/main/java/com/baeldung/guava/tutorial/StreamsUtility.java b/guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/StreamsUtility.java similarity index 100% rename from guava21/src/main/java/com/baeldung/guava/tutorial/StreamsUtility.java rename to guava-modules/guava-21/src/main/java/com/baeldung/guava/tutorial/StreamsUtility.java diff --git a/guava21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java b/guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java similarity index 100% rename from guava21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java rename to guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/AtomicLongMapIntegrationTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/AtomicLongMapIntegrationTest.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/AtomicLongMapIntegrationTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/AtomicLongMapIntegrationTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/ComparatorsUnitTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/ComparatorsUnitTest.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/ComparatorsUnitTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/ComparatorsUnitTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/GuavaStreamsUnitTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/GuavaStreamsUnitTest.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/GuavaStreamsUnitTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/GuavaStreamsUnitTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/InternBuilderUnitTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/InternBuilderUnitTest.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/InternBuilderUnitTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/InternBuilderUnitTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/MonitorUnitTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/MonitorUnitTest.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/MonitorUnitTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/MonitorUnitTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/MoreCollectorsUnitTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/MoreCollectorsUnitTest.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/MoreCollectorsUnitTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/MoreCollectorsUnitTest.java diff --git a/guava21/src/test/java/com/baeldung/guava/tutorial/StreamUtility.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/StreamUtility.java similarity index 100% rename from guava21/src/test/java/com/baeldung/guava/tutorial/StreamUtility.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/tutorial/StreamUtility.java diff --git a/guest/spring-security/README.md b/guest/spring-security/README.md new file mode 100644 index 0000000000..9e5cd64a04 --- /dev/null +++ b/guest/spring-security/README.md @@ -0,0 +1,17 @@ +## Building + +To build the module, use Maven's `package` goal: + +``` +mvn clean package +``` + +## Running + +To run the application, use Spring Boot's `run` goal: + +``` +mvn spring-boot:run +``` + +The application will be accessible at [http://localhost:8080/](http://localhost:8080/) diff --git a/guest/spring-security/pom.xml b/guest/spring-security/pom.xml new file mode 100644 index 0000000000..c41637bfc2 --- /dev/null +++ b/guest/spring-security/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + + com.stackify.guest + spring-security + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.M6 + + + + spring-security + Spring Security Sample Project + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.thymeleaf + thymeleaf-spring5 + 3.0.8.RELEASE + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-jdbc + + + com.h2database + h2 + runtime + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + UTF-8 + UTF-8 + 1.8 + + + \ No newline at end of file diff --git a/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/Application.java b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/Application.java new file mode 100644 index 0000000000..fbd0eee044 --- /dev/null +++ b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/Application.java @@ -0,0 +1,15 @@ +package com.stackify.guest.springsecurity; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = {"com.stackify.guest.springsecurity"}) +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebMvcConfiguration.java b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebMvcConfiguration.java new file mode 100644 index 0000000000..b8dfe9050d --- /dev/null +++ b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebMvcConfiguration.java @@ -0,0 +1,16 @@ +package com.stackify.guest.springsecurity.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebMvcConfiguration implements WebMvcConfigurer { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/customLogin").setViewName("customLogin"); + registry.addViewController("/loginSuccess").setViewName("index"); + } + +} \ No newline at end of file diff --git a/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebSecurityConfig.java b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebSecurityConfig.java new file mode 100644 index 0000000000..164808d5b3 --- /dev/null +++ b/guest/spring-security/src/main/java/com/stackify/guest/springsecurity/config/WebSecurityConfig.java @@ -0,0 +1,40 @@ +package com.stackify.guest.springsecurity.config; + +import org.springframework.context.annotation.Bean; +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.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.JdbcUserDetailsManager; + +import javax.sql.DataSource; + +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Bean + public UserDetailsService jdbcUserDetailsService(DataSource dataSource) { + JdbcUserDetailsManager manager = new JdbcUserDetailsManager(); + manager.setDataSource(dataSource); + return manager; + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/css/**").permitAll() + .anyRequest().authenticated() + .and().formLogin() + .loginPage("/customLogin") + .defaultSuccessUrl("/loginSuccess", true) + .permitAll(); + } + +} \ No newline at end of file diff --git a/guest/spring-security/src/main/resources/data.sql b/guest/spring-security/src/main/resources/data.sql new file mode 100644 index 0000000000..b3f7db9105 --- /dev/null +++ b/guest/spring-security/src/main/resources/data.sql @@ -0,0 +1,2 @@ +INSERT INTO users VALUES ('jill', '$2a$04$qUlqAEEYF1YvrpJMosodoewgL6aO.qgHytl2k5L7kdXEWnJsFdxvq', TRUE); +INSERT INTO authorities VALUES ('jill', 'USERS'); diff --git a/guest/spring-security/src/main/resources/schema.sql b/guest/spring-security/src/main/resources/schema.sql new file mode 100644 index 0000000000..3de1b9a29f --- /dev/null +++ b/guest/spring-security/src/main/resources/schema.sql @@ -0,0 +1,10 @@ +CREATE TABLE users ( + username VARCHAR(256) PRIMARY KEY, + password VARCHAR(256), + enabled BOOLEAN +); + +CREATE TABLE authorities ( + username VARCHAR(256) REFERENCES users (username), + authority VARCHAR(256) +); diff --git a/guest/spring-security/src/main/resources/static/css/styles.css b/guest/spring-security/src/main/resources/static/css/styles.css new file mode 100644 index 0000000000..72bcc4934f --- /dev/null +++ b/guest/spring-security/src/main/resources/static/css/styles.css @@ -0,0 +1,3 @@ +.bad-login { + color: red; +} \ No newline at end of file diff --git a/guest/spring-security/src/main/resources/templates/customLogin.html b/guest/spring-security/src/main/resources/templates/customLogin.html new file mode 100644 index 0000000000..c689c78514 --- /dev/null +++ b/guest/spring-security/src/main/resources/templates/customLogin.html @@ -0,0 +1,21 @@ + + + + + + +
+
+ + + + +
+ + + +
Log out successful.
+ + + \ No newline at end of file diff --git a/guest/spring-security/src/main/resources/templates/index.html b/guest/spring-security/src/main/resources/templates/index.html new file mode 100644 index 0000000000..0769f9015f --- /dev/null +++ b/guest/spring-security/src/main/resources/templates/index.html @@ -0,0 +1,11 @@ + + +

Hello, !

+
+ + + + \ No newline at end of file diff --git a/hibernate5/README.md b/hibernate5/README.md index 9ef170a134..4690ebbe76 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping) +- [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers) diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 0282673218..c3bf8c2aa9 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -2,8 +2,27 @@ package com.baeldung.hibernate; import com.baeldung.hibernate.pojo.Employee; import com.baeldung.hibernate.pojo.EntityDescription; +import com.baeldung.hibernate.pojo.OrderEntry; +import com.baeldung.hibernate.pojo.OrderEntryIdClass; +import com.baeldung.hibernate.pojo.OrderEntryPK; +import com.baeldung.hibernate.pojo.Product; import com.baeldung.hibernate.pojo.Phone; import com.baeldung.hibernate.pojo.TemporalValues; +import com.baeldung.hibernate.pojo.Course; +import com.baeldung.hibernate.pojo.Student; +import com.baeldung.hibernate.pojo.User; +import com.baeldung.hibernate.pojo.UserProfile; +import com.baeldung.hibernate.pojo.inheritance.Animal; +import com.baeldung.hibernate.pojo.inheritance.Bag; +import com.baeldung.hibernate.pojo.inheritance.Book; +import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.MyEmployee; +import com.baeldung.hibernate.pojo.inheritance.MyProduct; +import com.baeldung.hibernate.pojo.inheritance.Pen; +import com.baeldung.hibernate.pojo.inheritance.Person; +import com.baeldung.hibernate.pojo.inheritance.Pet; +import com.baeldung.hibernate.pojo.inheritance.Vehicle; + import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; @@ -33,6 +52,24 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(Phone.class); metadataSources.addAnnotatedClass(EntityDescription.class); metadataSources.addAnnotatedClass(TemporalValues.class); + metadataSources.addAnnotatedClass(User.class); + metadataSources.addAnnotatedClass(Student.class); + metadataSources.addAnnotatedClass(Course.class); + metadataSources.addAnnotatedClass(Product.class); + metadataSources.addAnnotatedClass(OrderEntryPK.class); + metadataSources.addAnnotatedClass(OrderEntry.class); + metadataSources.addAnnotatedClass(OrderEntryIdClass.class); + metadataSources.addAnnotatedClass(UserProfile.class); + metadataSources.addAnnotatedClass(Book.class); + metadataSources.addAnnotatedClass(MyEmployee.class); + metadataSources.addAnnotatedClass(MyProduct.class); + metadataSources.addAnnotatedClass(Pen.class); + metadataSources.addAnnotatedClass(Person.class); + metadataSources.addAnnotatedClass(Animal.class); + metadataSources.addAnnotatedClass(Pet.class); + metadataSources.addAnnotatedClass(Vehicle.class); + metadataSources.addAnnotatedClass(Car.class); + metadataSources.addAnnotatedClass(Bag.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder() diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java new file mode 100644 index 0000000000..97760acd3b --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo; + +import java.util.UUID; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Course { + + @Id + @GeneratedValue + private UUID courseId; + + public UUID getCourseId() { + return courseId; + } + + public void setCourseId(UUID courseId) { + this.courseId = courseId; + } + + + + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java new file mode 100644 index 0000000000..6dd106b88e --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.TableGenerator; + +@Entity +public class Department { + @Id + @GeneratedValue(strategy = GenerationType.TABLE, generator="table-generator") + @TableGenerator (name="table-generator", table="dep_ids", pkColumnName="seq_id", valueColumnName="seq_value") + private long depId; + + public long getDepId() { + return depId; + } + + public void setDepId(long depId) { + this.depId = depId; + } + + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java new file mode 100644 index 0000000000..a28b7c8dbe --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java @@ -0,0 +1,20 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; + +@Entity +public class OrderEntry { + + @EmbeddedId + private OrderEntryPK entryId; + + public OrderEntryPK getEntryId() { + return entryId; + } + + public void setEntryId(OrderEntryPK entryId) { + this.entryId = entryId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java new file mode 100644 index 0000000000..18926640af --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.IdClass; + +@Entity +@IdClass(OrderEntryPK.class) +public class OrderEntryIdClass { + @Id + private long orderId; + @Id + private long productId; + + public long getOrderId() { + return orderId; + } + + public void setOrderId(long orderId) { + this.orderId = orderId; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java new file mode 100644 index 0000000000..637d590629 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java @@ -0,0 +1,46 @@ +package com.baeldung.hibernate.pojo; + +import java.io.Serializable; +import java.util.Objects; + +import javax.persistence.Embeddable; + +@Embeddable +public class OrderEntryPK implements Serializable { + + private long orderId; + private long productId; + + public long getOrderId() { + return orderId; + } + + public void setOrderId(long orderId) { + this.orderId = orderId; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OrderEntryPK pk = (OrderEntryPK) o; + return Objects.equals(orderId, pk.orderId) && Objects.equals(productId, pk.productId); + } + + @Override + public int hashCode() { + return Objects.hash(orderId, productId); + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java new file mode 100644 index 0000000000..efd6b63dc0 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java @@ -0,0 +1,26 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Parameter; + +@Entity +public class Product { + + @Id + @GeneratedValue(generator = "prod-generator") + @GenericGenerator(name = "prod-generator", parameters = @Parameter(name = "prefix", value = "prod"), strategy = "com.baeldung.hibernate.pojo.generator.MyGenerator") + private String prodId; + + public String getProdId() { + return prodId; + } + + public void setProdId(String prodId) { + this.prodId = prodId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java new file mode 100644 index 0000000000..a6dec4a30d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java @@ -0,0 +1,23 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue (strategy = GenerationType.SEQUENCE) + private long studentId; + + public long getStudentId() { + return studentId; + } + + public void setStudent_id(long studentId) { + this.studentId = studentId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java new file mode 100644 index 0000000000..90203d29ec --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java @@ -0,0 +1,24 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; + +@Entity +public class User { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence-generator") + @SequenceGenerator(name = "sequence-generator", sequenceName = "user_sequence", initialValue = 4) + private long userId; + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java new file mode 100644 index 0000000000..ac870c2818 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.pojo; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.MapsId; +import javax.persistence.OneToOne; + +@Entity +public class UserProfile { + + @Id + private long profileId; + + @OneToOne + @MapsId + private User user; + + public long getProfileId() { + return profileId; + } + + public void setProfileId(long profileId) { + this.profileId = profileId; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java new file mode 100644 index 0000000000..17ffe9b7e1 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java @@ -0,0 +1,41 @@ +package com.baeldung.hibernate.pojo.generator; + +import java.io.Serializable; +import java.util.Properties; +import java.util.stream.Stream; + +import org.hibernate.HibernateException; +import org.hibernate.MappingException; +import org.hibernate.engine.spi.SharedSessionContractImplementor; +import org.hibernate.id.Configurable; +import org.hibernate.id.IdentifierGenerator; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.type.Type; + +public class MyGenerator implements IdentifierGenerator, Configurable { + + private String prefix; + + @Override + public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException { + + String query = String.format("select %s from %s", + session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName(), + obj.getClass().getSimpleName()); + + Stream ids = session.createQuery(query).stream(); + + Long max = ids.map(o -> o.replace(prefix + "-", "")) + .mapToLong(Long::parseLong) + .max() + .orElse(0L); + + return prefix + "-" + (max + 1); + } + + @Override + public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException { + prefix = properties.getProperty("prefix"); + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java new file mode 100644 index 0000000000..6fe7f915fc --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.JOINED) +public class Animal { + + @Id + private long animalId; + + private String species; + + public Animal() {} + + public Animal(long animalId, String species) { + this.animalId = animalId; + this.species = species; + } + + public long getAnimalId() { + return animalId; + } + + public void setAnimalId(long animalId) { + this.animalId = animalId; + } + + public String getSpecies() { + return species; + } + + public void setSpecies(String species) { + this.species = species; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java new file mode 100644 index 0000000000..fa6e1b4bef --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; + +import org.hibernate.annotations.Polymorphism; +import org.hibernate.annotations.PolymorphismType; + +@Entity +@Polymorphism(type = PolymorphismType.EXPLICIT) +public class Bag implements Item { + + @Id + private long bagId; + + private String type; + + public Bag(long bagId, String type) { + this.bagId = bagId; + this.type = type; + } + + public long getBagId() { + return bagId; + } + + public void setBagId(long bagId) { + this.bagId = bagId; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java new file mode 100644 index 0000000000..36ca8dd77c --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("1") +public class Book extends MyProduct { + private String author; + + public Book() { + } + + public Book(long productId, String name, String author) { + super(productId, name); + this.author = author; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java new file mode 100644 index 0000000000..49d1f7749a --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java @@ -0,0 +1,25 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; + +@Entity +public class Car extends Vehicle { + private String engine; + + public Car() { + } + + public Car(long vehicleId, String manufacturer, String engine) { + super(vehicleId, manufacturer); + this.engine = engine; + } + + public String getEngine() { + return engine; + } + + public void setEngine(String engine) { + this.engine = engine; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java new file mode 100644 index 0000000000..9656030736 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java @@ -0,0 +1,5 @@ +package com.baeldung.hibernate.pojo.inheritance; + +public interface Item { + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java new file mode 100644 index 0000000000..9a6bce16cf --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java @@ -0,0 +1,22 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; + +@Entity +public class MyEmployee extends Person { + private String company; + + public MyEmployee(long personId, String name, String company) { + super(personId, name); + this.company = company; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java new file mode 100644 index 0000000000..13f04d8904 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +import org.hibernate.annotations.DiscriminatorFormula; + +@Entity +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name = "product_type", discriminatorType = DiscriminatorType.INTEGER) +// @DiscriminatorFormula("case when author is not null then 1 else 2 end") +public class MyProduct { + @Id + private long productId; + + private String name; + + public MyProduct() { + } + + public MyProduct(long productId, String name) { + super(); + this.productId = productId; + this.name = name; + } + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java new file mode 100644 index 0000000000..32b77e52af --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("2") +public class Pen extends MyProduct { + private String color; + + public Pen() { + } + + public Pen(long productId, String name, String color) { + super(productId, name); + this.color = color; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java new file mode 100644 index 0000000000..99084b88af --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; + +@MappedSuperclass +public class Person { + + @Id + private long personId; + + private String name; + + public Person() { + } + + public Person(long personId, String name) { + this.personId = personId; + this.name = name; + } + + public long getPersonId() { + return personId; + } + + public void setPersonId(long personId) { + this.personId = personId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java new file mode 100644 index 0000000000..870b3cd684 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.PrimaryKeyJoinColumn; + +@Entity +@PrimaryKeyJoinColumn(name = "petId") +public class Pet extends Animal { + private String name; + + public Pet() { + } + + public Pet(long animalId, String species, String name) { + super(animalId, species); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java new file mode 100644 index 0000000000..b2a920573e --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java @@ -0,0 +1,40 @@ +package com.baeldung.hibernate.pojo.inheritance; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) +public class Vehicle { + @Id + private long vehicleId; + + private String manufacturer; + + public Vehicle() { + } + + public Vehicle(long vehicleId, String manufacturer) { + this.vehicleId = vehicleId; + this.manufacturer = manufacturer; + } + + public long getVehicleId() { + return vehicleId; + } + + public void setVehicleId(long vehicleId) { + this.vehicleId = vehicleId; + } + + public String getManufacturer() { + return manufacturer; + } + + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java new file mode 100644 index 0000000000..6b54dc80a8 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java @@ -0,0 +1,100 @@ +package com.baeldung.hibernate; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.hibernate.Transaction; +import java.io.IOException; +import org.hibernate.Session; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.hibernate.pojo.Product; +import com.baeldung.hibernate.pojo.Course; +import com.baeldung.hibernate.pojo.OrderEntry; +import com.baeldung.hibernate.pojo.OrderEntryIdClass; +import com.baeldung.hibernate.pojo.OrderEntryPK; +import com.baeldung.hibernate.pojo.Student; +import com.baeldung.hibernate.pojo.User; +import com.baeldung.hibernate.pojo.UserProfile; + +public class IdentifiersIntegrationTest { + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory() + .openSession(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void whenSaveSimpleIdEntities_thenOk() { + Student student = new Student(); + session.save(student); + User user = new User(); + session.save(user); + + assertThat(student.getStudentId()).isEqualTo(1L); + assertThat(user.getUserId()).isEqualTo(4L); + + Course course = new Course(); + session.save(course); + + } + + @Test + public void whenSaveCustomGeneratedId_thenOk() { + Product product = new Product(); + session.save(product); + Product product2 = new Product(); + session.save(product2); + + assertThat(product2.getProdId()).isEqualTo("prod-2"); + } + + @Test + public void whenSaveCompositeIdEntity_thenOk() { + OrderEntryPK entryPK = new OrderEntryPK(); + entryPK.setOrderId(1L); + entryPK.setProductId(30L); + + OrderEntry entry = new OrderEntry(); + entry.setEntryId(entryPK); + session.save(entry); + + assertThat(entry.getEntryId() + .getOrderId()).isEqualTo(1L); + } + + @Test + public void whenSaveIdClassEntity_thenOk() { + OrderEntryIdClass entry = new OrderEntryIdClass(); + entry.setOrderId(1L); + entry.setProductId(30L); + session.save(entry); + + assertThat(entry.getOrderId()).isEqualTo(1L); + } + + @Test + public void whenSaveDerivedIdEntity_thenOk() { + User user = new User(); + session.save(user); + + UserProfile profile = new UserProfile(); + profile.setUser(user); + session.save(profile); + + assertThat(profile.getProfileId()).isEqualTo(user.getUserId()); + } + +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java new file mode 100644 index 0000000000..0f35dbb8af --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java @@ -0,0 +1,89 @@ +package com.baeldung.hibernate; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; + +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.pojo.inheritance.Bag; +import com.baeldung.hibernate.pojo.inheritance.Book; +import com.baeldung.hibernate.pojo.inheritance.Car; +import com.baeldung.hibernate.pojo.inheritance.MyEmployee; +import com.baeldung.hibernate.pojo.inheritance.Pen; +import com.baeldung.hibernate.pojo.inheritance.Pet; + +public class InheritanceMappingIntegrationTest { + private Session session; + + private Transaction transaction; + + @Before + public void setUp() throws IOException { + session = HibernateUtil.getSessionFactory() + .openSession(); + transaction = session.beginTransaction(); + } + + @After + public void tearDown() { + transaction.rollback(); + session.close(); + } + + @Test + public void givenSubclasses_whenQuerySingleTableSuperclass_thenOk() { + Book book = new Book(1, "1984", "George Orwell"); + session.save(book); + Pen pen = new Pen(2, "my pen", "blue"); + session.save(pen); + + assertThat(session.createQuery("from MyProduct") + .getResultList() + .size()).isEqualTo(2); + } + + @Test + public void givenSubclasses_whenQueryMappedSuperclass_thenOk() { + MyEmployee emp = new MyEmployee(1, "john", "baeldung"); + session.save(emp); + + assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Person") + .getResultList() + .size()).isEqualTo(1); + } + + @Test + public void givenSubclasses_whenQueryJoinedTableSuperclass_thenOk() { + Pet pet = new Pet(1, "dog", "lassie"); + session.save(pet); + + assertThat(session.createQuery("from Animal") + .getResultList() + .size()).isEqualTo(1); + } + + @Test + public void givenSubclasses_whenQueryTablePerClassSuperclass_thenOk() { + Car car = new Car(1, "audi", "xyz"); + session.save(car); + + assertThat(session.createQuery("from Vehicle") + .getResultList() + .size()).isEqualTo(1); + } + + @Test + public void givenSubclasses_whenQueryNonMappedInterface_thenOk() { + Bag bag = new Bag(1, "large"); + session.save(bag); + + assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Item") + .getResultList() + .size()).isEqualTo(0); + } +} diff --git a/jee7/.gitignore b/jee-7/.gitignore similarity index 100% rename from jee7/.gitignore rename to jee-7/.gitignore diff --git a/jee7/README.md b/jee-7/README.md similarity index 100% rename from jee7/README.md rename to jee-7/README.md diff --git a/jee7/pom.xml b/jee-7/pom.xml similarity index 99% rename from jee7/pom.xml rename to jee-7/pom.xml index 6858a05d17..f1d50f55c6 100644 --- a/jee7/pom.xml +++ b/jee-7/pom.xml @@ -4,7 +4,7 @@ 4.0.0 com.baeldung - jee7 + jee-7 1.0-SNAPSHOT war JavaEE 7 Arquillian Archetype Sample diff --git a/jee7/src/main/java/com/baeldung/arquillian/CapsConvertor.java b/jee-7/src/main/java/com/baeldung/arquillian/CapsConvertor.java similarity index 100% rename from jee7/src/main/java/com/baeldung/arquillian/CapsConvertor.java rename to jee-7/src/main/java/com/baeldung/arquillian/CapsConvertor.java diff --git a/jee7/src/main/java/com/baeldung/arquillian/CapsService.java b/jee-7/src/main/java/com/baeldung/arquillian/CapsService.java similarity index 100% rename from jee7/src/main/java/com/baeldung/arquillian/CapsService.java rename to jee-7/src/main/java/com/baeldung/arquillian/CapsService.java diff --git a/jee7/src/main/java/com/baeldung/arquillian/Car.java b/jee-7/src/main/java/com/baeldung/arquillian/Car.java similarity index 100% rename from jee7/src/main/java/com/baeldung/arquillian/Car.java rename to jee-7/src/main/java/com/baeldung/arquillian/Car.java diff --git a/jee7/src/main/java/com/baeldung/arquillian/CarEJB.java b/jee-7/src/main/java/com/baeldung/arquillian/CarEJB.java similarity index 100% rename from jee7/src/main/java/com/baeldung/arquillian/CarEJB.java rename to jee-7/src/main/java/com/baeldung/arquillian/CarEJB.java diff --git a/jee7/src/main/java/com/baeldung/arquillian/Component.java b/jee-7/src/main/java/com/baeldung/arquillian/Component.java similarity index 100% rename from jee7/src/main/java/com/baeldung/arquillian/Component.java rename to jee-7/src/main/java/com/baeldung/arquillian/Component.java diff --git a/jee7/src/main/java/com/baeldung/arquillian/ConvertToLowerCase.java b/jee-7/src/main/java/com/baeldung/arquillian/ConvertToLowerCase.java similarity index 100% rename from jee7/src/main/java/com/baeldung/arquillian/ConvertToLowerCase.java rename to jee-7/src/main/java/com/baeldung/arquillian/ConvertToLowerCase.java diff --git a/jee7/src/main/java/com/baeldung/convListVal/ConvListVal.java b/jee-7/src/main/java/com/baeldung/convListVal/ConvListVal.java similarity index 100% rename from jee7/src/main/java/com/baeldung/convListVal/ConvListVal.java rename to jee-7/src/main/java/com/baeldung/convListVal/ConvListVal.java diff --git a/jee7/src/main/java/com/baeldung/convListVal/MyListener.java b/jee-7/src/main/java/com/baeldung/convListVal/MyListener.java similarity index 100% rename from jee7/src/main/java/com/baeldung/convListVal/MyListener.java rename to jee-7/src/main/java/com/baeldung/convListVal/MyListener.java diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/README.txt diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/pom.xml diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java similarity index 100% rename from jee7/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/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/AccountServlet.java diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java similarity index 100% rename from jee7/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/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/BankAppServletContextListener.java diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java similarity index 100% rename from jee7/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/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/LogInFilter.java diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java similarity index 100% rename from jee7/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/JavaEEAnnotationsSample/src/main/java/com/baeldung/javaeeannotations/UploadCustomerDocumentsServlet.java diff --git a/jee7/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 similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/WEB-INF/web.xml diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/index.jsp diff --git a/jee7/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 similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/login.jsp diff --git a/jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp b/jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp similarity index 100% rename from jee7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp rename to jee-7/src/main/java/com/baeldung/javaeeannotations/JavaEEAnnotationsSample/src/main/webapp/upload.jsp diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/AddEmployee.java b/jee-7/src/main/java/com/baeldung/jaxws/client/AddEmployee.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/AddEmployee.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/AddEmployee.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/AddEmployeeResponse.java b/jee-7/src/main/java/com/baeldung/jaxws/client/AddEmployeeResponse.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/AddEmployeeResponse.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/AddEmployeeResponse.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/CountEmployees.java b/jee-7/src/main/java/com/baeldung/jaxws/client/CountEmployees.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/CountEmployees.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/CountEmployees.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/CountEmployeesResponse.java b/jee-7/src/main/java/com/baeldung/jaxws/client/CountEmployeesResponse.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/CountEmployeesResponse.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/CountEmployeesResponse.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/DeleteEmployee.java b/jee-7/src/main/java/com/baeldung/jaxws/client/DeleteEmployee.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/DeleteEmployee.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/DeleteEmployee.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/DeleteEmployeeResponse.java b/jee-7/src/main/java/com/baeldung/jaxws/client/DeleteEmployeeResponse.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/DeleteEmployeeResponse.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/DeleteEmployeeResponse.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/Employee.java b/jee-7/src/main/java/com/baeldung/jaxws/client/Employee.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/Employee.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/Employee.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists_Exception.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists_Exception.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists_Exception.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeAlreadyExists_Exception.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound_Exception.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound_Exception.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound_Exception.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeNotFound_Exception.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeService.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeService.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeService.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeService.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeServiceClient.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeServiceClient.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeServiceClient.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeServiceClient.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/EmployeeService_Service.java b/jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeService_Service.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/EmployeeService_Service.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/EmployeeService_Service.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/GetAllEmployees.java b/jee-7/src/main/java/com/baeldung/jaxws/client/GetAllEmployees.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/GetAllEmployees.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/GetAllEmployees.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/GetAllEmployeesResponse.java b/jee-7/src/main/java/com/baeldung/jaxws/client/GetAllEmployeesResponse.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/GetAllEmployeesResponse.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/GetAllEmployeesResponse.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/GetEmployee.java b/jee-7/src/main/java/com/baeldung/jaxws/client/GetEmployee.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/GetEmployee.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/GetEmployee.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/GetEmployeeResponse.java b/jee-7/src/main/java/com/baeldung/jaxws/client/GetEmployeeResponse.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/GetEmployeeResponse.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/GetEmployeeResponse.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/ObjectFactory.java b/jee-7/src/main/java/com/baeldung/jaxws/client/ObjectFactory.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/ObjectFactory.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/ObjectFactory.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/UpdateEmployee.java b/jee-7/src/main/java/com/baeldung/jaxws/client/UpdateEmployee.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/UpdateEmployee.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/UpdateEmployee.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/UpdateEmployeeResponse.java b/jee-7/src/main/java/com/baeldung/jaxws/client/UpdateEmployeeResponse.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/UpdateEmployeeResponse.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/UpdateEmployeeResponse.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/client/package-info.java b/jee-7/src/main/java/com/baeldung/jaxws/client/package-info.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/client/package-info.java rename to jee-7/src/main/java/com/baeldung/jaxws/client/package-info.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeService.java b/jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeService.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeService.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeService.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeServiceImpl.java b/jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeServiceImpl.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeServiceImpl.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/EmployeeServiceImpl.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeAlreadyExists.java b/jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeAlreadyExists.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeAlreadyExists.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeAlreadyExists.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeNotFound.java b/jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeNotFound.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeNotFound.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/exception/EmployeeNotFound.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/bottomup/model/Employee.java b/jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/model/Employee.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/bottomup/model/Employee.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/bottomup/model/Employee.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/config/EmployeeServicePublisher.java b/jee-7/src/main/java/com/baeldung/jaxws/server/config/EmployeeServicePublisher.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/config/EmployeeServicePublisher.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/config/EmployeeServicePublisher.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepository.java b/jee-7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepository.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepository.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepository.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepositoryImpl.java b/jee-7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepositoryImpl.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepositoryImpl.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/repository/EmployeeRepositoryImpl.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown.java b/jee-7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDownImpl.java b/jee-7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDownImpl.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDownImpl.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDownImpl.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown_Service.java b/jee-7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown_Service.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown_Service.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/topdown/EmployeeServiceTopDown_Service.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/server/topdown/ObjectFactory.java b/jee-7/src/main/java/com/baeldung/jaxws/server/topdown/ObjectFactory.java similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/server/topdown/ObjectFactory.java rename to jee-7/src/main/java/com/baeldung/jaxws/server/topdown/ObjectFactory.java diff --git a/jee7/src/main/java/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl b/jee-7/src/main/java/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl similarity index 100% rename from jee7/src/main/java/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl rename to jee-7/src/main/java/com/baeldung/jaxws/wsdl/employeeservicetopdown.wsdl diff --git a/jee7/src/main/java/com/baeldung/json/Person.java b/jee-7/src/main/java/com/baeldung/json/Person.java similarity index 100% rename from jee7/src/main/java/com/baeldung/json/Person.java rename to jee-7/src/main/java/com/baeldung/json/Person.java diff --git a/jee7/src/main/java/com/baeldung/json/PersonBuilder.java b/jee-7/src/main/java/com/baeldung/json/PersonBuilder.java similarity index 100% rename from jee7/src/main/java/com/baeldung/json/PersonBuilder.java rename to jee-7/src/main/java/com/baeldung/json/PersonBuilder.java diff --git a/jee7/src/main/java/com/baeldung/json/PersonWriter.java b/jee-7/src/main/java/com/baeldung/json/PersonWriter.java similarity index 100% rename from jee7/src/main/java/com/baeldung/json/PersonWriter.java rename to jee-7/src/main/java/com/baeldung/json/PersonWriter.java diff --git a/jee7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java b/jee-7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java similarity index 100% rename from jee7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java rename to jee-7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java diff --git a/jee7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java b/jee-7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java similarity index 100% rename from jee7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java rename to jee-7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java diff --git a/jee7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java b/jee-7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java similarity index 100% rename from jee7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java rename to jee-7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java diff --git a/jee7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java b/jee-7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java similarity index 100% rename from jee7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java rename to jee-7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java diff --git a/jee7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java b/jee-7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java similarity index 100% rename from jee7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java rename to jee-7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java diff --git a/jee7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java b/jee-7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java rename to jee-7/src/main/java/com/baeldung/timer/AutomaticTimerBean.java diff --git a/jee7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java b/jee-7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java rename to jee-7/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java diff --git a/jee7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java b/jee-7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java rename to jee-7/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java diff --git a/jee7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java b/jee-7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java rename to jee-7/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java diff --git a/jee7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java b/jee-7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java rename to jee-7/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java diff --git a/jee7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java b/jee-7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java rename to jee-7/src/main/java/com/baeldung/timer/ScheduleTimerBean.java diff --git a/jee7/src/main/java/com/baeldung/timer/TimerEvent.java b/jee-7/src/main/java/com/baeldung/timer/TimerEvent.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/TimerEvent.java rename to jee-7/src/main/java/com/baeldung/timer/TimerEvent.java diff --git a/jee7/src/main/java/com/baeldung/timer/TimerEventListener.java b/jee-7/src/main/java/com/baeldung/timer/TimerEventListener.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/TimerEventListener.java rename to jee-7/src/main/java/com/baeldung/timer/TimerEventListener.java diff --git a/jee7/src/main/java/com/baeldung/timer/WorkerBean.java b/jee-7/src/main/java/com/baeldung/timer/WorkerBean.java similarity index 100% rename from jee7/src/main/java/com/baeldung/timer/WorkerBean.java rename to jee-7/src/main/java/com/baeldung/timer/WorkerBean.java diff --git a/jee7/src/main/resources/META-INF/persistence.xml b/jee-7/src/main/resources/META-INF/persistence.xml similarity index 100% rename from jee7/src/main/resources/META-INF/persistence.xml rename to jee-7/src/main/resources/META-INF/persistence.xml diff --git a/jee7/src/main/webapp/ConvListVal.xhtml b/jee-7/src/main/webapp/ConvListVal.xhtml similarity index 100% rename from jee7/src/main/webapp/ConvListVal.xhtml rename to jee-7/src/main/webapp/ConvListVal.xhtml diff --git a/jee7/src/main/webapp/WEB-INF/beans.xml b/jee-7/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from jee7/src/main/webapp/WEB-INF/beans.xml rename to jee-7/src/main/webapp/WEB-INF/beans.xml diff --git a/jee7/src/main/webapp/WEB-INF/faces-config.xml b/jee-7/src/main/webapp/WEB-INF/faces-config.xml similarity index 100% rename from jee7/src/main/webapp/WEB-INF/faces-config.xml rename to jee-7/src/main/webapp/WEB-INF/faces-config.xml diff --git a/jee7/src/main/webapp/WEB-INF/spring/security.xml b/jee-7/src/main/webapp/WEB-INF/spring/security.xml similarity index 100% rename from jee7/src/main/webapp/WEB-INF/spring/security.xml rename to jee-7/src/main/webapp/WEB-INF/spring/security.xml diff --git a/jee7/src/main/webapp/WEB-INF/views/admin.jsp b/jee-7/src/main/webapp/WEB-INF/views/admin.jsp similarity index 100% rename from jee7/src/main/webapp/WEB-INF/views/admin.jsp rename to jee-7/src/main/webapp/WEB-INF/views/admin.jsp diff --git a/jee7/src/main/webapp/WEB-INF/views/home.jsp b/jee-7/src/main/webapp/WEB-INF/views/home.jsp similarity index 100% rename from jee7/src/main/webapp/WEB-INF/views/home.jsp rename to jee-7/src/main/webapp/WEB-INF/views/home.jsp diff --git a/jee7/src/main/webapp/WEB-INF/views/login.jsp b/jee-7/src/main/webapp/WEB-INF/views/login.jsp similarity index 100% rename from jee7/src/main/webapp/WEB-INF/views/login.jsp rename to jee-7/src/main/webapp/WEB-INF/views/login.jsp diff --git a/jee7/src/main/webapp/WEB-INF/views/user.jsp b/jee-7/src/main/webapp/WEB-INF/views/user.jsp similarity index 100% rename from jee7/src/main/webapp/WEB-INF/views/user.jsp rename to jee-7/src/main/webapp/WEB-INF/views/user.jsp diff --git a/jee7/src/main/webapp/WEB-INF/web.xml b/jee-7/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from jee7/src/main/webapp/WEB-INF/web.xml rename to jee-7/src/main/webapp/WEB-INF/web.xml diff --git a/jee7/src/main/webapp/index.jsp b/jee-7/src/main/webapp/index.jsp similarity index 100% rename from jee7/src/main/webapp/index.jsp rename to jee-7/src/main/webapp/index.jsp diff --git a/jee7/src/main/webapp/secure.jsp b/jee-7/src/main/webapp/secure.jsp similarity index 100% rename from jee7/src/main/webapp/secure.jsp rename to jee-7/src/main/webapp/secure.jsp diff --git a/jee7/src/test/java/com/baeldug/json/JsonUnitTest.java b/jee-7/src/test/java/com/baeldug/json/JsonUnitTest.java similarity index 100% rename from jee7/src/test/java/com/baeldug/json/JsonUnitTest.java rename to jee-7/src/test/java/com/baeldug/json/JsonUnitTest.java diff --git a/jee7/src/test/java/com/baeldung/arquillan/ArquillianLiveTest.java b/jee-7/src/test/java/com/baeldung/arquillan/ArquillianLiveTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/arquillan/ArquillianLiveTest.java rename to jee-7/src/test/java/com/baeldung/arquillan/ArquillianLiveTest.java diff --git a/jee7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java diff --git a/jee7/src/test/java/com/baeldung/jaxws/EmployeeServiceLiveTest.java b/jee-7/src/test/java/com/baeldung/jaxws/EmployeeServiceLiveTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/jaxws/EmployeeServiceLiveTest.java rename to jee-7/src/test/java/com/baeldung/jaxws/EmployeeServiceLiveTest.java diff --git a/jee7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java diff --git a/jee7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java diff --git a/jee7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java diff --git a/jee7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java diff --git a/jee7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java similarity index 100% rename from jee7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java diff --git a/jee7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java b/jee-7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java similarity index 100% rename from jee7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java rename to jee-7/src/test/java/com/baeldung/timer/WithinWindowMatcher.java diff --git a/jee7/src/test/resources/META-INF/persistence.xml b/jee-7/src/test/resources/META-INF/persistence.xml similarity index 100% rename from jee7/src/test/resources/META-INF/persistence.xml rename to jee-7/src/test/resources/META-INF/persistence.xml diff --git a/jsonb/.gitignore b/jsonb/.gitignore new file mode 100644 index 0000000000..dec013dfa4 --- /dev/null +++ b/jsonb/.gitignore @@ -0,0 +1,12 @@ +#folders# +.idea +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/jsonb/README.md b/jsonb/README.md new file mode 100644 index 0000000000..a638f0355c --- /dev/null +++ b/jsonb/README.md @@ -0,0 +1 @@ +## JSON B diff --git a/jsonb/pom.xml b/jsonb/pom.xml new file mode 100644 index 0000000000..5058d89c31 --- /dev/null +++ b/jsonb/pom.xml @@ -0,0 +1,106 @@ + + + 4.0.0 + + com.baeldung + json-b + 0.0.1-SNAPSHOT + jar + + json-b + json-b sample project + + + yasson + + true + + + + + org.eclipse + yasson + ${yasson.version} + + + org.glassfish + javax.json + ${javax.json.version} + + + + + johnzon + + + + org.apache.geronimo.specs + geronimo-json_1.1_spec + ${geronimo-json_1.1_spec.version} + + + org.apache.johnzon + johnzon-jsonb + ${johnzon.version} + + + + + + + javax.json.bind + javax.json.bind-api + ${jsonb-api.version} + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + test + + + + org.junit.jupiter + junit-jupiter-api + ${junit.jupiter.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + + + + UTF-8 + UTF-8 + 1.8 + 1.8 + 1.0.0 + 5.0.0 + 2.20 + 1.0 + 1.1.3 + 1.0 + 1.0.1 + 1.1.2 + 4.1 + + + \ No newline at end of file diff --git a/jsonb/src/main/java/com/baeldung/adapter/PersonAdapter.java b/jsonb/src/main/java/com/baeldung/adapter/PersonAdapter.java new file mode 100644 index 0000000000..dfab2eb0d2 --- /dev/null +++ b/jsonb/src/main/java/com/baeldung/adapter/PersonAdapter.java @@ -0,0 +1,26 @@ +package com.baeldung.adapter; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.bind.adapter.JsonbAdapter; + +import com.baeldung.jsonb.Person; + +public class PersonAdapter implements JsonbAdapter { + + @Override + public JsonObject adaptToJson(Person p) throws Exception { + return Json.createObjectBuilder() + .add("id", p.getId()) + .add("name", p.getName()) + .build(); + } + + @Override + public Person adaptFromJson(JsonObject adapted) throws Exception { + Person person = new Person(); + person.setId(adapted.getInt("id")); + person.setName(adapted.getString("name")); + return person; + } +} \ No newline at end of file diff --git a/jsonb/src/main/java/com/baeldung/jsonb/Person.java b/jsonb/src/main/java/com/baeldung/jsonb/Person.java new file mode 100644 index 0000000000..a506c1b000 --- /dev/null +++ b/jsonb/src/main/java/com/baeldung/jsonb/Person.java @@ -0,0 +1,127 @@ +package com.baeldung.jsonb; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import javax.json.bind.annotation.JsonbDateFormat; +import javax.json.bind.annotation.JsonbNumberFormat; +import javax.json.bind.annotation.JsonbProperty; +import javax.json.bind.annotation.JsonbTransient; + +public class Person { + + private int id; + @JsonbProperty("person-name") + private String name; + @JsonbProperty(nillable = true) + private String email; + @JsonbTransient + private int age; + @JsonbDateFormat("dd-MM-yyyy") + private LocalDate registeredDate; + private BigDecimal salary; + + public Person() { + this(0, "", "", 0, LocalDate.now(), new BigDecimal(0)); + } + + public Person(int id, String name, String email, int age, LocalDate registeredDate, BigDecimal salary) { + this.id = id; + this.name = name; + this.email = email; + this.age = age; + this.registeredDate = registeredDate; + this.salary = salary; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @JsonbNumberFormat(locale = "en_US", value = "#0.0") + public BigDecimal getSalary() { + return salary; + } + + public void setSalary(BigDecimal salary) { + this.salary = salary; + } + + public LocalDate getRegisteredDate() { + return registeredDate; + } + + public void setRegisteredDate(LocalDate registeredDate) { + this.registeredDate = registeredDate; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Person [id="); + builder.append(id); + builder.append(", name="); + builder.append(name); + builder.append(", email="); + builder.append(email); + builder.append(", age="); + builder.append(age); + builder.append(", registeredDate="); + builder.append(registeredDate); + builder.append(", salary="); + builder.append(salary); + builder.append("]"); + return builder.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Person other = (Person) obj; + if (id != other.id) + return false; + return true; + } + +} diff --git a/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java b/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java new file mode 100644 index 0000000000..67beda77e1 --- /dev/null +++ b/jsonb/src/test/java/com/baeldung/jsonb/JsonbTest.java @@ -0,0 +1,188 @@ +package com.baeldung.jsonb; + +import static org.junit.Assert.assertTrue; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.json.bind.Jsonb; +import javax.json.bind.JsonbBuilder; +import javax.json.bind.JsonbConfig; +import javax.json.bind.config.PropertyNamingStrategy; +import javax.json.bind.config.PropertyOrderStrategy; + +import org.apache.commons.collections4.ListUtils; +import org.junit.Test; + +import com.baeldung.adapter.PersonAdapter; + +public class JsonbTest { + + @Test + public void givenPersonList_whenSerializeWithJsonb_thenGetPersonJsonArray() { + Jsonb jsonb = JsonbBuilder.create(); + // @formatter:off + List personList = Arrays.asList( + new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), + new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500))); + // @formatter:on + String jsonArrayPerson = jsonb.toJson(personList); + // @formatter:off + String jsonExpected = "[" + + "{\"email\":\"jhon@test.com\"," + + "\"id\":1,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"jhon1@test.com\"," + + "\"id\":2,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"},{\"email\":null," + + "\"id\":3,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"tom@test.com\"," + + "\"id\":4,\"person-name\":\"Tom\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"}" + + "]"; + // @formatter:on + assertTrue(jsonArrayPerson.equals(jsonExpected)); + } + + @Test + public void givenPersonJsonArray_whenDeserializeWithJsonb_thenGetPersonList() { + Jsonb jsonb = JsonbBuilder.create(); + // @formatter:off + String personJsonArray = + "[" + + "{\"email\":\"jhon@test.com\"," + + "\"id\":1,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"jhon1@test.com\"," + + "\"id\":2,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"},{\"email\":null," + + "\"id\":3,\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1000.0\"}," + + "{\"email\":\"tom@test.com\"," + + "\"id\":4,\"person-name\":\"Tom\"," + + "\"registeredDate\":\"09-09-2019\"," + + "\"salary\":\"1500.0\"}" + + "]"; + // @formatter:on + @SuppressWarnings("serial") + List personList = jsonb.fromJson(personJsonArray, new ArrayList() { + }.getClass() + .getGenericSuperclass()); + // @formatter:off + List personListExpected = Arrays.asList( + new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)), + new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)), + new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500))); + // @formatter:on + assertTrue(ListUtils.isEqualList(personList, personListExpected)); + } + + @Test + public void givenPersonObject_whenNamingStrategy_thenGetCustomPersonJson() { + JsonbConfig config = new JsonbConfig().withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES); + Jsonb jsonb = JsonbBuilder.create(config); + Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registered_date\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonObject_whenWithPropertyOrderStrategy_thenGetReversePersonJson() { + JsonbConfig config = new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE); + Jsonb jsonb = JsonbBuilder.create(config); + Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"salary\":\"1000.0\","+ + "\"registeredDate\":\"07-09-2019\"," + + "\"person-name\":\"Jhon\"," + + "\"id\":1," + + "\"email\":\"jhon@test.com\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() { + Jsonb jsonb = JsonbBuilder.create(); + Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() { + Jsonb jsonb = JsonbBuilder.create(); + Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0)); + // @formatter:off + String jsonPerson = + "{\"email\":\"jhon@test.com\"," + + "\"id\":1," + + "\"person-name\":\"Jhon\"," + + "\"registeredDate\":\"07-09-2019\"," + + "\"salary\":\"1000.0\"}"; + // @formatter:on + assertTrue(jsonb.fromJson(jsonPerson, Person.class) + .equals(person)); + } + + @Test + public void givenPersonObject_whenSerializeWithAdapter_thenGetPersonJson() { + JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter()); + Jsonb jsonb = JsonbBuilder.create(config); + Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon"); + String jsonPerson = jsonb.toJson(person); + // @formatter:off + String jsonExpected = + "{\"id\":1," + + "\"name\":\"Jhon\"}"; + // @formatter:on + assertTrue(jsonExpected.equals(jsonPerson)); + } + + @Test + public void givenPersonJson_whenDeserializeWithAdapter_thenGetPersonObject() { + JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter()); + Jsonb jsonb = JsonbBuilder.create(config); + Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon"); + // @formatter:off + String jsonPerson = + "{\"id\":1," + + "\"name\":\"Jhon\"}"; + // @formatter:on + assertTrue(jsonb.fromJson(jsonPerson, Person.class) + .equals(person)); + } + +} diff --git a/junit5/src/main/java/com/baeldung/junit5/DefaultOrderOfExecutionTest.java b/junit5/src/main/java/com/baeldung/junit5/DefaultOrderOfExecutionTest.java new file mode 100644 index 0000000000..15b07ee03a --- /dev/null +++ b/junit5/src/main/java/com/baeldung/junit5/DefaultOrderOfExecutionTest.java @@ -0,0 +1,33 @@ +package com.baeldung.junit5; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +@FixMethodOrder(MethodSorters.DEFAULT) +public class DefaultOrderOfExecutionTest { + private static StringBuilder output = new StringBuilder(""); + + @Test + public void secondTest() { + output.append("b"); + } + + @Test + public void thirdTest() { + output.append("c"); + } + + @Test + public void firstTest() { + output.append("a"); + } + + @AfterClass + public static void assertOutput() { + assertEquals(output.toString(), "cab"); + } +} diff --git a/junit5/src/main/java/com/baeldung/junit5/JVMOrderOfExecutionTest.java b/junit5/src/main/java/com/baeldung/junit5/JVMOrderOfExecutionTest.java new file mode 100644 index 0000000000..189efc8945 --- /dev/null +++ b/junit5/src/main/java/com/baeldung/junit5/JVMOrderOfExecutionTest.java @@ -0,0 +1,26 @@ +package com.baeldung.junit5; + +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +@FixMethodOrder(MethodSorters.JVM) +public class JVMOrderOfExecutionTest { + + private static StringBuilder output = new StringBuilder(""); + + @Test + public void secondTest() { + output.append("b"); + } + + @Test + public void thirdTest() { + output.append("c"); + } + + @Test + public void firstTest() { + output.append("a"); + } +} \ No newline at end of file diff --git a/junit5/src/main/java/com/baeldung/junit5/NameAscendingOrderOfExecutionTest.java b/junit5/src/main/java/com/baeldung/junit5/NameAscendingOrderOfExecutionTest.java new file mode 100644 index 0000000000..88de057fc8 --- /dev/null +++ b/junit5/src/main/java/com/baeldung/junit5/NameAscendingOrderOfExecutionTest.java @@ -0,0 +1,33 @@ +package com.baeldung.junit5; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class NameAscendingOrderOfExecutionTest { + private static StringBuilder output = new StringBuilder(""); + + @Test + public void secondTest() { + output.append("b"); + } + + @Test + public void thirdTest() { + output.append("c"); + } + + @Test + public void firstTest() { + output.append("a"); + } + + @AfterClass + public static void assertOutput() { + assertEquals(output.toString(), "abc"); + } +} diff --git a/libraries/README.md b/libraries/README.md index c6bbb5634c..ae2522ca9e 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -39,7 +39,6 @@ - [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv) - [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference) - [Introduction to NoException](http://www.baeldung.com/no-exception) -- [Introduction to FunctionalJava](http://www.baeldung.com/functional-java) - [Apache Commons IO](http://www.baeldung.com/apache-commons-io) - [Introduction to Conflict-Free Replicated Data Types](http://www.baeldung.com/java-conflict-free-replicated-data-types) - [Introduction to javax.measure](http://www.baeldung.com/javax-measure) @@ -53,7 +52,13 @@ - [Using Pairs in Java](http://www.baeldung.com/java-pairs) - [Apache Commons Collections Bag](http://www.baeldung.com/apache-commons-bag) - [Introduction to Caffeine](http://www.baeldung.com/java-caching-caffeine) -+-[Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) +- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) +- [Introduction To Docx4J](http://www.baeldung.com/docx4j) +- [Introduction to StreamEx](http://www.baeldung.com/streamex) +- [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle) +- [Intro to JDO Queries 2/2](http://www.baeldung.com/jdo-queries) +- [Guide to google-http-client](http://www.baeldung.com/google-http-client) + The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index 25c1113fea..546fe8a6d8 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -622,6 +622,21 @@ bcpkix-jdk15on 1.58 + + com.google.http-client + google-http-client + ${googleclient.version} + + + com.google.http-client + google-http-client-jackson2 + ${googleclient.version} + + + com.google.http-client + google-http-client-gson + ${googleclient.version} +
@@ -639,6 +654,7 @@ + 1.23.0 0.1.0 0.7.0 3.2.4 diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java new file mode 100644 index 0000000000..0618a7294d --- /dev/null +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java @@ -0,0 +1,65 @@ +package com.baeldung.googlehttpclientguide; + +import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; +import com.google.api.client.http.HttpRequest; +import com.google.api.client.http.HttpRequestFactory; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.HttpResponseException; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.apache.ApacheHttpTransport; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.JsonFactory; +import com.google.api.client.json.JsonObjectParser; +import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.client.util.ExponentialBackOff; +import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class GitHubExample { + static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); + //static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport(); + static final JsonFactory JSON_FACTORY = new JacksonFactory(); + //static final JsonFactory JSON_FACTORY = new GsonFactory(); + + private static void run() throws Exception { + HttpRequestFactory requestFactory + = HTTP_TRANSPORT.createRequestFactory( + (HttpRequest request) -> { + request.setParser(new JsonObjectParser(JSON_FACTORY)); + }); + GitHubUrl url = new GitHubUrl("https://api.github.com/users"); + url.per_page = 10; + url.page = 1; + HttpRequest request = requestFactory.buildGetRequest(url); + ExponentialBackOff backoff = new ExponentialBackOff.Builder() + .setInitialIntervalMillis(500) + .setMaxElapsedTimeMillis(900000) + .setMaxIntervalMillis(6000) + .setMultiplier(1.5) + .setRandomizationFactor(0.5) + .build(); + request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff)); + Type type = new TypeToken>() {}.getType(); + List users = (List)request.execute().parseAs(type); + System.out.println(users); + url.appendRawPath("/eugenp"); + request = requestFactory.buildGetRequest(url); + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future responseFuture = request.executeAsync(executor); + User eugen = responseFuture.get().parseAs(User.class); + System.out.println(eugen); + executor.shutdown(); + } + + public static void main(String[] args) { + try { + run(); + } catch (Exception e) { + System.err.println(e.getMessage()); + } + } +} diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java new file mode 100644 index 0000000000..c44de1e145 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java @@ -0,0 +1,18 @@ +package com.baeldung.googlehttpclientguide; + +import com.google.api.client.http.GenericUrl; +import com.google.api.client.util.Key; + +public class GitHubUrl extends GenericUrl{ + + public GitHubUrl(String encodedUrl) { + super(encodedUrl); + } + + @Key + public int per_page; + + @Key + public int page; + +} diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java new file mode 100644 index 0000000000..bf4ee96b25 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java @@ -0,0 +1,77 @@ +package com.baeldung.googlehttpclientguide; + +import com.google.api.client.json.GenericJson; +import com.google.api.client.util.Key; + +public class User extends GenericJson { + @Key + private String login; + @Key + private long id; + @Key + private String url; + @Key + private String company; + @Key + private String blog; + @Key + private String email; + + @Key("subscriptions_url") + private String subscriptionsUrl; + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getBlog() { + return blog; + } + + public void setBlog(String blog) { + this.blog = blog; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String toString() { + return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}'; + } + + +} diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/logging.properties b/libraries/src/main/java/com/baeldung/googlehttpclientguide/logging.properties new file mode 100644 index 0000000000..02489378df --- /dev/null +++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/logging.properties @@ -0,0 +1,10 @@ +# Properties file which configures the operation of the JDK logging facility. +# The system will look for this config file to be specified as a system property: +# -Djava.util.logging.config.file=${project_loc:dailymotion-simple-cmdline-sample}/logging.properties + +# Set up the console handler (uncomment "level" to show more fine-grained messages) +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = ALL + +# Set up logging of HTTP requests and responses (uncomment "level" to show) +com.google.api.client.http.level = ALL diff --git a/libraries/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java index 18488f9380..e95b63aa96 100644 --- a/libraries/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/MemberStatusIntegrationTest.java @@ -51,7 +51,6 @@ public class MemberStatusIntegrationTest { /** * This test should fail, comment out @Ignore to see how failed test can be reflected in Serenity report.
- * Remember to add <testFailureIgnore>true</testFailureIgnore> under maven-surefire-plugin configuration. */ @Test @Ignore diff --git a/logging-modules/README.md b/logging-modules/README.md new file mode 100644 index 0000000000..23458cf30b --- /dev/null +++ b/logging-modules/README.md @@ -0,0 +1,3 @@ + +## Logging Modules + diff --git a/log-mdc/README.md b/logging-modules/log-mdc/README.md similarity index 100% rename from log-mdc/README.md rename to logging-modules/log-mdc/README.md diff --git a/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml similarity index 98% rename from log-mdc/pom.xml rename to logging-modules/log-mdc/pom.xml index e91d4e231e..918e052a15 100644 --- a/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -12,6 +12,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/log-mdc/src/main/java/com/baeldung/config/AppConfiguration.java b/logging-modules/log-mdc/src/main/java/com/baeldung/config/AppConfiguration.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/config/AppConfiguration.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/config/AppConfiguration.java diff --git a/log-mdc/src/main/java/com/baeldung/config/AppInitializer.java b/logging-modules/log-mdc/src/main/java/com/baeldung/config/AppInitializer.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/config/AppInitializer.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/config/AppInitializer.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/TransactionFactory.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/TransactionFactory.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/TransactionFactory.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/TransactionFactory.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/Transfer.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/Transfer.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/Transfer.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/Transfer.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/TransferDemo.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/TransferDemo.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/TransferDemo.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/TransferDemo.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/TransferService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/TransferService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/TransferService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/TransferService.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JRunnable.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JRunnable.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JRunnable.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JRunnable.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JTransferService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JTransferService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JTransferService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j/Log4JTransferService.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2Runnable.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2Runnable.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2Runnable.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2Runnable.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2TransferService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2TransferService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2TransferService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/log4j2/Log4J2TransferService.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4TransferService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4TransferService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4TransferService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4TransferService.java diff --git a/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4jRunnable.java b/logging-modules/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4jRunnable.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4jRunnable.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/mdc/slf4j/Slf4jRunnable.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/Investment.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/Investment.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/Investment.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/Investment.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/controller/JBossLoggingController.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/controller/JBossLoggingController.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/controller/JBossLoggingController.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/controller/JBossLoggingController.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/controller/Log4J2Controller.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/controller/Log4J2Controller.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/controller/Log4J2Controller.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/controller/Log4J2Controller.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/controller/Log4JController.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/controller/Log4JController.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/controller/Log4JController.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/controller/Log4JController.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/service/InvestmentService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/InvestmentService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/service/InvestmentService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/InvestmentService.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/service/JBossLoggingInvestmentService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/JBossLoggingInvestmentService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/service/JBossLoggingInvestmentService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/JBossLoggingInvestmentService.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/service/Log4J2InvestmentService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/Log4J2InvestmentService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/service/Log4J2InvestmentService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/Log4J2InvestmentService.java diff --git a/log-mdc/src/main/java/com/baeldung/ndc/service/Log4JInvestmentService.java b/logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/Log4JInvestmentService.java similarity index 100% rename from log-mdc/src/main/java/com/baeldung/ndc/service/Log4JInvestmentService.java rename to logging-modules/log-mdc/src/main/java/com/baeldung/ndc/service/Log4JInvestmentService.java diff --git a/log-mdc/src/main/resources/log4j.properties b/logging-modules/log-mdc/src/main/resources/log4j.properties similarity index 100% rename from log-mdc/src/main/resources/log4j.properties rename to logging-modules/log-mdc/src/main/resources/log4j.properties diff --git a/log-mdc/src/main/resources/log4j2.xml b/logging-modules/log-mdc/src/main/resources/log4j2.xml similarity index 100% rename from log-mdc/src/main/resources/log4j2.xml rename to logging-modules/log-mdc/src/main/resources/log4j2.xml diff --git a/log-mdc/src/main/resources/logback.xml b/logging-modules/log-mdc/src/main/resources/logback.xml similarity index 100% rename from log-mdc/src/main/resources/logback.xml rename to logging-modules/log-mdc/src/main/resources/logback.xml diff --git a/log-mdc/src/test/java/com/baeldung/mdc/log4j/DemoIntegrationTest.java b/logging-modules/log-mdc/src/test/java/com/baeldung/mdc/log4j/DemoIntegrationTest.java similarity index 100% rename from log-mdc/src/test/java/com/baeldung/mdc/log4j/DemoIntegrationTest.java rename to logging-modules/log-mdc/src/test/java/com/baeldung/mdc/log4j/DemoIntegrationTest.java diff --git a/log-mdc/src/test/java/com/baeldung/mdc/log4j2/DemoIntegrationTest.java b/logging-modules/log-mdc/src/test/java/com/baeldung/mdc/log4j2/DemoIntegrationTest.java similarity index 100% rename from log-mdc/src/test/java/com/baeldung/mdc/log4j2/DemoIntegrationTest.java rename to logging-modules/log-mdc/src/test/java/com/baeldung/mdc/log4j2/DemoIntegrationTest.java diff --git a/log-mdc/src/test/java/com/baeldung/mdc/slf4j/DemoIntegrationTest.java b/logging-modules/log-mdc/src/test/java/com/baeldung/mdc/slf4j/DemoIntegrationTest.java similarity index 100% rename from log-mdc/src/test/java/com/baeldung/mdc/slf4j/DemoIntegrationTest.java rename to logging-modules/log-mdc/src/test/java/com/baeldung/mdc/slf4j/DemoIntegrationTest.java diff --git a/log-mdc/src/test/java/com/baeldung/ndc/NDCLogIntegrationTest.java b/logging-modules/log-mdc/src/test/java/com/baeldung/ndc/NDCLogIntegrationTest.java similarity index 100% rename from log-mdc/src/test/java/com/baeldung/ndc/NDCLogIntegrationTest.java rename to logging-modules/log-mdc/src/test/java/com/baeldung/ndc/NDCLogIntegrationTest.java diff --git a/log4j/README.md b/logging-modules/log4j/README.md similarity index 83% rename from log4j/README.md rename to logging-modules/log4j/README.md index 3c0258142c..8aae1b5826 100644 --- a/log4j/README.md +++ b/logging-modules/log4j/README.md @@ -2,6 +2,5 @@ - [Introduction to Java Logging](http://www.baeldung.com/java-logging-intro) - [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback) - [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode) -- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java) - [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback) - [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders) diff --git a/log4j/pom.xml b/logging-modules/log4j/pom.xml similarity index 97% rename from log4j/pom.xml rename to logging-modules/log4j/pom.xml index 20906c4c05..a3bfb0a33a 100644 --- a/log4j/pom.xml +++ b/logging-modules/log4j/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/log4j/src/main/java/com/baeldung/log4j/Log4jExample.java b/logging-modules/log4j/src/main/java/com/baeldung/log4j/Log4jExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/log4j/Log4jExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/log4j/Log4jExample.java diff --git a/log4j/src/main/java/com/baeldung/log4j/Log4jRollingExample.java b/logging-modules/log4j/src/main/java/com/baeldung/log4j/Log4jRollingExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/log4j/Log4jRollingExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/log4j/Log4jRollingExample.java diff --git a/log4j/src/main/java/com/baeldung/log4j2/Log4j2Example.java b/logging-modules/log4j/src/main/java/com/baeldung/log4j2/Log4j2Example.java similarity index 100% rename from log4j/src/main/java/com/baeldung/log4j2/Log4j2Example.java rename to logging-modules/log4j/src/main/java/com/baeldung/log4j2/Log4j2Example.java diff --git a/log4j/src/main/java/com/baeldung/log4j2/Log4j2RollingExample.java b/logging-modules/log4j/src/main/java/com/baeldung/log4j2/Log4j2RollingExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/log4j2/Log4j2RollingExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/log4j2/Log4j2RollingExample.java diff --git a/log4j/src/main/java/com/baeldung/logback/LogbackExample.java b/logging-modules/log4j/src/main/java/com/baeldung/logback/LogbackExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/logback/LogbackExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/logback/LogbackExample.java diff --git a/log4j/src/main/java/com/baeldung/logback/LogbackRollingExample.java b/logging-modules/log4j/src/main/java/com/baeldung/logback/LogbackRollingExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/logback/LogbackRollingExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/logback/LogbackRollingExample.java diff --git a/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java b/logging-modules/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/slf4j/Slf4jExample.java diff --git a/log4j/src/main/java/com/baeldung/slf4j/Slf4jRollingExample.java b/logging-modules/log4j/src/main/java/com/baeldung/slf4j/Slf4jRollingExample.java similarity index 100% rename from log4j/src/main/java/com/baeldung/slf4j/Slf4jRollingExample.java rename to logging-modules/log4j/src/main/java/com/baeldung/slf4j/Slf4jRollingExample.java diff --git a/log4j/src/main/resources/log4j.xml b/logging-modules/log4j/src/main/resources/log4j.xml similarity index 100% rename from log4j/src/main/resources/log4j.xml rename to logging-modules/log4j/src/main/resources/log4j.xml diff --git a/log4j/src/main/resources/log4j2.xml b/logging-modules/log4j/src/main/resources/log4j2.xml similarity index 100% rename from log4j/src/main/resources/log4j2.xml rename to logging-modules/log4j/src/main/resources/log4j2.xml diff --git a/log4j/src/main/resources/logback.xml b/logging-modules/log4j/src/main/resources/logback.xml similarity index 100% rename from log4j/src/main/resources/logback.xml rename to logging-modules/log4j/src/main/resources/logback.xml diff --git a/log4j2/README.md b/logging-modules/log4j2/README.md similarity index 100% rename from log4j2/README.md rename to logging-modules/log4j2/README.md diff --git a/log4j2/pom.xml b/logging-modules/log4j2/pom.xml similarity index 98% rename from log4j2/pom.xml rename to logging-modules/log4j2/pom.xml index ea398af845..58bc4b74e7 100644 --- a/log4j2/pom.xml +++ b/logging-modules/log4j2/pom.xml @@ -9,7 +9,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - .. + ../ diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java similarity index 100% rename from log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/CustomLoggingIntegrationTest.java diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java similarity index 100% rename from log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/LambdaExpressionsIntegrationTest.java diff --git a/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java similarity index 100% rename from log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/jdbc/ConnectionFactory.java diff --git a/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml b/logging-modules/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml similarity index 100% rename from log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml rename to logging-modules/log4j2/src/test/resources/log4j2-includes/console-appender_pattern-layout_colored.xml diff --git a/log4j2/src/test/resources/log4j2.xml b/logging-modules/log4j2/src/test/resources/log4j2.xml similarity index 100% rename from log4j2/src/test/resources/log4j2.xml rename to logging-modules/log4j2/src/test/resources/log4j2.xml diff --git a/lucene/pom.xml b/lucene/pom.xml new file mode 100644 index 0000000000..6659d9ac32 --- /dev/null +++ b/lucene/pom.xml @@ -0,0 +1,35 @@ + + 4.0.0 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + lucene + 0.0.1-SNAPSHOT + lucene + An Apache Lucene demo application + + + + + org.apache.lucene + lucene-core + 7.1.0 + + + + org.apache.lucene + lucene-queryparser + 7.1.0 + + + + junit + junit + 4.12 + test + + + \ No newline at end of file diff --git a/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java b/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java new file mode 100644 index 0000000000..97b1ec7b5d --- /dev/null +++ b/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java @@ -0,0 +1,128 @@ +package com.baeldung.lucene; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Field; +import org.apache.lucene.document.SortedDocValuesField; +import org.apache.lucene.document.TextField; +import org.apache.lucene.index.DirectoryReader; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.index.IndexWriter; +import org.apache.lucene.index.IndexWriterConfig; +import org.apache.lucene.index.Term; +import org.apache.lucene.queryparser.classic.ParseException; +import org.apache.lucene.queryparser.classic.QueryParser; +import org.apache.lucene.search.IndexSearcher; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.ScoreDoc; +import org.apache.lucene.search.Sort; +import org.apache.lucene.search.TopDocs; +import org.apache.lucene.store.Directory; +import org.apache.lucene.util.BytesRef; + +public class InMemoryLuceneIndex { + + private Directory memoryIndex; + private StandardAnalyzer analyzer; + + public InMemoryLuceneIndex(Directory memoryIndex, StandardAnalyzer analyzer) { + super(); + this.memoryIndex = memoryIndex; + this.analyzer = analyzer; + } + + /** + * + * @param title + * @param body + */ + public void indexDocument(String title, String body) { + + IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); + try { + IndexWriter writter = new IndexWriter(memoryIndex, indexWriterConfig); + Document document = new Document(); + + document.add(new TextField("title", title, Field.Store.YES)); + document.add(new TextField("body", body, Field.Store.YES)); + document.add(new SortedDocValuesField("title", new BytesRef(title))); + + writter.addDocument(document); + writter.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public List searchIndex(String inField, String queryString) { + try { + Query query = new QueryParser(inField, analyzer).parse(queryString); + + IndexReader indexReader = DirectoryReader.open(memoryIndex); + IndexSearcher searcher = new IndexSearcher(indexReader); + TopDocs topDocs = searcher.search(query, 10); + List documents = new ArrayList<>(); + for (ScoreDoc scoreDoc : topDocs.scoreDocs) { + documents.add(searcher.doc(scoreDoc.doc)); + } + + return documents; + } catch (IOException | ParseException e) { + e.printStackTrace(); + } + return null; + + } + + public void deleteDocument(Term term) { + try { + IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); + IndexWriter writter = new IndexWriter(memoryIndex, indexWriterConfig); + writter.deleteDocuments(term); + writter.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public List searchIndex(Query query) { + try { + IndexReader indexReader = DirectoryReader.open(memoryIndex); + IndexSearcher searcher = new IndexSearcher(indexReader); + TopDocs topDocs = searcher.search(query, 10); + List documents = new ArrayList<>(); + for (ScoreDoc scoreDoc : topDocs.scoreDocs) { + documents.add(searcher.doc(scoreDoc.doc)); + } + + return documents; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + + } + + public List searchIndex(Query query, Sort sort) { + try { + IndexReader indexReader = DirectoryReader.open(memoryIndex); + IndexSearcher searcher = new IndexSearcher(indexReader); + TopDocs topDocs = searcher.search(query, 10, sort); + List documents = new ArrayList<>(); + for (ScoreDoc scoreDoc : topDocs.scoreDocs) { + documents.add(searcher.doc(scoreDoc.doc)); + } + + return documents; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + + } + +} diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java new file mode 100644 index 0000000000..acf688cb99 --- /dev/null +++ b/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java @@ -0,0 +1,152 @@ +package com.baeldung.lucene; + +import java.util.List; + +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.BooleanClause; +import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.FuzzyQuery; +import org.apache.lucene.search.PhraseQuery; +import org.apache.lucene.search.PrefixQuery; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.Sort; +import org.apache.lucene.search.SortField; +import org.apache.lucene.search.TermQuery; +import org.apache.lucene.search.WildcardQuery; +import org.apache.lucene.store.RAMDirectory; +import org.apache.lucene.util.BytesRef; +import org.junit.Assert; +import org.junit.Test; + +public class LuceneInMemorySearchTest { + + @Test + public void givenSearchQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("Hello world", "Some hello world "); + + List documents = inMemoryLuceneIndex.searchIndex("body", "world"); + + Assert.assertEquals("Hello world", documents.get(0).get("title")); + } + + @Test + public void givenTermQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("activity", "running in track"); + inMemoryLuceneIndex.indexDocument("activity", "Cars are running on road"); + + Term term = new Term("body", "running"); + Query query = new TermQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(2, documents.size()); + } + + @Test + public void givenPrefixQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("article", "Lucene introduction"); + inMemoryLuceneIndex.indexDocument("article", "Introduction to Lucene"); + + Term term = new Term("body", "intro"); + Query query = new PrefixQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(2, documents.size()); + } + + @Test + public void givenBooleanQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("Destination", "Las Vegas singapore car"); + inMemoryLuceneIndex.indexDocument("Commutes in singapore", "Bus Car Bikes"); + + Term term1 = new Term("body", "singapore"); + Term term2 = new Term("body", "car"); + + TermQuery query1 = new TermQuery(term1); + TermQuery query2 = new TermQuery(term2); + + BooleanQuery booleanQuery = new BooleanQuery.Builder().add(query1, BooleanClause.Occur.MUST) + .add(query2, BooleanClause.Occur.MUST).build(); + + List documents = inMemoryLuceneIndex.searchIndex(booleanQuery); + Assert.assertEquals(1, documents.size()); + } + + @Test + public void givenPhraseQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("quotes", "A rose by any other name would smell as sweet."); + + Query query = new PhraseQuery(1, "body", new BytesRef("smell"), new BytesRef("sweet")); + List documents = inMemoryLuceneIndex.searchIndex(query); + + Assert.assertEquals(1, documents.size()); + } + + @Test + public void givenFuzzyQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("article", "Halloween Festival"); + inMemoryLuceneIndex.indexDocument("decoration", "Decorations for Halloween"); + + Term term = new Term("body", "hallowen"); + Query query = new FuzzyQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(2, documents.size()); + } + + @Test + public void givenWildCardQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("article", "Lucene introduction"); + inMemoryLuceneIndex.indexDocument("article", "Introducing Lucene with Spring"); + + Term term = new Term("body", "intro*"); + Query query = new WildcardQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(2, documents.size()); + } + + @Test + public void givenSortFieldWhenSortedThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("Ganges", "River in India"); + inMemoryLuceneIndex.indexDocument("Mekong", "This river flows in south Asia"); + inMemoryLuceneIndex.indexDocument("Amazon", "Rain forest river"); + inMemoryLuceneIndex.indexDocument("Rhine", "Belongs to Europe"); + inMemoryLuceneIndex.indexDocument("Nile", "Longest River"); + + Term term = new Term("body", "river"); + Query query = new WildcardQuery(term); + + SortField sortField = new SortField("title", SortField.Type.STRING_VAL, false); + Sort sortByTitle = new Sort(sortField); + + List documents = inMemoryLuceneIndex.searchIndex(query, sortByTitle); + Assert.assertEquals(4, documents.size()); + Assert.assertEquals("Amazon", documents.get(0).getField("title").stringValue()); + } + + @Test + public void whenDocumentDeletedThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("Ganges", "River in India"); + inMemoryLuceneIndex.indexDocument("Mekong", "This river flows in south Asia"); + + Term term = new Term("title", "ganges"); + inMemoryLuceneIndex.deleteDocument(term); + + Query query = new TermQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(0, documents.size()); + } + +} \ No newline at end of file diff --git a/metrics/README.md b/metrics/README.md index 09fe925604..c7772bffa0 100644 --- a/metrics/README.md +++ b/metrics/README.md @@ -2,3 +2,4 @@ - [Intro to Dropwizard Metrics](http://www.baeldung.com/dropwizard-metrics) - [Introduction to Netflix Servo](http://www.baeldung.com/netflix-servo) +- [Quick Guide to Micrometer](http://www.baeldung.com/micrometer) diff --git a/muleesb/.gitignore b/muleesb/.gitignore new file mode 100644 index 0000000000..541f92c42e --- /dev/null +++ b/muleesb/.gitignore @@ -0,0 +1 @@ +# Add any directories, files, or patterns you don't want to be tracked by version control \ No newline at end of file diff --git a/muleesb/.mule/objectstore/b2fe1a90-c473-11e7-8eb5-98e7f44e8ac8/partition-descriptor b/muleesb/.mule/objectstore/b2fe1a90-c473-11e7-8eb5-98e7f44e8ac8/partition-descriptor new file mode 100644 index 0000000000..0b8060f303 --- /dev/null +++ b/muleesb/.mule/objectstore/b2fe1a90-c473-11e7-8eb5-98e7f44e8ac8/partition-descriptor @@ -0,0 +1 @@ +DEFAULT_PARTITION \ No newline at end of file diff --git a/muleesb/.mule/queue-tx-log/tx1.log b/muleesb/.mule/queue-tx-log/tx1.log new file mode 100644 index 0000000000..e69de29bb2 diff --git a/muleesb/.mule/queue-tx-log/tx2.log b/muleesb/.mule/queue-tx-log/tx2.log new file mode 100644 index 0000000000..e69de29bb2 diff --git a/muleesb/.mule/queue-xa-tx-log/tx1.log b/muleesb/.mule/queue-xa-tx-log/tx1.log new file mode 100644 index 0000000000..e69de29bb2 diff --git a/muleesb/.mule/queue-xa-tx-log/tx2.log b/muleesb/.mule/queue-xa-tx-log/tx2.log new file mode 100644 index 0000000000..e69de29bb2 diff --git a/muleesb/mule-project.xml b/muleesb/mule-project.xml new file mode 100644 index 0000000000..0d522b0141 --- /dev/null +++ b/muleesb/mule-project.xml @@ -0,0 +1,5 @@ + + + muleesb + + diff --git a/muleesb/pom.xml b/muleesb/pom.xml new file mode 100644 index 0000000000..2c88bf83da --- /dev/null +++ b/muleesb/pom.xml @@ -0,0 +1,214 @@ + + + + 4.0.0 + com.mycompany + muleesb + 1.0.0-SNAPSHOT + mule + Mule muleesb Application + + + UTF-8 + UTF-8 + + 3.8.1 + 1.2 + 1.3.6 + 3.9.0 + + + + + + org.mule.tools.maven + mule-app-maven-plugin + ${mule.tools.version} + true + + true + + + + org.mule.tools + muleesb-maven-plugin + 1.0 + + 3.7.0 + /home/abir/AnypointStudio/workspace/variablescopetest + + + + deploy + + start + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.7 + + + add-resource + generate-resources + + add-resource + + + + + src/main/app/ + + + mappings/ + + + src/main/api/ + + + + + + + + com.mulesoft.munit.tools + munit-maven-plugin + ${munit.version} + + + test + test + + test + + + + + + true + + html + + + + + + + + src/test/munit + + + src/test/resources + + + + + + + + + org.mule.modules + mule-module-spring-config + ${mule.version} + provided + + + + org.mule.transports + mule-transport-file + ${mule.version} + provided + + + org.mule.transports + mule-transport-http + ${mule.version} + provided + + + org.mule.transports + mule-transport-jdbc + ${mule.version} + provided + + + org.mule.transports + mule-transport-jms + ${mule.version} + provided + + + org.mule.transports + mule-transport-vm + ${mule.version} + provided + + + + org.mule.modules + mule-module-scripting + ${mule.version} + provided + + + org.mule.modules + mule-module-xml + ${mule.version} + provided + + + + org.mule.tests + mule-tests-functional + ${mule.version} + test + + + org.mule.modules + mule-module-apikit + ${mule.version} + provided + + + com.mulesoft.munit + mule-munit-support + ${mule.munit.support.version} + test + + + com.mulesoft.munit + munit-runner + ${munit.version} + test + + + + + + Central + Central + http://repo1.maven.org/maven2/ + default + + + mulesoft-releases + MuleSoft Releases Repository + http://repository.mulesoft.org/releases/ + default + + + + + mulesoft-release + mulesoft release repository + default + http://repository.mulesoft.org/releases/ + + false + + + + diff --git a/muleesb/src/main/app/mule-app.properties b/muleesb/src/main/app/mule-app.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/muleesb/src/main/app/mule-deploy.properties b/muleesb/src/main/app/mule-deploy.properties new file mode 100644 index 0000000000..07eabe9cc6 --- /dev/null +++ b/muleesb/src/main/app/mule-deploy.properties @@ -0,0 +1,6 @@ +#** GENERATED CONTENT ** Mule Application Deployment Descriptor +#Mon Nov 06 15:54:37 BDT 2017 +redeployment.enabled=true +encoding=UTF-8 +domain=default +config.resources=variablescopetest.xml diff --git a/muleesb/src/main/app/variablescopetest.xml b/muleesb/src/main/app/variablescopetest.xml new file mode 100644 index 0000000000..518b901084 --- /dev/null +++ b/muleesb/src/main/app/variablescopetest.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/muleesb/src/main/java/com/baeldung/transformer/FromFlow2Component.java b/muleesb/src/main/java/com/baeldung/transformer/FromFlow2Component.java new file mode 100644 index 0000000000..0e180062a7 --- /dev/null +++ b/muleesb/src/main/java/com/baeldung/transformer/FromFlow2Component.java @@ -0,0 +1,18 @@ +package com.baeldung.transformer; + +import org.mule.api.MuleEventContext; +import org.mule.api.MuleMessage; +import org.mule.api.lifecycle.Callable; + +public class FromFlow2Component implements Callable { + + @Override + public Object onCall(MuleEventContext eventContext) throws Exception { + + MuleMessage message = eventContext.getMessage(); + message.setPayload("Converted in flow 2"); + + return message; + } + +} diff --git a/muleesb/src/main/java/com/baeldung/transformer/InitializationTransformer.java b/muleesb/src/main/java/com/baeldung/transformer/InitializationTransformer.java new file mode 100644 index 0000000000..1e1ad15be8 --- /dev/null +++ b/muleesb/src/main/java/com/baeldung/transformer/InitializationTransformer.java @@ -0,0 +1,29 @@ +package com.baeldung.transformer; + +import org.mule.api.MuleMessage; +import org.mule.api.transformer.TransformerException; +import org.mule.api.transport.PropertyScope; +import org.mule.transformer.AbstractMessageTransformer; + +public class InitializationTransformer extends AbstractMessageTransformer { + + @Override + public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException { + // TODO Auto-generated method stub + + String payload = null; + + try { + payload = message.getPayloadAsString(); + }catch (Exception e) { + e.printStackTrace(); + } + + System.out.println("Logged Payload: "+payload); + message.setPayload("Payload from Initialization"); + message.setProperty("outboundKey", "outboundpropertyvalue",PropertyScope.OUTBOUND); + + + return message; + } +} \ No newline at end of file diff --git a/muleesb/src/main/java/com/baeldung/transformer/InvokingMessageComponent.java b/muleesb/src/main/java/com/baeldung/transformer/InvokingMessageComponent.java new file mode 100644 index 0000000000..105522e5b4 --- /dev/null +++ b/muleesb/src/main/java/com/baeldung/transformer/InvokingMessageComponent.java @@ -0,0 +1,16 @@ +package com.baeldung.transformer; + +import org.mule.api.MuleMessage; +import org.mule.api.transformer.TransformerException; +import org.mule.transformer.AbstractMessageTransformer; + +public class InvokingMessageComponent extends AbstractMessageTransformer { + + @Override + public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException { + // TODO Auto-generated method stub + String InboundProp = (String) message.getInboundProperty("outboundKey"); + System.out.println("InboundProp:" + InboundProp); + return InboundProp; + } +} \ No newline at end of file diff --git a/muleesb/src/main/resources/log4j2.xml b/muleesb/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..98c4b02433 --- /dev/null +++ b/muleesb/src/main/resources/log4j2.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/muleesb/src/test/munit/variablescopetest-test-suite.xml b/muleesb/src/test/munit/variablescopetest-test-suite.xml new file mode 100644 index 0000000000..43e410a327 --- /dev/null +++ b/muleesb/src/test/munit/variablescopetest-test-suite.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/muleesb/src/test/resources/log4j2-test.xml b/muleesb/src/test/resources/log4j2-test.xml new file mode 100644 index 0000000000..6351ae041c --- /dev/null +++ b/muleesb/src/test/resources/log4j2-test.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/mustache/pom.xml b/mustache/pom.xml index 8aab038313..230aeecd60 100644 --- a/mustache/pom.xml +++ b/mustache/pom.xml @@ -85,7 +85,6 @@ **/JdbcTest.java **/*LiveTest.java - true diff --git a/noexception/README.md b/noexception/README.md index d840191369..9dd4c11190 100644 --- a/noexception/README.md +++ b/noexception/README.md @@ -1,2 +1,2 @@ ### Relevant Articles: -- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception) +- [Introduction to NoException](http://www.baeldung.com/introduction-to-noexception) diff --git a/osgi/osgi-intro-sample-activator/pom.xml b/osgi/osgi-intro-sample-activator/pom.xml new file mode 100644 index 0000000000..1584913627 --- /dev/null +++ b/osgi/osgi-intro-sample-activator/pom.xml @@ -0,0 +1,55 @@ + + + + + + osgi-intro + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + + bundle + + osgi-intro-sample-activator + + + + org.osgi + org.osgi.core + + + + + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.groupId}.${project.artifactId} + ${project.artifactId} + ${project.version} + + + com.baeldung.osgi.sample.activator.HelloWorld + + + + com.baeldung.osgi.sample.activator + + + + + + + + diff --git a/osgi/osgi-intro-sample-activator/src/main/java/com/baeldung/osgi/sample/activator/HelloWorld.java b/osgi/osgi-intro-sample-activator/src/main/java/com/baeldung/osgi/sample/activator/HelloWorld.java new file mode 100644 index 0000000000..72fe624bac --- /dev/null +++ b/osgi/osgi-intro-sample-activator/src/main/java/com/baeldung/osgi/sample/activator/HelloWorld.java @@ -0,0 +1,16 @@ +package com.baeldung.osgi.sample.activator; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +public class HelloWorld implements BundleActivator { + + public void start(BundleContext ctx) { + System.out.println("Hello World."); + } + + public void stop(BundleContext bundleContext) { + System.out.println("Goodbye World."); + } + +} \ No newline at end of file diff --git a/osgi/osgi-intro-sample-client/pom.xml b/osgi/osgi-intro-sample-client/pom.xml new file mode 100644 index 0000000000..4096674d7d --- /dev/null +++ b/osgi/osgi-intro-sample-client/pom.xml @@ -0,0 +1,49 @@ + + + + osgi-intro + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + + osgi-intro-sample-client + + bundle + + + + com.baeldung + osgi-intro-sample-service + 1.0-SNAPSHOT + + + org.osgi + org.osgi.core + + + + + + + org.apache.felix + maven-bundle-plugin + + + ${project.groupId}.${project.artifactId} + ${project.artifactId} + ${project.version} + com.baeldung.osgi.sample.client.Client + + com.baeldung.osgi.sample.client + + + + + + + + \ No newline at end of file diff --git a/osgi/osgi-intro-sample-client/src/main/java/com/baeldung/osgi/sample/client/Client.java b/osgi/osgi-intro-sample-client/src/main/java/com/baeldung/osgi/sample/client/Client.java new file mode 100644 index 0000000000..a82ed63fa7 --- /dev/null +++ b/osgi/osgi-intro-sample-client/src/main/java/com/baeldung/osgi/sample/client/Client.java @@ -0,0 +1,44 @@ +package com.baeldung.osgi.sample.client; + +import com.baeldung.osgi.sample.service.definition.Greeter; +import org.osgi.framework.*; + +public class Client implements BundleActivator, ServiceListener { + + private BundleContext ctx; + private ServiceReference serviceReference; + + public void start(BundleContext ctx) { + this.ctx = ctx; + try { + ctx.addServiceListener(this, "(objectclass=" + Greeter.class.getName() + ")"); + } catch (InvalidSyntaxException ise) { + ise.printStackTrace(); + } + } + + public void stop(BundleContext bundleContext) { + if (serviceReference != null) { + ctx.ungetService(serviceReference); + } + this.ctx = null; + } + + public void serviceChanged(ServiceEvent serviceEvent) { + int type = serviceEvent.getType(); + switch (type) { + case (ServiceEvent.REGISTERED): + System.out.println("Notification of service registered."); + serviceReference = serviceEvent.getServiceReference(); + Greeter service = (Greeter) (ctx.getService(serviceReference)); + System.out.println(service.sayHiTo("John")); + break; + case (ServiceEvent.UNREGISTERING): + System.out.println("Notification of service unregistered."); + ctx.ungetService(serviceEvent.getServiceReference()); + break; + default: + break; + } + } +} diff --git a/osgi/osgi-intro-sample-service/pom.xml b/osgi/osgi-intro-sample-service/pom.xml new file mode 100644 index 0000000000..cbc660bb74 --- /dev/null +++ b/osgi/osgi-intro-sample-service/pom.xml @@ -0,0 +1,46 @@ + + + + + + osgi-intro + com.baeldung + 1.0-SNAPSHOT + + 4.0.0 + + osgi-intro-sample-service + + + bundle + + + + org.osgi + org.osgi.core + + + + + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.groupId}.${project.artifactId} + ${project.artifactId} + ${project.version} + com.baeldung.osgi.sample.service.implementation.GreeterImpl + com.baeldung.osgi.sample.service.implementation + com.baeldung.osgi.sample.service.definition + + + + + + + \ No newline at end of file diff --git a/osgi/osgi-intro-sample-service/src/main/java/com/baeldung/osgi/sample/service/definition/Greeter.java b/osgi/osgi-intro-sample-service/src/main/java/com/baeldung/osgi/sample/service/definition/Greeter.java new file mode 100644 index 0000000000..f1e82a3465 --- /dev/null +++ b/osgi/osgi-intro-sample-service/src/main/java/com/baeldung/osgi/sample/service/definition/Greeter.java @@ -0,0 +1,7 @@ +package com.baeldung.osgi.sample.service.definition; + +public interface Greeter { + + public String sayHiTo(String name); + +} diff --git a/osgi/osgi-intro-sample-service/src/main/java/com/baeldung/osgi/sample/service/implementation/GreeterImpl.java b/osgi/osgi-intro-sample-service/src/main/java/com/baeldung/osgi/sample/service/implementation/GreeterImpl.java new file mode 100644 index 0000000000..48e26e3e6b --- /dev/null +++ b/osgi/osgi-intro-sample-service/src/main/java/com/baeldung/osgi/sample/service/implementation/GreeterImpl.java @@ -0,0 +1,30 @@ +package com.baeldung.osgi.sample.service.implementation; + +import com.baeldung.osgi.sample.service.definition.Greeter; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.ServiceRegistration; + +import java.util.Hashtable; + +public class GreeterImpl implements Greeter, BundleActivator { + + private ServiceReference reference; + private ServiceRegistration registration; + + @Override public String sayHiTo(String name) { + return "Hello " + name; + } + + @Override public void start(BundleContext context) throws Exception { + System.out.println("Registering service."); + registration = context.registerService(Greeter.class, new GreeterImpl(), new Hashtable()); + reference = registration.getReference(); + } + + @Override public void stop(BundleContext context) throws Exception { + System.out.println("Unregistering service."); + registration.unregister(); + } +} diff --git a/osgi/pom.xml b/osgi/pom.xml new file mode 100644 index 0000000000..e6ef9c3192 --- /dev/null +++ b/osgi/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + osgi-intro + pom + 1.0-SNAPSHOT + + osgi-intro-sample-activator + osgi-intro-sample-service + osgi-intro-sample-client + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + + + + ${project.groupId} + osgi-intro-client + ${project.version} + + + + ${project.groupId} + osgi-intro-service + ${project.version} + + + + ${project.groupId} + osgi-intro-gxyz + ${project.version} + + + + ${project.groupId} + osgi-intro-mapquest + ${project.version} + + + + com.squareup.okhttp3 + okhttp + 3.9.0 + + + javax.json + javax.json-api + 1.1 + + + org.glassfish + javax.json + 1.1 + + + org.osgi + org.osgi.core + 6.0.0 + provided + + + + + + + + + org.apache.felix + maven-bundle-plugin + 3.3.0 + true + + + + + + \ No newline at end of file diff --git a/osgi/readme.md b/osgi/readme.md new file mode 100644 index 0000000000..ea4a411c7b --- /dev/null +++ b/osgi/readme.md @@ -0,0 +1,91 @@ +OSGi +==== + +Info +--- + +com.baeldung.osgi +com.baeldung.osgi.sample.activator + +Apache Felix +--- + + +### Start + +Download Apache Felix Framework Distribution +from +org.apache.felix.main.distribution-5.6.8 + +No! The Apache Karaf container is best. +Download it from: + +Download a binary distribution and unzip wherever you prefer. + +Then run + + bin\karaf.bat start + + +Unzip, pay attention to the files not being clipped(!). + + system:exit + +exit! + + shutdown -h + +or `^D` + +### clean start + +full clean, remove "data directory " + +or... + + bin\karaf.bat clean + + bin\start.bat clean + +### run mode + +can be launched in + +- the "regular" mode starts Apache Karaf in foreground, including the shell console. +- the "server" mode starts Apache Karaf in foreground, without the shell console. +- the "background" mode starts Apache Karaf in background. + +### Logging + +https://karaf.apache.org/manual/latest/#_log + +can be logged to console + + +### Bundle deploy + + bundle:install mvn:com.baeldung/osgi-intro-sample-activator/1.0-SNAPSHOT + + install mvn:com.baeldung/osgi-intro-sample-service/1.0-SNAPSHOT + install mvn:com.baeldung/osgi-intro-sample-client/1.0-SNAPSHOT + +Eclipse's Equinox +==== + +Eclipse's OSGi platform +http://www.eclipse.org/equinox/ + +http://www.eclipse.org/equinox/documents/quickstart-framework.php + +click on "download" + +Latest Release +Oxygen.1 Wed, 6 Sep 2017 -- 17:00 (-0400) + +org.eclipse.osgi_3.12.1.v20170821-1548.jar + + = = NOT GOOD = = + + + + diff --git a/parent-boot-4/pom.xml b/parent-boot-4/pom.xml index 2af36e9365..608e57ddaf 100644 --- a/parent-boot-4/pom.xml +++ b/parent-boot-4/pom.xml @@ -63,7 +63,7 @@ **/JdbcTest.java **/*LiveTest.java - true + diff --git a/parent-boot-5/pom.xml b/parent-boot-5/pom.xml index 57e9ed3c67..2fa397f298 100644 --- a/parent-boot-5/pom.xml +++ b/parent-boot-5/pom.xml @@ -65,7 +65,6 @@ **/*EntryPointsTest.java **/*LiveTest.java - true diff --git a/patterns/README.md b/patterns/README.md index bcd54a64b1..67d84154cb 100644 --- a/patterns/README.md +++ b/patterns/README.md @@ -1,3 +1,4 @@ ###Relevant Articles: - [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern) - [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java) +- [Implementing the Template Method Pattern in Java](http://www.baeldung.com/template-method-pattern-in-java) diff --git a/patterns/template-method/pom.xml b/patterns/behavioral-patterns/pom.xml similarity index 56% rename from patterns/template-method/pom.xml rename to patterns/behavioral-patterns/pom.xml index c3b6a084ac..3c40520ce1 100644 --- a/patterns/template-method/pom.xml +++ b/patterns/behavioral-patterns/pom.xml @@ -1,15 +1,17 @@ 4.0.0 - com.baeldung.templatemethodpattern - templatemethodpattern + com.baeldung.pattern.templatemethod + pattern.templatemethod 1.0 jar - - UTF-8 - 1.8 - 1.8 - + + com.baeldung.patterns + patterns-parent + 1.0.0-SNAPSHOT + .. + + junit @@ -18,4 +20,18 @@ test + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + + + + UTF-8 + 1.8 + 1.8 + \ No newline at end of file diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/application/Application.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/application/Application.java new file mode 100644 index 0000000000..9ab34c3cd8 --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/application/Application.java @@ -0,0 +1,21 @@ +package com.baeldung.pattern.templatemethod.application; + +import com.baeldung.pattern.templatemethod.model.Computer; +import com.baeldung.pattern.templatemethod.model.StandardComputer; +import com.baeldung.pattern.templatemethod.model.HighEndComputer; +import com.baeldung.pattern.templatemethod.model.ComputerBuilder; +import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder; +import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder; + +public class Application { + + public static void main(String[] args) { + ComputerBuilder standardComputerBuilder = new StandardComputerBuilder(); + Computer standardComputer = standardComputerBuilder.buildComputer(); + standardComputer.getComputerParts().forEach((k, v) -> System.out.println("Part : " + k + " Value : " + v)); + + ComputerBuilder highEndComputerBuilder = new HighEndComputerBuilder(); + Computer highEndComputer = highEndComputerBuilder.buildComputer(); + highEndComputer.getComputerParts().forEach((k, v) -> System.out.println("Part : " + k + " Value : " + v)); + } +} diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/Computer.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/Computer.java new file mode 100644 index 0000000000..1419398f62 --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/Computer.java @@ -0,0 +1,17 @@ +package com.baeldung.pattern.templatemethod.model; + +import java.util.HashMap; +import java.util.Map; + +public class Computer { + + private Map computerParts = new HashMap<>(); + + public Computer(Map computerParts) { + this.computerParts = computerParts; + } + + public Map getComputerParts() { + return computerParts; + } +} diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/ComputerBuilder.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/ComputerBuilder.java new file mode 100644 index 0000000000..515a6940f5 --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/ComputerBuilder.java @@ -0,0 +1,38 @@ +package com.baeldung.pattern.templatemethod.model; + +import com.baeldung.pattern.templatemethod.model.Computer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public abstract class ComputerBuilder { + + protected Map computerParts = new HashMap<>(); + protected List motherboardSetupStatus = new ArrayList<>(); + + public final Computer buildComputer() { + addMotherboard(); + setupMotherboard(); + addProcessor(); + return getComputer(); + } + + public abstract void addMotherboard(); + + public abstract void setupMotherboard(); + + public abstract void addProcessor(); + + public List getMotherboardSetupStatus() { + return motherboardSetupStatus; + } + + public Map getComputerParts() { + return computerParts; + } + + private Computer getComputer() { + return new Computer(computerParts); + } +} diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/HighEndComputer.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/HighEndComputer.java new file mode 100644 index 0000000000..0684b1b233 --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/HighEndComputer.java @@ -0,0 +1,11 @@ +package com.baeldung.pattern.templatemethod.model; + +import com.baeldung.pattern.templatemethod.model.Computer; +import java.util.Map; + +public class HighEndComputer extends Computer { + + public HighEndComputer(Map computerParts) { + super(computerParts); + } +} diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/HighEndComputerBuilder.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/HighEndComputerBuilder.java new file mode 100644 index 0000000000..c992aa2bff --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/HighEndComputerBuilder.java @@ -0,0 +1,21 @@ +package com.baeldung.pattern.templatemethod.model; + +public class HighEndComputerBuilder extends ComputerBuilder { + + @Override + public void addMotherboard() { + computerParts.put("Motherboard", "High-end Motherboard"); + } + + @Override + public void setupMotherboard() { + motherboardSetupStatus.add("Screwing the high-end motherboard to the case."); + motherboardSetupStatus.add("Pluging in the power supply connectors."); + motherboardSetupStatus.forEach(step -> System.out.println(step)); + } + + @Override + public void addProcessor() { + computerParts.put("Processor", "High-end Processor"); + } +} diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/StandardComputer.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/StandardComputer.java new file mode 100644 index 0000000000..4e1d857016 --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/StandardComputer.java @@ -0,0 +1,11 @@ +package com.baeldung.pattern.templatemethod.model; + +import com.baeldung.pattern.templatemethod.model.Computer; +import java.util.Map; + +public class StandardComputer extends Computer { + + public StandardComputer(Map computerParts) { + super(computerParts); + } +} diff --git a/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/StandardComputerBuilder.java b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/StandardComputerBuilder.java new file mode 100644 index 0000000000..cc81dddc1b --- /dev/null +++ b/patterns/behavioral-patterns/src/main/java/com/baeldung/pattern/templatemethod/model/StandardComputerBuilder.java @@ -0,0 +1,21 @@ +package com.baeldung.pattern.templatemethod.model; + +public class StandardComputerBuilder extends ComputerBuilder { + + @Override + public void addMotherboard() { + computerParts.put("Motherboard", "Standard Motherboard"); + } + + @Override + public void setupMotherboard() { + motherboardSetupStatus.add("Screwing the standard motherboard to the case."); + motherboardSetupStatus.add("Pluging in the power supply connectors."); + motherboardSetupStatus.forEach(step -> System.out.println(step)); + } + + @Override + public void addProcessor() { + computerParts.put("Processor", "Standard Processor"); + } +} diff --git a/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/templatemethod/test/TemplateMethodPatternTest.java b/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/templatemethod/test/TemplateMethodPatternTest.java new file mode 100644 index 0000000000..679559af9f --- /dev/null +++ b/patterns/behavioral-patterns/src/test/java/com/baeldung/pattern/templatemethod/test/TemplateMethodPatternTest.java @@ -0,0 +1,87 @@ +package com.baeldung.pattern.templatemethod.test; + +import com.baeldung.pattern.templatemethod.model.Computer; +import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder; +import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder; +import org.junit.Assert; +import static org.junit.Assert.assertEquals; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.assertThat; + +public class TemplateMethodPatternTest { + + private static StandardComputerBuilder standardComputerBuilder; + private static HighEndComputerBuilder highEndComputerBuilder; + + @BeforeClass + public static void setUpStandardComputerBuilderInstance() { + standardComputerBuilder = new StandardComputerBuilder(); + } + + @BeforeClass + public static void setUpHighEndComputerBuilderInstance() { + highEndComputerBuilder = new HighEndComputerBuilder(); + } + + @Test + public void givenStandardMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { + standardComputerBuilder.addMotherboard(); + assertEquals("Standard Motherboard", standardComputerBuilder.getComputerParts().get("Motherboard")); + } + + @Test + public void givenStandardMotherboard_whenSetup_thenTwoEqualAssertions() { + standardComputerBuilder.setupMotherboard(); + assertEquals("Screwing the standard motherboard to the case.", standardComputerBuilder.getMotherboardSetupStatus().get(0)); + assertEquals("Pluging in the power supply connectors.", standardComputerBuilder.getMotherboardSetupStatus().get(1)); + } + + @Test + public void givenStandardProcessor_whenAddingProcessor_thenEqualAssertion() { + standardComputerBuilder.addProcessor(); + assertEquals("Standard Processor", standardComputerBuilder.getComputerParts().get("Processor")); + } + + @Test + public void givenAllStandardParts_whenBuildingComputer_thenTwoParts() { + standardComputerBuilder.buildComputer(); + assertEquals(2, standardComputerBuilder.getComputerParts().size()); + } + + @Test + public void givenAllStandardParts_whenComputerisBuilt_thenComputerInstance() { + assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class)); + } + + @Test + public void givenHighEnddMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { + highEndComputerBuilder.addMotherboard(); + Assert.assertEquals("High-end Motherboard", highEndComputerBuilder.getComputerParts().get("Motherboard")); + } + + @Test + public void givenHighEnddMotheroboard_whenSetup_thenTwoEqualAssertions() { + highEndComputerBuilder.setupMotherboard(); + assertEquals("Screwing the high-end motherboard to the case.", highEndComputerBuilder.getMotherboardSetupStatus().get(0)); + assertEquals("Pluging in the power supply connectors.", highEndComputerBuilder.getMotherboardSetupStatus().get(1)); + } + + @Test + public void givenHightEndProcessor_whenAddingProcessor_thenEqualAssertion() { + highEndComputerBuilder.addProcessor(); + assertEquals("High-end Processor", highEndComputerBuilder.getComputerParts().get("Processor")); + } + + @Test + public void givenAllHighEnddParts_whenBuildingComputer_thenTwoParts() { + highEndComputerBuilder.buildComputer(); + assertEquals(2, highEndComputerBuilder.getComputerParts().size()); + } + + @Test + public void givenAllHighEndParts_whenComputerisBuilt_thenComputerInstance() { + assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class)); + } +} diff --git a/patterns/pom.xml b/patterns/pom.xml index c40d7c58b7..1462952e37 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -9,6 +9,7 @@ front-controller intercepting-filter + behavioral-patterns @@ -51,4 +52,4 @@ 3.0.0 9.4.0.v20161208
- + \ No newline at end of file diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/application/Application.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/application/Application.java deleted file mode 100644 index 581c774f52..0000000000 --- a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/application/Application.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.templatemethodpattern.application; - -import com.baeldung.templatemethodpattern.model.Computer; -import com.baeldung.templatemethodpattern.model.HighEndComputer; -import com.baeldung.templatemethodpattern.model.StandardComputer; - -public class Application { - - public static void main(String[] args) { - Computer standardComputer = new StandardComputer(); - standardComputer.buildComputer(); - standardComputer.getComputerParts().forEach((k, v) -> System.out.println("Part : " + k + " Value : " + v)); - - Computer highEndComputer = new HighEndComputer(); - highEndComputer.buildComputer(); - highEndComputer.getComputerParts().forEach((k, v) -> System.out.println("Part : " + k + " Value : " + v)); - } -} diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java deleted file mode 100644 index c5d1a2cde8..0000000000 --- a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/Computer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.templatemethodpattern.model; - -import java.util.HashMap; -import java.util.Map; - -public abstract class Computer { - - protected Map computerParts = new HashMap<>(); - - public final void buildComputer() { - addMotherboard(); - addProcessor(); - addMemory(); - addHardDrive(); - addGraphicCard(); - addSoundCard(); - } - - public abstract void addProcessor(); - - public abstract void addMotherboard(); - - public abstract void addMemory(); - - public abstract void addHardDrive(); - - public abstract void addGraphicCard(); - - public abstract void addSoundCard(); - - public Map getComputerParts() { - return computerParts; - } -} diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java deleted file mode 100644 index 11baeca6f7..0000000000 --- a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/HighEndComputer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.templatemethodpattern.model; - -public class HighEndComputer extends Computer { - - @Override - public void addProcessor() { - computerParts.put("Processor", "High End Processor"); - } - - @Override - public void addMotherboard() { - computerParts.put("Motherboard", "High End Motherboard"); - } - - @Override - public void addMemory() { - computerParts.put("Memory", "16GB"); - } - - @Override - public void addHardDrive() { - computerParts.put("Hard Drive", "2TB Hard Drive"); - } - - @Override - public void addGraphicCard() { - computerParts.put("Graphic Card", "High End Graphic Card"); - } - - @Override - public void addSoundCard() { - computerParts.put("Sound Card", "High End Sound Card"); - } -} diff --git a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java b/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java deleted file mode 100644 index 22ff370203..0000000000 --- a/patterns/template-method/src/main/java/com/baeldung/templatemethodpattern/model/StandardComputer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.templatemethodpattern.model; - -public class StandardComputer extends Computer { - - @Override - public void addProcessor() { - computerParts.put("Processor", "Standard Processor"); - } - - @Override - public void addMotherboard() { - computerParts.put("Motherboard", "Standard Motherboard"); - } - - @Override - public void addMemory() { - computerParts.put("Memory", "8GB"); - } - - @Override - public void addHardDrive() { - computerParts.put("Hard Drive", "1TB Hard Drive"); - } - - @Override - public void addGraphicCard() { - computerParts.put("Graphic Card", "Standard Graphic Card"); - } - - @Override - public void addSoundCard() { - computerParts.put("Sound Card", "Standard Sound Card"); - } -} diff --git a/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java b/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java deleted file mode 100644 index afe66883ac..0000000000 --- a/patterns/template-method/src/test/java/com/baeldung/templatemethodpatterntest/TemplateMethodPatternTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.baeldung.templatemethodpatterntest; - -import com.baeldung.templatemethodpattern.model.HighEndComputer; -import com.baeldung.templatemethodpattern.model.StandardComputer; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - -public class TemplateMethodPatternTest { - - private static StandardComputer standardComputer; - private static HighEndComputer highEndComputer; - - @BeforeClass - public static void setUpStandardComputerInstance() { - standardComputer = new StandardComputer(); - } - - @BeforeClass - public static void setUpHighEndComputerInstance() { - highEndComputer = new HighEndComputer(); - } - - @Test - public void givenStandardProcessor_whenAddingProcessor_thenEqualAssertion() { - standardComputer.addProcessor(); - Assert.assertEquals("Standard Processor", standardComputer - .getComputerParts().get("Processor")); - } - - @Test - public void givenStandardMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { - standardComputer.addMotherboard(); - Assert.assertEquals("Standard Motherboard", standardComputer - .getComputerParts().get("Motherboard")); - } - - @Test - public void givenStandardMemory_whenAddingMemory_thenEqualAssertion() { - standardComputer.addMemory(); - Assert.assertEquals("8GB", standardComputer - .getComputerParts().get("Memory")); - } - - @Test - public void givenStandardHardDrive_whenAddingHardDrive_thenEqualAssertion() { - standardComputer.addHardDrive(); - Assert.assertEquals("1TB Hard Drive", standardComputer - .getComputerParts().get("Hard Drive")); - } - - @Test - public void givenStandardGraphicaCard_whenAddingGraphicCard_thenEqualAssertion() { - standardComputer.addGraphicCard(); - Assert.assertEquals("Standard Graphic Card", standardComputer - .getComputerParts().get("Graphic Card")); - } - - @Test - public void givenStandardSoundCard_whenAddingSoundCard_thenEqualAssertion() { - standardComputer.addSoundCard(); - Assert.assertEquals("Standard Sound Card", standardComputer - .getComputerParts().get("Sound Card")); - } - - @Test - public void givenAllStandardParts_whenBuildingComputer_thenSixParts() { - standardComputer.buildComputer(); - Assert.assertEquals(6, standardComputer - .getComputerParts().size()); - } - - @Test - public void givenHightEndProcessor_whenAddingProcessor_thenEqualAssertion() { - highEndComputer.addProcessor(); - Assert.assertEquals("High End Processor", highEndComputer - .getComputerParts().get("Processor")); - } - - @Test - public void givenHighEnddMotherBoard_whenAddingMotherBoard_thenEqualAssertion() { - highEndComputer.addMotherboard(); - Assert.assertEquals("High End Motherboard", highEndComputer - .getComputerParts().get("Motherboard")); - } - - @Test - public void givenHighEndMemory_whenAddingMemory_thenEqualAssertion() { - highEndComputer.addMemory(); - Assert.assertEquals("16GB", highEndComputer - .getComputerParts().get("Memory")); - } - - @Test - public void givenHighEndHardDrive_whenAddingHardDrive_thenEqualAssertion() { - highEndComputer.addHardDrive(); - Assert.assertEquals("2TB Hard Drive", highEndComputer - .getComputerParts().get("Hard Drive")); - } - - @Test - public void givenHighEndGraphicCard_whenAddingGraphicCard_thenEqualAssertion() { - highEndComputer.addGraphicCard(); - Assert.assertEquals("High End Graphic Card", highEndComputer - .getComputerParts().get("Graphic Card")); - } - - @Test - public void givenHighEndSoundCard_whenAddingSoundCard_thenEqualAssertion() { - highEndComputer.addSoundCard(); - Assert.assertEquals("High End Sound Card", highEndComputer - .getComputerParts().get("Sound Card")); - } - - @Test - public void givenAllHighEndParts_whenBuildingComputer_thenSixParts() { - highEndComputer.buildComputer(); - Assert.assertEquals(6, highEndComputer.getComputerParts().size()); - } -} diff --git a/persistence-modules/README.md b/persistence-modules/README.md new file mode 100644 index 0000000000..6c2b1d2ca9 --- /dev/null +++ b/persistence-modules/README.md @@ -0,0 +1,3 @@ + +## Persistence Modules + diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java index 61d821e85e..614de6d3ad 100644 --- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.hibernate.manytomany; - import java.util.HashSet; import java.util.Set; import org.hibernate.Session; @@ -17,10 +16,8 @@ import com.baeldung.hibernate.manytomany.model.Employee; import com.baeldung.hibernate.manytomany.model.Project; import com.baeldung.manytomany.spring.PersistenceConfig; - - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest { @Autowired @@ -28,7 +25,6 @@ public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest { private Session session; - @Before public final void before() { session = sessionFactory.openSession(); @@ -43,11 +39,11 @@ public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest { @Test public final void whenEntitiesAreCreated_thenNoExceptions() { - Set projects = new HashSet(); - projects.add(new Project("IT Project")); - projects.add(new Project("Networking Project")); - session.persist(new Employee("Peter", "Oven", projects)); - session.persist(new Employee("Allan", "Norman", projects)); + Set projects = new HashSet(); + projects.add(new Project("IT Project")); + projects.add(new Project("Networking Project")); + session.persist(new Employee("Peter", "Oven", projects)); + session.persist(new Employee("Allan", "Norman", projects)); } } diff --git a/spring-jpa/src/test/resources/.gitignore b/persistence-modules/spring-jpa/.gitignore similarity index 100% rename from spring-jpa/src/test/resources/.gitignore rename to persistence-modules/spring-jpa/.gitignore diff --git a/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md similarity index 100% rename from spring-jpa/README.md rename to persistence-modules/spring-jpa/README.md diff --git a/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml similarity index 99% rename from spring-jpa/pom.xml rename to persistence-modules/spring-jpa/pom.xml index 960dcbc588..04c64fafc3 100644 --- a/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -13,6 +13,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java diff --git a/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfig.java diff --git a/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java diff --git a/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigXml.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigXml.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigXml.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigXml.java diff --git a/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/config/ProductConfig.java diff --git a/spring-jpa/src/main/java/org/baeldung/config/SpringWebConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/SpringWebConfig.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/config/SpringWebConfig.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/config/SpringWebConfig.java diff --git a/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJPAH2Config.java diff --git a/spring-jpa/src/main/java/org/baeldung/config/StudentJpaConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJpaConfig.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/config/StudentJpaConfig.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/config/StudentJpaConfig.java diff --git a/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/config/UserConfig.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/config/UserConfig.java diff --git a/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/config/WebInitializer.java diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java new file mode 100644 index 0000000000..180f54326e --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDao.java @@ -0,0 +1,29 @@ +package org.baeldung.dsrouting; + +import javax.sql.DataSource; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +/** + * Database access code for datasource routing example. + */ +public class ClientDao { + + private static final String SQL_GET_CLIENT_NAME = "select name from client"; + + private final JdbcTemplate jdbcTemplate; + + public ClientDao(DataSource datasource) { + this.jdbcTemplate = new JdbcTemplate(datasource); + } + + public String getClientName() { + return this.jdbcTemplate.query(SQL_GET_CLIENT_NAME, rowMapper) + .get(0); + } + + private static RowMapper rowMapper = (rs, rowNum) -> { + return rs.getString("name"); + }; +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java new file mode 100644 index 0000000000..997e461cde --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDataSourceRouter.java @@ -0,0 +1,14 @@ +package org.baeldung.dsrouting; + +import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; + +/** + * Returns thread bound client lookup key for current context. + */ +public class ClientDataSourceRouter extends AbstractRoutingDataSource { + + @Override + protected Object determineCurrentLookupKey() { + return ClientDatabaseContextHolder.getClientDatabase(); + } +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabase.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabase.java new file mode 100644 index 0000000000..619b8707d8 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabase.java @@ -0,0 +1,7 @@ +package org.baeldung.dsrouting; + +public enum ClientDatabase { + + CLIENT_A, CLIENT_B + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java new file mode 100644 index 0000000000..c08559e877 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientDatabaseContextHolder.java @@ -0,0 +1,26 @@ +package org.baeldung.dsrouting; + +import org.springframework.util.Assert; + +/** + * Thread shared context to point to the datasource which should be used. This + * enables context switches between different clients. + */ +public class ClientDatabaseContextHolder { + + private static final ThreadLocal CONTEXT = new ThreadLocal<>(); + + public static void set(ClientDatabase clientDatabase) { + Assert.notNull(clientDatabase, "clientDatabase cannot be null"); + CONTEXT.set(clientDatabase); + } + + public static ClientDatabase getClientDatabase() { + return CONTEXT.get(); + } + + public static void clear() { + CONTEXT.remove(); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientService.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientService.java new file mode 100644 index 0000000000..4b63c6333c --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/dsrouting/ClientService.java @@ -0,0 +1,21 @@ +package org.baeldung.dsrouting; + +/** + * Service layer code for datasource routing example. Here, the service methods are responsible + * for setting and clearing the context. + */ +public class ClientService { + + private final ClientDao clientDao; + + public ClientService(ClientDao clientDao) { + this.clientDao = clientDao; + } + + public String getClientName(ClientDatabase clientDb) { + ClientDatabaseContextHolder.set(clientDb); + String clientName = this.clientDao.getClientName(); + ClientDatabaseContextHolder.clear(); + return clientName; + } +} diff --git a/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepository.java diff --git a/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedRepositoryImpl.java diff --git a/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/extended/persistence/dao/ExtendedStudentRepository.java diff --git a/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/dao/StudentRepository.java diff --git a/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/inmemory/persistence/model/Student.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/dao/AbstractJpaDAO.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/AbstractJpaDAO.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/persistence/dao/AbstractJpaDAO.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/AbstractJpaDAO.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/dao/FooDao.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/FooDao.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/persistence/dao/FooDao.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/FooDao.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/dao/IFooDao.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/IFooDao.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/persistence/dao/IFooDao.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/dao/IFooDao.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/model/Bar.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Bar.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/persistence/model/Bar.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Bar.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/product/ProductRepository.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/PossessionRepository.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/dao/user/UserRepository.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/product/Product.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/Possession.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/multiple/model/user/User.java diff --git a/spring-jpa/src/main/java/org/baeldung/persistence/service/FooService.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/service/FooService.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/persistence/service/FooService.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/service/FooService.java diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java new file mode 100644 index 0000000000..0555c8186c --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/sqlfiles/Country.java @@ -0,0 +1,33 @@ +package org.baeldung.sqlfiles; + +import static javax.persistence.GenerationType.IDENTITY; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Country { + + @Id + @GeneratedValue(strategy = IDENTITY) + private Integer id; + + @Column(nullable = false) + private String name; + + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + +} diff --git a/spring-jpa/src/main/java/org/baeldung/web/MainController.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/web/MainController.java similarity index 100% rename from spring-jpa/src/main/java/org/baeldung/web/MainController.java rename to persistence-modules/spring-jpa/src/main/java/org/baeldung/web/MainController.java diff --git a/spring-jpa/src/main/resources/context.xml b/persistence-modules/spring-jpa/src/main/resources/context.xml similarity index 100% rename from spring-jpa/src/main/resources/context.xml rename to persistence-modules/spring-jpa/src/main/resources/context.xml diff --git a/rest-assured/src/test/resources/logback.xml b/persistence-modules/spring-jpa/src/main/resources/logback.xml similarity index 100% rename from rest-assured/src/test/resources/logback.xml rename to persistence-modules/spring-jpa/src/main/resources/logback.xml diff --git a/spring-jpa/src/main/resources/persistence-h2.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-jpa/src/main/resources/persistence-h2.properties rename to persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties diff --git a/spring-jpa/src/main/resources/persistence-jndi.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-jndi.properties similarity index 100% rename from spring-jpa/src/main/resources/persistence-jndi.properties rename to persistence-modules/spring-jpa/src/main/resources/persistence-jndi.properties diff --git a/spring-jpa/src/main/resources/persistence-multiple-db.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties similarity index 100% rename from spring-jpa/src/main/resources/persistence-multiple-db.properties rename to persistence-modules/spring-jpa/src/main/resources/persistence-multiple-db.properties diff --git a/spring-jpa/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-mysql.properties similarity index 100% rename from spring-jpa/src/main/resources/persistence-mysql.properties rename to persistence-modules/spring-jpa/src/main/resources/persistence-mysql.properties diff --git a/spring-jpa/src/main/resources/persistence-student-h2.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties similarity index 100% rename from spring-jpa/src/main/resources/persistence-student-h2.properties rename to persistence-modules/spring-jpa/src/main/resources/persistence-student-h2.properties diff --git a/spring-jpa/src/main/resources/persistence-student.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-student.properties similarity index 100% rename from spring-jpa/src/main/resources/persistence-student.properties rename to persistence-modules/spring-jpa/src/main/resources/persistence-student.properties diff --git a/spring-jpa/src/main/resources/persistence.xml b/persistence-modules/spring-jpa/src/main/resources/persistence.xml similarity index 100% rename from spring-jpa/src/main/resources/persistence.xml rename to persistence-modules/spring-jpa/src/main/resources/persistence.xml diff --git a/spring-jpa/src/main/resources/server.xml b/persistence-modules/spring-jpa/src/main/resources/server.xml similarity index 100% rename from spring-jpa/src/main/resources/server.xml rename to persistence-modules/spring-jpa/src/main/resources/server.xml diff --git a/persistence-modules/spring-jpa/src/main/resources/sqlfiles.properties b/persistence-modules/spring-jpa/src/main/resources/sqlfiles.properties new file mode 100644 index 0000000000..0bea6adad1 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/resources/sqlfiles.properties @@ -0,0 +1 @@ +spring.jpa.hibernate.ddl-auto=none \ No newline at end of file diff --git a/spring-jpa/src/main/webapp/WEB-INF/views/jsp/index.jsp b/persistence-modules/spring-jpa/src/main/webapp/WEB-INF/views/jsp/index.jsp similarity index 100% rename from spring-jpa/src/main/webapp/WEB-INF/views/jsp/index.jsp rename to persistence-modules/spring-jpa/src/main/webapp/WEB-INF/views/jsp/index.jsp diff --git a/spring-jpa/src/test/java/META-INF/persistence.xml b/persistence-modules/spring-jpa/src/test/java/META-INF/persistence.xml similarity index 100% rename from spring-jpa/src/test/java/META-INF/persistence.xml rename to persistence-modules/spring-jpa/src/test/java/META-INF/persistence.xml diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java new file mode 100644 index 0000000000..f81247e3cd --- /dev/null +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingIntegrationTest.java @@ -0,0 +1,53 @@ +package org.baeldung.dsrouting; + +import static org.junit.Assert.assertEquals; + +import javax.sql.DataSource; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = DataSourceRoutingTestConfiguration.class) +public class DataSourceRoutingIntegrationTest { + + @Autowired + DataSource routingDatasource; + + @Autowired + ClientService clientService; + + @Before + public void setup() { + final String SQL_CLIENT_A = "insert into client (id, name) values (1, 'CLIENT A')"; + final String SQL_CLIENT_B = "insert into client (id, name) values (2, 'CLIENT B')"; + + JdbcTemplate jdbcTemplate = new JdbcTemplate(); + jdbcTemplate.setDataSource(routingDatasource); + + ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_A); + jdbcTemplate.execute(SQL_CLIENT_A); + ClientDatabaseContextHolder.clear(); + + ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_B); + jdbcTemplate.execute(SQL_CLIENT_B); + ClientDatabaseContextHolder.clear(); + } + + @Test + public void givenClientDbs_whenContextsSwitch_thenRouteToCorrectDatabase() throws Exception { + + // test ACME WIDGETS + String clientName = clientService.getClientName(ClientDatabase.CLIENT_A); + assertEquals(clientName, "CLIENT A"); + + // test WIDGETS_ARE_US + clientName = clientService.getClientName(ClientDatabase.CLIENT_B); + assertEquals(clientName, "CLIENT B"); + } +} diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java new file mode 100644 index 0000000000..dee9d58722 --- /dev/null +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/dsrouting/DataSourceRoutingTestConfiguration.java @@ -0,0 +1,51 @@ +package org.baeldung.dsrouting; + +import java.util.HashMap; +import java.util.Map; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +@Configuration +public class DataSourceRoutingTestConfiguration { + + @Bean + public ClientService clientService() { + return new ClientService(new ClientDao(clientDatasource())); + } + + @Bean + public DataSource clientDatasource() { + Map targetDataSources = new HashMap<>(); + DataSource clientADatasource = clientADatasource(); + DataSource clientBDatasource = clientBDatasource(); + targetDataSources.put(ClientDatabase.CLIENT_A, clientADatasource); + targetDataSources.put(ClientDatabase.CLIENT_B, clientBDatasource); + + ClientDataSourceRouter clientRoutingDatasource = new ClientDataSourceRouter(); + clientRoutingDatasource.setTargetDataSources(targetDataSources); + clientRoutingDatasource.setDefaultTargetDataSource(clientADatasource); + return clientRoutingDatasource; + } + + private DataSource clientADatasource() { + EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); + return dbBuilder.setType(EmbeddedDatabaseType.H2) + .setName("CLIENT_A") + .addScript("classpath:dsrouting-db.sql") + .build(); + } + + private DataSource clientBDatasource() { + EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); + return dbBuilder.setType(EmbeddedDatabaseType.H2) + .setName("CLIENT_B") + .addScript("classpath:dsrouting-db.sql") + .build(); + } +} diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Bar.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Bar.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Bar.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Bar.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Foo.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Foo.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Foo.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Foo.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/ExtendedStudentRepositoryIntegrationTest.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/repository/InMemoryDBIntegrationTest.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java similarity index 100% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java rename to persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java diff --git a/persistence-modules/spring-jpa/src/test/resources/.gitignore b/persistence-modules/spring-jpa/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/persistence-modules/spring-jpa/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/test/resources/dsrouting-db.sql b/persistence-modules/spring-jpa/src/test/resources/dsrouting-db.sql new file mode 100644 index 0000000000..c9ca52907a --- /dev/null +++ b/persistence-modules/spring-jpa/src/test/resources/dsrouting-db.sql @@ -0,0 +1,5 @@ +create table client ( + id numeric, + name varchar(50), + constraint pk_client primary key (id) +); \ No newline at end of file diff --git a/spring-jpa/src/test/resources/persistence-student.properties b/persistence-modules/spring-jpa/src/test/resources/persistence-student.properties similarity index 100% rename from spring-jpa/src/test/resources/persistence-student.properties rename to persistence-modules/spring-jpa/src/test/resources/persistence-student.properties diff --git a/pom.xml b/pom.xml index 9aa45b1d5d..9b1f50f05e 100644 --- a/pom.xml +++ b/pom.xml @@ -62,15 +62,15 @@ feign flyway - + geotools - groovy-spock + testing-modules/groovy-spock gson guava - guava18 - guava19 - guava21 + guava-modules/guava-18 + guava-modules/guava-19 + guava-modules/guava-21 guice disruptor @@ -90,7 +90,7 @@ javax-servlets javaxval jaxb - jee7 + jee-7 jjwt jpa-storedprocedure @@ -98,26 +98,27 @@ json-path json jsoup - junit5 + testing-modules/junit-5 jws libraries libraries-data linkrest - log-mdc - log4j - log4j2 + logging-modules/log-mdc + logging-modules/log4j + logging-modules/log4j2 lombok mapstruct metrics mesos-marathon - mockito - mockito2 - mocks + testing-modules/mockito + testing-modules/mockito-2 + testing-modules/mocks mustache noexception + osgi orika patterns @@ -129,13 +130,13 @@ reactor-core persistence-modules/redis - rest-assured - rest-testing + testing-modules/rest-assured + testing-modules/rest-testing resteasy rxjava spring-swagger-codegen - selenium-junit-testng + testing-modules/selenium-junit-testng persistence-modules/solr spark-java @@ -149,6 +150,7 @@ spring-batch spring-bom spring-boot + spring-boot-keycloak spring-boot-bootstrap spring-cloud-data-flow spring-cloud @@ -175,7 +177,7 @@ spring-jmeter-jenkins spring-jms spring-jooq - spring-jpa + persistence-modules/spring-jpa spring-kafka spring-katharsis spring-ldap @@ -230,16 +232,18 @@ spring-zuul spring-reactor spring-vertx + + spring-rest-embedded-tomcat - testing - testng + testing-modules/testing + testing-modules/testng video-tutorials xml - xmlunit2 - struts2 + xmlunit-2 + struts-2 apache-velocity apache-solrj @@ -251,12 +255,13 @@ drools persistence-modules/liquibase spring-boot-property-exp - mockserver + testing-modules/mockserver undertow vertx-and-rxjava saas deeplearning4j spring-boot-admin + lucene @@ -339,7 +344,7 @@ **/JdbcTest.java **/*LiveTest.java - true + diff --git a/rxjava/README.md b/rxjava/README.md index 71231cc391..c88ec36991 100644 --- a/rxjava/README.md +++ b/rxjava/README.md @@ -8,3 +8,4 @@ - [Observable Utility Operators in RxJava](http://www.baeldung.com/rxjava-observable-operators) - [Introduction to rxjava-jdbc](http://www.baeldung.com/rxjava-jdbc) - [Schedulers in RxJava](http://www.baeldung.com/rxjava-schedulers) +- [Mathematical and Aggregate Operators in RxJava](http://www.baeldung.com/rxjava-math) diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 7b7ddcba88..b188ee590a 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -152,7 +152,7 @@ org.apache.maven.plugins maven-surefire-plugin - true + false **/*IntegrationTest.java diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 4dfede4dab..7e30179f07 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.M3 + 2.0.0.M6 @@ -49,6 +49,18 @@ javax.json.bind-api ${jsonb-api.version} + + + + + + + + + + + + org.apache.geronimo.specs geronimo-json_1.1_spec @@ -87,6 +99,18 @@ spring-boot-starter-test test + + org.springframework.security + spring-security-test + test + + + + org.apache.commons + commons-collections4 + 4.1 + test + org.junit.jupiter @@ -170,7 +194,7 @@ 1.0.0 5.0.0 2.20 - 5.0.0.RELEASE + 5.0.1.RELEASE 1.0.1.RELEASE 1.1.3 1.0 diff --git a/spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java b/spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java new file mode 100644 index 0000000000..02c91a1879 --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/SpringSecurity5Application.java @@ -0,0 +1,34 @@ +package com.baeldung; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.http.server.reactive.HttpHandler; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.web.reactive.config.EnableWebFlux; +import org.springframework.web.server.adapter.WebHttpHandlerBuilder; +import reactor.ipc.netty.NettyContext; +import reactor.ipc.netty.http.server.HttpServer; + +@ComponentScan(basePackages = {"com.baeldung.security"}) +@EnableWebFlux +public class SpringSecurity5Application { + + public static void main(String[] args) { + try (AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(SpringSecurity5Application.class)) { + context.getBean(NettyContext.class).onClose().block(); + } + } + + @Bean + public NettyContext nettyContext(ApplicationContext context) { + HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context) + .build(); + ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); + HttpServer httpServer = HttpServer.create("localhost", 8080); + return httpServer.newHandler(adapter).block(); + } + +} diff --git a/spring-5/src/main/java/com/baeldung/security/GreetController.java b/spring-5/src/main/java/com/baeldung/security/GreetController.java new file mode 100644 index 0000000000..6b69e3bc9b --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/security/GreetController.java @@ -0,0 +1,37 @@ +package com.baeldung.security; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + +import java.security.Principal; + +@RestController +public class GreetController { + + private GreetService greetService; + + public GreetController(GreetService greetService) { + this.greetService = greetService; + } + + @GetMapping("/") + public Mono greet(Mono principal) { + return principal + .map(Principal::getName) + .map(name -> String.format("Hello, %s", name)); + } + + @GetMapping("/admin") + public Mono greetAdmin(Mono principal) { + return principal + .map(Principal::getName) + .map(name -> String.format("Admin access: %s", name)); + } + + @GetMapping("/greetService") + public Mono greetService() { + return greetService.greet(); + } + +} diff --git a/spring-5/src/main/java/com/baeldung/security/GreetService.java b/spring-5/src/main/java/com/baeldung/security/GreetService.java new file mode 100644 index 0000000000..7622b360be --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/security/GreetService.java @@ -0,0 +1,15 @@ +package com.baeldung.security; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; +import reactor.core.publisher.Mono; + +@Service +public class GreetService { + + @PreAuthorize("hasRole('ADMIN')") + public Mono greet() { + return Mono.just("Hello from service!"); + } + +} diff --git a/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java b/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java new file mode 100644 index 0000000000..a9e44a2eee --- /dev/null +++ b/spring-5/src/main/java/com/baeldung/security/SecurityConfig.java @@ -0,0 +1,42 @@ +package com.baeldung.security; + +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.server.SecurityWebFilterChain; + +@EnableWebFluxSecurity +@EnableReactiveMethodSecurity +public class SecurityConfig { + + @Bean + public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { + return http.authorizeExchange() + .pathMatchers("/admin").hasAuthority("ROLE_ADMIN") + .anyExchange().authenticated() + .and().formLogin() + .and().build(); + } + + @Bean + public MapReactiveUserDetailsService userDetailsService() { + UserDetails user = User.withDefaultPasswordEncoder() + .username("user") + .password("password") + .roles("USER") + .build(); + + UserDetails admin = User.withDefaultPasswordEncoder() + .username("admin") + .password("password") + .roles("ADMIN") + .build(); + + return new MapReactiveUserDetailsService(user, admin); + } + +} diff --git a/spring-5/src/main/resources/application.properties b/spring-5/src/main/resources/application.properties index 886ea1978b..ccec014c2b 100644 --- a/spring-5/src/main/resources/application.properties +++ b/spring-5/src/main/resources/application.properties @@ -1,6 +1,3 @@ server.port=8081 -security.user.name=user -security.user.password=pass - logging.level.root=INFO \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java b/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java deleted file mode 100644 index 4caab86f7d..0000000000 --- a/spring-5/src/test/java/com/baeldung/jsonb/JsonbTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.jsonb; - -import static org.junit.Assert.assertTrue; - -import java.math.BigDecimal; -import java.time.LocalDate; - -import javax.json.bind.Jsonb; -import javax.json.bind.JsonbBuilder; - -import org.junit.Before; -import org.junit.Test; - -public class JsonbTest { - - private Jsonb jsonb; - - @Before - public void setup() { - jsonb = JsonbBuilder.create(); - } - - @Test - public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() { - Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000)); - String jsonPerson = jsonb.toJson(person); - assertTrue("{\"email\":\"jhon@test.com\",\"id\":1,\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}".equals(jsonPerson)); - } - - @Test - public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() { - Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0)); - String jsonPerson = "{\"email\":\"jhon@test.com\",\"id\":1,\"person-name\":\"Jhon\",\"registeredDate\":\"07-09-2019\",\"salary\":\"1000.0\"}"; - assertTrue(jsonb.fromJson(jsonPerson, Person.class) - .equals(person)); - } - -} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/EnabledOnJava8.java b/spring-5/src/test/java/com/baeldung/jupiter/EnabledOnJava8.java new file mode 100644 index 0000000000..c6d3b7ff10 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jupiter/EnabledOnJava8.java @@ -0,0 +1,18 @@ +package com.baeldung.jupiter; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.springframework.test.context.junit.jupiter.EnabledIf; + +@Target({ ElementType.TYPE, ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +@EnabledIf( + expression = "#{systemProperties['java.version'].startsWith('1.8')}", + reason = "Enabled on Java 8" +) +public @interface EnabledOnJava8 { + +} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java new file mode 100644 index 0000000000..ae058bc8ba --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java @@ -0,0 +1,50 @@ +package com.baeldung.jupiter; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.DisabledIf; +import org.springframework.test.context.junit.jupiter.EnabledIf; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +@SpringJUnitConfig(Spring5EnabledAnnotationTest.Config.class) +@TestPropertySource(properties = { "tests.enabled=true" }) +public class Spring5EnabledAnnotationTest { + + @Configuration + static class Config { + } + + @EnabledIf("true") + @Test + void givenEnabledIfLiteral_WhenTrue_ThenTestExecuted() { + assertTrue(true); + } + + @EnabledIf(expression = "${tests.enabled}", loadContext = true) + @Test + void givenEnabledIfExpression_WhenTrue_ThenTestExecuted() { + assertTrue(true); + } + + @EnabledIf("#{systemProperties['java.version'].startsWith('1.8')}") + @Test + void givenEnabledIfSpel_WhenTrue_ThenTestExecuted() { + assertTrue(true); + } + + @EnabledOnJava8 + @Test + void givenEnabledOnJava8_WhenTrue_ThenTestExecuted() { + assertTrue(true); + } + + @DisabledIf("#{systemProperties['java.version'].startsWith('1.7')}") + @Test + void givenDisabledIf_WhenTrue_ThenTestNotExecuted() { + assertTrue(true); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java new file mode 100644 index 0000000000..6b0a6f9808 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java @@ -0,0 +1,33 @@ +package com.baeldung.jupiter; + +import static org.junit.Assert.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +/** + * @SpringJUnitConfig(SpringJUnitConfigTest.Config.class) is equivalent to: + * + * @ExtendWith(SpringExtension.class) + * @ContextConfiguration(classes = SpringJUnitConfigTest.Config.class ) + * + */ +@SpringJUnitConfig(SpringJUnitConfigTest.Config.class) +public class SpringJUnitConfigTest { + + @Configuration + static class Config { + } + + @Autowired + private ApplicationContext applicationContext; + + @Test + void givenAppContext_WhenInjected_ThenItShouldNotBeNull() { + assertNotNull(applicationContext); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java new file mode 100644 index 0000000000..c679dce77f --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java @@ -0,0 +1,34 @@ +package com.baeldung.jupiter; + +import static org.junit.Assert.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; +import org.springframework.web.context.WebApplicationContext; + +/** + * @SpringJUnitWebConfig(SpringJUnitWebConfigTest.Config.class) is equivalent to: + * + * @ExtendWith(SpringExtension.class) + * @WebAppConfiguration + * @ContextConfiguration(classes = SpringJUnitWebConfigTest.Config.class ) + * + */ +@SpringJUnitWebConfig(SpringJUnitWebConfigTest.Config.class) +public class SpringJUnitWebConfigTest { + + @Configuration + static class Config { + } + + @Autowired + private WebApplicationContext webAppContext; + + @Test + void givenWebAppContext_WhenInjected_ThenItShouldNotBeNull() { + assertNotNull(webAppContext); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/security/SecurityTest.java b/spring-5/src/test/java/com/baeldung/security/SecurityTest.java new file mode 100644 index 0000000000..a1c940a17a --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/security/SecurityTest.java @@ -0,0 +1,48 @@ +package com.baeldung.security; + +import com.baeldung.SpringSecurity5Application; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = SpringSecurity5Application.class) +public class SecurityTest { + + @Autowired + ApplicationContext context; + + private WebTestClient rest; + + @Before + public void setup() { + this.rest = WebTestClient + .bindToApplicationContext(this.context) + .configureClient() + .build(); + } + + @Test + public void whenNoCredentials_thenRedirectToLogin() { + this.rest.get() + .uri("/") + .exchange() + .expectStatus().is3xxRedirection(); + } + + @Test + @WithMockUser + public void whenHasCredentials_thenSeesGreeting() { + this.rest.get() + .uri("/") + .exchange() + .expectStatus().isOk() + .expectBody(String.class).isEqualTo("Hello, user"); + } +} diff --git a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java index b05f903b4b..43114b5b50 100644 --- a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java +++ b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientTest.java @@ -53,7 +53,7 @@ public class WebTestClientTest { .uri("/resource") .exchange() .expectStatus() - .is4xxClientError() + .is3xxRedirection() .expectBody(); } diff --git a/spring-activiti/README.md b/spring-activiti/README.md index 3580e29a52..703dfeec52 100644 --- a/spring-activiti/README.md +++ b/spring-activiti/README.md @@ -2,4 +2,5 @@ - [A Guide to Activiti with Java](http://www.baeldung.com/java-activiti) - [Introduction to Activiti with Spring](http://www.baeldung.com/spring-activiti) - +- [Activiti with Spring Security](http://www.baeldung.com/activiti-spring-security) +- [ProcessEngine Configuration in Activiti](http://www.baeldung.com/activiti-process-engine) diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index f6f992b7c0..92d9618b65 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -74,7 +74,7 @@ **/JdbcTest.java **/*LiveTest.java - true + diff --git a/spring-all/README.md b/spring-all/README.md index 36bf7da778..e1504a66db 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -23,3 +23,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent) - [A CLI with Spring Shell](http://www.baeldung.com/spring-shell-cli) - [JasperReports with Spring](http://www.baeldung.com/spring-jasper) +- [Model, ModelMap, and ModelView in Spring MVC](http://www.baeldung.com/spring-mvc-model-model-map-model-view) diff --git a/spring-aop/src/main/resources/logback.xml b/spring-aop/src/main/resources/logback.xml index ec0dc2469a..3245e94f08 100644 --- a/spring-aop/src/main/resources/logback.xml +++ b/spring-aop/src/main/resources/logback.xml @@ -13,7 +13,11 @@ - + + + + + \ No newline at end of file diff --git a/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationTests.java b/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationIntegrationTest.java similarity index 97% rename from spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationTests.java rename to spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationIntegrationTest.java index d70fb1c7cf..0201deabca 100644 --- a/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationTests.java +++ b/spring-boot-admin/spring-boot-admin-client/src/test/java/com/baeldung/springbootadminclient/SpringBootAdminClientApplicationIntegrationTest.java @@ -19,7 +19,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT) -public class SpringBootAdminClientApplicationTests { +public class SpringBootAdminClientApplicationIntegrationTest { @Autowired Environment environment; diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigIntegrationTest.java similarity index 95% rename from spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigTest.java rename to spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigIntegrationTest.java index 8ca50a6f75..7c1b1881a4 100644 --- a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigTest.java +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/HazelcastConfigIntegrationTest.java @@ -13,7 +13,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @RunWith(SpringRunner.class) @SpringBootTest(classes = { HazelcastConfig.class }, webEnvironment = NONE) -public class HazelcastConfigTest { +public class HazelcastConfigIntegrationTest { @Autowired private ApplicationContext applicationContext; diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationIntegrationTest.java similarity index 96% rename from spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationTest.java rename to spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationIntegrationTest.java index 85f6b374a4..465d079ac3 100644 --- a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationTest.java +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/NotifierConfigurationIntegrationTest.java @@ -16,7 +16,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @RunWith(SpringRunner.class) @SpringBootTest(classes = { NotifierConfiguration.class }, webEnvironment = NONE) -public class NotifierConfigurationTest { +public class NotifierConfigurationIntegrationTest { @Autowired private ApplicationContext applicationContext; diff --git a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigTest.java b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigIntegrationTest.java similarity index 97% rename from spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigTest.java rename to spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigIntegrationTest.java index 40611f00f6..0c0695e6c2 100644 --- a/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigTest.java +++ b/spring-boot-admin/spring-boot-admin-server/src/test/java/com/baeldung/springbootadminserver/WebSecurityConfigIntegrationTest.java @@ -17,7 +17,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class WebSecurityConfigTest { +public class WebSecurityConfigIntegrationTest { @Autowired WebApplicationContext wac; diff --git a/spring-boot-keycloak/pom.xml b/spring-boot-keycloak/pom.xml index 657f96a265..ab76d0af43 100644 --- a/spring-boot-keycloak/pom.xml +++ b/spring-boot-keycloak/pom.xml @@ -12,10 +12,12 @@ This is a simple application demonstrating integration between Keycloak and Spring Boot. - org.springframework.boot - spring-boot-starter-parent - 1.5.8.RELEASE - + + com.baeldung + parent-boot-4 + 0.0.1-SNAPSHOT + ../parent-boot-4 + diff --git a/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java b/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationIntegrationTest.java similarity index 97% rename from spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java rename to spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationIntegrationTest.java index 41662e5c17..e0bbef1c7f 100644 --- a/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationTest.java +++ b/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationIntegrationTest.java @@ -20,7 +20,7 @@ import static org.mockito.Mockito.when; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = SpringBoot.class) -public class KeycloakConfigurationTest { +public class KeycloakConfigurationIntegrationTest { @Spy private KeycloakSecurityContextClientRequestInterceptor factory; diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 5d7eb11954..f126df00af 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -27,4 +27,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Java Client for a WebSockets API](http://www.baeldung.com/websockets-api-java-spring-client) - [Spring Boot and Togglz Aspect](http://www.baeldung.com/spring-togglz) - [Getting Started with GraphQL and Spring Boot](http://www.baeldung.com/spring-graphql) +- [Guide to Spring Type Conversions](http://www.baeldung.com/spring-type-conversions) diff --git a/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java index a51e3a6884..ffd5bf55d6 100644 --- a/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/properties/ConfigPropertiesIntegrationTest.java @@ -1,7 +1,5 @@ package org.baeldung.properties; -import org.baeldung.properties.ConfigProperties; -import org.baeldung.properties.ConfigPropertiesDemoApplication; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot/src/test/resources/data.sql b/spring-boot/src/test/resources/data.sql new file mode 100644 index 0000000000..f36e034ce1 --- /dev/null +++ b/spring-boot/src/test/resources/data.sql @@ -0,0 +1,5 @@ +INSERT INTO country (name) VALUES ('India'); +INSERT INTO country (name) VALUES ('Brazil'); +INSERT INTO country (name) VALUES ('USA'); +INSERT INTO country (name) VALUES ('Italy'); +COMMIT; diff --git a/spring-boot/src/test/resources/schema.sql b/spring-boot/src/test/resources/schema.sql new file mode 100644 index 0000000000..15d7788cd7 --- /dev/null +++ b/spring-boot/src/test/resources/schema.sql @@ -0,0 +1,5 @@ +CREATE TABLE country ( + id INTEGER NOT NULL AUTO_INCREMENT, + name VARCHAR(128) NOT NULL, + PRIMARY KEY (id) +); diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 53ac4e04b4..e6d78f292d 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -1,7 +1,7 @@ + xmlns="http://maven.apache.org/POM/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 com.baeldung.spring.cloud @@ -15,9 +15,10 @@ spring-cloud-ribbon-client spring-cloud-rest spring-cloud-zookeeper - spring-cloud-gateway - spring-cloud-stream - spring-cloud-connectors-heroku + spring-cloud-gateway + spring-cloud-stream + spring-cloud-connectors-heroku + spring-cloud-aws pom diff --git a/spring-cloud/spring-cloud-aws/README.md b/spring-cloud/spring-cloud-aws/README.md new file mode 100644 index 0000000000..c5f58159c8 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/README.md @@ -0,0 +1,21 @@ +# Spring Cloud AWS + +#### Running the Integration Tests + +To run the Integration Tests, we need to have an AWS account and have API keys generated for programmatic access. Edit +the `application.properties` file to add the following properties: + +``` +cloud.aws.credentials.accessKey=YourAccessKey +cloud.aws.credentials.secretKey=YourSecretKey +cloud.aws.region.static=us-east-1 +``` + +To test automatic DataSource creation from RDS instance, we also need to create an RDS instance in the AWS account. +Let's say that the RDS instance is called `spring-cloud-test-db` having the master password `se3retpass`, then we need +to write the following in `application.properties`: + +``` +cloud.aws.rds.spring-cloud-test-db +cloud.aws.rds.spring-cloud-test-db.password=se3retpass +``` diff --git a/spring-cloud/spring-cloud-aws/pom.xml b/spring-cloud/spring-cloud-aws/pom.xml new file mode 100644 index 0000000000..632e050d92 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/pom.xml @@ -0,0 +1,91 @@ + + + 4.0.0 + + com.baeldung.spring.cloud + spring-cloud-aws + 0.0.1-SNAPSHOT + jar + + Spring Cloud AWS + Spring Cloud AWS Examples + + + org.springframework.boot + spring-boot-starter-parent + 1.5.8.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + Dalston.SR4 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-aws + + + org.springframework.cloud + spring-cloud-starter-aws-jdbc + + + org.springframework.cloud + spring-cloud-starter-aws-messaging + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.postgresql + postgresql + + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + maven-surefire-plugin + + + **/*IntegrationTest.java + + + + + + + + + diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/SpringCloudAwsApplication.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/SpringCloudAwsApplication.java new file mode 100644 index 0000000000..81bbc579ec --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/SpringCloudAwsApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.cloud.aws; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ImportResource; + +@SpringBootApplication +@ImportResource("classpath:aws-config.xml") +public class SpringCloudAwsApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringCloudAwsApplication.class, args); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/config/SpringCloudAwsConfig.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/config/SpringCloudAwsConfig.java new file mode 100644 index 0000000000..85dcd05c86 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/config/SpringCloudAwsConfig.java @@ -0,0 +1,22 @@ +package com.baeldung.spring.cloud.aws.config; + +import com.amazonaws.services.sns.AmazonSNS; +import com.amazonaws.services.sqs.AmazonSQSAsync; +import org.springframework.cloud.aws.messaging.core.NotificationMessagingTemplate; +import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class SpringCloudAwsConfig { + + @Bean + public QueueMessagingTemplate queueMessagingTemplate(AmazonSQSAsync amazonSQSAsync) { + return new QueueMessagingTemplate(amazonSQSAsync); + } + + @Bean + public NotificationMessagingTemplate notificationMessagingTemplate(AmazonSNS amazonSNS) { + return new NotificationMessagingTemplate(amazonSNS); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/ec2/EC2EnableMetadata.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/ec2/EC2EnableMetadata.java new file mode 100644 index 0000000000..03a7db26de --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/ec2/EC2EnableMetadata.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.cloud.aws.ec2; + +import org.springframework.cloud.aws.context.config.annotation.EnableContextInstanceData; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableContextInstanceData +public class EC2EnableMetadata { +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/ec2/EC2Metadata.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/ec2/EC2Metadata.java new file mode 100644 index 0000000000..9466c14560 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/ec2/EC2Metadata.java @@ -0,0 +1,62 @@ +package com.baeldung.spring.cloud.aws.ec2; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +@Lazy +@Component +public class EC2Metadata { + + @Value("${ami-id:N/A}") + private String amiId; + + @Value("${hostname:N/A}") + private String hostname; + + @Value("${instance-type:N/A}") + private String instanceType; + + @Value("${services/domain:N/A}") + private String serviceDomain; + + @Value("#{instanceData['Name'] ?: 'N/A'}") + private String name; + + public String getAmiId() { + return amiId; + } + + public String getHostname() { + return hostname; + } + + public String getInstanceType() { + return instanceType; + } + + public String getServiceDomain() { + return serviceDomain; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("EC2Metadata [amiId="); + builder.append(amiId); + builder.append(", hostname="); + builder.append(hostname); + builder.append(", instanceType="); + builder.append(instanceType); + builder.append(", serviceDomain="); + builder.append(serviceDomain); + builder.append(", name="); + builder.append(name); + builder.append("]"); + return builder.toString(); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3.java new file mode 100644 index 0000000000..cfad6e904f --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.cloud.aws.s3; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.core.io.WritableResource; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; + +@Component +public class SpringCloudS3 { + + @Autowired + ResourceLoader resourceLoader; + + @Autowired + ResourcePatternResolver resourcePatternResolver; + + public void downloadS3Object(String s3Url) throws IOException { + Resource resource = resourceLoader.getResource(s3Url); + File downloadedS3Object = new File(resource.getFilename()); + try (InputStream inputStream = resource.getInputStream()) { + Files.copy(inputStream, downloadedS3Object.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + } + + public void uploadFileToS3(File file, String s3Url) throws IOException { + WritableResource resource = (WritableResource) resourceLoader.getResource(s3Url); + try (OutputStream outputStream = resource.getOutputStream()) { + Files.copy(file.toPath(), outputStream); + } + } + + public void downloadMultipleS3Objects(String s3UrlPattern) throws IOException { + Resource[] allFileMatchingPatten = this.resourcePatternResolver.getResources(s3UrlPattern); + for (Resource resource : allFileMatchingPatten) { + String fileName = resource.getFilename(); + fileName = fileName.substring(0, fileName.lastIndexOf("/") + 1); + File downloadedS3Object = new File(fileName); + try (InputStream inputStream = resource.getInputStream()) { + Files.copy(inputStream, downloadedS3Object.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + } + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sns/SNSEndpointController.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sns/SNSEndpointController.java new file mode 100644 index 0000000000..7c78fcbe37 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sns/SNSEndpointController.java @@ -0,0 +1,36 @@ +package com.baeldung.spring.cloud.aws.sns; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.aws.messaging.config.annotation.NotificationMessage; +import org.springframework.cloud.aws.messaging.config.annotation.NotificationSubject; +import org.springframework.cloud.aws.messaging.endpoint.NotificationStatus; +import org.springframework.cloud.aws.messaging.endpoint.annotation.NotificationMessageMapping; +import org.springframework.cloud.aws.messaging.endpoint.annotation.NotificationSubscriptionMapping; +import org.springframework.cloud.aws.messaging.endpoint.annotation.NotificationUnsubscribeConfirmationMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/topic-subscriber") +public class SNSEndpointController { + + private static final Logger logger = LoggerFactory.getLogger(SNSEndpointController.class); + + @NotificationMessageMapping + public void receiveNotification(@NotificationMessage String message, @NotificationSubject String subject) { + logger.info("Received message: {}, having subject: {}", message, subject); + } + + @NotificationUnsubscribeConfirmationMapping + public void confirmSubscriptionMessage(NotificationStatus notificationStatus) { + logger.info("Unsubscribed from Topic"); + notificationStatus.confirmSubscription(); + } + + @NotificationSubscriptionMapping + public void confirmUnsubscribeMessage(NotificationStatus notificationStatus) { + logger.info("Subscribed to Topic"); + notificationStatus.confirmSubscription(); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sns/SNSMessageSender.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sns/SNSMessageSender.java new file mode 100644 index 0000000000..58cb03644b --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sns/SNSMessageSender.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.cloud.aws.sns; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.aws.messaging.core.NotificationMessagingTemplate; +import org.springframework.stereotype.Component; + +@Component +public class SNSMessageSender { + + @Autowired + NotificationMessagingTemplate notificationMessagingTemplate; + + public void send(String topicName, Object message, String subject) { + notificationMessagingTemplate.sendNotification(topicName, message, subject); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sqs/SpringCloudSQS.java b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sqs/SpringCloudSQS.java new file mode 100644 index 0000000000..d2a5fcf9ca --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/java/com/baeldung/spring/cloud/aws/sqs/SpringCloudSQS.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.cloud.aws.sqs; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate; +import org.springframework.cloud.aws.messaging.listener.annotation.SqsListener; +import org.springframework.context.annotation.Lazy; +import org.springframework.messaging.handler.annotation.Header; +import org.springframework.stereotype.Component; + +import java.util.concurrent.CountDownLatch; + +@Component +@Lazy +public class SpringCloudSQS { + + private static final Logger logger = LoggerFactory.getLogger(SpringCloudSQS.class); + + static final String QUEUE_NAME = "spring-cloud-test-queue"; + + /* + * CountDownLatch is added to wait for messages + * during integration test + */ + CountDownLatch countDownLatch; + + public void setCountDownLatch(CountDownLatch countDownLatch) { + this.countDownLatch = countDownLatch; + } + + @Autowired + QueueMessagingTemplate queueMessagingTemplate; + + @SqsListener(QUEUE_NAME) + public void receiveMessage(String message, @Header("SenderId") String senderId) { + logger.info("Received message: {}, having SenderId: {}", message, senderId); + if (countDownLatch != null) { + countDownLatch.countDown(); + } + } + + public void send(String queueName, Object message) { + queueMessagingTemplate.convertAndSend(queueName, message); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/main/resources/application.properties b/spring-cloud/spring-cloud-aws/src/main/resources/application.properties new file mode 100644 index 0000000000..a769b70ddd --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/resources/application.properties @@ -0,0 +1,14 @@ +cloud.aws.credentials.accessKey=YourAccessKey +cloud.aws.credentials.secretKey=YourSecretKey +cloud.aws.region.static=us-east-1 + +cloud.aws.rds.spring-cloud-test-db +cloud.aws.rds.spring-cloud-test-db.password=se3retpass + +# These 3 properties are optional +cloud.aws.rds.spring-cloud-test-db.username=testuser +cloud.aws.rds.spring-cloud-test-db.readReplicaSupport=true +cloud.aws.rds.spring-cloud-test-db.databaseName=test + +# Disable auto cloudfromation +cloud.aws.stack.auto=false diff --git a/spring-cloud/spring-cloud-aws/src/main/resources/aws-config.xml b/spring-cloud/spring-cloud-aws/src/main/resources/aws-config.xml new file mode 100644 index 0000000000..5ca48f6b1e --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/main/resources/aws-config.xml @@ -0,0 +1,11 @@ + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/SpringCloudAwsTestUtil.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/SpringCloudAwsTestUtil.java new file mode 100644 index 0000000000..fe10eb6f15 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/SpringCloudAwsTestUtil.java @@ -0,0 +1,73 @@ +package com.baeldung.spring.cloud.aws; + +import com.amazonaws.auth.AWSCredentials; +import com.amazonaws.auth.AWSCredentialsProvider; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.AmazonS3ClientBuilder; +import com.amazonaws.services.sns.AmazonSNS; +import com.amazonaws.services.sns.AmazonSNSClientBuilder; +import com.amazonaws.services.sqs.AmazonSQS; +import com.amazonaws.services.sqs.AmazonSQSClientBuilder; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.junit.BeforeClass; + +/** + * This class is needed only for testing. This is because we need to + * create AWS resources before Spring's Application context is created + * in a {@link BeforeClass} method. Since Autowired dependencies don't + * work in static context, we will use this class for AWS clients. + */ +public class SpringCloudAwsTestUtil { + + private static String awsAccessKey; + private static String awsSecretKey; + private static String defaultRegion; + + static { + try { + InputStream is = SpringCloudAwsTestUtil.class.getResourceAsStream("/application.properties"); + Properties properties = new Properties(); + properties.load(is); + awsAccessKey = properties.getProperty("cloud.aws.credentials.accessKey"); + awsSecretKey = properties.getProperty("cloud.aws.credentials.secretKey"); + defaultRegion = properties.getProperty("cloud.aws.region.static"); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static AWSCredentials awsCredentials() { + return new BasicAWSCredentials(awsAccessKey, awsSecretKey); + } + + public static AWSCredentialsProvider awsCredentialsProvider() { + return new AWSStaticCredentialsProvider(awsCredentials()); + } + + public static AmazonS3 amazonS3() { + return AmazonS3ClientBuilder.standard() + .withCredentials(awsCredentialsProvider()) + .withRegion(defaultRegion) + .build(); + } + + public static AmazonSNS amazonSNS() { + return AmazonSNSClientBuilder.standard() + .withCredentials(awsCredentialsProvider()) + .withRegion(defaultRegion) + .build(); + } + + public static AmazonSQS amazonSQS() { + return AmazonSQSClientBuilder.standard() + .withCredentials(awsCredentialsProvider()) + .withRegion(defaultRegion) + .build(); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/ec2/EC2MetadataIntegrationTest.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/ec2/EC2MetadataIntegrationTest.java new file mode 100644 index 0000000000..1e75134194 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/ec2/EC2MetadataIntegrationTest.java @@ -0,0 +1,61 @@ +package com.baeldung.spring.cloud.aws.ec2; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Assume; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import com.amazonaws.regions.Regions; +import com.amazonaws.services.ec2.AmazonEC2; + +@SpringBootTest +@RunWith(SpringRunner.class) +@TestPropertySource("classpath:application-test.properties") +public class EC2MetadataIntegrationTest { + + private static final Logger logger = LoggerFactory.getLogger(EC2MetadataIntegrationTest.class); + + private boolean serverEc2; + + @Before + public void setUp() { + serverEc2 = Regions.getCurrentRegion() != null; + } + + @Autowired + private EC2Metadata eC2Metadata; + + @Autowired + private AmazonEC2 amazonEC2; + + @Test + public void whenEC2ClinentNotNull_thenSuccess() { + assertThat(amazonEC2).isNotNull(); + } + + @Test + public void whenEC2MetadataNotNull_thenSuccess() { + assertThat(eC2Metadata).isNotNull(); + } + + @Test + public void whenMetdataValuesNotNull_thenSuccess() { + Assume.assumeTrue(serverEc2); + assertThat(eC2Metadata.getAmiId()).isNotEqualTo("N/A"); + assertThat(eC2Metadata.getInstanceType()).isNotEqualTo("N/A"); + } + + @Test + public void whenMetadataLogged_thenSuccess() { + logger.info("Environment is EC2: {}", serverEc2); + logger.info(eC2Metadata.toString()); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/rds/SpringCloudRDSIntegrationTest.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/rds/SpringCloudRDSIntegrationTest.java new file mode 100644 index 0000000000..9e163d6dc4 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/rds/SpringCloudRDSIntegrationTest.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.cloud.aws.rds; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@RunWith(SpringRunner.class) +public class SpringCloudRDSIntegrationTest { + + @Autowired + DataSource dataSource; + + @Test + public void whenDataSourceCreated_thenSuccess() { + assertThat(dataSource).isNotNull(); + } + + @Test + public void givenDataSource_whenConnectionCreated_thenSuccess() throws SQLException { + Connection connection = dataSource.getConnection(); + assertThat(connection).isNotNull(); + } + + @Test + public void givenConnection_whenQueryExecuted_thenSuccess() throws SQLException { + Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT 1"); + while (resultSet.next()) { + int result = resultSet.getInt(1); + assertThat(result).isEqualTo(1); + } + connection.close(); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3IntegrationTest.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3IntegrationTest.java new file mode 100644 index 0000000000..a866287dec --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/s3/SpringCloudS3IntegrationTest.java @@ -0,0 +1,101 @@ +package com.baeldung.spring.cloud.aws.s3; + +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.model.ListObjectsV2Result; +import com.amazonaws.services.s3.model.S3ObjectSummary; +import com.baeldung.spring.cloud.aws.SpringCloudAwsTestUtil; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@RunWith(SpringRunner.class) +@TestPropertySource("classpath:application-test.properties") +public class SpringCloudS3IntegrationTest { + + @Autowired + private SpringCloudS3 springCloudS3; + + private static String bucketName; + private static String testFileToDownload; + private static String testFileToUpload; + + private static String[] filesWithSimilarName; + private static List similarNameFiles; + + @BeforeClass + public static void setupResources() throws IOException { + + bucketName = UUID.randomUUID().toString(); + testFileToDownload = "test-file-download.txt"; + testFileToUpload = "test-file-upload.txt"; + + filesWithSimilarName = new String[] { "foo/hello-apple.txt", "foo/hello-orange.txt", "bar/hello-grapes.txt", }; + + similarNameFiles = new ArrayList<>(); + for (String name : filesWithSimilarName) { + similarNameFiles.add(new File(name.substring(0, name.lastIndexOf("/") + 1))); + } + + Files.write(Paths.get(testFileToUpload), "Hello World Uploaded!".getBytes()); + + AmazonS3 amazonS3 = SpringCloudAwsTestUtil.amazonS3(); + amazonS3.createBucket(bucketName); + + amazonS3.putObject(bucketName, testFileToDownload, "Hello World"); + + for (String s3Key : filesWithSimilarName) { + amazonS3.putObject(bucketName, s3Key, "Hello World"); + } + } + + @Test + public void whenS3ObjectDownloaded_thenSuccess() throws IOException { + String s3Url = "s3://" + bucketName + "/" + testFileToDownload; + springCloudS3.downloadS3Object(s3Url); + assertThat(new File(testFileToDownload)).exists(); + } + + @Test + public void whenS3ObjectUploaded_thenSuccess() throws IOException { + String s3Url = "s3://" + bucketName + "/" + testFileToUpload; + File file = new File(testFileToUpload); + springCloudS3.uploadFileToS3(file, s3Url); + } + + @Test + public void whenMultipleS3ObjectsDownloaded_thenSuccess() throws IOException { + String s3Url = "s3://" + bucketName + "/**/hello-*.txt"; + springCloudS3.downloadMultipleS3Objects(s3Url); + similarNameFiles.forEach(f -> assertThat(f).exists()); + } + + @AfterClass + public static void cleanUpResources() { + AmazonS3 amazonS3 = SpringCloudAwsTestUtil.amazonS3(); + ListObjectsV2Result listObjectsV2Result = amazonS3.listObjectsV2(bucketName); + for (S3ObjectSummary objectSummary : listObjectsV2Result.getObjectSummaries()) { + amazonS3.deleteObject(bucketName, objectSummary.getKey()); + } + amazonS3.deleteBucket(bucketName); + + new File(testFileToDownload).delete(); + new File(testFileToUpload).delete(); + similarNameFiles.forEach(File::delete); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sns/SNSEndpointControllerUnitTest.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sns/SNSEndpointControllerUnitTest.java new file mode 100644 index 0000000000..14958570e2 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sns/SNSEndpointControllerUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.spring.cloud.aws.sns; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.cloud.aws.messaging.endpoint.NotificationStatus; + +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; + +public class SNSEndpointControllerUnitTest { + + SNSEndpointController snsEndpointController; + + @Before + public void setUp() { + snsEndpointController = new SNSEndpointController(); + } + + @Test + public void whenReceivedNotificationInvoked_thenSuccess() { + snsEndpointController.receiveNotification("Message", "Subject"); + } + + @Test + public void whenConfirmUnsubscribeReturned_thenSuccess() { + NotificationStatus notificationStatus = mock(NotificationStatus.class); + doNothing().when(notificationStatus).confirmSubscription(); + snsEndpointController.confirmUnsubscribeMessage(notificationStatus); + } + + @Test + public void whenConfirmSubscriptionReturned_thenSuccess() { + NotificationStatus notificationStatus = mock(NotificationStatus.class); + doNothing().when(notificationStatus).confirmSubscription(); + snsEndpointController.confirmSubscriptionMessage(notificationStatus); + } + +} diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sns/SpringCloudSNSIntegrationTest.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sns/SpringCloudSNSIntegrationTest.java new file mode 100644 index 0000000000..e1f23d5c76 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sns/SpringCloudSNSIntegrationTest.java @@ -0,0 +1,61 @@ +package com.baeldung.spring.cloud.aws.sns; + +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import com.amazonaws.services.sns.AmazonSNS; +import com.amazonaws.services.sns.model.CreateTopicResult; +import com.baeldung.spring.cloud.aws.SpringCloudAwsTestUtil; +import com.baeldung.spring.cloud.aws.sqs.Greeting; + +@SpringBootTest +@RunWith(SpringRunner.class) +@TestPropertySource("classpath:application-test.properties") +public class SpringCloudSNSIntegrationTest { + + @Autowired + private SNSMessageSender snsMessageSender; + + private static String topicName; + private static String topicArn; + + @BeforeClass + public static void setupAwsResources() { + + topicName = UUID.randomUUID().toString(); + + AmazonSNS amazonSNS = SpringCloudAwsTestUtil.amazonSNS(); + + CreateTopicResult result = amazonSNS.createTopic(topicName); + topicArn = result.getTopicArn(); + } + + @Test + public void whenMessagePublished_thenSuccess() { + String subject = "Test Message"; + String message = "Hello World"; + snsMessageSender.send(topicName, message, subject); + } + + @Test + public void whenConvertedMessagePublished_thenSuccess() { + String subject = "Test Message"; + Greeting message = new Greeting("Helo", "World"); + snsMessageSender.send(topicName, message, subject); + } + + @AfterClass + public static void cleanupAwsResources() { + AmazonSNS amazonSNS = SpringCloudAwsTestUtil.amazonSNS(); + amazonSNS.deleteTopic(topicArn); + } + +} diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sqs/Greeting.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sqs/Greeting.java new file mode 100644 index 0000000000..3d14d55f14 --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sqs/Greeting.java @@ -0,0 +1,63 @@ +package com.baeldung.spring.cloud.aws.sqs; + +public class Greeting { + private String message; + private String name; + + public Greeting() { + + } + + public Greeting(String mesage, String name) { + this.message = mesage; + this.name = name; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((message == null) ? 0 : message.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Greeting other = (Greeting) obj; + if (message == null) { + if (other.message != null) + return false; + } else if (!message.equals(other.message)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sqs/SpringCloudSQSIntegrationTest.java b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sqs/SpringCloudSQSIntegrationTest.java new file mode 100644 index 0000000000..76d2fd7c0d --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/sqs/SpringCloudSQSIntegrationTest.java @@ -0,0 +1,135 @@ +package com.baeldung.spring.cloud.aws.sqs; + +import com.amazonaws.services.sqs.AmazonSQS; +import com.amazonaws.services.sqs.model.CreateQueueResult; +import com.amazonaws.services.sqs.model.PurgeQueueRequest; +import com.amazonaws.services.sqs.model.ReceiveMessageRequest; +import com.amazonaws.services.sqs.model.ReceiveMessageResult; +import com.baeldung.spring.cloud.aws.SpringCloudAwsTestUtil; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Lazy; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@RunWith(SpringRunner.class) +@TestPropertySource("classpath:application-test.properties") +public class SpringCloudSQSIntegrationTest { + + private static final Logger logger = LoggerFactory.getLogger(SpringCloudSQSIntegrationTest.class); + + @Autowired + @Lazy + private SpringCloudSQS springCloudSQS; + + private static String receiveQueueName; + private static String receiveQueueUrl; + + private static String sendQueueName; + private static String sendQueueURl; + + @BeforeClass + public static void setupAwsResources() { + + sendQueueName = UUID.randomUUID().toString(); + receiveQueueName = SpringCloudSQS.QUEUE_NAME; + + AmazonSQS amazonSQS = SpringCloudAwsTestUtil.amazonSQS(); + + CreateQueueResult receiveQueue = amazonSQS.createQueue(receiveQueueName); + receiveQueueUrl = receiveQueue.getQueueUrl(); + + CreateQueueResult sendQueue = amazonSQS.createQueue(sendQueueName); + sendQueueURl = sendQueue.getQueueUrl(); + } + + @Test + public void whenMessageSentAndVerified_thenSuccess() throws InterruptedException { + + String message = "Hello World"; + springCloudSQS.send(sendQueueName, message); + + AmazonSQS amazonSQS = SpringCloudAwsTestUtil.amazonSQS(); + + ReceiveMessageRequest request = new ReceiveMessageRequest(sendQueueURl); + request.setMaxNumberOfMessages(1); + + ReceiveMessageResult result = null; + do { + result = amazonSQS.receiveMessage(request); + if (result.getMessages().size() == 0) { + logger.info("Message not received at first time, waiting for 1 second"); + } + } while (result.getMessages().size() == 0); + assertThat(result.getMessages().get(0).getBody()).isEqualTo(message); + + // Delete message so that it doen't interfere with other test + amazonSQS.deleteMessage(sendQueueURl, result.getMessages().get(0).getReceiptHandle()); + + } + + @Test + public void whenConvertedMessageSentAndVerified_thenSuccess() throws InterruptedException, IOException { + + Greeting message = new Greeting("Hello", "World"); + springCloudSQS.send(sendQueueName, message); + + AmazonSQS amazonSQS = SpringCloudAwsTestUtil.amazonSQS(); + + ReceiveMessageRequest request = new ReceiveMessageRequest(sendQueueURl); + request.setMaxNumberOfMessages(1); + + ReceiveMessageResult result = null; + do { + result = amazonSQS.receiveMessage(request); + if (result.getMessages().size() == 0) { + logger.info("Message not received at first time, waiting for 1 second"); + } + } while (result.getMessages().size() == 0); + assertThat(new ObjectMapper().readValue(result.getMessages().get(0).getBody(), Greeting.class)).isEqualTo(message); + + // Delete message so that it doen't interfere with other test + amazonSQS.deleteMessage(sendQueueURl, result.getMessages().get(0).getReceiptHandle()); + } + + @Test + public void givenMessageSent_whenMessageReceived_thenSuccess() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(5); + springCloudSQS.setCountDownLatch(countDownLatch); + + AmazonSQS amazonSQS = SpringCloudAwsTestUtil.amazonSQS(); + for (int i = 0; i < 5; i++) { + amazonSQS.sendMessage(receiveQueueUrl, "Hello World " + i); + logger.info("Sent message {}, waiting for 1 second", i + 1); + Thread.sleep(1000L); + } + countDownLatch.await(); + } + + @AfterClass + public static void cleanupAwsResources() { + AmazonSQS amazonSQS = SpringCloudAwsTestUtil.amazonSQS(); + PurgeQueueRequest receiveQueuePurge = new PurgeQueueRequest(receiveQueueUrl); + amazonSQS.purgeQueue(receiveQueuePurge); + amazonSQS.deleteQueue(receiveQueueUrl); + + PurgeQueueRequest sendQueuePurge = new PurgeQueueRequest(sendQueueURl); + amazonSQS.purgeQueue(sendQueuePurge); + amazonSQS.deleteQueue(sendQueueURl); + } +} diff --git a/spring-cloud/spring-cloud-aws/src/test/resources/application-test.properties b/spring-cloud/spring-cloud-aws/src/test/resources/application-test.properties new file mode 100644 index 0000000000..0d3d90b03a --- /dev/null +++ b/spring-cloud/spring-cloud-aws/src/test/resources/application-test.properties @@ -0,0 +1,4 @@ +# Don't try to create DataSouce when running tests which don't need a DataSource +spring.autoconfigure.exclude=\ + org.springframework.cloud.aws.autoconfigure.jdbc.AmazonRdsDatabaseAutoConfiguration,\ + org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration diff --git a/spring-cloud/spring-cloud-stream/README.md b/spring-cloud/spring-cloud-stream/README.md new file mode 100644 index 0000000000..5ecb852df5 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Introduction to Spring Cloud Stream](http://www.baeldung.com/spring-cloud-stream) diff --git a/spring-cloud/spring-cloud-stream/pom.xml b/spring-cloud/spring-cloud-stream/pom.xml index 2104ba1827..1666a440b9 100644 --- a/spring-cloud/spring-cloud-stream/pom.xml +++ b/spring-cloud/spring-cloud-stream/pom.xml @@ -1,14 +1,12 @@ + xmlns="http://maven.apache.org/POM/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 org.baeldung spring-cloud-stream - - spring-cloud-stream-rabbit - + pom spring-cloud-stream @@ -19,6 +17,10 @@ 1.0.0-SNAPSHOT + + spring-cloud-stream-rabbit + + UTF-8 3.6.0 @@ -31,7 +33,7 @@ spring-cloud-starter-stream-rabbit ${spring-cloud-stream.version} - + org.springframework.cloud spring-cloud-stream diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplicationIntegrationTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplicationIntegrationTest.java new file mode 100644 index 0000000000..898d06897f --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsServiceApplicationIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.cloud.stream.rabbit; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.stream.test.binder.MessageCollector; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.cloud.stream.rabbit.processor.MyProcessor; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MultipleOutputsServiceApplication.class) +@DirtiesContext +public class MultipleOutputsServiceApplicationIntegrationTest { + + @Autowired + private MyProcessor pipe; + + @Autowired + private MessageCollector messageCollector; + + @Test + public void whenSendMessage_thenResponseIsInAOutput() { + whenSendMessage(1); + thenPayloadInChannelIs(pipe.anOutput(), 1); + } + + @Test + public void whenSendMessage_thenResponseIsInAnotherOutput() { + whenSendMessage(11); + thenPayloadInChannelIs(pipe.anotherOutput(), 11); + } + + private void whenSendMessage(Integer val) { + pipe.myInput() + .send(MessageBuilder.withPayload(val) + .build()); + } + + private void thenPayloadInChannelIs(MessageChannel channel, Integer expectedValue) { + Object payload = messageCollector.forChannel(channel) + .poll() + .getPayload(); + assertEquals(expectedValue, payload); + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceIntegrationTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceIntegrationTest.java new file mode 100644 index 0000000000..c3bf5a1205 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MultipleOutputsWithConditionsServiceIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.spring.cloud.stream.rabbit; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.stream.test.binder.MessageCollector; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.cloud.stream.rabbit.processor.MyProcessor; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MultipleOutputsWithConditionsServiceApplication.class) +@DirtiesContext +public class MultipleOutputsWithConditionsServiceIntegrationTest { + + @Autowired + private MyProcessor pipe; + + @Autowired + private MessageCollector messageCollector; + + @Test + public void whenSendMessage_thenResponseIsInAOutput() { + whenSendMessage(1); + thenPayloadInChannelIs(pipe.anOutput(), 1); + } + + @Test + public void whenSendMessage_thenResponseIsInAnotherOutput() { + whenSendMessage(11); + thenPayloadInChannelIs(pipe.anotherOutput(), 11); + } + + private void whenSendMessage(Integer val) { + pipe.myInput() + .send(MessageBuilder.withPayload(val) + .build()); + } + + private void thenPayloadInChannelIs(MessageChannel channel, Integer expectedValue) { + Object payload = messageCollector.forChannel(channel) + .poll() + .getPayload(); + assertEquals(expectedValue, payload); + } +} diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerApplicationIntegrationTest.java b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerApplicationIntegrationTest.java new file mode 100644 index 0000000000..21d84e79e0 --- /dev/null +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-rabbit/src/test/java/com/baeldung/spring/cloud/stream/rabbit/MyLoggerApplicationIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.cloud.stream.rabbit; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.stream.messaging.Processor; +import org.springframework.cloud.stream.test.binder.MessageCollector; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.cloud.stream.rabbit.model.LogMessage; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MyLoggerServiceApplication.class) +@DirtiesContext +public class MyLoggerApplicationIntegrationTest { + + @Autowired + private Processor pipe; + + @Autowired + private MessageCollector messageCollector; + + @Test + public void whenSendMessage_thenResponseShouldUpdateText() { + pipe.input() + .send(MessageBuilder.withPayload(new LogMessage("This is my message")) + .build()); + + Object payload = messageCollector.forChannel(pipe.output()) + .poll() + .getPayload(); + + assertEquals("[1]: This is my message", payload.toString()); + } +} diff --git a/spring-core/src/main/resources/com.baeldung.di.spring.xml b/spring-core/src/main/resources/com.baeldung.di.spring.xml index 9c44d911d1..e0c5d22abb 100644 --- a/spring-core/src/main/resources/com.baeldung.di.spring.xml +++ b/spring-core/src/main/resources/com.baeldung.di.spring.xml @@ -5,7 +5,7 @@ - + @@ -29,15 +29,15 @@ - + - + - + \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java index 1d133faf63..1660b99726 100644 --- a/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java @@ -15,31 +15,17 @@ public class BeanInjectionTest { applicationContext = new ClassPathXmlApplicationContext("com.baeldung.di.spring.xml"); } - @Test - public void protoBean_getBean_returnsMultipleInstance() { - final MessageApp messageApp1 = applicationContext.getBean("messageWorldApp", MessageApp.class); - final MessageApp messageApp2 = applicationContext.getBean("messageWorldApp", MessageApp.class); - assertNotEquals(messageApp1, messageApp2); - } - - @Test - public void protoFactoryMethod_getBean_returnsMultipleInstance() { - final IndexApp indexApp1 = applicationContext.getBean("indexAppWithFactoryMethod", IndexApp.class); - final IndexApp indexApp2 = applicationContext.getBean("indexAppWithFactoryMethod", IndexApp.class); - assertNotEquals(indexApp1, indexApp2); - } - - @Test - public void protoStaticFactory_getBean_returnsMultipleInstance() { - final IndexApp indexApp1 = applicationContext.getBean("indexAppWithStaticFactory", IndexApp.class); - final IndexApp indexApp2 = applicationContext.getBean("indexAppWithStaticFactory", IndexApp.class); - assertNotEquals(indexApp1, indexApp2); - } - @Test public void singletonBean_getBean_returnsSingleInstance() { final IndexApp indexApp1 = applicationContext.getBean("indexApp", IndexApp.class); final IndexApp indexApp2 = applicationContext.getBean("indexApp", IndexApp.class); assertEquals(indexApp1, indexApp2); } + + @Test + public void getBean_returnsInstance() { + final IndexApp indexApp = applicationContext.getBean("indexApp", IndexApp.class); + assertNotNull(indexApp); + } + } diff --git a/spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationTests.java b/spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationIntegrationTest.java similarity index 82% rename from spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationTests.java rename to spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationIntegrationTest.java index b39a5605b1..71eec9cf45 100644 --- a/spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationTests.java +++ b/spring-jmeter-jenkins/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class SpringJMeterJenkinsApplicationTests { +public class SpringJMeterJenkinsApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml new file mode 100644 index 0000000000..554040e763 --- /dev/null +++ b/spring-rest-embedded-tomcat/pom.xml @@ -0,0 +1,83 @@ + + 4.0.0 + org.baeldung.embedded + SpringRestTomcat + 0.0.1-SNAPSHOT + + spring-rest-embedded-tomcat + war + + + + junit + junit + ${junit.version} + test + + + + org.springframework + spring-core + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + + javax.servlet + javax.servlet-api + 4.0.0 + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.library} + + + + org.apache.tomcat.embed + tomcat-embed-core + 9.0.1 + test + + + + org.apache.tomcat + tomcat-jasper + 9.0.1 + test + + + + org.apache.httpcomponents + httpclient + 4.5.3 + + + + org.apache.httpcomponents + httpcore + 4.4.8 + + + + + + spring-rest-embedded-tomcat + + + + 5.0.1.RELEASE + 4.12 + 2.9.2 + 1.8 + 1.8 + false + + + \ No newline at end of file diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/AppInitializer.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/AppInitializer.java new file mode 100644 index 0000000000..24bd28166b --- /dev/null +++ b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/AppInitializer.java @@ -0,0 +1,22 @@ +package org.baeldung.embedded.configuration; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return new Class[] { UserConfiguration.class }; + } + + @Override + protected Class[] getServletConfigClasses() { + return null; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + +} diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/UserConfiguration.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/UserConfiguration.java new file mode 100644 index 0000000000..4c102a74cb --- /dev/null +++ b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/configuration/UserConfiguration.java @@ -0,0 +1,12 @@ +package org.baeldung.embedded.configuration; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "org.baeldung.embedded") +public class UserConfiguration { + +} diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/controller/UserController.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/controller/UserController.java new file mode 100644 index 0000000000..a9a5faa0c6 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/controller/UserController.java @@ -0,0 +1,28 @@ +package org.baeldung.embedded.controller; + +import org.baeldung.embedded.domain.User; +import org.baeldung.embedded.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserController { + + @Autowired + UserService userService; + + @RequestMapping("/") + public String welcome() { + return "Hello World!"; + } + + @RequestMapping(method = RequestMethod.GET, value = "/user/{userName}") + @ResponseBody + public User user(@PathVariable String userName) { + return this.userService.getUser(userName); + } +} diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/domain/User.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/domain/User.java new file mode 100644 index 0000000000..2f9443daea --- /dev/null +++ b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/domain/User.java @@ -0,0 +1,23 @@ +package org.baeldung.embedded.domain; + +public class User { + + private String name; + private String hobby; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getHobby() { + return hobby; + } + + public void setHobby(String hobby) { + this.hobby = hobby; + } +} diff --git a/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/service/UserService.java b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/service/UserService.java new file mode 100644 index 0000000000..76696e12c2 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/main/java/org/baeldung/embedded/service/UserService.java @@ -0,0 +1,38 @@ +package org.baeldung.embedded.service; + +import java.util.ArrayList; +import java.util.List; + +import org.baeldung.embedded.domain.User; +import org.springframework.stereotype.Service; + +@Service +public class UserService { + private List users = new ArrayList<>(); + + public void addUser(String name) { + User user = new User(); + user.setName(name); + if (name == "HarryPotter") { + user.setHobby("Quidditch"); + } else { + user.setHobby("MuggleActivity"); + } + users.add(user); + } + + public User getUser(String name) { + for (User user : users) { + if (user.getName() + .equalsIgnoreCase(name)) { + return user; + } + } + + User user = new User(); + user.setName(name); + user.setHobby("None"); + + return user; + } +} diff --git a/spring-rest-embedded-tomcat/src/main/webapp/emptyFile b/spring-rest-embedded-tomcat/src/main/webapp/emptyFile new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatApp.java b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatApp.java new file mode 100644 index 0000000000..f340f6c837 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatApp.java @@ -0,0 +1,70 @@ +package org.baeldung.embedded; + +import java.io.File; +import java.util.concurrent.CountDownLatch; +import org.apache.catalina.Context; +import org.apache.catalina.startup.Tomcat; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.WebApplicationContextUtils; + +public class EmbeddedTomcatApp { + + private Tomcat tomcatInstance; + private WebApplicationContext webApplicationContext; + private CountDownLatch started = new CountDownLatch(1); + + public void start() throws Exception { + tomcatInstance = new Tomcat(); + tomcatInstance.setBaseDir(new File(getClass().getResource(".") + .toURI()).getAbsolutePath()); // Tomcat's temporary directory + tomcatInstance.setPort(0); + + Context webapp = tomcatInstance.addWebapp("", new File("src/main/webapp/").getAbsolutePath()); + + webapp.addLifecycleListener(event -> { + if (event.getType() + .equals("after_stop")) { + started.countDown(); + } else if (event.getType() + .equals("after_start")) { + webApplicationContext = WebApplicationContextUtils + .findWebApplicationContext(webapp.getServletContext()); + + ((ConfigurableListableBeanFactory) webApplicationContext + .getAutowireCapableBeanFactory()).registerSingleton("baseUrl", getBaseUrl()); + + started.countDown(); + } + }); + + tomcatInstance.start(); + started.await(); + } + + public Tomcat getTomcatInstance() { + return this.tomcatInstance; + } + + public String getBaseUrl() { + return String.format("http://localhost:%d%s", getLocalPort(), getWebApplicationContext().getServletContext() + .getContextPath()); + } + + public int getLocalPort() { + return tomcatInstance.getConnector() + .getLocalPort(); + } + + public WebApplicationContext getWebApplicationContext() { + return webApplicationContext; + } + + public boolean isStarted() { + return started.getCount() == 0; + } + + public boolean isStartedSucessfully() { + return webApplicationContext != null; + } +} diff --git a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatRunner.java b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatRunner.java new file mode 100644 index 0000000000..1bf15556e8 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/EmbeddedTomcatRunner.java @@ -0,0 +1,45 @@ +package org.baeldung.embedded; + +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.BlockJUnit4ClassRunner; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.Statement; + +public class EmbeddedTomcatRunner extends BlockJUnit4ClassRunner { + + public EmbeddedTomcatRunner(Class klass) throws InitializationError { + super(klass); + } + + // use one static Tomcat instance shared across all tests + private static EmbeddedTomcatApp embeddedTomcatApp = new EmbeddedTomcatApp(); + + @Override + protected Statement classBlock(RunNotifier notifier) { + ensureSharedTomcatStarted(); + Statement result = super.classBlock(notifier); + return result; + } + + private void ensureSharedTomcatStarted() { + if (!embeddedTomcatApp.isStarted()) { + try { + embeddedTomcatApp.start(); + } catch (Exception e) { + throw new RuntimeException("Error while starting embedded Tomcat server", e); + } + } + } + + @Override + protected Object createTest() throws Exception { + if (!embeddedTomcatApp.isStartedSucessfully()) { + throw new RuntimeException("Tomcat server not started successfully. Skipping test"); + } + Object testInstance = super.createTest(); + embeddedTomcatApp.getWebApplicationContext() + .getAutowireCapableBeanFactory() + .autowireBean(testInstance); + return testInstance; + } +} \ No newline at end of file diff --git a/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/UserIntegrationTest.java b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/UserIntegrationTest.java new file mode 100644 index 0000000000..1c5d482171 --- /dev/null +++ b/spring-rest-embedded-tomcat/src/test/java/org/baeldung/embedded/UserIntegrationTest.java @@ -0,0 +1,60 @@ +package org.baeldung.embedded; + +import java.io.IOException; +import java.util.Map; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.baeldung.embedded.service.UserService; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(EmbeddedTomcatRunner.class) +public class UserIntegrationTest { + + @Autowired + protected String baseUrl; + + @Autowired + private UserService userService; + + private String userName = "HarryPotter"; + + @Before + public void setUp() { + userService.addUser(userName); + } + + @Test + public void givenUserName_whenSendGetForHarryPotter_thenHobbyQuidditch() throws IOException { + String url = baseUrl + "/user/" + userName; + + HttpClient httpClient = HttpClientBuilder.create() + .build(); + HttpGet getUserRequest = new HttpGet(url); + getUserRequest.addHeader("Content-type", "application/json"); + HttpResponse response = httpClient.execute(getUserRequest); + + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine() + .getStatusCode()); + + HttpEntity responseEntity = response.getEntity(); + + Assert.assertNotNull(responseEntity); + + ObjectMapper mapper = new ObjectMapper(); + String retSrc = EntityUtils.toString(responseEntity); + Map result = mapper.readValue(retSrc, Map.class); + + Assert.assertEquals("Quidditch", result.get("hobby")); + } +} diff --git a/spring-rest-full/src/testFile b/spring-rest-full/src/testFile new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-rest-full/src/testFile @@ -0,0 +1 @@ + diff --git a/spring-rest-shell/README.md b/spring-rest-shell/README.md index 06e18450c6..901d9a51ee 100644 --- a/spring-rest-shell/README.md +++ b/spring-rest-shell/README.md @@ -2,4 +2,4 @@ ### Relevant Articles -- [Spring REST Shell](http://www.baeldung.com/) \ No newline at end of file +- [Spring REST Shell](http://www.baeldung.com/spring-rest-shell) \ No newline at end of file diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index f662b736ad..f3fdd78ff4 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -230,7 +230,7 @@ **/JdbcTest.java **/*LiveTest.java - true + diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index 3a8bc1f3aa..6566c0eea6 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -122,6 +122,25 @@ jstl-api ${jstl.version} + + + org.springframework.security + spring-security-acl + + + org.springframework.security + spring-security-config + + + org.springframework + spring-context-support + + + net.sf.ehcache + ehcache-core + 2.6.11 + jar + diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/ACLContext.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/ACLContext.java new file mode 100644 index 0000000000..63a4ea58ef --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/ACLContext.java @@ -0,0 +1,80 @@ +package org.baeldung.acl.config; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.cache.ehcache.EhCacheFactoryBean; +import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; +import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; +import org.springframework.security.acls.AclPermissionCacheOptimizer; +import org.springframework.security.acls.AclPermissionEvaluator; +import org.springframework.security.acls.domain.AclAuthorizationStrategy; +import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl; +import org.springframework.security.acls.domain.ConsoleAuditLogger; +import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy; +import org.springframework.security.acls.domain.EhCacheBasedAclCache; +import org.springframework.security.acls.jdbc.BasicLookupStrategy; +import org.springframework.security.acls.jdbc.JdbcMutableAclService; +import org.springframework.security.acls.jdbc.LookupStrategy; +import org.springframework.security.acls.model.PermissionGrantingStrategy; +import org.springframework.security.core.authority.SimpleGrantedAuthority; + +@Configuration +@EnableAutoConfiguration +public class ACLContext { + + @Autowired + DataSource dataSource; + + @Bean + public EhCacheBasedAclCache aclCache() { + return new EhCacheBasedAclCache(aclEhCacheFactoryBean().getObject(), permissionGrantingStrategy(), aclAuthorizationStrategy()); + } + + @Bean + public EhCacheFactoryBean aclEhCacheFactoryBean() { + EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean(); + ehCacheFactoryBean.setCacheManager(aclCacheManager().getObject()); + ehCacheFactoryBean.setCacheName("aclCache"); + return ehCacheFactoryBean; + } + + @Bean + public EhCacheManagerFactoryBean aclCacheManager() { + return new EhCacheManagerFactoryBean(); + } + + @Bean + public PermissionGrantingStrategy permissionGrantingStrategy() { + return new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()); + } + + @Bean + public AclAuthorizationStrategy aclAuthorizationStrategy() { + return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMIN")); + } + + @Bean + public MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler() { + DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); + AclPermissionEvaluator permissionEvaluator = new AclPermissionEvaluator(aclService()); + expressionHandler.setPermissionEvaluator(permissionEvaluator); + expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService())); + return expressionHandler; + } + + @Bean + public LookupStrategy lookupStrategy() { + return new BasicLookupStrategy(dataSource, aclCache(), aclAuthorizationStrategy(), new ConsoleAuditLogger()); + } + + @Bean + public JdbcMutableAclService aclService() { + return new JdbcMutableAclService(dataSource, lookupStrategy(), aclCache()); + } + +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java new file mode 100644 index 0000000000..110c4a6d24 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java @@ -0,0 +1,21 @@ +package org.baeldung.acl.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; + +@Configuration +@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) +public class AclMethodSecurityConfiguration extends GlobalMethodSecurityConfiguration { + + @Autowired + MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler; + + @Override + protected MethodSecurityExpressionHandler createExpressionHandler() { + return defaultMethodSecurityExpressionHandler; + } + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java new file mode 100644 index 0000000000..9b87efa92c --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java @@ -0,0 +1,16 @@ +package org.baeldung.acl.config; + +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories(basePackages = "org.baeldung.acl.persistence.dao") +@PropertySource("classpath:org.baeldung.acl.datasource.properties") +@EntityScan(basePackages={ "org.baeldung.acl.persistence.entity" }) +public class JPAPersistenceConfig { + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java new file mode 100644 index 0000000000..8662c88d6c --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java @@ -0,0 +1,24 @@ +package org.baeldung.acl.persistence.dao; + +import java.util.List; + +import org.baeldung.acl.persistence.entity.NoticeMessage; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.security.access.prepost.PostAuthorize; +import org.springframework.security.access.prepost.PostFilter; +import org.springframework.security.access.prepost.PreAuthorize; + +public interface NoticeMessageRepository extends JpaRepository{ + + @PostFilter("hasPermission(filterObject, 'READ')") + List findAll(); + + @PostAuthorize("hasPermission(returnObject, 'READ')") + NoticeMessage findById(Integer id); + + @SuppressWarnings("unchecked") + @PreAuthorize("hasPermission(#noticeMessage, 'WRITE')") + NoticeMessage save(@Param("noticeMessage")NoticeMessage noticeMessage); + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java new file mode 100644 index 0000000000..23f01a8edb --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java @@ -0,0 +1,29 @@ +package org.baeldung.acl.persistence.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="system_message") +public class NoticeMessage { + + @Id + @Column + private Integer id; + @Column + private String content; + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + public String getContent() { + return content; + } + public void setContent(String content) { + this.content = content; + } +} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/acl-data.sql b/spring-security-mvc-boot/src/main/resources/acl-data.sql new file mode 100644 index 0000000000..6c01eaacc2 --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/acl-data.sql @@ -0,0 +1,28 @@ +INSERT INTO system_message(id,content) VALUES (1,'First Level Message'); +INSERT INTO system_message(id,content) VALUES (2,'Second Level Message'); +INSERT INTO system_message(id,content) VALUES (3,'Third Level Message'); + +INSERT INTO acl_class (id, class) VALUES +(1, 'org.baeldung.acl.persistence.entity.NoticeMessage'); + +INSERT INTO acl_sid (id, principal, sid) VALUES +(1, 1, 'manager'), +(2, 1, 'hr'), +(3, 1, 'admin'), +(4, 0, 'ROLE_EDITOR'); + +INSERT INTO acl_object_identity (id, object_id_class, object_id_identity, parent_object, owner_sid, entries_inheriting) VALUES +(1, 1, 1, NULL, 3, 0), +(2, 1, 2, NULL, 3, 0), +(3, 1, 3, NULL, 3, 0) +; + +INSERT INTO acl_entry (id, acl_object_identity, ace_order, sid, mask, granting, audit_success, audit_failure) VALUES +(1, 1, 1, 1, 1, 1, 1, 1), +(2, 1, 2, 1, 2, 1, 1, 1), +(3, 1, 3, 4, 1, 1, 1, 1), +(4, 2, 1, 2, 1, 1, 1, 1), +(5, 2, 2, 4, 1, 1, 1, 1), +(6, 3, 1, 4, 1, 1, 1, 1), +(7, 3, 2, 4, 2, 1, 1, 1) +; \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/acl-schema.sql b/spring-security-mvc-boot/src/main/resources/acl-schema.sql new file mode 100644 index 0000000000..58e9394b2b --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/acl-schema.sql @@ -0,0 +1,58 @@ +create table system_message (id integer not null, content varchar(255), primary key (id)); + +CREATE TABLE IF NOT EXISTS acl_sid ( + id bigint(20) NOT NULL AUTO_INCREMENT, + principal tinyint(1) NOT NULL, + sid varchar(100) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY unique_uk_1 (sid,principal) +); + +CREATE TABLE IF NOT EXISTS acl_class ( + id bigint(20) NOT NULL AUTO_INCREMENT, + class varchar(255) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY unique_uk_2 (class) +); + +CREATE TABLE IF NOT EXISTS acl_entry ( + id bigint(20) NOT NULL AUTO_INCREMENT, + acl_object_identity bigint(20) NOT NULL, + ace_order int(11) NOT NULL, + sid bigint(20) NOT NULL, + mask int(11) NOT NULL, + granting tinyint(1) NOT NULL, + audit_success tinyint(1) NOT NULL, + audit_failure tinyint(1) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY unique_uk_4 (acl_object_identity,ace_order) +); + +CREATE TABLE IF NOT EXISTS acl_object_identity ( + id bigint(20) NOT NULL AUTO_INCREMENT, + object_id_class bigint(20) NOT NULL, + object_id_identity bigint(20) NOT NULL, + parent_object bigint(20) DEFAULT NULL, + owner_sid bigint(20) DEFAULT NULL, + entries_inheriting tinyint(1) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY unique_uk_3 (object_id_class,object_id_identity) +); + +ALTER TABLE acl_entry +ADD FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity(id); + +ALTER TABLE acl_entry +ADD FOREIGN KEY (sid) REFERENCES acl_sid(id); + +-- +-- Constraints for table acl_object_identity +-- +ALTER TABLE acl_object_identity +ADD FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id); + +ALTER TABLE acl_object_identity +ADD FOREIGN KEY (object_id_class) REFERENCES acl_class (id); + +ALTER TABLE acl_object_identity +ADD FOREIGN KEY (owner_sid) REFERENCES acl_sid (id); \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/org.baeldung.acl.datasource.properties b/spring-security-mvc-boot/src/main/resources/org.baeldung.acl.datasource.properties new file mode 100644 index 0000000000..739dd3f07c --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/org.baeldung.acl.datasource.properties @@ -0,0 +1,12 @@ +spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE +spring.datasource.username=sa +spring.datasource.password= +spring.datasource.driverClassName=org.h2.Driver +spring.jpa.hibernate.ddl-auto=update +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect + +spring.h2.console.path=/myconsole +spring.h2.console.enabled=true +spring.datasource.initialize=true +spring.datasource.schema=classpath:acl-schema.sql +spring.datasource.data=classpath:acl-data.sql \ No newline at end of file diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..cf1ac7de89 --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/acl/SpringAclIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/acl/SpringAclIntegrationTest.java new file mode 100644 index 0000000000..38e1a2a9e7 --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/acl/SpringAclIntegrationTest.java @@ -0,0 +1,119 @@ +package org.baeldung.acl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.List; + +import org.baeldung.acl.persistence.dao.NoticeMessageRepository; +import org.baeldung.acl.persistence.entity.NoticeMessage; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import org.springframework.test.context.support.DirtiesContextTestExecutionListener; +import org.springframework.test.context.transaction.TransactionalTestExecutionListener; +import org.springframework.test.context.web.ServletTestExecutionListener; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +@TestExecutionListeners(listeners={ServletTestExecutionListener.class, + DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + TransactionalTestExecutionListener.class, + WithSecurityContextTestExecutionListener.class}) +public class SpringAclIntegrationTest extends AbstractJUnit4SpringContextTests{ + + private static Integer FIRST_MESSAGE_ID = 1; + private static Integer SECOND_MESSAGE_ID = 2; + private static Integer THIRD_MESSAGE_ID = 3; + private static String EDITTED_CONTENT = "EDITED"; + + @Configuration + @ComponentScan("org.baeldung.acl.*") + public static class SpringConfig { + + } + + @Autowired + NoticeMessageRepository repo; + + @Test + @WithMockUser(username="manager") + public void givenUsernameManager_whenFindAllMessage_thenReturnFirstMessage(){ + List details = repo.findAll(); + assertNotNull(details); + assertEquals(1,details.size()); + assertEquals(FIRST_MESSAGE_ID,details.get(0).getId()); + } + + @Test + @WithMockUser(username="manager") + public void givenUsernameManager_whenFindFirstMessageByIdAndUpdateFirstMessageContent_thenOK(){ + NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID); + assertNotNull(firstMessage); + assertEquals(FIRST_MESSAGE_ID,firstMessage.getId()); + + firstMessage.setContent(EDITTED_CONTENT); + repo.save(firstMessage); + + NoticeMessage editedFirstMessage = repo.findById(FIRST_MESSAGE_ID); + assertNotNull(editedFirstMessage); + assertEquals(FIRST_MESSAGE_ID,editedFirstMessage.getId()); + assertEquals(EDITTED_CONTENT,editedFirstMessage.getContent()); + } + + @Test + @WithMockUser(username="hr") + public void givenUsernameHr_whenFindMessageById2_thenOK(){ + NoticeMessage secondMessage = repo.findById(SECOND_MESSAGE_ID); + assertNotNull(secondMessage); + assertEquals(SECOND_MESSAGE_ID,secondMessage.getId()); + } + + @Test(expected=AccessDeniedException.class) + @WithMockUser(username="hr") + public void givenUsernameHr_whenUpdateMessageWithId2_thenFail(){ + NoticeMessage secondMessage = new NoticeMessage(); + secondMessage.setId(SECOND_MESSAGE_ID); + secondMessage.setContent(EDITTED_CONTENT); + repo.save(secondMessage); + } + + @Test + @WithMockUser(roles={"EDITOR"}) + public void givenRoleEditor_whenFindAllMessage_thenReturnThreeMessage(){ + List details = repo.findAll(); + assertNotNull(details); + assertEquals(3,details.size()); + } + + @Test + @WithMockUser(roles={"EDITOR"}) + public void givenRoleEditor_whenUpdateThirdMessage_thenOK(){ + NoticeMessage thirdMessage = new NoticeMessage(); + thirdMessage.setId(THIRD_MESSAGE_ID); + thirdMessage.setContent(EDITTED_CONTENT); + repo.save(thirdMessage); + } + + @Test(expected=AccessDeniedException.class) + @WithMockUser(roles={"EDITOR"}) + public void givenRoleEditor_whenFindFirstMessageByIdAndUpdateFirstMessageContent_thenFail(){ + NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID); + assertNotNull(firstMessage); + assertEquals(FIRST_MESSAGE_ID,firstMessage.getId()); + firstMessage.setContent(EDITTED_CONTENT); + repo.save(firstMessage); + } +} + \ No newline at end of file diff --git a/spring-vertx/pom.xml b/spring-vertx/pom.xml index 2ab506f667..2b26d939a5 100644 --- a/spring-vertx/pom.xml +++ b/spring-vertx/pom.xml @@ -80,7 +80,7 @@ **/JdbcTest.java **/*LiveTest.java - true + diff --git a/struts2/README.md b/struts-2/README.md similarity index 100% rename from struts2/README.md rename to struts-2/README.md diff --git a/struts2/WebContent/WEB-INF/web.xml b/struts-2/WebContent/WEB-INF/web.xml similarity index 100% rename from struts2/WebContent/WEB-INF/web.xml rename to struts-2/WebContent/WEB-INF/web.xml diff --git a/struts2/WebContent/input.jsp b/struts-2/WebContent/input.jsp similarity index 100% rename from struts2/WebContent/input.jsp rename to struts-2/WebContent/input.jsp diff --git a/struts2/WebContent/result.jsp b/struts-2/WebContent/result.jsp similarity index 100% rename from struts2/WebContent/result.jsp rename to struts-2/WebContent/result.jsp diff --git a/struts2/pom.xml b/struts-2/pom.xml similarity index 100% rename from struts2/pom.xml rename to struts-2/pom.xml diff --git a/struts2/src/main/java/com/baeldung/struts/CarAction.java b/struts-2/src/main/java/com/baeldung/struts/CarAction.java similarity index 100% rename from struts2/src/main/java/com/baeldung/struts/CarAction.java rename to struts-2/src/main/java/com/baeldung/struts/CarAction.java diff --git a/struts2/src/main/java/com/baeldung/struts/CarMessageService.java b/struts-2/src/main/java/com/baeldung/struts/CarMessageService.java similarity index 100% rename from struts2/src/main/java/com/baeldung/struts/CarMessageService.java rename to struts-2/src/main/java/com/baeldung/struts/CarMessageService.java diff --git a/struts2/src/test/java/com/baeldung/struts/test/CarActionTest.java b/struts-2/src/test/java/com/baeldung/struts/test/CarActionTest.java similarity index 100% rename from struts2/src/test/java/com/baeldung/struts/test/CarActionTest.java rename to struts-2/src/test/java/com/baeldung/struts/test/CarActionTest.java diff --git a/testing-modules/README.md b/testing-modules/README.md new file mode 100644 index 0000000000..3fbeea6188 --- /dev/null +++ b/testing-modules/README.md @@ -0,0 +1,3 @@ + +## Testing Modules + diff --git a/gatling/README.md b/testing-modules/gatling/README.md similarity index 100% rename from gatling/README.md rename to testing-modules/gatling/README.md diff --git a/gatling/pom.xml b/testing-modules/gatling/pom.xml similarity index 100% rename from gatling/pom.xml rename to testing-modules/gatling/pom.xml diff --git a/gatling/src/test/resources/gatling.conf b/testing-modules/gatling/src/test/resources/gatling.conf similarity index 100% rename from gatling/src/test/resources/gatling.conf rename to testing-modules/gatling/src/test/resources/gatling.conf diff --git a/gatling/src/test/resources/logback.xml b/testing-modules/gatling/src/test/resources/logback.xml similarity index 100% rename from gatling/src/test/resources/logback.xml rename to testing-modules/gatling/src/test/resources/logback.xml diff --git a/gatling/src/test/resources/recorder.conf b/testing-modules/gatling/src/test/resources/recorder.conf similarity index 100% rename from gatling/src/test/resources/recorder.conf rename to testing-modules/gatling/src/test/resources/recorder.conf diff --git a/gatling/src/test/scala/Engine.scala b/testing-modules/gatling/src/test/scala/Engine.scala similarity index 100% rename from gatling/src/test/scala/Engine.scala rename to testing-modules/gatling/src/test/scala/Engine.scala diff --git a/gatling/src/test/scala/IDEPathHelper.scala b/testing-modules/gatling/src/test/scala/IDEPathHelper.scala similarity index 100% rename from gatling/src/test/scala/IDEPathHelper.scala rename to testing-modules/gatling/src/test/scala/IDEPathHelper.scala diff --git a/gatling/src/test/scala/Recorder.scala b/testing-modules/gatling/src/test/scala/Recorder.scala similarity index 100% rename from gatling/src/test/scala/Recorder.scala rename to testing-modules/gatling/src/test/scala/Recorder.scala diff --git a/gatling/src/test/scala/org/baeldung/RecordedSimulation.scala b/testing-modules/gatling/src/test/scala/org/baeldung/RecordedSimulation.scala similarity index 100% rename from gatling/src/test/scala/org/baeldung/RecordedSimulation.scala rename to testing-modules/gatling/src/test/scala/org/baeldung/RecordedSimulation.scala diff --git a/groovy-spock/README.md b/testing-modules/groovy-spock/README.md similarity index 100% rename from groovy-spock/README.md rename to testing-modules/groovy-spock/README.md diff --git a/groovy-spock/pom.xml b/testing-modules/groovy-spock/pom.xml similarity index 97% rename from groovy-spock/pom.xml rename to testing-modules/groovy-spock/pom.xml index d9b51c5e1a..f4e61e6786 100644 --- a/groovy-spock/pom.xml +++ b/testing-modules/groovy-spock/pom.xml @@ -17,6 +17,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/groovy-spock/src/test/groovy/FirstSpecification.groovy b/testing-modules/groovy-spock/src/test/groovy/FirstSpecification.groovy similarity index 100% rename from groovy-spock/src/test/groovy/FirstSpecification.groovy rename to testing-modules/groovy-spock/src/test/groovy/FirstSpecification.groovy diff --git a/groovy-spock/src/test/groovy/Notifier.groovy b/testing-modules/groovy-spock/src/test/groovy/Notifier.groovy similarity index 100% rename from groovy-spock/src/test/groovy/Notifier.groovy rename to testing-modules/groovy-spock/src/test/groovy/Notifier.groovy diff --git a/groovy-spock/src/test/groovy/PaymentGateway.groovy b/testing-modules/groovy-spock/src/test/groovy/PaymentGateway.groovy similarity index 100% rename from groovy-spock/src/test/groovy/PaymentGateway.groovy rename to testing-modules/groovy-spock/src/test/groovy/PaymentGateway.groovy diff --git a/junit5/README.md b/testing-modules/junit-5/README.md similarity index 91% rename from junit5/README.md rename to testing-modules/junit-5/README.md index d0fa19bd83..20ecb1eeab 100644 --- a/junit5/README.md +++ b/testing-modules/junit-5/README.md @@ -7,3 +7,4 @@ - [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) - [Inject Parameters into JUnit Jupiter Unit Tests](http://www.baeldung.com/junit-5-parameters) - [Mockito and JUnit 5 – Using ExtendWith](http://www.baeldung.com/mockito-junit-5-extension) +- [JUnit 5 – @RunWith](http://www.baeldung.com/junit-5-runwith) diff --git a/junit5/pom.xml b/testing-modules/junit-5/pom.xml similarity index 96% rename from junit5/pom.xml rename to testing-modules/junit-5/pom.xml index b8a7622b3d..2be8937d04 100644 --- a/junit5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -4,22 +4,23 @@ 4.0.0 - junit5 + junit-5 1.0-SNAPSHOT - junit5 + junit-5 Intro to JUnit 5 com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ UTF-8 1.8 - 5.0.1 + 5.0.2 1.0.1 4.12.1 2.8.2 @@ -126,4 +127,4 @@ - \ No newline at end of file + diff --git a/junit5/src/main/java/com/baeldung/junit5/Greetings.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/Greetings.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/Greetings.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/User.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/User.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/User.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/User.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/repository/MailClient.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/repository/SettingRepository.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/repository/UserRepository.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/service/DefaultUserService.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/service/Errors.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/service/Errors.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/service/Errors.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/service/Errors.java diff --git a/junit5/src/main/java/com/baeldung/junit5/mockito/service/UserService.java b/testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/service/UserService.java similarity index 100% rename from junit5/src/main/java/com/baeldung/junit5/mockito/service/UserService.java rename to testing-modules/junit-5/src/main/java/com/baeldung/junit5/mockito/service/UserService.java diff --git a/junit5/src/test/java/com/baeldung/AssertionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/AssertionUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/AssertionUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/AssumptionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/AssumptionUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/AssumptionUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/AssumptionUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/DynamicTestsExample.java b/testing-modules/junit-5/src/test/java/com/baeldung/DynamicTestsExample.java similarity index 100% rename from junit5/src/test/java/com/baeldung/DynamicTestsExample.java rename to testing-modules/junit-5/src/test/java/com/baeldung/DynamicTestsExample.java diff --git a/junit5/src/test/java/com/baeldung/EmployeesTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/EmployeesTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/EmployeesTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/EmployeesTest.java diff --git a/junit5/src/test/java/com/baeldung/ExceptionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/ExceptionUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/ExceptionUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/ExceptionUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/FirstUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/FirstUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/FirstUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/FirstUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/GreetingsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java similarity index 99% rename from junit5/src/test/java/com/baeldung/GreetingsTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java index e894d5857c..efde4e7404 100644 --- a/junit5/src/test/java/com/baeldung/GreetingsTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java @@ -16,4 +16,4 @@ public class GreetingsTest { assertTrue("Hello".equals(Greetings.sayHello())); } -} +} \ No newline at end of file diff --git a/junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/LiveTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/LiveTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/LiveTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/LiveTest.java diff --git a/junit5/src/test/java/com/baeldung/NestedUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/NestedUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/NestedUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/NestedUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/RepeatedTestExample.java b/testing-modules/junit-5/src/test/java/com/baeldung/RepeatedTestExample.java similarity index 100% rename from junit5/src/test/java/com/baeldung/RepeatedTestExample.java rename to testing-modules/junit-5/src/test/java/com/baeldung/RepeatedTestExample.java diff --git a/junit5/src/test/java/com/baeldung/StringUtils.java b/testing-modules/junit-5/src/test/java/com/baeldung/StringUtils.java similarity index 100% rename from junit5/src/test/java/com/baeldung/StringUtils.java rename to testing-modules/junit-5/src/test/java/com/baeldung/StringUtils.java diff --git a/junit5/src/test/java/com/baeldung/TaggedUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/TaggedUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/TaggedUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/TaggedUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/TestLauncher.java b/testing-modules/junit-5/src/test/java/com/baeldung/TestLauncher.java similarity index 100% rename from junit5/src/test/java/com/baeldung/TestLauncher.java rename to testing-modules/junit-5/src/test/java/com/baeldung/TestLauncher.java diff --git a/junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java similarity index 100% rename from junit5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java rename to testing-modules/junit-5/src/test/java/com/baeldung/extensions/EmployeeDaoParameterResolver.java diff --git a/junit5/src/test/java/com/baeldung/extensions/EmployeeDatabaseSetupExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/EmployeeDatabaseSetupExtension.java similarity index 100% rename from junit5/src/test/java/com/baeldung/extensions/EmployeeDatabaseSetupExtension.java rename to testing-modules/junit-5/src/test/java/com/baeldung/extensions/EmployeeDatabaseSetupExtension.java diff --git a/junit5/src/test/java/com/baeldung/extensions/EnvironmentExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/EnvironmentExtension.java similarity index 100% rename from junit5/src/test/java/com/baeldung/extensions/EnvironmentExtension.java rename to testing-modules/junit-5/src/test/java/com/baeldung/extensions/EnvironmentExtension.java diff --git a/junit5/src/test/java/com/baeldung/extensions/IgnoreFileNotFoundExceptionExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/IgnoreFileNotFoundExceptionExtension.java similarity index 100% rename from junit5/src/test/java/com/baeldung/extensions/IgnoreFileNotFoundExceptionExtension.java rename to testing-modules/junit-5/src/test/java/com/baeldung/extensions/IgnoreFileNotFoundExceptionExtension.java diff --git a/junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/LoggingExtension.java similarity index 100% rename from junit5/src/test/java/com/baeldung/extensions/LoggingExtension.java rename to testing-modules/junit-5/src/test/java/com/baeldung/extensions/LoggingExtension.java diff --git a/junit5/src/test/java/com/baeldung/helpers/Employee.java b/testing-modules/junit-5/src/test/java/com/baeldung/helpers/Employee.java similarity index 100% rename from junit5/src/test/java/com/baeldung/helpers/Employee.java rename to testing-modules/junit-5/src/test/java/com/baeldung/helpers/Employee.java diff --git a/junit5/src/test/java/com/baeldung/helpers/EmployeeDao.java b/testing-modules/junit-5/src/test/java/com/baeldung/helpers/EmployeeDao.java similarity index 100% rename from junit5/src/test/java/com/baeldung/helpers/EmployeeDao.java rename to testing-modules/junit-5/src/test/java/com/baeldung/helpers/EmployeeDao.java diff --git a/junit5/src/test/java/com/baeldung/helpers/EmployeeJdbcDao.java b/testing-modules/junit-5/src/test/java/com/baeldung/helpers/EmployeeJdbcDao.java similarity index 100% rename from junit5/src/test/java/com/baeldung/helpers/EmployeeJdbcDao.java rename to testing-modules/junit-5/src/test/java/com/baeldung/helpers/EmployeeJdbcDao.java diff --git a/junit5/src/test/java/com/baeldung/helpers/JdbcConnectionUtil.java b/testing-modules/junit-5/src/test/java/com/baeldung/helpers/JdbcConnectionUtil.java similarity index 100% rename from junit5/src/test/java/com/baeldung/helpers/JdbcConnectionUtil.java rename to testing-modules/junit-5/src/test/java/com/baeldung/helpers/JdbcConnectionUtil.java diff --git a/junit5/src/test/java/com/baeldung/junit5/mockito/MockitoExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/mockito/MockitoExtension.java similarity index 100% rename from junit5/src/test/java/com/baeldung/junit5/mockito/MockitoExtension.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5/mockito/MockitoExtension.java diff --git a/junit5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java diff --git a/junit5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java similarity index 99% rename from junit5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java index e7a8a1c1e7..3b89508c88 100644 --- a/junit5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java @@ -18,4 +18,4 @@ public class GreetingsSpringTest { assertTrue("Hello".equals(Greetings.sayHello())); } -} +} \ No newline at end of file diff --git a/junit5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java similarity index 100% rename from junit5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/SpringTestConfiguration.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/Annotations.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/rules/TraceUnitTestRule.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java diff --git a/junit5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java similarity index 100% rename from junit5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/extensions/TraceUnitExtension.java diff --git a/junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java similarity index 100% rename from junit5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java rename to testing-modules/junit-5/src/test/java/com/baeldung/param/InvalidPersonParameterResolver.java diff --git a/junit5/src/test/java/com/baeldung/param/Person.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/Person.java similarity index 100% rename from junit5/src/test/java/com/baeldung/param/Person.java rename to testing-modules/junit-5/src/test/java/com/baeldung/param/Person.java diff --git a/junit5/src/test/java/com/baeldung/param/PersonValidator.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidator.java similarity index 100% rename from junit5/src/test/java/com/baeldung/param/PersonValidator.java rename to testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidator.java diff --git a/junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorTest.java similarity index 100% rename from junit5/src/test/java/com/baeldung/param/PersonValidatorTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorTest.java diff --git a/junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java similarity index 100% rename from junit5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java rename to testing-modules/junit-5/src/test/java/com/baeldung/param/ValidPersonParameterResolver.java diff --git a/junit5/src/test/java/com/baeldung/suites/AllTests.java b/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllTests.java similarity index 100% rename from junit5/src/test/java/com/baeldung/suites/AllTests.java rename to testing-modules/junit-5/src/test/java/com/baeldung/suites/AllTests.java diff --git a/junit5/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension b/testing-modules/junit-5/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension similarity index 100% rename from junit5/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension rename to testing-modules/junit-5/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension diff --git a/junit5/src/test/resources/com/baeldung/extensions/application.properties b/testing-modules/junit-5/src/test/resources/com/baeldung/extensions/application.properties similarity index 100% rename from junit5/src/test/resources/com/baeldung/extensions/application.properties rename to testing-modules/junit-5/src/test/resources/com/baeldung/extensions/application.properties diff --git a/junit5/src/test/resources/com/baeldung/helpers/jdbc.properties b/testing-modules/junit-5/src/test/resources/com/baeldung/helpers/jdbc.properties similarity index 100% rename from junit5/src/test/resources/com/baeldung/helpers/jdbc.properties rename to testing-modules/junit-5/src/test/resources/com/baeldung/helpers/jdbc.properties diff --git a/mockito2/.gitignore b/testing-modules/mockito-2/.gitignore similarity index 100% rename from mockito2/.gitignore rename to testing-modules/mockito-2/.gitignore diff --git a/mockito2/README.md b/testing-modules/mockito-2/README.md similarity index 100% rename from mockito2/README.md rename to testing-modules/mockito-2/README.md diff --git a/mockito2/pom.xml b/testing-modules/mockito-2/pom.xml similarity index 96% rename from mockito2/pom.xml rename to testing-modules/mockito-2/pom.xml index a7c4683c30..0291ac4ec1 100644 --- a/mockito2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -3,7 +3,7 @@ 4.0.0 com.baeldung - mockito2 + mockito-2 0.0.1-SNAPSHOT jar mockito-2-with-java8 @@ -12,6 +12,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/mockito2/src/main/java/com/baeldung/mockito/java8/JobPosition.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/JobPosition.java similarity index 100% rename from mockito2/src/main/java/com/baeldung/mockito/java8/JobPosition.java rename to testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/JobPosition.java diff --git a/mockito2/src/main/java/com/baeldung/mockito/java8/JobService.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/JobService.java similarity index 100% rename from mockito2/src/main/java/com/baeldung/mockito/java8/JobService.java rename to testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/JobService.java diff --git a/mockito2/src/main/java/com/baeldung/mockito/java8/Person.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/Person.java similarity index 100% rename from mockito2/src/main/java/com/baeldung/mockito/java8/Person.java rename to testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/Person.java diff --git a/mockito2/src/main/java/com/baeldung/mockito/java8/UnemploymentService.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/UnemploymentService.java similarity index 100% rename from mockito2/src/main/java/com/baeldung/mockito/java8/UnemploymentService.java rename to testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/UnemploymentService.java diff --git a/mockito2/src/main/java/com/baeldung/mockito/java8/UnemploymentServiceImpl.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/UnemploymentServiceImpl.java similarity index 100% rename from mockito2/src/main/java/com/baeldung/mockito/java8/UnemploymentServiceImpl.java rename to testing-modules/mockito-2/src/main/java/com/baeldung/mockito/java8/UnemploymentServiceImpl.java diff --git a/mockito2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithLambdaUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithLambdaUnitTest.java similarity index 100% rename from mockito2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithLambdaUnitTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithLambdaUnitTest.java diff --git a/mockito2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithoutLambdaUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithoutLambdaUnitTest.java similarity index 100% rename from mockito2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithoutLambdaUnitTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithoutLambdaUnitTest.java diff --git a/mockito2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithLambdaUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithLambdaUnitTest.java similarity index 100% rename from mockito2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithLambdaUnitTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithLambdaUnitTest.java diff --git a/mockito2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithoutLambdaUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithoutLambdaUnitTest.java similarity index 100% rename from mockito2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithoutLambdaUnitTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithoutLambdaUnitTest.java diff --git a/mockito2/src/test/java/com/baeldung/mockito/java8/JobServiceUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/JobServiceUnitTest.java similarity index 100% rename from mockito2/src/test/java/com/baeldung/mockito/java8/JobServiceUnitTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/JobServiceUnitTest.java diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationTest.java new file mode 100644 index 0000000000..43b39d6859 --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.mockito.java8; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.util.List; + +import org.junit.Test; +import org.mockito.exceptions.base.MockitoAssertionError; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.VerificationCollector; + +public class LazyVerificationTest { + + @Test + public void whenLazilyVerified_thenReportsMultipleFailures() { + VerificationCollector collector = MockitoJUnit.collector() + .assertLazily(); + + List mockList = mock(List.class); + verify(mockList).add("one"); + verify(mockList).clear(); + + try { + collector.collectAndReport(); + } catch (MockitoAssertionError error) { + assertTrue(error.getMessage() + .contains("1. Wanted but not invoked:")); + assertTrue(error.getMessage() + .contains("2. Wanted but not invoked:")); + } + } +} diff --git a/mockito2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java similarity index 100% rename from mockito2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java diff --git a/testing-modules/mockito/.gitignore b/testing-modules/mockito/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/testing-modules/mockito/.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/mockito/README.md b/testing-modules/mockito/README.md similarity index 87% rename from mockito/README.md rename to testing-modules/mockito/README.md index 2407a5c3c5..0d6f69a64f 100644 --- a/mockito/README.md +++ b/testing-modules/mockito/README.md @@ -11,3 +11,4 @@ - [Mockito’s Mock Methods](http://www.baeldung.com/mockito-mock-methods) - [Introduction to PowerMock](http://www.baeldung.com/intro-to-powermock) - [Mocking Exception Throwing using Mockito](http://www.baeldung.com/mockito-exceptions) +- [Mocking Void Methods with Mockito](http://www.baeldung.com/mockito-void-methods) diff --git a/mockito/pom.xml b/testing-modules/mockito/pom.xml similarity index 98% rename from mockito/pom.xml rename to testing-modules/mockito/pom.xml index 19dd2f6468..aa3dd9b20a 100644 --- a/mockito/pom.xml +++ b/testing-modules/mockito/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/rest-testing/src/main/resources/logback.xml b/testing-modules/mockito/src/main/resources/logback.xml similarity index 100% rename from rest-testing/src/main/resources/logback.xml rename to testing-modules/mockito/src/main/resources/logback.xml diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java similarity index 100% rename from mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java similarity index 100% rename from mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java similarity index 100% rename from mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java similarity index 100% rename from mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java similarity index 100% rename from mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java similarity index 100% rename from mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/FinalList.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/FinalList.java new file mode 100644 index 0000000000..3824de619c --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/FinalList.java @@ -0,0 +1,10 @@ +package org.baeldung.mockito; + +public class FinalList extends MyList { + + @Override + public int size() { + return 1; + } + +} diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockFinals.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockFinals.java new file mode 100644 index 0000000000..5f064e1355 --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockFinals.java @@ -0,0 +1,35 @@ +package org.baeldung.mockito; + +import org.junit.Test; + +import static org.junit.Assert.assertNotEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class MockFinals { + + @Test + public void whenMockFinalClassMockWorks() { + + FinalList finalList = new FinalList(); + + FinalList mock = mock(FinalList.class); + when(mock.size()).thenReturn(2); + + assertNotEquals(mock.size(), finalList.size()); + + } + + @Test + public void whenMockFinalMethodMockWorks() { + + MyList myList = new MyList(); + + MyList mock = mock(MyList.class); + when(mock.finalMethod()).thenReturn(1); + + assertNotEquals(mock.finalMethod(), myList.finalMethod()); + } + + + } diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationIntegrationTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationIntegrationTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoConfigExamplesIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoConfigExamplesIntegrationTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoConfigExamplesIntegrationTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoConfigExamplesIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoExceptionIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoVerifyExamplesIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVerifyExamplesIntegrationTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoVerifyExamplesIntegrationTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVerifyExamplesIntegrationTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java similarity index 100% rename from mockito/src/test/java/org/baeldung/mockito/MyDictionary.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java diff --git a/mockito/src/test/java/org/baeldung/mockito/MyList.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyList.java similarity index 84% rename from mockito/src/test/java/org/baeldung/mockito/MyList.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MyList.java index 0b501225ad..4fcddb3164 100644 --- a/mockito/src/test/java/org/baeldung/mockito/MyList.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyList.java @@ -19,4 +19,7 @@ class MyList extends AbstractList { // no-op } + final public int finalMethod() { + return 0; + } } diff --git a/testing-modules/mockito/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/testing-modules/mockito/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 0000000000..ca6ee9cea8 --- /dev/null +++ b/testing-modules/mockito/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +mock-maker-inline \ No newline at end of file diff --git a/mocks/README.md b/testing-modules/mocks/README.md similarity index 82% rename from mocks/README.md rename to testing-modules/mocks/README.md index 15370b812b..d7b817c518 100644 --- a/mocks/README.md +++ b/testing-modules/mocks/README.md @@ -1,6 +1,5 @@ ## Relevant articles: -- [Introduction to MockServer](http://www.baeldung.com/mockserver) - [JMockit Advanced Usage](http://www.baeldung.com/jmockit-advanced-usage) - [A Guide to JMockit Expectations](http://www.baeldung.com/jmockit-expectations) - [JMockit 101](http://www.baeldung.com/jmockit-101) diff --git a/mocks/jmockit/README.md b/testing-modules/mocks/jmockit/README.md similarity index 100% rename from mocks/jmockit/README.md rename to testing-modules/mocks/jmockit/README.md diff --git a/mocks/jmockit/pom.xml b/testing-modules/mocks/jmockit/pom.xml similarity index 95% rename from mocks/jmockit/pom.xml rename to testing-modules/mocks/jmockit/pom.xml index 173a981e09..d998cb6918 100644 --- a/mocks/jmockit/pom.xml +++ b/testing-modules/mocks/jmockit/pom.xml @@ -6,7 +6,7 @@ com.baeldung mocks 1.0.0-SNAPSHOT - ../pom.xml + ../ jmockit diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/AdvancedCollaborator.java b/testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/AdvancedCollaborator.java similarity index 100% rename from mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/AdvancedCollaborator.java rename to testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/AdvancedCollaborator.java diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java b/testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java similarity index 100% rename from mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java rename to testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/ExpectationsCollaborator.java b/testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/ExpectationsCollaborator.java similarity index 100% rename from mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/ExpectationsCollaborator.java rename to testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/ExpectationsCollaborator.java diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java b/testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java similarity index 100% rename from mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java rename to testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Performer.java b/testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Performer.java similarity index 100% rename from mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Performer.java rename to testing-modules/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Performer.java diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/AdvancedCollaboratorIntegrationTest.java b/testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/AdvancedCollaboratorIntegrationTest.java similarity index 100% rename from mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/AdvancedCollaboratorIntegrationTest.java rename to testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/AdvancedCollaboratorIntegrationTest.java diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ExpectationsIntegrationTest.java b/testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ExpectationsIntegrationTest.java similarity index 100% rename from mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ExpectationsIntegrationTest.java rename to testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ExpectationsIntegrationTest.java diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerIntegrationTest.java b/testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerIntegrationTest.java similarity index 100% rename from mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerIntegrationTest.java rename to testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerIntegrationTest.java diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ReusingIntegrationTest.java b/testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ReusingIntegrationTest.java similarity index 100% rename from mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ReusingIntegrationTest.java rename to testing-modules/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/ReusingIntegrationTest.java diff --git a/mocks/mock-comparisons/README.md b/testing-modules/mocks/mock-comparisons/README.md similarity index 100% rename from mocks/mock-comparisons/README.md rename to testing-modules/mocks/mock-comparisons/README.md diff --git a/mocks/mock-comparisons/pom.xml b/testing-modules/mocks/mock-comparisons/pom.xml similarity index 97% rename from mocks/mock-comparisons/pom.xml rename to testing-modules/mocks/mock-comparisons/pom.xml index 11bc59d710..84f1d20401 100644 --- a/mocks/mock-comparisons/pom.xml +++ b/testing-modules/mocks/mock-comparisons/pom.xml @@ -6,7 +6,7 @@ com.baeldung mocks 1.0.0-SNAPSHOT - ../pom.xml + ../ mock-comparisons diff --git a/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java b/testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java similarity index 100% rename from mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java rename to testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java diff --git a/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java b/testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java similarity index 100% rename from mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java rename to testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java diff --git a/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java b/testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java similarity index 100% rename from mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java rename to testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java diff --git a/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java b/testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java similarity index 100% rename from mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java rename to testing-modules/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java diff --git a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerIntegrationTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerIntegrationTest.java similarity index 100% rename from mocks/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerIntegrationTest.java rename to testing-modules/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerIntegrationTest.java diff --git a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerIntegrationTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerIntegrationTest.java similarity index 100% rename from mocks/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerIntegrationTest.java rename to testing-modules/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerIntegrationTest.java diff --git a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java similarity index 100% rename from mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java rename to testing-modules/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java diff --git a/mocks/pom.xml b/testing-modules/mocks/pom.xml similarity index 92% rename from mocks/pom.xml rename to testing-modules/mocks/pom.xml index 84243a25d2..959c1851d6 100644 --- a/mocks/pom.xml +++ b/testing-modules/mocks/pom.xml @@ -6,7 +6,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - ../pom.xml + ../ mocks diff --git a/mockserver/README.md b/testing-modules/mockserver/README.md similarity index 100% rename from mockserver/README.md rename to testing-modules/mockserver/README.md diff --git a/mockserver/pom.xml b/testing-modules/mockserver/pom.xml similarity index 100% rename from mockserver/pom.xml rename to testing-modules/mockserver/pom.xml diff --git a/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java b/testing-modules/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java similarity index 100% rename from mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java rename to testing-modules/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java diff --git a/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java b/testing-modules/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java similarity index 100% rename from mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java rename to testing-modules/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java diff --git a/rest-assured/.gitignore b/testing-modules/rest-assured/.gitignore similarity index 100% rename from rest-assured/.gitignore rename to testing-modules/rest-assured/.gitignore diff --git a/rest-assured/README.md b/testing-modules/rest-assured/README.md similarity index 100% rename from rest-assured/README.md rename to testing-modules/rest-assured/README.md diff --git a/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml similarity index 99% rename from rest-assured/pom.xml rename to testing-modules/rest-assured/pom.xml index 3fca54c80f..0c0826c5c3 100644 --- a/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -10,6 +10,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java similarity index 100% rename from rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java rename to testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java similarity index 100% rename from rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java rename to testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java similarity index 100% rename from rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java rename to testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java similarity index 100% rename from rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java rename to testing-modules/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java diff --git a/rest-assured/src/test/java/com/baeldung/restassured/Util.java b/testing-modules/rest-assured/src/test/java/com/baeldung/restassured/Util.java similarity index 100% rename from rest-assured/src/test/java/com/baeldung/restassured/Util.java rename to testing-modules/rest-assured/src/test/java/com/baeldung/restassured/Util.java diff --git a/rest-assured/src/test/resources/employees.xml b/testing-modules/rest-assured/src/test/resources/employees.xml similarity index 100% rename from rest-assured/src/test/resources/employees.xml rename to testing-modules/rest-assured/src/test/resources/employees.xml diff --git a/rest-assured/src/test/resources/event_0.json b/testing-modules/rest-assured/src/test/resources/event_0.json similarity index 100% rename from rest-assured/src/test/resources/event_0.json rename to testing-modules/rest-assured/src/test/resources/event_0.json diff --git a/spring-jpa/src/main/resources/logback.xml b/testing-modules/rest-assured/src/test/resources/logback.xml similarity index 100% rename from spring-jpa/src/main/resources/logback.xml rename to testing-modules/rest-assured/src/test/resources/logback.xml diff --git a/rest-assured/src/test/resources/odds.json b/testing-modules/rest-assured/src/test/resources/odds.json similarity index 100% rename from rest-assured/src/test/resources/odds.json rename to testing-modules/rest-assured/src/test/resources/odds.json diff --git a/rest-assured/src/test/resources/teachers.xml b/testing-modules/rest-assured/src/test/resources/teachers.xml similarity index 100% rename from rest-assured/src/test/resources/teachers.xml rename to testing-modules/rest-assured/src/test/resources/teachers.xml diff --git a/rest-testing/.gitignore b/testing-modules/rest-testing/.gitignore similarity index 100% rename from rest-testing/.gitignore rename to testing-modules/rest-testing/.gitignore diff --git a/rest-testing/README.md b/testing-modules/rest-testing/README.md similarity index 85% rename from rest-testing/README.md rename to testing-modules/rest-testing/README.md index 37a53dd815..c6185de05f 100644 --- a/rest-testing/README.md +++ b/testing-modules/rest-testing/README.md @@ -10,3 +10,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to WireMock](http://www.baeldung.com/introduction-to-wiremock) - [REST API Testing with Cucumber](http://www.baeldung.com/cucumber-rest-api-testing) - [Testing a REST API with JBehave](http://www.baeldung.com/jbehave-rest-testing) +- [REST API Testing with Karate](http://www.baeldung.com/karate-rest-api-testing) diff --git a/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml similarity index 99% rename from rest-testing/pom.xml rename to testing-modules/rest-testing/pom.xml index 74ea5760c4..4b838720da 100644 --- a/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/rest-testing/src/main/resources/cucumber.json b/testing-modules/rest-testing/src/main/resources/cucumber.json similarity index 100% rename from rest-testing/src/main/resources/cucumber.json rename to testing-modules/rest-testing/src/main/resources/cucumber.json diff --git a/rest-testing/src/main/resources/karate/cucumber.feature b/testing-modules/rest-testing/src/main/resources/karate/cucumber.feature similarity index 100% rename from rest-testing/src/main/resources/karate/cucumber.feature rename to testing-modules/rest-testing/src/main/resources/karate/cucumber.feature diff --git a/testing-modules/rest-testing/src/main/resources/logback.xml b/testing-modules/rest-testing/src/main/resources/logback.xml new file mode 100644 index 0000000000..ec0dc2469a --- /dev/null +++ b/testing-modules/rest-testing/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/rest-testing/src/main/resources/wiremock_intro.json b/testing-modules/rest-testing/src/main/resources/wiremock_intro.json similarity index 100% rename from rest-testing/src/main/resources/wiremock_intro.json rename to testing-modules/rest-testing/src/main/resources/wiremock_intro.json diff --git a/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberIntegrationTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/AbstractStory.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/AbstractStory.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/AbstractStory.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/AbstractStory.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundSteps.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundSteps.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundSteps.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundSteps.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundStoryLiveTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundStoryLiveTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundStoryLiveTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserNotFoundStoryLiveTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeSteps.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeSteps.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeSteps.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeSteps.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeStoryLiveTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeStoryLiveTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeStoryLiveTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponseMediaTypeStoryLiveTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadSteps.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadSteps.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadSteps.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadSteps.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadStoryLiveTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadStoryLiveTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadStoryLiveTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/GithubUserResponsePayloadStoryLiveTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseSteps.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseSteps.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseSteps.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseSteps.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseStoryLiveTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseStoryLiveTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseStoryLiveTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/jbehave/IncreaseStoryLiveTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/karate/KarateUnitTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/karate/KarateUnitTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/karate/KarateUnitTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/karate/KarateUnitTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java diff --git a/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/ProgrammaticallyManagedLiveTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/ProgrammaticallyManagedLiveTest.java similarity index 100% rename from rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/ProgrammaticallyManagedLiveTest.java rename to testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/ProgrammaticallyManagedLiveTest.java diff --git a/rest-testing/src/test/java/org/baeldung/rest/GitHubUser.java b/testing-modules/rest-testing/src/test/java/org/baeldung/rest/GitHubUser.java similarity index 100% rename from rest-testing/src/test/java/org/baeldung/rest/GitHubUser.java rename to testing-modules/rest-testing/src/test/java/org/baeldung/rest/GitHubUser.java diff --git a/rest-testing/src/test/java/org/baeldung/rest/GithubBasicLiveTest.java b/testing-modules/rest-testing/src/test/java/org/baeldung/rest/GithubBasicLiveTest.java similarity index 100% rename from rest-testing/src/test/java/org/baeldung/rest/GithubBasicLiveTest.java rename to testing-modules/rest-testing/src/test/java/org/baeldung/rest/GithubBasicLiveTest.java diff --git a/rest-testing/src/test/java/org/baeldung/rest/RetrieveUtil.java b/testing-modules/rest-testing/src/test/java/org/baeldung/rest/RetrieveUtil.java similarity index 100% rename from rest-testing/src/test/java/org/baeldung/rest/RetrieveUtil.java rename to testing-modules/rest-testing/src/test/java/org/baeldung/rest/RetrieveUtil.java diff --git a/rest-testing/src/test/resources/github_user_not_found.story b/testing-modules/rest-testing/src/test/resources/github_user_not_found.story similarity index 100% rename from rest-testing/src/test/resources/github_user_not_found.story rename to testing-modules/rest-testing/src/test/resources/github_user_not_found.story diff --git a/rest-testing/src/test/resources/github_user_response_mediatype.story b/testing-modules/rest-testing/src/test/resources/github_user_response_mediatype.story similarity index 100% rename from rest-testing/src/test/resources/github_user_response_mediatype.story rename to testing-modules/rest-testing/src/test/resources/github_user_response_mediatype.story diff --git a/rest-testing/src/test/resources/github_user_response_payload.story b/testing-modules/rest-testing/src/test/resources/github_user_response_payload.story similarity index 100% rename from rest-testing/src/test/resources/github_user_response_payload.story rename to testing-modules/rest-testing/src/test/resources/github_user_response_payload.story diff --git a/rest-testing/src/test/resources/increase.story b/testing-modules/rest-testing/src/test/resources/increase.story similarity index 100% rename from rest-testing/src/test/resources/increase.story rename to testing-modules/rest-testing/src/test/resources/increase.story diff --git a/rest-testing/src/test/resources/karate/user.feature b/testing-modules/rest-testing/src/test/resources/karate/user.feature similarity index 100% rename from rest-testing/src/test/resources/karate/user.feature rename to testing-modules/rest-testing/src/test/resources/karate/user.feature diff --git a/selenium-junit-testng/README.md b/testing-modules/selenium-junit-testng/README.md similarity index 77% rename from selenium-junit-testng/README.md rename to testing-modules/selenium-junit-testng/README.md index 29393b956b..0137212290 100644 --- a/selenium-junit-testng/README.md +++ b/testing-modules/selenium-junit-testng/README.md @@ -1,4 +1,3 @@ ### Relevant Articles: - [Guide to Selenium with JUnit / TestNG](http://www.baeldung.com/java-selenium-with-junit-and-testng) -- [Testing a Site with Selenium / Webdriver](http://www.baeldung.com) - [Testing with Selenium/WebDriver and the Page Object Pattern](http://www.baeldung.com/selenium-webdriver-page-object) diff --git a/selenium-junit-testng/geckodriver.mac b/testing-modules/selenium-junit-testng/geckodriver.mac similarity index 100% rename from selenium-junit-testng/geckodriver.mac rename to testing-modules/selenium-junit-testng/geckodriver.mac diff --git a/selenium-junit-testng/pom.xml b/testing-modules/selenium-junit-testng/pom.xml similarity index 97% rename from selenium-junit-testng/pom.xml rename to testing-modules/selenium-junit-testng/pom.xml index 5b695ca900..14169e5749 100644 --- a/selenium-junit-testng/pom.xml +++ b/testing-modules/selenium-junit-testng/pom.xml @@ -9,6 +9,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ @@ -27,7 +28,6 @@ **/*LiveTest.java - false diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java b/testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java similarity index 100% rename from selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java rename to testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/config/SeleniumConfig.java b/testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/config/SeleniumConfig.java similarity index 100% rename from selenium-junit-testng/src/main/java/com/baeldung/selenium/config/SeleniumConfig.java rename to testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/config/SeleniumConfig.java diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/models/BaeldungAbout.java b/testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/models/BaeldungAbout.java similarity index 100% rename from selenium-junit-testng/src/main/java/com/baeldung/selenium/models/BaeldungAbout.java rename to testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/models/BaeldungAbout.java diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungAboutPage.java b/testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungAboutPage.java similarity index 100% rename from selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungAboutPage.java rename to testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungAboutPage.java diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungHomePage.java b/testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungHomePage.java similarity index 100% rename from selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungHomePage.java rename to testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/BaeldungHomePage.java diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/StartHerePage.java b/testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/StartHerePage.java similarity index 100% rename from selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/StartHerePage.java rename to testing-modules/selenium-junit-testng/src/main/java/com/baeldung/selenium/pages/StartHerePage.java diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumPageObjectLiveTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumPageObjectLiveTest.java similarity index 100% rename from selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumPageObjectLiveTest.java rename to testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumPageObjectLiveTest.java diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java similarity index 100% rename from selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java rename to testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumWithJUnitLiveTest.java diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java similarity index 100% rename from selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java rename to testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/SeleniumWithTestNGLiveTest.java diff --git a/testing/README.md b/testing-modules/testing/README.md similarity index 92% rename from testing/README.md rename to testing-modules/testing/README.md index 889f6706d4..143cb792cf 100644 --- a/testing/README.md +++ b/testing-modules/testing/README.md @@ -15,3 +15,4 @@ - [Cucumber Java 8 Support](http://www.baeldung.com/cucumber-java-8-support) - [Introduction to Lambda Behave](http://www.baeldung.com/lambda-behave) - [Introduction to Jukito](http://www.baeldung.com/jukito) +- [Custom JUnit 4 Test Runners](http://www.baeldung.com/junit-4-custom-runners) diff --git a/testing/pom.xml b/testing-modules/testing/pom.xml similarity index 99% rename from testing/pom.xml rename to testing-modules/testing/pom.xml index 8f5c6ddb3d..3ad503558f 100644 --- a/testing/pom.xml +++ b/testing-modules/testing/pom.xml @@ -10,6 +10,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/testing/src/main/java/com/baeldung/cucumber/Calculator.java b/testing-modules/testing/src/main/java/com/baeldung/cucumber/Calculator.java similarity index 100% rename from testing/src/main/java/com/baeldung/cucumber/Calculator.java rename to testing-modules/testing/src/main/java/com/baeldung/cucumber/Calculator.java diff --git a/testing/src/main/java/com/baeldung/introductionjukito/Calculator.java b/testing-modules/testing/src/main/java/com/baeldung/introductionjukito/Calculator.java similarity index 100% rename from testing/src/main/java/com/baeldung/introductionjukito/Calculator.java rename to testing-modules/testing/src/main/java/com/baeldung/introductionjukito/Calculator.java diff --git a/testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java b/testing-modules/testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java similarity index 100% rename from testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java rename to testing-modules/testing/src/main/java/com/baeldung/introductionjukito/ScientificCalculator.java diff --git a/testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java b/testing-modules/testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java similarity index 100% rename from testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java rename to testing-modules/testing/src/main/java/com/baeldung/introductionjukito/SimpleCalculator.java diff --git a/testing/src/main/java/com/baeldung/junit/Calculator.java b/testing-modules/testing/src/main/java/com/baeldung/junit/Calculator.java similarity index 100% rename from testing/src/main/java/com/baeldung/junit/Calculator.java rename to testing-modules/testing/src/main/java/com/baeldung/junit/Calculator.java diff --git a/testing/src/main/java/com/baeldung/junitparams/SafeAdditionUtil.java b/testing-modules/testing/src/main/java/com/baeldung/junitparams/SafeAdditionUtil.java similarity index 100% rename from testing/src/main/java/com/baeldung/junitparams/SafeAdditionUtil.java rename to testing-modules/testing/src/main/java/com/baeldung/junitparams/SafeAdditionUtil.java diff --git a/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java b/testing-modules/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java similarity index 100% rename from testing/src/main/java/com/baeldung/lambdabehave/Calculator.java rename to testing-modules/testing/src/main/java/com/baeldung/lambdabehave/Calculator.java diff --git a/testing/src/main/java/com/baeldung/testing/assertj/Dog.java b/testing-modules/testing/src/main/java/com/baeldung/testing/assertj/Dog.java similarity index 100% rename from testing/src/main/java/com/baeldung/testing/assertj/Dog.java rename to testing-modules/testing/src/main/java/com/baeldung/testing/assertj/Dog.java diff --git a/testing/src/main/java/com/baeldung/testing/assertj/Person.java b/testing-modules/testing/src/main/java/com/baeldung/testing/assertj/Person.java similarity index 100% rename from testing/src/main/java/com/baeldung/testing/assertj/Person.java rename to testing-modules/testing/src/main/java/com/baeldung/testing/assertj/Person.java diff --git a/testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java b/testing-modules/testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java similarity index 100% rename from testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java rename to testing-modules/testing/src/main/java/com/baeldung/testing/mutation/Palindrome.java diff --git a/testing/src/main/java/com/baeldung/testing/truth/User.java b/testing-modules/testing/src/main/java/com/baeldung/testing/truth/User.java similarity index 100% rename from testing/src/main/java/com/baeldung/testing/truth/User.java rename to testing-modules/testing/src/main/java/com/baeldung/testing/truth/User.java diff --git a/testing/src/main/java/com/baeldung/testing/truth/UserSubject.java b/testing-modules/testing/src/main/java/com/baeldung/testing/truth/UserSubject.java similarity index 100% rename from testing/src/main/java/com/baeldung/testing/truth/UserSubject.java rename to testing-modules/testing/src/main/java/com/baeldung/testing/truth/UserSubject.java diff --git a/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java b/testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java rename to testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java diff --git a/testing/src/test/java/com/baeldung/junit/AdditionTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/AdditionTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/junit/AdditionTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/AdditionTest.java diff --git a/testing/src/test/java/com/baeldung/junit/BlockingTestRunner.java b/testing-modules/testing/src/test/java/com/baeldung/junit/BlockingTestRunner.java similarity index 100% rename from testing/src/test/java/com/baeldung/junit/BlockingTestRunner.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/BlockingTestRunner.java diff --git a/testing/src/test/java/com/baeldung/junit/CalculatorTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/junit/CalculatorTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorTest.java diff --git a/testing/src/test/java/com/baeldung/junit/SubstractionTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/junit/SubstractionTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionTest.java diff --git a/testing/src/test/java/com/baeldung/junit/SuiteTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/SuiteTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/junit/SuiteTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/SuiteTest.java diff --git a/testing/src/test/java/com/baeldung/junit/TestRunner.java b/testing-modules/testing/src/test/java/com/baeldung/junit/TestRunner.java similarity index 100% rename from testing/src/test/java/com/baeldung/junit/TestRunner.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/TestRunner.java diff --git a/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java b/testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java diff --git a/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java b/testing-modules/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java similarity index 100% rename from testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java rename to testing-modules/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java diff --git a/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java b/testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java rename to testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java diff --git a/testing/src/test/java/com/baeldung/mutation/test/PalindromeUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/mutation/test/PalindromeUnitTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/mutation/test/PalindromeUnitTest.java rename to testing-modules/testing/src/test/java/com/baeldung/mutation/test/PalindromeUnitTest.java diff --git a/testing/src/test/java/com/baeldung/testing/assertj/AssertJCoreUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/AssertJCoreUnitTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/assertj/AssertJCoreUnitTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/assertj/AssertJCoreUnitTest.java diff --git a/testing/src/test/java/com/baeldung/testing/assertj/AssertJGuavaUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/AssertJGuavaUnitTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/assertj/AssertJGuavaUnitTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/assertj/AssertJGuavaUnitTest.java diff --git a/testing/src/test/java/com/baeldung/testing/assertj/AssertJJava8UnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/assertj/AssertJJava8UnitTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/assertj/AssertJJava8UnitTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/assertj/AssertJJava8UnitTest.java diff --git a/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java diff --git a/testing/src/test/java/com/baeldung/testing/calculator/CalculatorRunSteps.java b/testing-modules/testing/src/test/java/com/baeldung/testing/calculator/CalculatorRunSteps.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/calculator/CalculatorRunSteps.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/calculator/CalculatorRunSteps.java diff --git a/testing/src/test/java/com/baeldung/testing/jgotesting/JGoTestingUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/jgotesting/JGoTestingUnitTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/jgotesting/JGoTestingUnitTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/jgotesting/JGoTestingUnitTest.java diff --git a/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java diff --git a/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java b/testing-modules/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java diff --git a/testing/src/test/java/com/baeldung/testing/truth/GoogleTruthUnitTest.java b/testing-modules/testing/src/test/java/com/baeldung/testing/truth/GoogleTruthUnitTest.java similarity index 100% rename from testing/src/test/java/com/baeldung/testing/truth/GoogleTruthUnitTest.java rename to testing-modules/testing/src/test/java/com/baeldung/testing/truth/GoogleTruthUnitTest.java diff --git a/testing/src/test/resources/JunitParamsTestParameters.csv b/testing-modules/testing/src/test/resources/JunitParamsTestParameters.csv similarity index 100% rename from testing/src/test/resources/JunitParamsTestParameters.csv rename to testing-modules/testing/src/test/resources/JunitParamsTestParameters.csv diff --git a/testing/src/test/resources/features/calculator-scenario-outline.feature b/testing-modules/testing/src/test/resources/features/calculator-scenario-outline.feature similarity index 100% rename from testing/src/test/resources/features/calculator-scenario-outline.feature rename to testing-modules/testing/src/test/resources/features/calculator-scenario-outline.feature diff --git a/testing/src/test/resources/features/calculator.feature b/testing-modules/testing/src/test/resources/features/calculator.feature similarity index 100% rename from testing/src/test/resources/features/calculator.feature rename to testing-modules/testing/src/test/resources/features/calculator.feature diff --git a/testing/src/test/resources/features/shopping.feature b/testing-modules/testing/src/test/resources/features/shopping.feature similarity index 100% rename from testing/src/test/resources/features/shopping.feature rename to testing-modules/testing/src/test/resources/features/shopping.feature diff --git a/testng/README.md b/testing-modules/testng/README.md similarity index 100% rename from testng/README.md rename to testing-modules/testng/README.md diff --git a/testng/pom.xml b/testing-modules/testng/pom.xml similarity index 95% rename from testng/pom.xml rename to testing-modules/testng/pom.xml index 0ca775a00c..f7a50954fc 100644 --- a/testng/pom.xml +++ b/testing-modules/testng/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../ diff --git a/testng/src/test/java/com/baeldung/DependentLongRunningUnitTest.java b/testing-modules/testng/src/test/java/com/baeldung/DependentLongRunningUnitTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/DependentLongRunningUnitTest.java rename to testing-modules/testng/src/test/java/com/baeldung/DependentLongRunningUnitTest.java diff --git a/testng/src/test/java/com/baeldung/GroupIntegrationTest.java b/testing-modules/testng/src/test/java/com/baeldung/GroupIntegrationTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/GroupIntegrationTest.java rename to testing-modules/testng/src/test/java/com/baeldung/GroupIntegrationTest.java diff --git a/testng/src/test/java/com/baeldung/MultiThreadedIntegrationTest.java b/testing-modules/testng/src/test/java/com/baeldung/MultiThreadedIntegrationTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/MultiThreadedIntegrationTest.java rename to testing-modules/testng/src/test/java/com/baeldung/MultiThreadedIntegrationTest.java diff --git a/testng/src/test/java/com/baeldung/ParametrizedLongRunningUnitTest.java b/testing-modules/testng/src/test/java/com/baeldung/ParametrizedLongRunningUnitTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/ParametrizedLongRunningUnitTest.java rename to testing-modules/testng/src/test/java/com/baeldung/ParametrizedLongRunningUnitTest.java diff --git a/testng/src/test/java/com/baeldung/PriorityLongRunningUnitTest.java b/testing-modules/testng/src/test/java/com/baeldung/PriorityLongRunningUnitTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/PriorityLongRunningUnitTest.java rename to testing-modules/testng/src/test/java/com/baeldung/PriorityLongRunningUnitTest.java diff --git a/testng/src/test/java/com/baeldung/RegistrationLongRunningUnitTest.java b/testing-modules/testng/src/test/java/com/baeldung/RegistrationLongRunningUnitTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/RegistrationLongRunningUnitTest.java rename to testing-modules/testng/src/test/java/com/baeldung/RegistrationLongRunningUnitTest.java diff --git a/testng/src/test/java/com/baeldung/SignInLongRunningUnitTest.java b/testing-modules/testng/src/test/java/com/baeldung/SignInLongRunningUnitTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/SignInLongRunningUnitTest.java rename to testing-modules/testng/src/test/java/com/baeldung/SignInLongRunningUnitTest.java diff --git a/testng/src/test/java/com/baeldung/SimpleLongRunningUnitTest.java b/testing-modules/testng/src/test/java/com/baeldung/SimpleLongRunningUnitTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/SimpleLongRunningUnitTest.java rename to testing-modules/testng/src/test/java/com/baeldung/SimpleLongRunningUnitTest.java diff --git a/testng/src/test/java/com/baeldung/SummationServiceIntegrationTest.java b/testing-modules/testng/src/test/java/com/baeldung/SummationServiceIntegrationTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/SummationServiceIntegrationTest.java rename to testing-modules/testng/src/test/java/com/baeldung/SummationServiceIntegrationTest.java diff --git a/testng/src/test/java/com/baeldung/TimeOutIntegrationTest.java b/testing-modules/testng/src/test/java/com/baeldung/TimeOutIntegrationTest.java similarity index 100% rename from testng/src/test/java/com/baeldung/TimeOutIntegrationTest.java rename to testing-modules/testng/src/test/java/com/baeldung/TimeOutIntegrationTest.java diff --git a/testng/src/test/java/com/baeldung/reports/CustomisedListener.java b/testing-modules/testng/src/test/java/com/baeldung/reports/CustomisedListener.java similarity index 100% rename from testng/src/test/java/com/baeldung/reports/CustomisedListener.java rename to testing-modules/testng/src/test/java/com/baeldung/reports/CustomisedListener.java diff --git a/testng/src/test/java/com/baeldung/reports/CustomisedReports.java b/testing-modules/testng/src/test/java/com/baeldung/reports/CustomisedReports.java similarity index 100% rename from testng/src/test/java/com/baeldung/reports/CustomisedReports.java rename to testing-modules/testng/src/test/java/com/baeldung/reports/CustomisedReports.java diff --git a/testng/src/test/resources/logback.xml b/testing-modules/testng/src/test/resources/logback.xml similarity index 100% rename from testng/src/test/resources/logback.xml rename to testing-modules/testng/src/test/resources/logback.xml diff --git a/testng/src/test/resources/parametrized_testng.xml b/testing-modules/testng/src/test/resources/parametrized_testng.xml similarity index 100% rename from testng/src/test/resources/parametrized_testng.xml rename to testing-modules/testng/src/test/resources/parametrized_testng.xml diff --git a/testng/src/test/resources/reportTemplate.html b/testing-modules/testng/src/test/resources/reportTemplate.html similarity index 100% rename from testng/src/test/resources/reportTemplate.html rename to testing-modules/testng/src/test/resources/reportTemplate.html diff --git a/testng/src/test/resources/test_group.xml b/testing-modules/testng/src/test/resources/test_group.xml similarity index 100% rename from testng/src/test/resources/test_group.xml rename to testing-modules/testng/src/test/resources/test_group.xml diff --git a/testng/src/test/resources/test_setup.xml b/testing-modules/testng/src/test/resources/test_setup.xml similarity index 100% rename from testng/src/test/resources/test_setup.xml rename to testing-modules/testng/src/test/resources/test_setup.xml diff --git a/testng/src/test/resources/test_suite.xml b/testing-modules/testng/src/test/resources/test_suite.xml similarity index 100% rename from testng/src/test/resources/test_suite.xml rename to testing-modules/testng/src/test/resources/test_suite.xml diff --git a/undertow/dependency-reduced-pom.xml b/undertow/dependency-reduced-pom.xml index f3bb8b78ed..6481c51285 100644 --- a/undertow/dependency-reduced-pom.xml +++ b/undertow/dependency-reduced-pom.xml @@ -1,40 +1,39 @@ - - - 4.0.0 - com.baeldung.undertow - undertow - undertow - 1.0-SNAPSHOT - http://maven.apache.org - - ${project.artifactId} - - - maven-shade-plugin - - - package - - shade - - - - - - maven-jar-plugin - - - - com.baeldung.undertow.SimpleServer - - - - - - - - 1.8 - 1.8 - - - + + + 4.0.0 + com.baeldung.undertow + undertow + undertow + 1.0-SNAPSHOT + http://maven.apache.org + + ${project.artifactId} + + + maven-shade-plugin + + + package + + shade + + + + + + maven-jar-plugin + + + + com.baeldung.undertow.SimpleServer + + + + + + + + 1.8 + 1.8 + + \ No newline at end of file diff --git a/vavr/pom.xml b/vavr/pom.xml index 878430611b..f9fed7d4fc 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -97,7 +97,7 @@ **/JdbcTest.java **/*LiveTest.java - true + diff --git a/xmlunit2/README.md b/xmlunit-2/README.md similarity index 100% rename from xmlunit2/README.md rename to xmlunit-2/README.md diff --git a/xmlunit2/pom.xml b/xmlunit-2/pom.xml similarity index 96% rename from xmlunit2/pom.xml rename to xmlunit-2/pom.xml index dd9fe9ac27..591cb70ec8 100644 --- a/xmlunit2/pom.xml +++ b/xmlunit-2/pom.xml @@ -2,7 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.baeldung - xmlunit2 + xmlunit-2 1.0 XMLUnit-2 diff --git a/xmlunit2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java b/xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java similarity index 100% rename from xmlunit2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java rename to xmlunit-2/src/main/java/com/baeldung/xmlunit/IgnoreAttributeDifferenceEvaluator.java diff --git a/xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java b/xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java similarity index 100% rename from xmlunit2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java rename to xmlunit-2/src/test/java/com/baeldung/xmlunit/XMLUnitTest.java diff --git a/xmlunit2/src/test/resources/control.xml b/xmlunit-2/src/test/resources/control.xml similarity index 100% rename from xmlunit2/src/test/resources/control.xml rename to xmlunit-2/src/test/resources/control.xml diff --git a/xmlunit2/src/test/resources/students.xml b/xmlunit-2/src/test/resources/students.xml similarity index 100% rename from xmlunit2/src/test/resources/students.xml rename to xmlunit-2/src/test/resources/students.xml diff --git a/xmlunit2/src/test/resources/students.xsd b/xmlunit-2/src/test/resources/students.xsd similarity index 100% rename from xmlunit2/src/test/resources/students.xsd rename to xmlunit-2/src/test/resources/students.xsd diff --git a/xmlunit2/src/test/resources/students_with_error.xml b/xmlunit-2/src/test/resources/students_with_error.xml similarity index 100% rename from xmlunit2/src/test/resources/students_with_error.xml rename to xmlunit-2/src/test/resources/students_with_error.xml diff --git a/xmlunit2/src/test/resources/teachers.xml b/xmlunit-2/src/test/resources/teachers.xml similarity index 100% rename from xmlunit2/src/test/resources/teachers.xml rename to xmlunit-2/src/test/resources/teachers.xml diff --git a/xmlunit2/src/test/resources/test.xml b/xmlunit-2/src/test/resources/test.xml similarity index 100% rename from xmlunit2/src/test/resources/test.xml rename to xmlunit-2/src/test/resources/test.xml
" + user.getUsername() + "" + user.getEmail() + "