From e2a675b348bcf52f551a83de059613da65a04045 Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Tue, 16 Oct 2018 00:44:02 +0200 Subject: [PATCH 01/76] [BAEL-2255] - Guide to BufferedReader --- .../bufferedreader/BufferedReaderExample.java | 106 ++++++++++++++++ core-java/src/main/resources/input.txt | 45 +++++++ .../BufferedReaderExampleUnitTest.java | 115 ++++++++++++++++++ 3 files changed, 266 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java create mode 100644 core-java/src/main/resources/input.txt create mode 100644 core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java b/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java new file mode 100644 index 0000000000..f381ab7c61 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java @@ -0,0 +1,106 @@ +package com.baeldung.bufferedreader; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.Arrays; + +public class BufferedReaderExample { + + public String readAllLines(BufferedReader reader) throws IOException { + StringBuilder content = new StringBuilder(); + String line; + + while ((line = reader.readLine()) != null) { + content.append(line); + content.append(System.lineSeparator()); + } + + return content.toString(); + } + + public String readAllLines2(BufferedReader reader) { + StringBuilder content = new StringBuilder(); + reader.lines().forEach(line -> content.append(line).append(System.lineSeparator())); + return content.toString(); + } + + public String readAllCharacters(BufferedReader reader) throws IOException { + StringBuilder content = new StringBuilder(); + + int value; + while ((value = reader.read()) != -1) { + content.append((char) value); + } + + return content.toString(); + } + + public String readAllCharacters2(BufferedReader reader) throws IOException { + StringBuilder content = new StringBuilder(); + + String title = "text: "; + char[] buf = Arrays.copyOf(title.toCharArray(), 512); + int offset = title.length(); + + int charsRead; + + while ((charsRead = reader.read(buf, offset, buf.length - offset)) != -1) { + content.append(buf, 0, offset + charsRead); + content.append(" --- "); + } + + return content.toString(); + } + + public String readWithSkipping(BufferedReader reader) throws IOException { + StringBuilder content = new StringBuilder(); + + int value; + while ((value = reader.read()) != -1) { + content.append((char) value); + reader.skip(4); + } + + return content.toString(); + } + + public void markAndReset(BufferedReader reader) throws IOException { + reader.mark(512); + + for (int i = 0; i < 3; i++) { + System.out.println(reader.readLine()); + reader.reset(); + reader.mark(512); + } + } + + public void readFile() { + BufferedReader reader = null; + try { + reader = new BufferedReader(new FileReader("src/main/resources/input.txt")); + String content = readAllLines(reader); + System.out.println(content); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (reader != null) { + reader.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public void readFileTryWithResources() { + try(BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/input.txt"))) { + String content = readAllLines(reader); + System.out.println(content); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/core-java/src/main/resources/input.txt b/core-java/src/main/resources/input.txt new file mode 100644 index 0000000000..650da894e8 --- /dev/null +++ b/core-java/src/main/resources/input.txt @@ -0,0 +1,45 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit. In lacus enim, scelerisque id sapien ut, semper euismod quam. Nunc ullamcorper semper blandit. Praesent quis quam mollis, iaculis lectus a, fringilla leo. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis vitae auctor mauris. Pellentesque eu pellentesque lorem, vel ultricies libero. Pellentesque vestibulum sagittis eros. In vestibulum lacus elit. Interdum et malesuada fames ac ante ipsum primis in faucibus. + +Vivamus pharetra lacus fringilla nisl molestie eleifend. Donec et dolor non quam mattis mattis. Proin malesuada maximus elit id semper. Donec facilisis dolor ut feugiat auctor. Proin accumsan semper consectetur. Vivamus facilisis odio vel bibendum imperdiet. Sed rutrum nisi nec nisi interdum fringilla. Aliquam laoreet velit ullamcorper egestas ultrices. Aliquam ultricies sem sed orci interdum, eu porta purus malesuada. Sed accumsan, nunc ut maximus rhoncus, arcu ante pretium ex, non ultrices magna nisi et velit. Pellentesque tempor mi quis lacus consectetur, quis imperdiet enim efficitur. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. + +Nunc sed maximus erat. Aenean imperdiet finibus massa ac aliquam. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis dignissim cursus purus, eu tempus urna. Nunc sed mauris scelerisque, luctus eros ut, viverra nisi. Maecenas congue sed ligula in eleifend. Praesent nec dignissim enim, dictum efficitur massa. Nullam eros dui, rutrum quis aliquam accumsan, sollicitudin cursus eros. Phasellus euismod, lorem vitae vehicula ullamcorper, leo lorem vestibulum magna, vitae malesuada libero ipsum id lorem. Aenean finibus turpis facilisis tortor bibendum, vitae dignissim dolor dictum. Ut quis ornare nisi, non rutrum sapien. + +Etiam placerat, est eget placerat imperdiet, neque urna tristique est, a dictum nisl dolor vitae leo. Vivamus porttitor mi vitae volutpat ultrices. Quisque at ante porta mauris ultricies iaculis. Phasellus iaculis sollicitudin urna nec facilisis. Suspendisse dapibus vulputate scelerisque. Fusce felis diam, eleifend in tristique in, malesuada a purus. Suspendisse euismod ipsum sed urna imperdiet, quis venenatis lacus dapibus. Maecenas vitae est vel sem fringilla ornare at ut mi. Quisque porta, nulla at rutrum fringilla, mi ligula egestas libero, ac convallis elit diam et sapien. Vestibulum purus tortor, ornare ut enim sed, mattis lobortis erat. Maecenas ac ante tincidunt, euismod mauris a, fermentum diam. Nullam arcu est, consequat sed enim in, bibendum aliquet velit. Donec bibendum magna ac augue sagittis vehicula. Curabitur nec mauris eu augue bibendum volutpat. Fusce fringilla varius fringilla. + +Aliquam faucibus massa non orci accumsan, porta consectetur diam vulputate. Nullam nec erat mollis, imperdiet libero nec, tincidunt neque. Aenean varius purus nec est auctor, sed vulputate libero varius. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vel neque elit. Donec vulputate fermentum nulla, ut aliquam neque tempor in. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec vel venenatis est. Suspendisse luctus elit quis dui dapibus, id sodales dolor cursus. Curabitur ut vehicula dui. Fusce aliquet est et ante feugiat, et tempus ex congue. Nunc eget dapibus leo. Nunc eu accumsan diam. Suspendisse risus eros, rutrum et volutpat in, consequat in nulla. Suspendisse id felis a orci accumsan iaculis. + +Duis tincidunt diam eget tortor aliquet sodales. Etiam sodales purus ac urna mollis, et cursus enim porttitor. Nulla viverra ligula nunc, ornare condimentum felis posuere sed. Fusce aliquet pretium sagittis. Sed ac mi elementum massa dictum ornare. Integer quis dapibus lectus. Curabitur in rhoncus justo, et vulputate justo. Integer eget efficitur felis. + +Sed finibus vel tortor ac egestas. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas vestibulum nulla mi, blandit efficitur sapien fermentum eu. Integer sed turpis eros. Phasellus sed aliquam ligula. Etiam dictum quam in dapibus mattis. Donec et tristique quam. Pellentesque gravida luctus dolor, eu ornare sapien. Donec justo ante, lacinia non sem et, ultricies dignissim nibh. Vivamus eu nisl et magna pulvinar efficitur. Sed at vehicula lectus, sit amet luctus sem. Morbi vehicula sapien nisi, nec sagittis orci vestibulum et. + +Praesent non finibus diam. Quisque sit amet nisl vitae augue lobortis commodo. Morbi ullamcorper, tortor id ornare maximus, erat ipsum ullamcorper ipsum, in imperdiet diam sem vel erat. Sed pellentesque quis ex sed volutpat. Vestibulum volutpat diam ac dignissim sollicitudin. Praesent at luctus ex, at volutpat dui. Nunc nulla dui, lobortis et pharetra quis, efficitur in turpis. Donec sodales auctor purus id mollis. Sed auctor eu erat eget bibendum. Mauris tincidunt ornare neque id consequat. Suspendisse non massa ante. Quisque velit enim, rhoncus at erat eget, scelerisque placerat elit. Donec finibus luctus dolor. In sed eleifend lorem. Sed tempor ullamcorper lorem nec tristique. Fusce nec volutpat neque, id elementum est. + +Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum mattis elementum tellus, vitae maximus nulla eleifend ut. Vestibulum eu nibh vulputate, posuere felis eget, aliquet ex. Nullam leo ex, lacinia a ante ac, accumsan efficitur ligula. Vestibulum ornare gravida tempus. Proin rhoncus felis sit amet dolor commodo facilisis. Integer aliquet, diam sed pharetra feugiat, sem massa mollis orci, eget pretium libero nunc at quam. Ut rhoncus quam vitae massa hendrerit, ornare condimentum odio varius. Donec odio sapien, tristique eget libero ac, interdum facilisis odio. Phasellus nec mauris vel dolor semper mattis et quis ligula. Donec nec porttitor nunc. Integer maximus quam vitae sem gravida, ut commodo ex porttitor. + +Sed cursus nisi turpis, vel laoreet massa blandit ut. Cras posuere velit nulla, nec pellentesque ipsum dignissim eget. Donec pharetra, ex et commodo viverra, leo dolor dapibus tellus, vel dignissim est sem ac lectus. Quisque a arcu dapibus, aliquet magna sed, rhoncus neque. Integer suscipit, nulla ac varius lacinia, orci metus scelerisque neque, a laoreet nibh risus vitae dolor. Pellentesque felis metus, pulvinar vel cursus id, ultrices non purus. Donec mi lectus, faucibus sit amet nunc at, sagittis pretium lectus. Fusce nec purus arcu. Mauris neque neque, blandit eget mi at, auctor tempus orci. Mauris sapien lorem, luctus nec tellus non, porttitor aliquam dui. + +Mauris non ex risus. Aliquam imperdiet in eros eget placerat. Sed congue sed sapien porta sollicitudin. Phasellus tempor hendrerit metus vitae tincidunt. Suspendisse congue nisi sed augue dapibus, at pretium ante mollis. Cras non posuere nulla. Proin malesuada finibus magna vel iaculis. Cras in dapibus lorem. Pellentesque volutpat dolor sit amet magna tincidunt mollis. Nunc et lectus sodales, accumsan est vitae, ornare augue. Maecenas malesuada arcu leo, eget blandit lectus porttitor et. Nam aliquam sapien sit amet purus consequat lobortis. Aenean varius, augue porta dignissim efficitur, felis velit dapibus leo, tincidunt ultricies magna felis id ligula. Duis hendrerit, lectus eu elementum euismod, elit lectus consequat mi, sit amet egestas justo massa ut urna. Proin eleifend interdum ultrices. + +Donec lacinia orci pharetra ornare tincidunt. Nulla facilisi. Maecenas malesuada dui ac elit sagittis tincidunt id dictum dolor. Quisque lobortis purus ac metus volutpat viverra. Proin finibus sapien ut odio semper consectetur. Sed gravida luctus egestas. Mauris pretium volutpat elit, at commodo arcu sagittis nec. Ut condimentum fringilla urna ac dignissim. Cras aliquam metus pulvinar, pulvinar nibh at, placerat arcu. Nulla ornare tortor sed lectus mollis, vitae fringilla tellus egestas. Vivamus efficitur tincidunt sapien, sed finibus mi congue eu. Nullam magna velit, lacinia vitae ligula eget, molestie consectetur felis. Suspendisse varius turpis orci, ac laoreet arcu accumsan sed. Fusce quis fermentum lacus, nec varius libero. Pellentesque ac odio ut justo lobortis elementum sit amet vehicula lorem. Nulla interdum nulla eget mi tristique, vitae egestas nunc egestas. + +Curabitur commodo libero eu elit tincidunt, quis placerat risus vehicula. Vestibulum vehicula id nunc iaculis fermentum. Aenean semper, tellus ac semper rutrum, justo lorem feugiat leo, quis vulputate neque dui non ligula. Etiam egestas, enim eget tempor porta, nunc est tristique ante, vel suscipit massa lorem vel diam. Donec faucibus ante id turpis rhoncus congue. Nullam laoreet, diam efficitur scelerisque consequat, ligula leo ultrices est, non fermentum elit mauris ut dolor. Morbi non porttitor lorem. Sed volutpat sapien et lorem porttitor, ultricies ultricies tellus congue. Mauris sodales, tortor nec sagittis finibus, dui odio aliquet nibh, in luctus sapien massa eu risus. Nulla in est sed ante molestie vehicula vel nec lectus. Fusce maximus a quam eget aliquam. Vivamus pulvinar quis nisi a maximus. Proin cursus lacus sapien, et hendrerit elit pretium a. Donec tellus lectus, consectetur id dolor a, luctus rutrum libero. Suspendisse auctor scelerisque dui, nec pellentesque felis viverra nec. Cras elit ex, varius sed pulvinar sed, suscipit ultrices lacus. + +Vivamus eu luctus lectus. Maecenas congue magna orci, quis semper nulla blandit vel. Phasellus dignissim risus placerat lacinia sagittis. Praesent at gravida nisi, at pulvinar diam. Nulla egestas lectus sed felis facilisis egestas. Curabitur posuere gravida urna eu vestibulum. Pellentesque at dolor gravida, placerat quam sit amet, fermentum ligula. Morbi fringilla, mi eget mollis dictum, neque dolor ullamcorper leo, a rutrum libero ipsum eget orci. Curabitur consectetur iaculis vestibulum. Suspendisse ultricies ligula et neque lacinia luctus. Sed dignissim neque id eros sollicitudin pellentesque. + +Donec et magna quis lectus pharetra finibus a fringilla sapien. Phasellus accumsan, erat eu sodales cursus, tortor elit dapibus risus, ut ornare neque arcu in tellus. Nam ac vehicula diam, at aliquam nisl. Cras in sem eget nisi ultrices rutrum sit amet eu velit. Sed molestie tellus eget ante scelerisque, sit amet pulvinar neque fringilla. Nunc volutpat facilisis egestas. Cras sodales dui ac massa egestas, in mattis leo rhoncus. Pellentesque vitae urna vehicula ipsum sodales suscipit. Sed commodo tempus fringilla. + +Etiam egestas elit vitae mi maximus fringilla quis eget libero. Fusce finibus ultrices tellus at molestie. Pellentesque posuere blandit elementum. Etiam eu erat eu urna hendrerit euismod. Nulla quis lectus rhoncus, ultricies urna eget, pretium neque. Cras sit amet ipsum sit amet purus rutrum ultricies nec vitae tortor. Sed tempor dapibus augue in pulvinar. Ut pretium sapien in malesuada accumsan. Donec eget ultrices erat, ut efficitur ligula. Sed posuere mauris est, nec convallis ipsum tempus non. + +Duis a ullamcorper ante. Quisque eu ultricies metus, at aliquet odio. Nullam tempus molestie augue ut varius. Fusce purus eros, dictum nec finibus sed, sodales et diam. Suspendisse sed mi purus. Donec eleifend ipsum diam, nec fringilla enim laoreet non. Phasellus condimentum, magna sit amet porttitor suscipit, arcu risus lobortis dolor, ac fringilla nibh nisl vel purus. Phasellus facilisis posuere orci sit amet tempus. Nam nec enim maximus, rhoncus felis a, rutrum diam. + +Suspendisse potenti. Donec vel tempor neque. In aliquet nulla in eleifend bibendum. Sed sapien sem, finibus in sodales vitae, euismod in sem. Phasellus nec elit a erat pulvinar semper. Aliquam luctus nisl in libero molestie aliquam. Nunc ac ornare felis. Ut non mauris ut ipsum rhoncus pretium. Curabitur tristique lacus a sagittis aliquam. Morbi vel volutpat tellus. Maecenas volutpat, lacus sed tempus imperdiet, eros tellus volutpat nisi, a egestas augue nulla quis arcu. In sollicitudin imperdiet efficitur. Suspendisse viverra aliquet nisi, congue ultrices arcu hendrerit in. + +Maecenas vitae vestibulum nunc. Nullam semper faucibus tincidunt. Etiam sed hendrerit risus. Proin gravida, urna nec tincidunt tempus, nulla sapien porttitor nibh, porttitor lobortis nunc quam et tortor. Praesent ut varius lacus, ut hendrerit enim. Ut nec turpis ac felis imperdiet bibendum. Phasellus porttitor enim odio, et vehicula mi convallis vel. Quisque porta scelerisque sagittis. Praesent dignissim sagittis vulputate. Aenean non justo ac est volutpat bibendum. Aliquam mattis, sapien dapibus pellentesque semper, velit urna malesuada diam, nec varius nibh eros at erat. Proin leo ante, ultricies id velit ut, faucibus porta nibh. Sed nec fermentum urna, sed mollis leo. Aliquam erat volutpat. + +Donec condimentum, urna sed hendrerit vestibulum, ante nibh lacinia dui, in tincidunt odio sem eget orci. In hac habitasse platea dictumst. Mauris id ex id ante tempus finibus eu sagittis erat. Quisque interdum urna risus, vel varius nibh euismod non. Nulla eget pellentesque quam. Aliquam vestibulum ac tortor non lobortis. Sed vitae erat sed libero dignissim dictum nec in turpis. Vivamus id ornare elit, ut facilisis lectus. Morbi dictum purus eget ipsum dignissim porttitor. Sed at vehicula purus, nec rhoncus quam. Nunc a nisl quis arcu blandit fermentum vel quis odio. Vivamus rhoncus, sapien sed lacinia hendrerit, velit urna fermentum dolor, id feugiat magna ligula sed urna. Proin euismod efficitur libero, eget porttitor lacus tempus quis. Duis tincidunt quis est a laoreet. Nam sit amet tristique nisl, sit amet mattis mi. + +Aenean id dictum nulla, sed laoreet magna. Morbi consectetur in turpis at aliquam. Maecenas rutrum feugiat metus, at ullamcorper augue fermentum ut. Vivamus in magna pretium nibh dictum rhoncus luctus at orci. In hac habitasse platea dictumst. Fusce convallis, nulla nec hendrerit suscipit, ipsum diam lobortis sem, vitae elementum lectus erat sit amet magna. Quisque sollicitudin fringilla purus, ac molestie justo congue vitae. Nulla sapien leo, ullamcorper ac tellus in, cursus rhoncus enim. Suspendisse rutrum magna non ex elementum elementum id vitae enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse ornare libero eu molestie pulvinar. Phasellus faucibus, magna eget rutrum porta, lorem turpis blandit lectus, eu viverra massa risus et ex. + +Ut consectetur eros lacus, ac ullamcorper lacus mattis a. Cras congue justo ut erat interdum, et scelerisque nisi malesuada. Quisque sed sapien sollicitudin purus tincidunt finibus vestibulum vel dolor. Cras iaculis bibendum erat, a dictum urna viverra et. Integer non neque vulputate, tincidunt purus nec, rutrum arcu. Aliquam nec magna non sem semper laoreet quis at quam. Mauris dui lectus, convallis eu efficitur at, facilisis nec lorem. Cras felis sem, egestas ac rutrum vel, mollis et ex. Aenean semper egestas libero, nec commodo mi blandit efficitur. Duis nec quam in massa dignissim sagittis vel vitae leo. Nam molestie hendrerit auctor. + +Sed suscipit egestas tellus sed cursus. Donec vel massa sit amet dui condimentum accumsan. Phasellus libero eros, lobortis a nisi id, porttitor maximus lectus. Praesent consectetur diam urna, id viverra turpis elementum in. Vivamus vitae pretium justo, nec tempor felis. Vivamus volutpat ultricies magna. Suspendisse vulputate lectus ac orci volutpat ullamcorper. Nulla eu leo pretium, commodo arcu accumsan, tempor nisl. Fusce sit amet tellus a ipsum vehicula laoreet sed vitae mauris. Duis porttitor massa mattis nibh placerat consequat. Fusce rutrum commodo tortor eget pellentesque. Suspendisse tempor enim libero, consequat dictum nibh dictum varius. Pellentesque feugiat sit amet urna sed facilisis. Curabitur a sagittis augue. \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java b/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java new file mode 100644 index 0000000000..8f70cf1419 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java @@ -0,0 +1,115 @@ +package com.baeldung.bufferedreader; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.util.StringUtils; + +import java.io.*; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BufferedReaderExampleUnitTest { + + public static final String FILE_NAME = "src/main/resources/input.txt"; + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + private final PrintStream originalOut = System.out; + private final PrintStream originalErr = System.err; + + @Before + public void setup() { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + } + + @After + public void restore() { + System.setOut(originalOut); + System.setErr(originalErr); + } + + @Test + public void givenBufferedReader_whenReadAllLines_thenReturnsContent() throws IOException { + BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); + + BufferedReaderExample bre = new BufferedReaderExample(); + String content = bre.readAllLines(reader); + + assertThat(content).isNotEmpty(); + assertThat(content).contains("Lorem ipsum"); + } + + @Test + public void givenBufferedReader_whenReadAllLines2_thenReturnsContent() throws IOException { + BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); + + BufferedReaderExample bre = new BufferedReaderExample(); + String content = bre.readAllLines2(reader); + + assertThat(content).isNotEmpty(); + assertThat(content).contains("Lorem ipsum"); + } + + @Test + public void whenReadFile_thenOutputsContent() { + BufferedReaderExample bre = new BufferedReaderExample(); + bre.readFile(); + + assertThat(outContent.toString()).contains("Lorem ipsum"); + } + + @Test + public void givenBufferedReader_whenReadAllCharacters_thenReturnsContent() throws IOException { + BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); + + BufferedReaderExample bre = new BufferedReaderExample(); + String content = bre.readAllCharacters(reader); + + assertThat(content).isNotEmpty(); + assertThat(content).contains("Lorem ipsum"); + } + + @Test + public void givenBufferedReader_whenReadAllCharacter2_thenReturnsContent() throws IOException { + BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); + + BufferedReaderExample bre = new BufferedReaderExample(); + String content = bre.readAllCharacters2(reader); + + assertThat(content).isNotEmpty(); + assertThat(content).contains("Lorem ipsum"); + } + + @Test + public void givenBufferedReader_whenReadWithSkipping_thenReturnsScrambledContent() throws IOException { + BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); + + BufferedReaderExample bre = new BufferedReaderExample(); + String content = bre.readWithSkipping(reader); + + assertThat(content).isNotEmpty(); + assertThat(content).contains("L mottneas"); + } + + @Test + public void givenBufferedReader_whenMarkAndReset_thenOutputsRepeatedContent() throws IOException { + BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); + + BufferedReaderExample bre = new BufferedReaderExample(); + bre.markAndReset(reader); + + assertThat(outContent.toString()).isNotEmpty(); + assertThat(StringUtils.countOccurrencesOf(outContent.toString(), "Lorem ipsum")).isEqualTo(3); + } + + @Test + public void whenReadFileTryWithResources_thenOutputsContent() { + BufferedReaderExample bre = new BufferedReaderExample(); + bre.readFileTryWithResources(); + + assertThat(outContent.toString()).contains("Lorem ipsum"); + } + +} From dc5640c86ba68c158d9ad6818e62c9772949b8be Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Tue, 16 Oct 2018 01:04:46 +0200 Subject: [PATCH 02/76] [BAEL-2255] - fix formatting --- .../com/baeldung/bufferedreader/BufferedReaderExample.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java b/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java index f381ab7c61..1d7a3d8fda 100644 --- a/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java +++ b/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java @@ -21,7 +21,9 @@ public class BufferedReaderExample { public String readAllLines2(BufferedReader reader) { StringBuilder content = new StringBuilder(); - reader.lines().forEach(line -> content.append(line).append(System.lineSeparator())); + reader.lines() + .forEach(line -> content.append(line) + .append(System.lineSeparator())); return content.toString(); } @@ -95,7 +97,7 @@ public class BufferedReaderExample { } public void readFileTryWithResources() { - try(BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/input.txt"))) { + try (BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/input.txt"))) { String content = readAllLines(reader); System.out.println(content); } catch (IOException e) { From 67cfde81f3a3ad6dd38e91cc775747152c4185dc Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Wed, 17 Oct 2018 20:05:21 +0200 Subject: [PATCH 03/76] [BAEL-2255] - apply requested changes from code review --- .../bufferedreader/BufferedReaderExample.java | 33 ++++++------ .../BufferedReaderExampleUnitTest.java | 51 +++++++------------ 2 files changed, 34 insertions(+), 50 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java b/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java index 1d7a3d8fda..2260c5e2bd 100644 --- a/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java +++ b/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java @@ -3,7 +3,6 @@ package com.baeldung.bufferedreader; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; -import java.util.Arrays; public class BufferedReaderExample { @@ -19,7 +18,7 @@ public class BufferedReaderExample { return content.toString(); } - public String readAllLines2(BufferedReader reader) { + public String readAllLinesWithStream(BufferedReader reader) { StringBuilder content = new StringBuilder(); reader.lines() .forEach(line -> content.append(line) @@ -38,18 +37,14 @@ public class BufferedReaderExample { return content.toString(); } - public String readAllCharacters2(BufferedReader reader) throws IOException { + public String readAllCharactersUsingArray(BufferedReader reader) throws IOException { StringBuilder content = new StringBuilder(); - String title = "text: "; - char[] buf = Arrays.copyOf(title.toCharArray(), 512); - int offset = title.length(); - + char[] buf = new char[512]; int charsRead; - while ((charsRead = reader.read(buf, offset, buf.length - offset)) != -1) { - content.append(buf, 0, offset + charsRead); - content.append(" --- "); + while ((charsRead = reader.read(buf, 0, buf.length)) != -1) { + content.append(buf, 0, charsRead); } return content.toString(); @@ -67,24 +62,29 @@ public class BufferedReaderExample { return content.toString(); } - public void markAndReset(BufferedReader reader) throws IOException { + public String markAndReset(BufferedReader reader) throws IOException { + StringBuilder content = new StringBuilder(); + reader.mark(512); for (int i = 0; i < 3; i++) { - System.out.println(reader.readLine()); + content.append(reader.readLine()); reader.reset(); reader.mark(512); } + + return content.toString(); } - public void readFile() { + public String readFile() { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("src/main/resources/input.txt")); String content = readAllLines(reader); - System.out.println(content); + return content; } catch (IOException e) { e.printStackTrace(); + return null; } finally { try { if (reader != null) { @@ -96,12 +96,13 @@ public class BufferedReaderExample { } } - public void readFileTryWithResources() { + public String readFileTryWithResources() { try (BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/input.txt"))) { String content = readAllLines(reader); - System.out.println(content); + return content; } catch (IOException e) { e.printStackTrace(); + return null; } } diff --git a/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java b/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java index 8f70cf1419..b90a4ab6ed 100644 --- a/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java +++ b/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java @@ -1,11 +1,11 @@ package com.baeldung.bufferedreader; -import org.junit.After; -import org.junit.Before; import org.junit.Test; import org.springframework.util.StringUtils; -import java.io.*; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; @@ -13,23 +13,6 @@ public class BufferedReaderExampleUnitTest { public static final String FILE_NAME = "src/main/resources/input.txt"; - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); - private final PrintStream originalOut = System.out; - private final PrintStream originalErr = System.err; - - @Before - public void setup() { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - } - - @After - public void restore() { - System.setOut(originalOut); - System.setErr(originalErr); - } - @Test public void givenBufferedReader_whenReadAllLines_thenReturnsContent() throws IOException { BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); @@ -42,22 +25,22 @@ public class BufferedReaderExampleUnitTest { } @Test - public void givenBufferedReader_whenReadAllLines2_thenReturnsContent() throws IOException { + public void givenBufferedReader_whenReadAllLinesWithStream_thenReturnsContent() throws IOException { BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); BufferedReaderExample bre = new BufferedReaderExample(); - String content = bre.readAllLines2(reader); + String content = bre.readAllLinesWithStream(reader); assertThat(content).isNotEmpty(); assertThat(content).contains("Lorem ipsum"); } @Test - public void whenReadFile_thenOutputsContent() { + public void whenReadFile_thenReturnsContent() { BufferedReaderExample bre = new BufferedReaderExample(); - bre.readFile(); + String content = bre.readFile(); - assertThat(outContent.toString()).contains("Lorem ipsum"); + assertThat(content.toString()).contains("Lorem ipsum"); } @Test @@ -72,11 +55,11 @@ public class BufferedReaderExampleUnitTest { } @Test - public void givenBufferedReader_whenReadAllCharacter2_thenReturnsContent() throws IOException { + public void givenBufferedReader_whenReadAllCharactersUsingArray_thenReturnsContent() throws IOException { BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); BufferedReaderExample bre = new BufferedReaderExample(); - String content = bre.readAllCharacters2(reader); + String content = bre.readAllCharactersUsingArray(reader); assertThat(content).isNotEmpty(); assertThat(content).contains("Lorem ipsum"); @@ -94,22 +77,22 @@ public class BufferedReaderExampleUnitTest { } @Test - public void givenBufferedReader_whenMarkAndReset_thenOutputsRepeatedContent() throws IOException { + public void givenBufferedReader_whenMarkAndReset_thenReturnsRepeatedContent() throws IOException { BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); BufferedReaderExample bre = new BufferedReaderExample(); - bre.markAndReset(reader); + String content = bre.markAndReset(reader); - assertThat(outContent.toString()).isNotEmpty(); - assertThat(StringUtils.countOccurrencesOf(outContent.toString(), "Lorem ipsum")).isEqualTo(3); + assertThat(content.toString()).isNotEmpty(); + assertThat(StringUtils.countOccurrencesOf(content.toString(), "Lorem ipsum")).isEqualTo(3); } @Test - public void whenReadFileTryWithResources_thenOutputsContent() { + public void whenReadFileTryWithResources_thenReturnsContent() { BufferedReaderExample bre = new BufferedReaderExample(); - bre.readFileTryWithResources(); + String content = bre.readFileTryWithResources(); - assertThat(outContent.toString()).contains("Lorem ipsum"); + assertThat(content.toString()).contains("Lorem ipsum"); } } From 7fa876cc6cc634234eac49297af0e2c12da496cb Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Sun, 21 Oct 2018 21:56:57 +0200 Subject: [PATCH 04/76] [BAEL-2255] - implement more meaningful unit-test-like code examples for skip, mark and reset methods --- .../bufferedreader/BufferedReaderExample.java | 54 ++++----------- .../BufferedReaderExampleUnitTest.java | 68 +++++++++++-------- 2 files changed, 54 insertions(+), 68 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java b/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java index 2260c5e2bd..591122d18f 100644 --- a/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java +++ b/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java @@ -3,6 +3,7 @@ package com.baeldung.bufferedreader; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; +import java.util.stream.Collectors; public class BufferedReaderExample { @@ -19,14 +20,12 @@ public class BufferedReaderExample { } public String readAllLinesWithStream(BufferedReader reader) { - StringBuilder content = new StringBuilder(); - reader.lines() - .forEach(line -> content.append(line) - .append(System.lineSeparator())); - return content.toString(); + return reader + .lines() + .collect(Collectors.joining(System.lineSeparator())); } - public String readAllCharacters(BufferedReader reader) throws IOException { + public String readAllCharsOneByOne(BufferedReader reader) throws IOException { StringBuilder content = new StringBuilder(); int value; @@ -37,43 +36,18 @@ public class BufferedReaderExample { return content.toString(); } - public String readAllCharactersUsingArray(BufferedReader reader) throws IOException { - StringBuilder content = new StringBuilder(); + public String readMultipleChars(BufferedReader reader) throws IOException { + char[] chars = new char[5]; + int charsRead = reader.read(chars, 0, 5); - char[] buf = new char[512]; - int charsRead; - - while ((charsRead = reader.read(buf, 0, buf.length)) != -1) { - content.append(buf, 0, charsRead); + String result; + if (charsRead != -1) { + result = new String(chars); + } else { + result = ""; } - return content.toString(); - } - - public String readWithSkipping(BufferedReader reader) throws IOException { - StringBuilder content = new StringBuilder(); - - int value; - while ((value = reader.read()) != -1) { - content.append((char) value); - reader.skip(4); - } - - return content.toString(); - } - - public String markAndReset(BufferedReader reader) throws IOException { - StringBuilder content = new StringBuilder(); - - reader.mark(512); - - for (int i = 0; i < 3; i++) { - content.append(reader.readLine()); - reader.reset(); - reader.mark(512); - } - - return content.toString(); + return result; } public String readFile() { diff --git a/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java b/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java index b90a4ab6ed..f47ba09097 100644 --- a/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java +++ b/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java @@ -1,13 +1,14 @@ package com.baeldung.bufferedreader; import org.junit.Test; -import org.springframework.util.StringUtils; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; +import java.io.StringReader; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; public class BufferedReaderExampleUnitTest { @@ -44,47 +45,25 @@ public class BufferedReaderExampleUnitTest { } @Test - public void givenBufferedReader_whenReadAllCharacters_thenReturnsContent() throws IOException { + public void givenBufferedReader_whenReadAllCharsOneByOne_thenReturnsContent() throws IOException { BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); BufferedReaderExample bre = new BufferedReaderExample(); - String content = bre.readAllCharacters(reader); + String content = bre.readAllCharsOneByOne(reader); assertThat(content).isNotEmpty(); assertThat(content).contains("Lorem ipsum"); } @Test - public void givenBufferedReader_whenReadAllCharactersUsingArray_thenReturnsContent() throws IOException { + public void givenBufferedReader_whenReadMultipleChars_thenReturnsContent() throws IOException { BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); BufferedReaderExample bre = new BufferedReaderExample(); - String content = bre.readAllCharactersUsingArray(reader); + String content = bre.readMultipleChars(reader); assertThat(content).isNotEmpty(); - assertThat(content).contains("Lorem ipsum"); - } - - @Test - public void givenBufferedReader_whenReadWithSkipping_thenReturnsScrambledContent() throws IOException { - BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); - - BufferedReaderExample bre = new BufferedReaderExample(); - String content = bre.readWithSkipping(reader); - - assertThat(content).isNotEmpty(); - assertThat(content).contains("L mottneas"); - } - - @Test - public void givenBufferedReader_whenMarkAndReset_thenReturnsRepeatedContent() throws IOException { - BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); - - BufferedReaderExample bre = new BufferedReaderExample(); - String content = bre.markAndReset(reader); - - assertThat(content.toString()).isNotEmpty(); - assertThat(StringUtils.countOccurrencesOf(content.toString(), "Lorem ipsum")).isEqualTo(3); + assertThat(content).contains("Lorem"); } @Test @@ -95,4 +74,37 @@ public class BufferedReaderExampleUnitTest { assertThat(content.toString()).contains("Lorem ipsum"); } + @Test + public void givenBufferedReader_whenSkipUnderscores_thenOk() throws IOException { + StringBuilder result = new StringBuilder(); + + try (BufferedReader reader = new BufferedReader(new StringReader("1__2__3__4__5"))) { + int value; + while((value = reader.read()) != -1) { + result.append((char) value); + reader.skip(2L); + } + } + + assertEquals("12345", result.toString()); + } + + @Test + public void givenBufferedReader_whenSkipsWhitespacesAtBeginning_thenOk() throws IOException { + String result; + + try (BufferedReader reader = new BufferedReader(new StringReader(" Lorem ipsum dolor sit amet."))) { + reader.mark(1); + + while (Character.isWhitespace(reader.read())) { + reader.mark(1); + } + + reader.reset(); + result = reader.readLine(); + } + + assertEquals("Lorem ipsum dolor sit amet.", result); + } + } From 940146e03e33a78f46315d279ee88f444dd18e23 Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Sun, 21 Oct 2018 22:20:56 +0200 Subject: [PATCH 05/76] [BAEL-2255] fix unit test --- .../baeldung/bufferedreader/BufferedReaderExampleUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java b/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java index f47ba09097..18b5f47397 100644 --- a/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java +++ b/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java @@ -63,7 +63,7 @@ public class BufferedReaderExampleUnitTest { String content = bre.readMultipleChars(reader); assertThat(content).isNotEmpty(); - assertThat(content).contains("Lorem"); + assertThat(content).isEqualTo("Lorem"); } @Test From d4db4ced085e064f282554f37d0b118a08fa80c0 Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Sat, 27 Oct 2018 13:05:31 +0200 Subject: [PATCH 06/76] [BAEL-2255] improved a few examples --- .../bufferedreader/BufferedReaderExample.java | 7 +++-- .../BufferedReaderExampleUnitTest.java | 30 +++++++++++++------ 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java b/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java index 591122d18f..01a998a0ba 100644 --- a/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java +++ b/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java @@ -37,12 +37,13 @@ public class BufferedReaderExample { } public String readMultipleChars(BufferedReader reader) throws IOException { - char[] chars = new char[5]; - int charsRead = reader.read(chars, 0, 5); + int length = 5; + char[] chars = new char[length]; + int charsRead = reader.read(chars, 0, length); String result; if (charsRead != -1) { - result = new String(chars); + result = new String(chars, charsRead, 0); } else { result = ""; } diff --git a/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java b/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java index 18b5f47397..7a831eb380 100644 --- a/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java +++ b/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java @@ -6,17 +6,19 @@ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.StringReader; +import java.nio.file.Files; +import java.nio.file.Paths; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; public class BufferedReaderExampleUnitTest { - public static final String FILE_NAME = "src/main/resources/input.txt"; + public static final String FILE_PATH = "src/main/resources/input.txt"; @Test public void givenBufferedReader_whenReadAllLines_thenReturnsContent() throws IOException { - BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); + BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH)); BufferedReaderExample bre = new BufferedReaderExample(); String content = bre.readAllLines(reader); @@ -27,7 +29,7 @@ public class BufferedReaderExampleUnitTest { @Test public void givenBufferedReader_whenReadAllLinesWithStream_thenReturnsContent() throws IOException { - BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); + BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH)); BufferedReaderExample bre = new BufferedReaderExample(); String content = bre.readAllLinesWithStream(reader); @@ -46,7 +48,7 @@ public class BufferedReaderExampleUnitTest { @Test public void givenBufferedReader_whenReadAllCharsOneByOne_thenReturnsContent() throws IOException { - BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); + BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH)); BufferedReaderExample bre = new BufferedReaderExample(); String content = bre.readAllCharsOneByOne(reader); @@ -57,7 +59,7 @@ public class BufferedReaderExampleUnitTest { @Test public void givenBufferedReader_whenReadMultipleChars_thenReturnsContent() throws IOException { - BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME)); + BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH)); BufferedReaderExample bre = new BufferedReaderExample(); String content = bre.readMultipleChars(reader); @@ -94,11 +96,11 @@ public class BufferedReaderExampleUnitTest { String result; try (BufferedReader reader = new BufferedReader(new StringReader(" Lorem ipsum dolor sit amet."))) { - reader.mark(1); + assertTrue(reader.markSupported()); - while (Character.isWhitespace(reader.read())) { + do { reader.mark(1); - } + } while(Character.isWhitespace(reader.read())); reader.reset(); result = reader.readLine(); @@ -107,4 +109,14 @@ public class BufferedReaderExampleUnitTest { assertEquals("Lorem ipsum dolor sit amet.", result); } + @Test + public void whenCreatesNewBufferedReader_thenOk() throws IOException { + BufferedReader reader = Files.newBufferedReader(Paths.get(FILE_PATH)); + + assertNotNull(reader); + assertTrue(reader.ready()); + + reader.close(); + } + } From 86e6fad300e9e5187616aade5d6ee22733103e25 Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Sat, 27 Oct 2018 13:36:39 +0200 Subject: [PATCH 07/76] [BAEL-2255] fix example --- .../java/com/baeldung/bufferedreader/BufferedReaderExample.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java b/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java index 01a998a0ba..c7f0e878ac 100644 --- a/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java +++ b/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java @@ -43,7 +43,7 @@ public class BufferedReaderExample { String result; if (charsRead != -1) { - result = new String(chars, charsRead, 0); + result = new String(chars, 0, charsRead); } else { result = ""; } From f1a98f97282b9bba4fbe7528172b374e0bce7a2e Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Wed, 31 Oct 2018 15:56:41 +0100 Subject: [PATCH 08/76] [BAEL-2255] applied requested changes --- .../bufferedreader/BufferedReaderExample.java | 0 .../src/main/resources/input.txt | 0 .../BufferedReaderExampleUnitTest.java | 49 +--------------- .../BufferedReaderUnitTest.java | 58 +++++++++++++++++++ 4 files changed, 59 insertions(+), 48 deletions(-) rename {core-java => core-java-io}/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java (100%) rename {core-java => core-java-io}/src/main/resources/input.txt (100%) rename {core-java => core-java-io}/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java (62%) create mode 100644 core-java-io/src/test/java/com/baeldung/bufferedreader/BufferedReaderUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java b/core-java-io/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java similarity index 100% rename from core-java/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java rename to core-java-io/src/main/java/com/baeldung/bufferedreader/BufferedReaderExample.java diff --git a/core-java/src/main/resources/input.txt b/core-java-io/src/main/resources/input.txt similarity index 100% rename from core-java/src/main/resources/input.txt rename to core-java-io/src/main/resources/input.txt diff --git a/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java b/core-java-io/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java similarity index 62% rename from core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java rename to core-java-io/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java index 7a831eb380..9af00c086a 100644 --- a/core-java/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java +++ b/core-java-io/src/test/java/com/baeldung/bufferedreader/BufferedReaderExampleUnitTest.java @@ -5,16 +5,12 @@ import org.junit.Test; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; -import java.io.StringReader; -import java.nio.file.Files; -import java.nio.file.Paths; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.*; public class BufferedReaderExampleUnitTest { - public static final String FILE_PATH = "src/main/resources/input.txt"; + private static final String FILE_PATH = "src/main/resources/input.txt"; @Test public void givenBufferedReader_whenReadAllLines_thenReturnsContent() throws IOException { @@ -76,47 +72,4 @@ public class BufferedReaderExampleUnitTest { assertThat(content.toString()).contains("Lorem ipsum"); } - @Test - public void givenBufferedReader_whenSkipUnderscores_thenOk() throws IOException { - StringBuilder result = new StringBuilder(); - - try (BufferedReader reader = new BufferedReader(new StringReader("1__2__3__4__5"))) { - int value; - while((value = reader.read()) != -1) { - result.append((char) value); - reader.skip(2L); - } - } - - assertEquals("12345", result.toString()); - } - - @Test - public void givenBufferedReader_whenSkipsWhitespacesAtBeginning_thenOk() throws IOException { - String result; - - try (BufferedReader reader = new BufferedReader(new StringReader(" Lorem ipsum dolor sit amet."))) { - assertTrue(reader.markSupported()); - - do { - reader.mark(1); - } while(Character.isWhitespace(reader.read())); - - reader.reset(); - result = reader.readLine(); - } - - assertEquals("Lorem ipsum dolor sit amet.", result); - } - - @Test - public void whenCreatesNewBufferedReader_thenOk() throws IOException { - BufferedReader reader = Files.newBufferedReader(Paths.get(FILE_PATH)); - - assertNotNull(reader); - assertTrue(reader.ready()); - - reader.close(); - } - } diff --git a/core-java-io/src/test/java/com/baeldung/bufferedreader/BufferedReaderUnitTest.java b/core-java-io/src/test/java/com/baeldung/bufferedreader/BufferedReaderUnitTest.java new file mode 100644 index 0000000000..985eb05aec --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/bufferedreader/BufferedReaderUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.bufferedreader; + +import org.junit.Test; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; +import java.nio.file.Files; +import java.nio.file.Paths; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class BufferedReaderUnitTest { + + private static final String FILE_PATH = "src/main/resources/input.txt"; + + @Test + public void givenBufferedReader_whenSkipUnderscores_thenOk() throws IOException { + StringBuilder result = new StringBuilder(); + + try (BufferedReader reader = new BufferedReader(new StringReader("1__2__3__4__5"))) { + int value; + while((value = reader.read()) != -1) { + result.append((char) value); + reader.skip(2L); + } + } + + assertEquals("12345", result.toString()); + } + + @Test + public void givenBufferedReader_whenSkipsWhitespacesAtBeginning_thenOk() throws IOException { + String result; + + try (BufferedReader reader = new BufferedReader(new StringReader(" Lorem ipsum dolor sit amet."))) { + do { + reader.mark(1); + } while(Character.isWhitespace(reader.read())); + + reader.reset(); + result = reader.readLine(); + } + + assertEquals("Lorem ipsum dolor sit amet.", result); + } + + @Test + public void whenCreatesNewBufferedReader_thenOk() throws IOException { + try(BufferedReader reader = Files.newBufferedReader(Paths.get(FILE_PATH))) { + assertNotNull(reader); + assertTrue(reader.ready()); + } + } + +} From 770b28f2418e9e875252f7a30213803faa1a9e08 Mon Sep 17 00:00:00 2001 From: Holger Ludvigsen Date: Mon, 5 Nov 2018 15:39:11 +0100 Subject: [PATCH 09/76] FileOutputStream is never closed The output file stream is not closed, so it is still in use by the Java process after the code runs. I noticed this when trying to delete the output files right afterwards. --- .../src/main/java/com/baeldung/download/FileDownload.java | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-io/src/main/java/com/baeldung/download/FileDownload.java b/core-java-io/src/main/java/com/baeldung/download/FileDownload.java index c7dd154023..a099406d4c 100644 --- a/core-java-io/src/main/java/com/baeldung/download/FileDownload.java +++ b/core-java-io/src/main/java/com/baeldung/download/FileDownload.java @@ -45,6 +45,7 @@ public class FileDownload { FileOutputStream fileOutputStream = new FileOutputStream(localFilename); FileChannel fileChannel = fileOutputStream.getChannel()) { fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE); + fileOutputStream.close(); } } From be17633174947ac55865dcc357bf615a7448470c Mon Sep 17 00:00:00 2001 From: chandra Date: Fri, 9 Nov 2018 21:08:02 -0500 Subject: [PATCH 10/76] BAEL-2313 Convert String to Byte Array and Reverse in Java --- .../conversion/ByteArrayToStringUnitTest.java | 91 ++++++++++++++ .../conversion/StringToByteArrayUnitTest.java | 119 ++++++++++++++++++ 2 files changed, 210 insertions(+) create mode 100644 java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java create mode 100644 java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java new file mode 100644 index 0000000000..cb18d04cc3 --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java @@ -0,0 +1,91 @@ +package com.baeldung.string.conversion; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; + +import org.junit.Test; + +public class ByteArrayToStringUnitTest { + + @Test + public void whenStringConstructorWithDefaultCharset_thenOK() { + final byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, + 108, 100, 33 }; + String string = new String(byteArrray); + System.out.println(string); + + assertNotNull(string); + } + + @Test + public void whenStringConstructorWithNamedCharset_thenOK() + throws UnsupportedEncodingException { + final String charsetName = "IBM01140"; + final byte[] byteArrray = { -56, -123, -109, -109, -106, 64, -26, -106, + -103, -109, -124, 90 }; + + String string = new String(byteArrray, charsetName); + + assertEquals("Hello World!", string); + } + + @Test + public void whenStringConstructorWithCharSet_thenOK() { + final Charset charset = Charset.forName("UTF-8"); + final byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, + 108, 100, 33 }; + + String string = new String(byteArrray, charset); + + assertEquals("Hello World!", string); + } + + @Test + public void whenStringConstructorWithStandardCharSet_thenOK() { + final Charset charset = StandardCharsets.UTF_16; + + final byte[] byteArrray = { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, + 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 }; + + String string = new String(byteArrray, charset); + + assertEquals("Hello World!", string); + } + + @Test + public void whenDecodeWithCharset_thenOK() { + byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, + 100, 33 }; + final Charset charset = StandardCharsets.UTF_8; + + String string = charset.decode(ByteBuffer.wrap(byteArrray)).toString(); + System.out.println(string); + + assertEquals("Hello World!", string); + } + + @Test + public void whenUsingCharsetDecoder_thenOK() + throws CharacterCodingException { + byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, + 100, 33 }; + CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(); + + decoder.onMalformedInput(CodingErrorAction.IGNORE) + .onUnmappableCharacter(CodingErrorAction.REPLACE) + .replaceWith("?"); + + String string = decoder.decode(ByteBuffer.wrap(byteArrray)).toString(); + + assertEquals("Hello World!", string); + } + +} diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java new file mode 100644 index 0000000000..6086e2f60b --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java @@ -0,0 +1,119 @@ +package com.baeldung.string.conversion; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.UnsupportedEncodingException; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +import org.junit.Test; + +public class StringToByteArrayUnitTest { + + @Test + public void whenGetBytesWithDefaultCharset_thenOK() { + final String inputString = "Hello World!"; + final String defaultCharSet = Charset.defaultCharset().displayName(); + + byte[] byteArrray = inputString.getBytes(); + + System.out.printf( + "Using default charset:%s, Input String:%s, Output byte array:%s\n", + defaultCharSet, inputString, Arrays.toString(byteArrray)); + + assertNotNull(byteArrray); + assert (byteArrray.length >= inputString.length()); + } + + @Test + public void whenGetBytesWithNamedCharset_thenOK() + throws UnsupportedEncodingException { + final String inputString = "Hello World!"; + final String charsetName = "IBM01140"; + + byte[] byteArrray = inputString.getBytes("IBM01140"); + + System.out.printf( + "Using named charset:%s, Input String:%s, Output byte array:%s\n", + charsetName, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals(new byte[] { -56, -123, -109, -109, -106, 64, -26, + -106, -103, -109, -124, 90 }, + byteArrray); + } + + @Test + public void whenGetBytesWithCharset_thenOK() { + final String inputString = "Hello World!"; + final Charset charset = Charset.forName("UTF-8"); + + byte[] byteArrray = inputString.getBytes(charset); + + System.out.printf( + "Using Charset:%s, Input String:%s, Output byte array:%s\n", + charset, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals(new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, + 108, 100, 33 }, + byteArrray); + } + + @Test + public void whenGetBytesWithStandardCharset_thenOK() { + final String inputString = "Hello World!"; + final Charset charset = StandardCharsets.UTF_16; + + byte[] byteArrray = inputString.getBytes(charset); + + System.out.printf( + "Using Standard Charset:%s, Input String:%s, Output byte array:%s\n", + charset, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals(new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, + 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 }, + byteArrray); + } + + @Test + public void whenEncodeWithCharset_thenOK() { + final String inputString = "Hello World!"; + final Charset charset = StandardCharsets.UTF_8; + + byte[] byteArrray = charset.encode(inputString).array(); + + System.out.printf( + "Using encode with Charset:%s, Input String:%s, Output byte array:%s\n", + charset, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals(new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, + 108, 100, 33, 0 }, + byteArrray); + } + + @Test + public void whenUsingCharsetEncoder_thenOK() + throws CharacterCodingException { + final String inputString = "Hello World!"; + CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder(); + encoder.onMalformedInput(CodingErrorAction.IGNORE) + .onUnmappableCharacter(CodingErrorAction.REPLACE) + .replaceWith(new byte[] { 0 }); + + byte[] byteArrray = encoder.encode(CharBuffer.wrap(inputString)).array(); + + System.out.printf( + "Using encode with CharsetEncoder:%s, Input String:%s, Output byte array:%s\n", + encoder, inputString, Arrays.toString(byteArrray)); + + assertArrayEquals(new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, + 108, 100, 33, 0 }, + byteArrray); + } + +} From 243323c55f2b879b37bab9817cb9f08f9e63958e Mon Sep 17 00:00:00 2001 From: chandra Date: Mon, 12 Nov 2018 21:36:21 -0500 Subject: [PATCH 11/76] Modified sample inputs to make the tests more meaningful. --- .../conversion/ByteArrayToStringUnitTest.java | 17 +++++----- .../conversion/StringToByteArrayUnitTest.java | 33 ++++++++++--------- 2 files changed, 26 insertions(+), 24 deletions(-) diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java index cb18d04cc3..a9f8a04c8d 100644 --- a/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/conversion/ByteArrayToStringUnitTest.java @@ -62,30 +62,29 @@ public class ByteArrayToStringUnitTest { @Test public void whenDecodeWithCharset_thenOK() { - byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, - 100, 33 }; - final Charset charset = StandardCharsets.UTF_8; + byte[] byteArrray = { 72, 101, 108, 108, 111, 32, -10, 111, 114, 108, -63, 33 }; + final Charset charset = StandardCharsets.US_ASCII; String string = charset.decode(ByteBuffer.wrap(byteArrray)).toString(); System.out.println(string); - assertEquals("Hello World!", string); + assertEquals("Hello �orl�!", string); } @Test public void whenUsingCharsetDecoder_thenOK() throws CharacterCodingException { - byte[] byteArrray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, - 100, 33 }; - CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(); + byte[] byteArrray = { 72, 101, 108, 108, 111, 32, -10, 111, 114, 108, -63, 33}; + CharsetDecoder decoder = StandardCharsets.US_ASCII.newDecoder(); - decoder.onMalformedInput(CodingErrorAction.IGNORE) + decoder.onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE) .replaceWith("?"); String string = decoder.decode(ByteBuffer.wrap(byteArrray)).toString(); - assertEquals("Hello World!", string); + assertEquals("Hello ?orl?!", string); } + } diff --git a/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java index 6086e2f60b..5377b4b28d 100644 --- a/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/conversion/StringToByteArrayUnitTest.java @@ -19,7 +19,8 @@ public class StringToByteArrayUnitTest { @Test public void whenGetBytesWithDefaultCharset_thenOK() { final String inputString = "Hello World!"; - final String defaultCharSet = Charset.defaultCharset().displayName(); + final String defaultCharSet = Charset.defaultCharset() + .displayName(); byte[] byteArrray = inputString.getBytes(); @@ -50,8 +51,8 @@ public class StringToByteArrayUnitTest { @Test public void whenGetBytesWithCharset_thenOK() { - final String inputString = "Hello World!"; - final Charset charset = Charset.forName("UTF-8"); + final String inputString = "Hello ਸੰਸਾਰ!"; + final Charset charset = Charset.forName("ASCII"); byte[] byteArrray = inputString.getBytes(charset); @@ -59,8 +60,8 @@ public class StringToByteArrayUnitTest { "Using Charset:%s, Input String:%s, Output byte array:%s\n", charset, inputString, Arrays.toString(byteArrray)); - assertArrayEquals(new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, - 108, 100, 33 }, + assertArrayEquals( + new byte[] { 72, 101, 108, 108, 111, 32, 63, 63, 63, 63, 63, 33 }, byteArrray); } @@ -82,37 +83,39 @@ public class StringToByteArrayUnitTest { @Test public void whenEncodeWithCharset_thenOK() { - final String inputString = "Hello World!"; - final Charset charset = StandardCharsets.UTF_8; + final String inputString = "Hello ਸੰਸਾਰ!"; + final Charset charset = StandardCharsets.US_ASCII; - byte[] byteArrray = charset.encode(inputString).array(); + byte[] byteArrray = charset.encode(inputString) + .array(); System.out.printf( "Using encode with Charset:%s, Input String:%s, Output byte array:%s\n", charset, inputString, Arrays.toString(byteArrray)); - assertArrayEquals(new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, - 108, 100, 33, 0 }, + assertArrayEquals( + new byte[] { 72, 101, 108, 108, 111, 32, 63, 63, 63, 63, 63, 33 }, byteArrray); } @Test public void whenUsingCharsetEncoder_thenOK() throws CharacterCodingException { - final String inputString = "Hello World!"; - CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder(); + final String inputString = "Hello ਸੰਸਾਰ!"; + CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder(); encoder.onMalformedInput(CodingErrorAction.IGNORE) .onUnmappableCharacter(CodingErrorAction.REPLACE) .replaceWith(new byte[] { 0 }); - byte[] byteArrray = encoder.encode(CharBuffer.wrap(inputString)).array(); + byte[] byteArrray = encoder.encode(CharBuffer.wrap(inputString)) + .array(); System.out.printf( "Using encode with CharsetEncoder:%s, Input String:%s, Output byte array:%s\n", encoder, inputString, Arrays.toString(byteArrray)); - assertArrayEquals(new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, - 108, 100, 33, 0 }, + assertArrayEquals( + new byte[] { 72, 101, 108, 108, 111, 32, 0, 0, 0, 0, 0, 33 }, byteArrray); } From 9a6688f638db1d94de0447ea15e5215f4e654330 Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Fri, 16 Nov 2018 14:45:51 -0500 Subject: [PATCH 12/76] initial code for implementation code --- hexagonal-architecture/.gitignore | 1 + hexagonal-architecture/pom.xml | 14 ++++ .../com/baeldung/hexagonal/Application.java | 27 +++++++ .../baeldung/hexagonal/domain/Employee.java | 70 +++++++++++++++++++ .../hexagonal/domain/EmployeeService.java | 26 +++++++ .../hexagonal/output/EmployeeCsvWriter.java | 64 +++++++++++++++++ .../hexagonal/output/EmployeeLogger.java | 17 +++++ .../hexagonal/output/EmployeeOutput.java | 9 +++ .../hexagonal/storage/EmployeeRepository.java | 11 +++ .../storage/InMemoryEmployeeRepository.java | 31 ++++++++ .../ui/EmployeeConsoleInputImpl.java | 53 ++++++++++++++ .../baeldung/hexagonal/ui/EmployeeInput.java | 7 ++ 12 files changed, 330 insertions(+) create mode 100644 hexagonal-architecture/.gitignore create mode 100644 hexagonal-architecture/pom.xml create mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/Application.java create mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java create mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/EmployeeService.java create mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java create mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeLogger.java create mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeOutput.java create mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/EmployeeRepository.java create mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/InMemoryEmployeeRepository.java create mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java create mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeInput.java diff --git a/hexagonal-architecture/.gitignore b/hexagonal-architecture/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/hexagonal-architecture/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/hexagonal-architecture/pom.xml b/hexagonal-architecture/pom.xml new file mode 100644 index 0000000000..c8eceae21a --- /dev/null +++ b/hexagonal-architecture/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + com.baeldung.hexagonal + hexagonal-architecture + jar + hexagonal-architecture + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + \ No newline at end of file diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/Application.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/Application.java new file mode 100644 index 0000000000..4691d498f4 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/Application.java @@ -0,0 +1,27 @@ +package com.baeldung.hexagonal; + +import java.io.File; + +import com.baeldung.hexagonal.domain.EmployeeService; +import com.baeldung.hexagonal.output.EmployeeCsvWriter; +import com.baeldung.hexagonal.output.EmployeeLogger; +import com.baeldung.hexagonal.output.EmployeeOutput; +import com.baeldung.hexagonal.storage.EmployeeRepository; +import com.baeldung.hexagonal.storage.InMemoryEmployeeRepository; +import com.baeldung.hexagonal.ui.EmployeeConsoleInputImpl; +import com.baeldung.hexagonal.ui.EmployeeInput; + +public class Application { + + public static void main(String[] args) { + EmployeeRepository repository = new InMemoryEmployeeRepository(); + EmployeeOutput output = new EmployeeLogger(); + EmployeeOutput csvOutput = new EmployeeCsvWriter(new File(".").getAbsolutePath(), "output.csv"); + EmployeeService service = new EmployeeService(repository, csvOutput); + EmployeeInput ui = new EmployeeConsoleInputImpl(); + ui.collectData(service); + service.generateOutput(); + + } + +} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java new file mode 100644 index 0000000000..91b22d0d11 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java @@ -0,0 +1,70 @@ +package com.baeldung.hexagonal.domain; + +import java.math.BigDecimal; + +public class Employee { + private Long id; + private String firstName; + private String lastName; + private String employeeId; + private BigDecimal salary; + + public Employee( + Long id, + String firstName, + String lastName, + String employeeId, + BigDecimal salary) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.employeeId = employeeId; + this.salary = salary; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(String employeeId) { + this.employeeId = employeeId; + } + + public BigDecimal getSalary() { + return salary; + } + + public void setSalary(BigDecimal salary) { + this.salary = salary; + } + + @Override + public String toString() { + return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", employeeId=" + employeeId + ", salary=" + salary + "]"; + } + +} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/EmployeeService.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/EmployeeService.java new file mode 100644 index 0000000000..12b2028035 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/EmployeeService.java @@ -0,0 +1,26 @@ +package com.baeldung.hexagonal.domain; + + +import java.util.List; + +import com.baeldung.hexagonal.output.EmployeeOutput; +import com.baeldung.hexagonal.storage.EmployeeRepository; + +public class EmployeeService { + private EmployeeRepository employeeRepository; + private EmployeeOutput employeeOutput; + + public EmployeeService(EmployeeRepository employeeRepository, EmployeeOutput employeeOutput) { + this.employeeRepository = employeeRepository; + this.employeeOutput = employeeOutput; + } + + public Long add(Employee employee) { + return employeeRepository.save(employee); + } + + public void generateOutput() { + List employees = employeeRepository.findAll(); + employeeOutput.writeAll(employees); + } +} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java new file mode 100644 index 0000000000..c434d19525 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java @@ -0,0 +1,64 @@ +package com.baeldung.hexagonal.output; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Iterator; +import java.util.List; + +import com.baeldung.hexagonal.domain.Employee; + +public class EmployeeCsvWriter implements EmployeeOutput { + private File outputFile; + + public EmployeeCsvWriter(String path, String fileName) throws IllegalArgumentException { + if (fileName == null || path == null || fileName.length() == 0 || path.length() == 0) { + throw new IllegalArgumentException("Path and FileName are required"); + } else if (!fileName.endsWith(".csv")) { + throw new IllegalArgumentException("File name must be a .csv file"); + } + + System.out.println(path); + if (!path.endsWith("/")) path += "/"; + + outputFile = new File(path, fileName); + } + + @Override + public void writeAll(List employees) { + BufferedWriter writer = null; + + try { + writer = new BufferedWriter(new FileWriter(outputFile)); + for (Iterator it = employees.iterator(); it.hasNext();) { + Employee emp = it.next(); + StringBuffer empLine = new StringBuffer(); + empLine.append(emp.getId()); + empLine.append(","); + empLine.append(emp.getFirstName()); + empLine.append(","); + empLine.append(emp.getLastName()); + empLine.append(","); + empLine.append(emp.getEmployeeId()); + empLine.append(","); + empLine.append(emp.getSalary()); + writer.write(empLine.toString()); + writer.newLine(); + } + writer.flush(); + } catch (IOException ioe) { + //handle the exception + } finally { + if (writer != null) { + try { + writer.close(); + } catch (IOException e) { + //handle the exception + } + } + } + + } + +} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeLogger.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeLogger.java new file mode 100644 index 0000000000..681e631012 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeLogger.java @@ -0,0 +1,17 @@ +package com.baeldung.hexagonal.output; + +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.hexagonal.domain.Employee; + +public class EmployeeLogger implements EmployeeOutput { + private static final Logger LOG = LoggerFactory.getLogger(EmployeeLogger.class); + + @Override + public void writeAll(List employees) { + employees.forEach(employee -> LOG.info(employee.toString())); + } + +} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeOutput.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeOutput.java new file mode 100644 index 0000000000..979c06e1f4 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeOutput.java @@ -0,0 +1,9 @@ +package com.baeldung.hexagonal.output; + +import java.util.List; + +import com.baeldung.hexagonal.domain.Employee; + +public interface EmployeeOutput { + public void writeAll(List employees); +} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/EmployeeRepository.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/EmployeeRepository.java new file mode 100644 index 0000000000..f12584f8e1 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/EmployeeRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.hexagonal.storage; + +import java.util.List; + +import com.baeldung.hexagonal.domain.Employee; + +public interface EmployeeRepository { + public Long save(Employee employee); + public Employee findById(Long id); + public List findAll(); +} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/InMemoryEmployeeRepository.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/InMemoryEmployeeRepository.java new file mode 100644 index 0000000000..e860c16462 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/InMemoryEmployeeRepository.java @@ -0,0 +1,31 @@ +package com.baeldung.hexagonal.storage; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.baeldung.hexagonal.domain.Employee; + +public class InMemoryEmployeeRepository implements EmployeeRepository { + private static Map employees = new HashMap<>(); + + @Override + public Long save(Employee employee) { + Long id = employee.getId(); + employees.put(id, employee); + return id; + } + + @Override + public Employee findById(Long id) { + return employees.get(id); + } + + @Override + public List findAll() { + List all = new ArrayList(employees.values()); + return all; + } + +} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java new file mode 100644 index 0000000000..5f613f7bf9 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java @@ -0,0 +1,53 @@ +package com.baeldung.hexagonal.ui; + +import java.math.BigDecimal; +import java.util.Scanner; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.hexagonal.domain.Employee; +import com.baeldung.hexagonal.domain.EmployeeService; + +public class EmployeeConsoleInputImpl implements EmployeeInput { + private static final Logger LOG = LoggerFactory.getLogger(EmployeeConsoleInputImpl.class); + + public void enterEmployee(EmployeeService service, Scanner scanner) { + + LOG.info("ID: "); + System.out.print("> "); + Long id = scanner.nextLong(); + LOG.info("First Name: "); + System.out.print("> "); + String firstName = scanner.next(); + LOG.info("Last Name: "); + System.out.print("> "); + String lastName = scanner.next(); + LOG.info("Employee ID: "); + System.out.print("> "); + String employeeId = scanner.next(); + LOG.info("Salary: " ); + System.out.print("> "); + BigDecimal salary = scanner.nextBigDecimal(); + + Employee employee = new Employee(id, firstName, lastName, employeeId, salary); + service.add(employee); + + } + + @Override + public void collectData(EmployeeService service) { + try (final Scanner scanner = new Scanner(System.in)) { + String keepGoing = "Y"; + do { + LOG.info("Enter information for an employee"); + enterEmployee(service, scanner); + LOG.info("Do you want to enter another employee? (Y/N)"); + System.out.print("> "); + keepGoing = scanner.next(); + if (keepGoing.length() > 1) keepGoing = keepGoing.substring(0, 1); + } while (keepGoing.equalsIgnoreCase("Y")); + } + } + +} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeInput.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeInput.java new file mode 100644 index 0000000000..62156fc6d9 --- /dev/null +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeInput.java @@ -0,0 +1,7 @@ +package com.baeldung.hexagonal.ui; + +import com.baeldung.hexagonal.domain.EmployeeService; + +public interface EmployeeInput { + void collectData(EmployeeService service); +} From 35db28ccfb884d8f277c6bdb3adc4e5fa5f0bb1c Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Fri, 16 Nov 2018 16:40:46 -0500 Subject: [PATCH 13/76] formatting changes --- .../com/baeldung/hexagonal/Application.java | 1 - .../baeldung/hexagonal/domain/Employee.java | 2 +- .../hexagonal/domain/EmployeeService.java | 33 +++++++------- .../hexagonal/output/EmployeeCsvWriter.java | 16 ++++--- .../hexagonal/output/EmployeeLogger.java | 2 +- .../hexagonal/storage/EmployeeRepository.java | 8 ++-- .../ui/EmployeeConsoleInputImpl.java | 43 ++++++++++--------- .../baeldung/hexagonal/ui/EmployeeInput.java | 2 +- 8 files changed, 55 insertions(+), 52 deletions(-) diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/Application.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/Application.java index 4691d498f4..237b664708 100644 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/Application.java +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/Application.java @@ -21,7 +21,6 @@ public class Application { EmployeeInput ui = new EmployeeConsoleInputImpl(); ui.collectData(service); service.generateOutput(); - } } diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java index 91b22d0d11..b785da1494 100644 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java @@ -8,7 +8,7 @@ public class Employee { private String lastName; private String employeeId; private BigDecimal salary; - + public Employee( Long id, String firstName, diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/EmployeeService.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/EmployeeService.java index 12b2028035..2ab3ce9712 100644 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/EmployeeService.java +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/EmployeeService.java @@ -1,26 +1,25 @@ package com.baeldung.hexagonal.domain; - import java.util.List; import com.baeldung.hexagonal.output.EmployeeOutput; import com.baeldung.hexagonal.storage.EmployeeRepository; public class EmployeeService { - private EmployeeRepository employeeRepository; - private EmployeeOutput employeeOutput; - - public EmployeeService(EmployeeRepository employeeRepository, EmployeeOutput employeeOutput) { - this.employeeRepository = employeeRepository; - this.employeeOutput = employeeOutput; - } - - public Long add(Employee employee) { - return employeeRepository.save(employee); - } - - public void generateOutput() { - List employees = employeeRepository.findAll(); - employeeOutput.writeAll(employees); - } + private EmployeeRepository employeeRepository; + private EmployeeOutput employeeOutput; + + public EmployeeService(EmployeeRepository employeeRepository, EmployeeOutput employeeOutput) { + this.employeeRepository = employeeRepository; + this.employeeOutput = employeeOutput; + } + + public Long add(Employee employee) { + return employeeRepository.save(employee); + } + + public void generateOutput() { + List employees = employeeRepository.findAll(); + employeeOutput.writeAll(employees); + } } diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java index c434d19525..6d364dd11b 100644 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java @@ -11,24 +11,26 @@ import com.baeldung.hexagonal.domain.Employee; public class EmployeeCsvWriter implements EmployeeOutput { private File outputFile; - + public EmployeeCsvWriter(String path, String fileName) throws IllegalArgumentException { if (fileName == null || path == null || fileName.length() == 0 || path.length() == 0) { throw new IllegalArgumentException("Path and FileName are required"); } else if (!fileName.endsWith(".csv")) { throw new IllegalArgumentException("File name must be a .csv file"); } - + System.out.println(path); - if (!path.endsWith("/")) path += "/"; - + if (!path.endsWith("/")) { + path += "/"; + } + outputFile = new File(path, fileName); } @Override public void writeAll(List employees) { BufferedWriter writer = null; - + try { writer = new BufferedWriter(new FileWriter(outputFile)); for (Iterator it = employees.iterator(); it.hasNext();) { @@ -48,13 +50,13 @@ public class EmployeeCsvWriter implements EmployeeOutput { } writer.flush(); } catch (IOException ioe) { - //handle the exception + // handle the exception } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { - //handle the exception + // handle the exception } } } diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeLogger.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeLogger.java index 681e631012..5272d18961 100644 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeLogger.java +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeLogger.java @@ -11,7 +11,7 @@ public class EmployeeLogger implements EmployeeOutput { @Override public void writeAll(List employees) { - employees.forEach(employee -> LOG.info(employee.toString())); + employees.forEach(employee -> LOG.info(employee.toString())); } } diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/EmployeeRepository.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/EmployeeRepository.java index f12584f8e1..2787601998 100644 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/EmployeeRepository.java +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/EmployeeRepository.java @@ -5,7 +5,9 @@ import java.util.List; import com.baeldung.hexagonal.domain.Employee; public interface EmployeeRepository { - public Long save(Employee employee); - public Employee findById(Long id); - public List findAll(); + public Long save(Employee employee); + + public Employee findById(Long id); + + public List findAll(); } diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java index 5f613f7bf9..4960dfd254 100644 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java @@ -13,26 +13,26 @@ public class EmployeeConsoleInputImpl implements EmployeeInput { private static final Logger LOG = LoggerFactory.getLogger(EmployeeConsoleInputImpl.class); public void enterEmployee(EmployeeService service, Scanner scanner) { - - LOG.info("ID: "); - System.out.print("> "); - Long id = scanner.nextLong(); - LOG.info("First Name: "); - System.out.print("> "); - String firstName = scanner.next(); - LOG.info("Last Name: "); - System.out.print("> "); - String lastName = scanner.next(); - LOG.info("Employee ID: "); - System.out.print("> "); - String employeeId = scanner.next(); - LOG.info("Salary: " ); - System.out.print("> "); - BigDecimal salary = scanner.nextBigDecimal(); - - Employee employee = new Employee(id, firstName, lastName, employeeId, salary); - service.add(employee); - + + LOG.info("ID: "); + System.out.print("> "); + Long id = scanner.nextLong(); + LOG.info("First Name: "); + System.out.print("> "); + String firstName = scanner.next(); + LOG.info("Last Name: "); + System.out.print("> "); + String lastName = scanner.next(); + LOG.info("Employee ID: "); + System.out.print("> "); + String employeeId = scanner.next(); + LOG.info("Salary: "); + System.out.print("> "); + BigDecimal salary = scanner.nextBigDecimal(); + + Employee employee = new Employee(id, firstName, lastName, employeeId, salary); + service.add(employee); + } @Override @@ -45,7 +45,8 @@ public class EmployeeConsoleInputImpl implements EmployeeInput { LOG.info("Do you want to enter another employee? (Y/N)"); System.out.print("> "); keepGoing = scanner.next(); - if (keepGoing.length() > 1) keepGoing = keepGoing.substring(0, 1); + if (keepGoing.length() > 1) + keepGoing = keepGoing.substring(0, 1); } while (keepGoing.equalsIgnoreCase("Y")); } } diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeInput.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeInput.java index 62156fc6d9..adec2852cd 100644 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeInput.java +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeInput.java @@ -3,5 +3,5 @@ package com.baeldung.hexagonal.ui; import com.baeldung.hexagonal.domain.EmployeeService; public interface EmployeeInput { - void collectData(EmployeeService service); + void collectData(EmployeeService service); } From f1c3029c59c71eabfcd302956b4f93069d3cea02 Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Sun, 18 Nov 2018 09:57:39 -0500 Subject: [PATCH 14/76] trim down Exmployee fields --- .../baeldung/hexagonal/domain/Employee.java | 80 ++++++++----------- .../hexagonal/output/EmployeeCsvWriter.java | 9 +-- .../ui/EmployeeConsoleInputImpl.java | 21 ++--- 3 files changed, 41 insertions(+), 69 deletions(-) diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java index b785da1494..0d883995b6 100644 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java @@ -1,25 +1,12 @@ package com.baeldung.hexagonal.domain; -import java.math.BigDecimal; - public class Employee { private Long id; - private String firstName; - private String lastName; - private String employeeId; - private BigDecimal salary; + private String name; - public Employee( - Long id, - String firstName, - String lastName, - String employeeId, - BigDecimal salary) { + public Employee(Long id, String name) { this.id = id; - this.firstName = firstName; - this.lastName = lastName; - this.employeeId = employeeId; - this.salary = salary; + this.name = name; } public Long getId() { @@ -30,41 +17,44 @@ public class Employee { this.id = id; } - public String getFirstName() { - return firstName; + public String getName() { + return name; } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getEmployeeId() { - return employeeId; - } - - public void setEmployeeId(String employeeId) { - this.employeeId = employeeId; - } - - public BigDecimal getSalary() { - return salary; - } - - public void setSalary(BigDecimal salary) { - this.salary = salary; + public void setName(String name) { + this.name = name; } @Override public String toString() { - return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", employeeId=" + employeeId + ", salary=" + salary + "]"; + return "Employee [id=" + id + ", name=" + name + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Employee other = (Employee) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + + return true; } } diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java index 6d364dd11b..799fbc28ba 100644 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java @@ -38,14 +38,7 @@ public class EmployeeCsvWriter implements EmployeeOutput { StringBuffer empLine = new StringBuffer(); empLine.append(emp.getId()); empLine.append(","); - empLine.append(emp.getFirstName()); - empLine.append(","); - empLine.append(emp.getLastName()); - empLine.append(","); - empLine.append(emp.getEmployeeId()); - empLine.append(","); - empLine.append(emp.getSalary()); - writer.write(empLine.toString()); + empLine.append(emp.getName()); writer.newLine(); } writer.flush(); diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java index 4960dfd254..77453da48f 100644 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java +++ b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java @@ -1,6 +1,5 @@ package com.baeldung.hexagonal.ui; -import java.math.BigDecimal; import java.util.Scanner; import org.slf4j.Logger; @@ -13,26 +12,15 @@ public class EmployeeConsoleInputImpl implements EmployeeInput { private static final Logger LOG = LoggerFactory.getLogger(EmployeeConsoleInputImpl.class); public void enterEmployee(EmployeeService service, Scanner scanner) { - LOG.info("ID: "); System.out.print("> "); Long id = scanner.nextLong(); - LOG.info("First Name: "); + LOG.info("Name: "); System.out.print("> "); - String firstName = scanner.next(); - LOG.info("Last Name: "); - System.out.print("> "); - String lastName = scanner.next(); - LOG.info("Employee ID: "); - System.out.print("> "); - String employeeId = scanner.next(); - LOG.info("Salary: "); - System.out.print("> "); - BigDecimal salary = scanner.nextBigDecimal(); + String name = scanner.next(); - Employee employee = new Employee(id, firstName, lastName, employeeId, salary); + Employee employee = new Employee(id, name); service.add(employee); - } @Override @@ -45,8 +33,9 @@ public class EmployeeConsoleInputImpl implements EmployeeInput { LOG.info("Do you want to enter another employee? (Y/N)"); System.out.print("> "); keepGoing = scanner.next(); - if (keepGoing.length() > 1) + if (keepGoing.length() > 1) { keepGoing = keepGoing.substring(0, 1); + } } while (keepGoing.equalsIgnoreCase("Y")); } } From 09e7119f89208eb42e535b3b4e1c9c85aa4cf108 Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Sun, 18 Nov 2018 10:07:05 -0500 Subject: [PATCH 15/76] add new line to pom.xml --- hexagonal-architecture/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hexagonal-architecture/pom.xml b/hexagonal-architecture/pom.xml index c8eceae21a..d184576705 100644 --- a/hexagonal-architecture/pom.xml +++ b/hexagonal-architecture/pom.xml @@ -11,4 +11,4 @@ 0.0.1-SNAPSHOT ../parent-java - \ No newline at end of file + From 6b7dfe79ba37a7dfacad60a7b9d26cfb7343b1b8 Mon Sep 17 00:00:00 2001 From: Chandra Prakash Date: Wed, 21 Nov 2018 20:31:03 -0500 Subject: [PATCH 16/76] Update README.md --- java-strings/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-strings/README.md b/java-strings/README.md index a653087401..a5db51c6a5 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -35,3 +35,4 @@ - [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) - [String Performance Hints](https://www.baeldung.com/java-string-performance) - [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences) +- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array) From f06a9f4106cff01c7de0b05b6d980dfc98533e7d Mon Sep 17 00:00:00 2001 From: Juan Moreno Date: Fri, 30 Nov 2018 01:30:19 -0300 Subject: [PATCH 17/76] Sample code for BAEL-2333 --- java-streams/pom.xml | 10 +- .../com/baeldung/stream/filter/Customer.java | 55 +++++++++ .../stream/filter/StreamFilterUnitTest.java | 115 ++++++++++++++++++ 3 files changed, 178 insertions(+), 2 deletions(-) create mode 100644 java-streams/src/main/java/com/baeldung/stream/filter/Customer.java create mode 100644 java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java diff --git a/java-streams/pom.xml b/java-streams/pom.xml index e4670c268d..2b52ebb4b3 100644 --- a/java-streams/pom.xml +++ b/java-streams/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 java-streams 0.1.0-SNAPSHOT @@ -74,6 +74,11 @@ aspectjweaver ${asspectj.version} + + pl.touk + throwing-function + ${throwing-function.version} + @@ -108,8 +113,9 @@ 1.15 0.6.5 2.10 + 1.3 - 3.6.1 + 3.11.1 1.8.9 diff --git a/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java b/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java new file mode 100644 index 0000000000..49da6e7175 --- /dev/null +++ b/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java @@ -0,0 +1,55 @@ +package com.baeldung.stream.filter; + +import javax.net.ssl.HttpsURLConnection; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; + +public class Customer { + private String name; + private int points; + private String profilePhotoUrl; + + public Customer(String name, int points) { + this(name, points, ""); + } + + public Customer(String name, int points, String profilePhotoUrl) { + this.name = name; + this.points = points; + this.profilePhotoUrl = profilePhotoUrl; + } + + public String getName() { + return name; + } + + public int getPoints() { + return points; + } + + public boolean hasOver(int points) { + return this.points > points; + } + + public boolean hasOverThousandPoints() { + return this.points > 100; + } + + public boolean hasValidProfilePhoto() throws IOException { + URL url = new URL(this.profilePhotoUrl); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + return connection.getResponseCode() == HttpURLConnection.HTTP_OK; + } + + public boolean hasValidProfilePhotoWithoutCheckedException() { + try { + URL url = new URL(this.profilePhotoUrl); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + return connection.getResponseCode() == HttpURLConnection.HTTP_OK; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java new file mode 100644 index 0000000000..c89a27cdf1 --- /dev/null +++ b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java @@ -0,0 +1,115 @@ +package com.baeldung.stream.filter; + +import org.junit.jupiter.api.Test; +import pl.touk.throwing.ThrowingPredicate; +import pl.touk.throwing.exception.WrappedException; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +public class StreamFilterUnitTest { + + @Test + public void givenListOfCustomers_whenFilterByLambda_thenGetTwo() { + List customers = Arrays.asList(new Customer("John P.", 15), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), new Customer("Mary T.", 1)); + + long customersWithMoreThan100Points = customers + .stream() + .filter(c -> c.getPoints() > 100) + .count(); + + assertThat(customersWithMoreThan100Points).isEqualTo(2); + } + + @Test + public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() { + List customers = Arrays.asList(new Customer("John P.", 15), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), new Customer("Mary T.", 1)); + + long customersWithMoreThan100Points = customers + .stream() + .filter(Customer::hasOverThousandPoints) + .count(); + + assertThat(customersWithMoreThan100Points).isEqualTo(2); + } + + @Test + public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() { + List> customers = Arrays.asList(Optional.of(new Customer("John P.", 15)), Optional.of(new Customer("Sarah M.", 200)), Optional.empty(), Optional.of(new Customer("Mary T.", 300)), Optional.empty()); + + long customersWithMoreThan100Points = customers + .stream() + .flatMap(c -> c + .map(Stream::of) + .orElseGet(Stream::empty)) + .filter(Customer::hasOverThousandPoints) + .count(); + + assertThat(customersWithMoreThan100Points).isEqualTo(2); + } + + @Test + public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() { + List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), + new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + + assertThatThrownBy(() -> customers + .stream() + .filter(Customer::hasValidProfilePhotoWithoutCheckedException) + .count()).isInstanceOf(RuntimeException.class); + } + + @Test + public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() { + List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), + new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + + assertThatThrownBy(() -> customers + .stream() + .filter((ThrowingPredicate.unchecked(Customer::hasValidProfilePhoto))) + .count()).isInstanceOf(WrappedException.class); + } + + @Test + public void givenListOfCustomers_whenFilterWithTryCatch_thenGetTwo() { + List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), + new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + + long customersWithValidProfilePhoto = customers + .stream() + .filter(c -> { + try { + return c.hasValidProfilePhoto(); + } catch (IOException e) { + //handle exception + } + return false; + }) + .count(); + + assertThat(customersWithValidProfilePhoto).isEqualTo(2); + } + + @Test + public void givenListOfCustomers_whenFilterWithTryCatchAndRuntime_thenThrowException() { + List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), + new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + + assertThatThrownBy(() -> customers + .stream() + .filter(c -> { + try { + return c.hasValidProfilePhoto(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }) + .count()).isInstanceOf(RuntimeException.class); + } +} From 0147b5c699123c2e4a6dff91e7c615e5fb42e2cb Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 2 Dec 2018 23:08:16 +0200 Subject: [PATCH 18/76] fix jedis map ex --- .../src/test/java/com/baeldung/JedisIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java index 5795e9912b..50d28af3d1 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/JedisIntegrationTest.java @@ -144,8 +144,8 @@ public class JedisIntegrationTest { scores.put("PlayerTwo", 1500.0); scores.put("PlayerThree", 8200.0); - scores.keySet().forEach(player -> { - jedis.zadd(key, scores.get(player), player); + scores.entrySet().forEach(playerScore -> { + jedis.zadd(key, playerScore.getValue(), playerScore.getKey()); }); Set players = jedis.zrevrange(key, 0, 1); From d737e15c6b4db542cd4e5ff42d4ffc327f470c29 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 8 Dec 2018 15:29:38 +0530 Subject: [PATCH 19/76] [BAEL-10840] - Create a libraries-apache-commons module --- libraries-apache-commons/.gitignore | 9 ++ libraries-apache-commons/README.md | 21 ++++ libraries-apache-commons/log4j.properties | 1 + libraries-apache-commons/pom.xml | 116 ++++++++++++++++++ .../baeldung/commons/beanutils/Course.java | 0 .../commons/beanutils/CourseEntity.java | 0 .../commons/beanutils/CourseService.java | 0 .../baeldung/commons/beanutils/Student.java | 0 .../chain/AbstractDenominationDispenser.java | 0 .../baeldung/commons/chain/AtmCatalog.java | 0 .../baeldung/commons/chain/AtmConstants.java | 0 .../commons/chain/AtmRequestContext.java | 0 .../commons/chain/AtmWithdrawalChain.java | 0 .../baeldung/commons/chain/AuditFilter.java | 0 .../chain/FiftyDenominationDispenser.java | 0 .../chain/HundredDenominationDispenser.java | 0 .../chain/TenDenominationDispenser.java | 0 .../commons/collectionutil/Address.java | 0 .../commons/collectionutil/Customer.java | 0 .../com/baeldung/commons/dbutils/Email.java | 0 .../baeldung/commons/dbutils/Employee.java | 0 .../commons/dbutils/EmployeeHandler.java | 0 .../com/baeldung/commons/io/FileMonitor.java | 0 .../commons/lang3/BuilderMethods.java | 0 .../commons/lang3/SampleLazyInitializer.java | 0 .../baeldung/commons/lang3/SampleObject.java | 0 .../lang3/application/Application.java | 0 .../baeldung/commons/lang3/beans/User.java | 0 .../commons/lang3/beans/UserInitializer.java | 0 .../com/baeldung/commons/math3/Histogram.java | 0 .../main/java/com/baeldung/ftp/FtpClient.java | 0 .../src/main/resources/logback.xml | 13 ++ .../CircularFifoQueueUnitTest.java | 0 .../beanutils/CourseServiceUnitTest.java | 0 .../commons/chain/AtmChainUnitTest.java | 0 .../commons/collections/BidiMapUnitTest.java | 0 .../CollectionUtilsGuideUnitTest.java | 0 .../commons/collections/MapUtilsUnitTest.java | 0 .../commons/collections/SetUtilsUnitTest.java | 0 .../orderedmap/OrderedMapUnitTest.java | 0 .../commons/collections4/BagUnitTest.java | 0 .../commons/csv/CSVReaderWriterUnitTest.java | 0 .../commons/dbutils/DbUtilsUnitTest.java | 0 .../commons/io/CommonsIOUnitTest.java | 0 .../commons/lang3/ArrayUtilsUnitTest.java | 0 .../commons/lang3/Lang3UtilsUnitTest.java | 0 .../commons/lang3/StringUtilsUnitTest.java | 0 .../lang3/test/ArrayUtilsUnitTest.java | 0 .../test/BasicThreadFactoryUnitTest.java | 0 .../lang3/test/ConstructorUtilsUnitTest.java | 0 .../lang3/test/FieldUtilsUnitTest.java | 0 .../commons/lang3/test/FractionUnitTest.java | 0 .../lang3/test/HashCodeBuilderUnitTest.java | 0 .../lang3/test/ImmutablePairUnitTest.java | 0 .../lang3/test/ImmutableTripleUnitTest.java | 0 .../lang3/test/LazyInitializerUnitTest.java | 0 .../lang3/test/MethodUtilsUnitTest.java | 0 .../lang3/test/MutableObjectUnitTest.java | 0 .../lang3/test/MutablePairUnitTest.java | 0 .../lang3/test/NumberUtilsUnitTest.java | 0 .../lang3/test/StringUtilsUnitTest.java | 0 .../lang3/test/SystemsUtilsManualTest.java | 0 .../commons/lang3/test/TripleUnitTest.java | 0 .../commons/math/ComplexUnitTest.java | 0 .../commons/math/FractionUnitTest.java | 0 .../commons/math/GeometryUnitTest.java | 0 .../commons/math/LinearAlgebraUnitTest.java | 0 .../commons/math/ProbabilitiesUnitTest.java | 0 .../commons/math/RootFindingUnitTest.java | 0 .../math/SimpsonIntegratorUnitTest.java | 0 .../commons/math/StatisticsUnitTest.java | 0 .../ftp/FtpClientIntegrationTest.java | 0 .../ftp/JdkFtpClientIntegrationTest.java | 0 .../java/com/baeldung/text/DiffUnitTest.java | 0 .../LongestCommonSubsequenceUnitTest.java | 0 .../com/baeldung/text/StrBuilderUnitTest.java | 0 .../baeldung/text/StrSubstitutorUnitTest.java | 0 .../baeldung/text/UnicodeEscaperUnitTest.java | 0 .../com/baeldung/text/WordUtilsUnitTest.java | 0 .../src/test/resources/aaa.txt | 0 .../src/test/resources/book.csv | 0 .../src/test/resources/employees.sql | 0 .../src/test/resources/fileTest.txt | 0 .../src/test/resources/ftp/baz.txt | 0 .../src/test/resources/sample.txt | 0 libraries/README.md | 19 --- libraries/pom.xml | 71 ----------- pom.xml | 1 + 88 files changed, 161 insertions(+), 90 deletions(-) create mode 100644 libraries-apache-commons/.gitignore create mode 100644 libraries-apache-commons/README.md create mode 100644 libraries-apache-commons/log4j.properties create mode 100644 libraries-apache-commons/pom.xml rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/beanutils/Course.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/beanutils/CourseService.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/beanutils/Student.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/chain/AtmCatalog.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/chain/AtmConstants.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/chain/AuditFilter.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/collectionutil/Address.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/collectionutil/Customer.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/dbutils/Email.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/dbutils/Employee.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/io/FileMonitor.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/lang3/SampleObject.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/lang3/application/Application.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/lang3/beans/User.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/commons/math3/Histogram.java (100%) rename {libraries => libraries-apache-commons}/src/main/java/com/baeldung/ftp/FtpClient.java (100%) create mode 100644 libraries-apache-commons/src/main/resources/logback.xml rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/math/FractionUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/text/DiffUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/text/StrBuilderUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/java/com/baeldung/text/WordUtilsUnitTest.java (100%) rename {libraries => libraries-apache-commons}/src/test/resources/aaa.txt (100%) rename {libraries => libraries-apache-commons}/src/test/resources/book.csv (100%) rename {libraries => libraries-apache-commons}/src/test/resources/employees.sql (100%) rename {libraries => libraries-apache-commons}/src/test/resources/fileTest.txt (100%) rename {libraries => libraries-apache-commons}/src/test/resources/ftp/baz.txt (100%) rename {libraries => libraries-apache-commons}/src/test/resources/sample.txt (100%) diff --git a/libraries-apache-commons/.gitignore b/libraries-apache-commons/.gitignore new file mode 100644 index 0000000000..e594daf27a --- /dev/null +++ b/libraries-apache-commons/.gitignore @@ -0,0 +1,9 @@ +*.class + +# Folders # +/gensrc +/target + +# Packaged files # +*.jar +/bin/ diff --git a/libraries-apache-commons/README.md b/libraries-apache-commons/README.md new file mode 100644 index 0000000000..66090e3709 --- /dev/null +++ b/libraries-apache-commons/README.md @@ -0,0 +1,21 @@ +### Relevant articles + +- [Array Processing with Apache Commons Lang 3](http://www.baeldung.com/array-processing-commons-lang) +- [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang) +- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math) +- [Apache Commons Collections SetUtils](http://www.baeldung.com/apache-commons-setutils) +- [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) +- [Introduction to Apache Commons Text](http://www.baeldung.com/java-apache-commons-text) +- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) +- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) +- [Apache Commons Chain](http://www.baeldung.com/apache-commons-chain) +- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv) +- [Apache Commons IO](http://www.baeldung.com/apache-commons-io) +- [Apache Commons Collections Bag](http://www.baeldung.com/apache-commons-bag) +- [A Guide to Apache Commons Collections CollectionUtils](http://www.baeldung.com/apache-commons-collection-utils) +- [Apache Commons BeanUtils](http://www.baeldung.com/apache-commons-beanutils) +- [Apache Commons Collections BidiMap](http://www.baeldung.com/commons-collections-bidi-map) +- [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) +- [Histograms with Apache Commons Frequency](http://www.baeldung.com/apache-commons-frequency) +- [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3) +- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) \ No newline at end of file diff --git a/libraries-apache-commons/log4j.properties b/libraries-apache-commons/log4j.properties new file mode 100644 index 0000000000..2173c5d96f --- /dev/null +++ b/libraries-apache-commons/log4j.properties @@ -0,0 +1 @@ +log4j.rootLogger=INFO, stdout diff --git a/libraries-apache-commons/pom.xml b/libraries-apache-commons/pom.xml new file mode 100644 index 0000000000..f61a7a4a9a --- /dev/null +++ b/libraries-apache-commons/pom.xml @@ -0,0 +1,116 @@ + + + 4.0.0 + libraries-apache-commons + libraries-apache-commons + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + org.assertj + assertj-core + ${assertj.version} + + + commons-beanutils + commons-beanutils + ${commons-beanutils.version} + + + org.apache.commons + commons-lang3 + ${commons-lang.version} + + + org.apache.commons + commons-text + ${commons-text.version} + + + commons-io + commons-io + ${commons.io.version} + + + commons-chain + commons-chain + ${commons-chain.version} + + + org.apache.commons + commons-csv + ${commons-csv.version} + + + commons-dbutils + commons-dbutils + ${commons.dbutils.version} + + + org.apache.commons + commons-math3 + ${common-math3.version} + + + commons-net + commons-net + ${commons-net.version} + + + com.h2database + h2 + ${h2.version} + + + org.knowm.xchart + xchart + ${xchart-version} + + + org.apache.commons + commons-collections4 + ${commons.collections.version} + + + org.hamcrest + java-hamcrest + ${org.hamcrest.java-hamcrest.version} + test + + + org.mockftpserver + MockFtpServer + ${mockftpserver.version} + test + + + + + + 3.6 + 1.1 + 1.9.3 + 1.2 + 1.4 + 3.6.2 + 2.5 + 1.6 + 1.4.196 + 4.1 + 4.12 + 2.0.0.0 + 1.10.L001 + 3.5.2 + 3.6 + 1.3 + 3.6.1 + 2.7.1 + + + diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/Course.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/Course.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/beanutils/Course.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/Course.java diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseService.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/CourseService.java diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/Student.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/Student.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/beanutils/Student.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/beanutils/Student.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmCatalog.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmCatalog.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmConstants.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmConstants.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AuditFilter.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/AuditFilter.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java diff --git a/libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java diff --git a/libraries/src/main/java/com/baeldung/commons/collectionutil/Address.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/collectionutil/Address.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/collectionutil/Address.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/collectionutil/Address.java diff --git a/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/collectionutil/Customer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/collectionutil/Customer.java diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/Email.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/dbutils/Email.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/Email.java diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/Employee.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/Employee.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/dbutils/Employee.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/Employee.java diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/dbutils/EmployeeHandler.java diff --git a/libraries/src/main/java/com/baeldung/commons/io/FileMonitor.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/io/FileMonitor.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/io/FileMonitor.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/io/FileMonitor.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/SampleObject.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/SampleObject.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/application/Application.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/application/Application.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/application/Application.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/application/Application.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/beans/User.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/beans/User.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/beans/User.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/beans/User.java diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/lang3/beans/UserInitializer.java diff --git a/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java b/libraries-apache-commons/src/main/java/com/baeldung/commons/math3/Histogram.java similarity index 100% rename from libraries/src/main/java/com/baeldung/commons/math3/Histogram.java rename to libraries-apache-commons/src/main/java/com/baeldung/commons/math3/Histogram.java diff --git a/libraries/src/main/java/com/baeldung/ftp/FtpClient.java b/libraries-apache-commons/src/main/java/com/baeldung/ftp/FtpClient.java similarity index 100% rename from libraries/src/main/java/com/baeldung/ftp/FtpClient.java rename to libraries-apache-commons/src/main/java/com/baeldung/ftp/FtpClient.java diff --git a/libraries-apache-commons/src/main/resources/logback.xml b/libraries-apache-commons/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/libraries-apache-commons/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/circularfifoqueue/CircularFifoQueueUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/chain/AtmChainUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/BidiMapUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/MapUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/collections4/BagUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/csv/CSVReaderWriterUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/ArrayUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/Lang3UtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/StringUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ArrayUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/BasicThreadFactoryUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ConstructorUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/FieldUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/FractionUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/HashCodeBuilderUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ImmutablePairUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/ImmutableTripleUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/LazyInitializerUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MethodUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MutableObjectUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/MutablePairUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/NumberUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/StringUtilsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/lang3/test/TripleUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/ComplexUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/FractionUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/FractionUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/FractionUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/FractionUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/GeometryUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/LinearAlgebraUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/ProbabilitiesUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/RootFindingUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/SimpsonIntegratorUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/commons/math/StatisticsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java b/libraries-apache-commons/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java diff --git a/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java b/libraries-apache-commons/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java diff --git a/libraries/src/test/java/com/baeldung/text/DiffUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/DiffUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/DiffUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/DiffUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/LongestCommonSubsequenceUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/StrBuilderUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/StrBuilderUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/StrBuilderUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/StrBuilderUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/StrSubstitutorUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/UnicodeEscaperUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/text/WordUtilsUnitTest.java b/libraries-apache-commons/src/test/java/com/baeldung/text/WordUtilsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/text/WordUtilsUnitTest.java rename to libraries-apache-commons/src/test/java/com/baeldung/text/WordUtilsUnitTest.java diff --git a/libraries/src/test/resources/aaa.txt b/libraries-apache-commons/src/test/resources/aaa.txt similarity index 100% rename from libraries/src/test/resources/aaa.txt rename to libraries-apache-commons/src/test/resources/aaa.txt diff --git a/libraries/src/test/resources/book.csv b/libraries-apache-commons/src/test/resources/book.csv similarity index 100% rename from libraries/src/test/resources/book.csv rename to libraries-apache-commons/src/test/resources/book.csv diff --git a/libraries/src/test/resources/employees.sql b/libraries-apache-commons/src/test/resources/employees.sql similarity index 100% rename from libraries/src/test/resources/employees.sql rename to libraries-apache-commons/src/test/resources/employees.sql diff --git a/libraries/src/test/resources/fileTest.txt b/libraries-apache-commons/src/test/resources/fileTest.txt similarity index 100% rename from libraries/src/test/resources/fileTest.txt rename to libraries-apache-commons/src/test/resources/fileTest.txt diff --git a/libraries/src/test/resources/ftp/baz.txt b/libraries-apache-commons/src/test/resources/ftp/baz.txt similarity index 100% rename from libraries/src/test/resources/ftp/baz.txt rename to libraries-apache-commons/src/test/resources/ftp/baz.txt diff --git a/libraries/src/test/resources/sample.txt b/libraries-apache-commons/src/test/resources/sample.txt similarity index 100% rename from libraries/src/test/resources/sample.txt rename to libraries-apache-commons/src/test/resources/sample.txt diff --git a/libraries/README.md b/libraries/README.md index 851e3a3d17..28184c161b 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -1,40 +1,29 @@ ### Relevant articles - [Intro to Jasypt](http://www.baeldung.com/jasypt) -- [Array Processing with Apache Commons Lang 3](http://www.baeldung.com/array-processing-commons-lang) -- [String Processing with Apache Commons Lang 3](http://www.baeldung.com/string-processing-commons-lang) - [Introduction to Javatuples](http://www.baeldung.com/java-tuples) - [Introduction to Javassist](http://www.baeldung.com/javassist) - [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink) - [Introduction to JSONassert](http://www.baeldung.com/jsonassert) - [Intro to JaVers](http://www.baeldung.com/javers) -- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math) - [Intro to Serenity BDD](http://www.baeldung.com/serenity-bdd) - [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) - [Serenity BDD and Screenplay](http://www.baeldung.com/serenity-screenplay) - [Introduction to Quartz](http://www.baeldung.com/quartz) - [How to Warm Up the JVM](http://www.baeldung.com/java-jvm-warmup) -- [Apache Commons Collections SetUtils](http://www.baeldung.com/apache-commons-setutils) - [Software Transactional Memory in Java Using Multiverse](http://www.baeldung.com/java-multiverse-stm) - [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave) - [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing) -- [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) -- [Introduction to Apache Commons Text](http://www.baeldung.com/java-apache-commons-text) -- [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) - [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) - [Introduction to Neuroph](http://www.baeldung.com/neuroph) -- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) - [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) - [Introduction to NoException](http://www.baeldung.com/introduction-to-noexception) - [Introduction to PCollections](http://www.baeldung.com/java-pcollections) - [Introduction to Hoverfly in Java](http://www.baeldung.com/hoverfly) -- [Apache Commons Chain](http://www.baeldung.com/apache-commons-chain) - [Introduction to Eclipse Collections](http://www.baeldung.com/eclipse-collections) - [DistinctBy in Java Stream API](http://www.baeldung.com/java-streams-distinct-by) -- [Introduction to Apache Commons CSV](http://www.baeldung.com/apache-commons-csv) - [Introduction to NoException](http://www.baeldung.com/no-exception) -- [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) - [Spring Yarg Integration](http://www.baeldung.com/spring-yarg) @@ -44,7 +33,6 @@ - [Introduction to MBassador](http://www.baeldung.com/mbassador) - [Introduction to Retrofit](http://www.baeldung.com/retrofit) - [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 Docx4J](http://www.baeldung.com/docx4j) @@ -62,26 +50,19 @@ - [Introduction to OpenCSV](http://www.baeldung.com/opencsv) - [A Guide to Unirest](http://www.baeldung.com/unirest) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) -- [A Guide to Apache Commons Collections CollectionUtils](http://www.baeldung.com/apache-commons-collection-utils) - [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy) - [Introduction to jOOL](http://www.baeldung.com/jool) - [Consumer Driven Contracts with Pact](http://www.baeldung.com/pact-junit-consumer-driven-contracts) -- [Apache Commons BeanUtils](http://www.baeldung.com/apache-commons-beanutils) -- [Apache Commons Collections BidiMap](http://www.baeldung.com/commons-collections-bidi-map) - [Introduction to Atlassian Fugue](http://www.baeldung.com/java-fugue) - [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client) - [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools) -- [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) - [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices) - [Introduction to JavaPoet](http://www.baeldung.com/java-poet) - [Introduction to Joda-Time](http://www.baeldung.com/joda-time) -- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) - [Convert String to Date in Java](http://www.baeldung.com/java-string-to-date) -- [Histograms with Apache Commons Frequency](http://www.baeldung.com/apache-commons-frequency) - [Guide to Resilience4j](http://www.baeldung.com/resilience4j) - [Parsing YAML with SnakeYAML](http://www.baeldung.com/java-snake-yaml) - [Guide to JMapper](http://www.baeldung.com/jmapper) -- [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3) - [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once) - [An Introduction to SuanShu](https://www.baeldung.com/suanshu) diff --git a/libraries/pom.xml b/libraries/pom.xml index fb1f1cd1b6..eb0bc58225 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -50,31 +50,16 @@ opencsv ${opencsv.version} - - commons-beanutils - commons-beanutils - ${commons-beanutils.version} - org.apache.commons commons-lang3 ${commons-lang.version} - - org.apache.commons - commons-text - ${commons-text.version} - tec.units unit-ri ${unit-ri.version} - - org.apache.commons - commons-collections4 - ${commons.collections.version} - org.jasypt jasypt @@ -134,32 +119,6 @@ - - commons-io - commons-io - ${commons.io.version} - - - commons-chain - commons-chain - ${commons-chain.version} - - - org.apache.commons - commons-csv - ${commons-csv.version} - - - commons-dbutils - commons-dbutils - ${commons.dbutils.version} - - - - org.apache.commons - commons-math3 - ${common-math3.version} - net.serenity-bdd serenity-core @@ -675,24 +634,6 @@ resilience4j-timelimiter ${resilience4j.version} - - org.knowm.xchart - xchart - ${xchart-version} - - - - commons-net - commons-net - ${commons-net.version} - - - org.mockftpserver - MockFtpServer - ${mockftpserver.version} - test - - com.squareup javapoet @@ -854,10 +795,6 @@ 0.7.0 3.2.7 3.6 - 1.1 - 1.9.3 - 1.2 - 1.4 1.9.2 1.2 3.21.0-GA @@ -865,13 +802,10 @@ 1.5.0 3.1.0 4.5.3 - 2.5 - 1.6 1.4.196 1.0 4.5.3 - 2.5 2.8.5 2.92 1.9.26 @@ -879,7 +813,6 @@ 1.9.0 1.9.27 1.1.0 - 4.1 4.12 0.10 3.5.0 @@ -917,13 +850,9 @@ 2.1.2 2.5.11 0.12.1 - 3.5.2 - 3.6 - 2.7.1 1.10.0 1.3 0.8.1 - 3.6.1 3.2.0-m7 5.1.1 5.0.2 diff --git a/pom.xml b/pom.xml index 4a1db4a937..44a844b6ee 100644 --- a/pom.xml +++ b/pom.xml @@ -982,6 +982,7 @@ libraries-data + libraries-apache-commons linkrest logging-modules/log-mdc logging-modules/log4j From be16616bb82749212e259b4d0e44d3f28601a9f4 Mon Sep 17 00:00:00 2001 From: Juan Moreno Date: Sat, 8 Dec 2018 16:21:30 -0300 Subject: [PATCH 20/76] Added new samples --- java-streams/.attach_pid12113 | 0 .../stream/filter/StreamFilterUnitTest.java | 94 ++++++++++++++----- 2 files changed, 69 insertions(+), 25 deletions(-) create mode 100644 java-streams/.attach_pid12113 diff --git a/java-streams/.attach_pid12113 b/java-streams/.attach_pid12113 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java index c89a27cdf1..cf82802940 100644 --- a/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java @@ -8,56 +8,93 @@ import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; public class StreamFilterUnitTest { @Test - public void givenListOfCustomers_whenFilterByLambda_thenGetTwo() { - List customers = Arrays.asList(new Customer("John P.", 15), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), new Customer("Mary T.", 1)); + public void givenListOfCustomers_whenFilterByPoints_thenGetTwo() { + Customer john = new Customer("John P.", 15); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1); + List customers = Arrays.asList(john, sarah, charles, mary); - long customersWithMoreThan100Points = customers + List customersWithMoreThan100Points = customers .stream() .filter(c -> c.getPoints() > 100) - .count(); + .collect(Collectors.toList()); - assertThat(customersWithMoreThan100Points).isEqualTo(2); + assertThat(customersWithMoreThan100Points).hasSize(2); + assertThat(customersWithMoreThan100Points).contains(sarah, charles); + } + + @Test + public void givenListOfCustomers_whenFilterByPointsAndName_thenGetOne() { + Customer john = new Customer("John P.", 15); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1); + List customers = Arrays.asList(john, sarah, charles, mary); + + List charlesWithMoreThan100Points = customers + .stream() + .filter(c -> c.getPoints() > 100 && c + .getName() + .startsWith("Charles")) + .collect(Collectors.toList()); + + assertThat(charlesWithMoreThan100Points).hasSize(1); + assertThat(charlesWithMoreThan100Points).contains(charles); } @Test public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() { - List customers = Arrays.asList(new Customer("John P.", 15), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), new Customer("Mary T.", 1)); + Customer john = new Customer("John P.", 15); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1); + List customers = Arrays.asList(john, sarah, charles, mary); - long customersWithMoreThan100Points = customers + List customersWithMoreThan100Points = customers .stream() .filter(Customer::hasOverThousandPoints) - .count(); + .collect(Collectors.toList()); - assertThat(customersWithMoreThan100Points).isEqualTo(2); + assertThat(customersWithMoreThan100Points).hasSize(2); + assertThat(customersWithMoreThan100Points).contains(sarah, charles); } @Test public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() { - List> customers = Arrays.asList(Optional.of(new Customer("John P.", 15)), Optional.of(new Customer("Sarah M.", 200)), Optional.empty(), Optional.of(new Customer("Mary T.", 300)), Optional.empty()); + Optional john = Optional.of(new Customer("John P.", 15)); + Optional sarah = Optional.of(new Customer("Sarah M.", 200)); + Optional mary = Optional.of(new Customer("Mary T.", 300)); + List> customers = Arrays.asList(john, sarah, Optional.empty(), mary, Optional.empty()); - long customersWithMoreThan100Points = customers + List customersWithMoreThan100Points = customers .stream() .flatMap(c -> c .map(Stream::of) .orElseGet(Stream::empty)) .filter(Customer::hasOverThousandPoints) - .count(); + .collect(Collectors.toList()); - assertThat(customersWithMoreThan100Points).isEqualTo(2); + assertThat(customersWithMoreThan100Points).hasSize(2); + assertThat(customersWithMoreThan100Points).contains(sarah.get(), mary.get()); } @Test public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() { - List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), - new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"); + List customers = Arrays.asList(john, sarah, charles, mary); assertThatThrownBy(() -> customers .stream() @@ -67,21 +104,27 @@ public class StreamFilterUnitTest { @Test public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() { - List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), - new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"); + List customers = Arrays.asList(john, sarah, charles, mary); assertThatThrownBy(() -> customers .stream() .filter((ThrowingPredicate.unchecked(Customer::hasValidProfilePhoto))) - .count()).isInstanceOf(WrappedException.class); + .collect(Collectors.toList())).isInstanceOf(WrappedException.class); } @Test public void givenListOfCustomers_whenFilterWithTryCatch_thenGetTwo() { - List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150), - new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e")); + Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); + Customer sarah = new Customer("Sarah M.", 200); + Customer charles = new Customer("Charles B.", 150); + Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"); + List customers = Arrays.asList(john, sarah, charles, mary); - long customersWithValidProfilePhoto = customers + List customersWithValidProfilePhoto = customers .stream() .filter(c -> { try { @@ -91,9 +134,10 @@ public class StreamFilterUnitTest { } return false; }) - .count(); + .collect(Collectors.toList()); - assertThat(customersWithValidProfilePhoto).isEqualTo(2); + assertThat(customersWithValidProfilePhoto).hasSize(2); + assertThat(customersWithValidProfilePhoto).contains(john, mary); } @Test @@ -110,6 +154,6 @@ public class StreamFilterUnitTest { throw new RuntimeException(e); } }) - .count()).isInstanceOf(RuntimeException.class); + .collect(Collectors.toList())).isInstanceOf(RuntimeException.class); } } From dfca36b9addbd24a123ca250d40a3c8dfda75258 Mon Sep 17 00:00:00 2001 From: Juan Moreno Date: Sat, 8 Dec 2018 16:31:20 -0300 Subject: [PATCH 21/76] Removed .attach_pid12113 file --- java-streams/.attach_pid12113 | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 java-streams/.attach_pid12113 diff --git a/java-streams/.attach_pid12113 b/java-streams/.attach_pid12113 deleted file mode 100644 index e69de29bb2..0000000000 From 5dec6f7006df5049355998bb111384968e50e227 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Mon, 10 Dec 2018 19:07:29 +0100 Subject: [PATCH 22/76] added example code for BAEL-2418 (#5882) * added example code for BAEL-2366 * moved example code for BAEL-2366 * example code for BAEL-1961 * moved example code into integration test * updated the test assertions * refactor the spring boot persistence mongodb module * remove redundant example code * declared the spring boot persistence module in the root pom * fixed issue with non-imported file * added example code for BAEL-2418 --- .../java/com/baeldung/basicsyntax/SimpleAddition.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java diff --git a/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java b/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java new file mode 100644 index 0000000000..20a13178cc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java @@ -0,0 +1,11 @@ +package com.baeldung.basicsyntax; + +public class SimpleAddition { + + public static void main(String[] args) { + int a = 10; + int b = 5; + double c = a + b; + System.out.println( a + " + " + b + " = " + c); + } +} From e51a0d042807edc5af3cc8a42d9e2e6dab95a71a Mon Sep 17 00:00:00 2001 From: Daniel Barrigas Date: Mon, 10 Dec 2018 21:42:28 +0000 Subject: [PATCH 23/76] Spring Boot Actuator + Kubernetes Issue: BAEL-2356 --- .../liveness-example/Dockerfile | 11 ++++ .../liveness-example/pom.xml | 51 ++++++++++++++++++ .../com/baeldung/liveness/Application.java | 12 +++++ .../health/CustomHealthIndicator.java | 27 ++++++++++ .../resources/application.properties | 1 + .../src/main/resources/resources/logback.xml | 13 +++++ .../SpringContextIntegrationTest.java | 17 ++++++ .../liveness-example-k8s-template.yaml | 54 +++++++++++++++++++ .../readiness-example-k8s-template.yaml | 54 +++++++++++++++++++ spring-cloud/spring-cloud-kubernetes/pom.xml | 2 + .../readiness-example/Dockerfile | 11 ++++ .../readiness-example/pom.xml | 49 +++++++++++++++++ .../com/baeldung/readiness/Application.java | 12 +++++ .../health/CustomHealthIndicator.java | 27 ++++++++++ .../resources/application.properties | 1 + .../src/main/resources/resources/logback.xml | 13 +++++ .../SpringContextIntegrationTest.java | 17 ++++++ 17 files changed, 372 insertions(+) create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml create mode 100644 spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java create mode 100644 spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml create mode 100644 spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml create mode 100644 spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile b/spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile new file mode 100644 index 0000000000..0fc0a9bd64 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/Dockerfile @@ -0,0 +1,11 @@ +FROM openjdk:8-jdk-alpine + +# Create app directory +RUN mkdir -p /usr/opt/service + +# Copy app +COPY target/*.jar /usr/opt/service/service.jar + +EXPOSE 8080 + +ENTRYPOINT exec java -jar /usr/opt/service/service.jar \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml new file mode 100644 index 0000000000..e963dafe67 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/pom.xml @@ -0,0 +1,51 @@ + + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.17.RELEASE + + + + 4.0.0 + + liveness-example + 1.0-SNAPSHOT + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java new file mode 100644 index 0000000000..2cfa242965 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.liveness; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java new file mode 100644 index 0000000000..715c4cb178 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/java/com/baeldung/liveness/health/CustomHealthIndicator.java @@ -0,0 +1,27 @@ +package com.baeldung.liveness.health; + +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +@Component +public class CustomHealthIndicator implements HealthIndicator { + + private boolean isHealthy = true; + + public CustomHealthIndicator() { + ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor(); + scheduled.schedule(() -> { + isHealthy = false; + }, 30, TimeUnit.SECONDS); + } + + @Override + public Health health() { + return isHealthy ? Health.up().build() : Health.down().build(); + } +} diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties new file mode 100644 index 0000000000..a3ac65cee5 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/application.properties @@ -0,0 +1 @@ +server.port=8080 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/main/resources/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..60b4a28aa6 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/liveness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.liveness.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml b/spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml new file mode 100644 index 0000000000..9fd3fd5674 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/object-configurations/liveness-example-k8s-template.yaml @@ -0,0 +1,54 @@ +apiVersion: v1 +kind: Service +metadata: + name: liveness-example +spec: + selector: + app: liveness-example + ports: + - port: 8080 + +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: liveness-example +spec: + selector: + matchLabels: + app: liveness-example + replicas: 1 + strategy: + rollingUpdate: + maxUnavailable: 0 + template: + metadata: + labels: + app: liveness-example + spec: + containers: + - name: liveness-example + image: dbdock/liveness-example:1.0.0 + imagePullPolicy: IfNotPresent + resources: + requests: + memory: 400Mi + cpu: 400m + ports: + - containerPort: 8080 + readinessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 10 + timeoutSeconds: 2 + periodSeconds: 3 + failureThreshold: 1 + livenessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 20 + timeoutSeconds: 2 + periodSeconds: 8 + failureThreshold: 1 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml b/spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml new file mode 100644 index 0000000000..010c468107 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/object-configurations/readiness-example-k8s-template.yaml @@ -0,0 +1,54 @@ +apiVersion: v1 +kind: Service +metadata: + name: readiness-example +spec: + selector: + app: readiness-example + ports: + - port: 8080 + +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: readiness-example +spec: + selector: + matchLabels: + app: readiness-example + replicas: 1 + strategy: + rollingUpdate: + maxUnavailable: 0 + template: + metadata: + labels: + app: readiness-example + spec: + containers: + - name: readiness-example + image: dbdock/readiness-example:1.0.0 + imagePullPolicy: IfNotPresent + resources: + requests: + memory: 400Mi + cpu: 400m + ports: + - containerPort: 8080 + readinessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 40 + timeoutSeconds: 2 + periodSeconds: 3 + failureThreshold: 5 + livenessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 100 + timeoutSeconds: 2 + periodSeconds: 8 + failureThreshold: 1 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/pom.xml b/spring-cloud/spring-cloud-kubernetes/pom.xml index 984b3811dd..de0718633e 100644 --- a/spring-cloud/spring-cloud-kubernetes/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/pom.xml @@ -11,6 +11,8 @@ demo-frontend demo-backend + liveness-example + readiness-example diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile b/spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile new file mode 100644 index 0000000000..0fc0a9bd64 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/Dockerfile @@ -0,0 +1,11 @@ +FROM openjdk:8-jdk-alpine + +# Create app directory +RUN mkdir -p /usr/opt/service + +# Copy app +COPY target/*.jar /usr/opt/service/service.jar + +EXPOSE 8080 + +ENTRYPOINT exec java -jar /usr/opt/service/service.jar \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml new file mode 100644 index 0000000000..fa85120d21 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/pom.xml @@ -0,0 +1,49 @@ + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.17.RELEASE + + + 4.0.0 + + readiness-example + 1.0-SNAPSHOT + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java new file mode 100644 index 0000000000..11ffe577c3 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.readiness; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java new file mode 100644 index 0000000000..d37a1905f6 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/java/com/baeldung/readiness/health/CustomHealthIndicator.java @@ -0,0 +1,27 @@ +package com.baeldung.readiness.health; + +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.stereotype.Component; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +@Component +public class CustomHealthIndicator implements HealthIndicator { + + private boolean isHealthy = false; + + public CustomHealthIndicator() { + ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor(); + scheduled.schedule(() -> { + isHealthy = true; + }, 40, TimeUnit.SECONDS); + } + + @Override + public Health health() { + return isHealthy ? Health.up().build() : Health.down().build(); + } +} diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties new file mode 100644 index 0000000000..a3ac65cee5 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/application.properties @@ -0,0 +1 @@ +server.port=8080 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/main/resources/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..18458182c7 --- /dev/null +++ b/spring-cloud/spring-cloud-kubernetes/readiness-example/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import com.baeldung.readiness.Application; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void contextLoads() { + } + +} From 7ddcb76c093d93394af403bd6ccf29a5906300a9 Mon Sep 17 00:00:00 2001 From: j-bennett Date: Mon, 10 Dec 2018 18:27:48 -0500 Subject: [PATCH 24/76] Persist a JSON object using Hibernate Issue: BAEL-2353 --- persistence-modules/hibernate5/pom.xml | 6 + .../hibernate/persistjson/Customer.java | 80 +++++++++++++ .../persistjson/HashMapConverter.java | 47 ++++++++ .../persistjson/PersistJSONUnitTest.java | 111 ++++++++++++++++++ .../hibernate-persistjson.properties | 7 ++ 5 files changed, 251 insertions(+) create mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java create mode 100644 persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java create mode 100644 persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java create mode 100644 persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 363e2153b6..7e9a0ddb29 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -51,6 +51,11 @@ hibernate-testing 5.2.2.Final + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + @@ -69,6 +74,7 @@ 2.2.3 1.4.196 3.8.0 + 2.8.11.3 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java new file mode 100644 index 0000000000..6bd1c24869 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/Customer.java @@ -0,0 +1,80 @@ +package com.baeldung.hibernate.persistjson; + +import java.io.IOException; +import java.util.Map; + +import javax.persistence.Convert; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Entity +@Table(name = "Customers") +public class Customer { + + @Id + private int id; + + private String firstName; + + private String lastName; + + private String customerAttributeJSON; + + @Convert(converter = HashMapConverter.class) + private Map customerAttributes; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCustomerAttributeJSON() { + return customerAttributeJSON; + } + + public void setCustomerAttributeJSON(String customerAttributeJSON) { + this.customerAttributeJSON = customerAttributeJSON; + } + + public Map getCustomerAttributes() { + return customerAttributes; + } + + public void setCustomerAttributes(Map customerAttributes) { + this.customerAttributes = customerAttributes; + } + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public void serializeCustomerAttributes() throws JsonProcessingException { + this.customerAttributeJSON = objectMapper.writeValueAsString(customerAttributes); + } + + public void deserializeCustomerAttributes() throws IOException { + this.customerAttributes = objectMapper.readValue(customerAttributeJSON, Map.class); + } + +} diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java new file mode 100644 index 0000000000..b1c2d50480 --- /dev/null +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/persistjson/HashMapConverter.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.persistjson; + +import java.io.IOException; +import java.util.Map; + +import javax.persistence.AttributeConverter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.hibernate.interceptors.CustomInterceptor; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HashMapConverter implements AttributeConverter, String> { + + private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class); + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public String convertToDatabaseColumn(Map customerInfo) { + + String customerInfoJson = null; + try { + customerInfoJson = objectMapper.writeValueAsString(customerInfo); + } catch (final JsonProcessingException e) { + logger.error("JSON writing error", e); + } + + return customerInfoJson; + } + + @Override + public Map convertToEntityAttribute(String customerInfoJSON) { + + Map customerInfo = null; + try { + customerInfo = objectMapper.readValue(customerInfoJSON, Map.class); + } catch (final IOException e) { + logger.error("JSON reading error", e); + } + + return customerInfo; + } + +} diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java new file mode 100644 index 0000000000..ecbb073e89 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/persistjson/PersistJSONUnitTest.java @@ -0,0 +1,111 @@ +package com.baeldung.hibernate.persistjson; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class PersistJSONUnitTest { + + private Session session; + + @Before + public void init() { + try { + Configuration configuration = new Configuration(); + + Properties properties = new Properties(); + properties.load(Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream("hibernate-persistjson.properties")); + + configuration.setProperties(properties); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) + .build(); + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Customer.class); + + SessionFactory factory = metadataSources.buildMetadata() + .buildSessionFactory(); + + session = factory.openSession(); + } catch (HibernateException | IOException e) { + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); + } + } + + @After + public void close() { + if (session != null) + session.close(); + } + + @Test + public void givenCustomer_whenCallingSerializeCustomerAttributes_thenAttributesAreConverted() throws IOException { + + Customer customer = new Customer(); + customer.setFirstName("first name"); + customer.setLastName("last name"); + + Map attributes = new HashMap<>(); + attributes.put("address", "123 Main Street"); + attributes.put("zipcode", 12345); + + customer.setCustomerAttributes(attributes); + + customer.serializeCustomerAttributes(); + + String serialized = customer.getCustomerAttributeJSON(); + + customer.setCustomerAttributeJSON(serialized); + customer.deserializeCustomerAttributes(); + + Map deserialized = customer.getCustomerAttributes(); + + assertEquals("123 Main Street", deserialized.get("address")); + } + + @Test + public void givenCustomer_whenSaving_thenAttributesAreConverted() { + + Customer customer = new Customer(); + customer.setFirstName("first name"); + customer.setLastName("last name"); + + Map attributes = new HashMap<>(); + attributes.put("address", "123 Main Street"); + attributes.put("zipcode", 12345); + + customer.setCustomerAttributes(attributes); + + session.beginTransaction(); + + int id = (int) session.save(customer); + + session.flush(); + session.clear(); + + Customer result = session.createNativeQuery("select * from Customers where Customers.id = :id", Customer.class) + .setParameter("id", id) + .getSingleResult(); + + assertEquals(2, result.getCustomerAttributes() + .size()); + } + +} diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties new file mode 100644 index 0000000000..2cf8ac5b63 --- /dev/null +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-persistjson.properties @@ -0,0 +1,7 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.dialect=org.hibernate.dialect.H2Dialect + +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file From 3e685aa12d47f428a3dcb11bb6073d297078dd5c Mon Sep 17 00:00:00 2001 From: mprevisic Date: Tue, 11 Dec 2018 01:30:10 +0100 Subject: [PATCH 25/76] BAEL-2351 programmatically restart spring boot application --- spring-boot-ops/pom.xml | 7 + spring-boot-ops/pom.xml~ | 164 ++++++++++++++++++ .../com/baeldung/restart/Application.java | 30 ++++ .../baeldung/restart/RestartController.java | 23 +++ .../com/baeldung/restart/RestartService.java | 17 ++ .../src/main/resources/application.properties | 3 +- .../RestartApplicationIntegrationTest.java | 34 ++++ .../src/test/resources/application.properties | 4 +- 8 files changed, 280 insertions(+), 2 deletions(-) create mode 100644 spring-boot-ops/pom.xml~ create mode 100644 spring-boot-ops/src/main/java/com/baeldung/restart/Application.java create mode 100644 spring-boot-ops/src/main/java/com/baeldung/restart/RestartController.java create mode 100644 spring-boot-ops/src/main/java/com/baeldung/restart/RestartService.java create mode 100644 spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index 57779c3f8e..9717a352d3 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -86,6 +86,12 @@ ${jquery.version} + + org.springframework.cloud + spring-cloud-context + ${springcloud.version} + + @@ -153,6 +159,7 @@ 2.2 18.0 3.1.7 + 2.0.2.RELEASE diff --git a/spring-boot-ops/pom.xml~ b/spring-boot-ops/pom.xml~ new file mode 100644 index 0000000000..2c3b650c30 --- /dev/null +++ b/spring-boot-ops/pom.xml~ @@ -0,0 +1,164 @@ + + + 4.0.0 + + spring-boot-ops + war + spring-boot-ops + Demo project for Spring Boot + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-thymeleaf + provided + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-mail + + + + org.springframework.boot + spring-boot-starter-actuator + + + + com.h2database + h2 + runtime + + + + javax.persistence + javax.persistence-api + ${jpa.version} + + + + com.google.guava + guava + ${guava.version} + + + + org.subethamail + subethasmtp + ${subethasmtp.version} + test + + + + org.webjars + bootstrap + ${bootstrap.version} + + + + org.webjars + jquery + ${jquery.version} + + + + org.springframework.cloud + spring-cloud-context + ${springcloud.version} + + + + + + ${project.artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.baeldung.webjar.WebjarsdemoApplication + + + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + + + + + org.baeldung.boot.Application + 3.1.1 + 3.3.7-1 + 2.2 + 18.0 + 3.1.7 + + + diff --git a/spring-boot-ops/src/main/java/com/baeldung/restart/Application.java b/spring-boot-ops/src/main/java/com/baeldung/restart/Application.java new file mode 100644 index 0000000000..a6605a0baa --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/restart/Application.java @@ -0,0 +1,30 @@ +package com.baeldung.restart; + +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.ConfigurableApplicationContext; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + private static ConfigurableApplicationContext context; + + public static void main(String[] args) { + context = SpringApplication.run(Application.class, args); + } + + public static void restart() { + ApplicationArguments args = context.getBean(ApplicationArguments.class); + + Thread thread = new Thread(() -> { + context.close(); + context = SpringApplication.run(Application.class, args.getSourceArgs()); + }); + + thread.setDaemon(false); + thread.start(); + } + +} \ No newline at end of file diff --git a/spring-boot-ops/src/main/java/com/baeldung/restart/RestartController.java b/spring-boot-ops/src/main/java/com/baeldung/restart/RestartController.java new file mode 100644 index 0000000000..68a8dc7073 --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/restart/RestartController.java @@ -0,0 +1,23 @@ +package com.baeldung.restart; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RestartController { + + @Autowired + private RestartService restartService; + + @PostMapping("/restart") + public void restart() { + Application.restart(); + } + + @PostMapping("/restartApp") + public void restartUsingActuator() { + restartService.restartApp(); + } + +} diff --git a/spring-boot-ops/src/main/java/com/baeldung/restart/RestartService.java b/spring-boot-ops/src/main/java/com/baeldung/restart/RestartService.java new file mode 100644 index 0000000000..9883ec653b --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/restart/RestartService.java @@ -0,0 +1,17 @@ +package com.baeldung.restart; + +import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.context.restart.RestartEndpoint; + +@Service +public class RestartService { + + @Autowired + private RestartEndpoint restartEndpoint; + + public void restartApp() { + restartEndpoint.restart(); + } + +} \ No newline at end of file diff --git a/spring-boot-ops/src/main/resources/application.properties b/spring-boot-ops/src/main/resources/application.properties index a86bd3052e..644a3edabc 100644 --- a/spring-boot-ops/src/main/resources/application.properties +++ b/spring-boot-ops/src/main/resources/application.properties @@ -1,3 +1,4 @@ management.endpoints.web.exposure.include=* management.metrics.enable.root=true -management.metrics.enable.jvm=true \ No newline at end of file +management.metrics.enable.jvm=true +management.endpoint.restart.enabled=true \ No newline at end of file diff --git a/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java new file mode 100644 index 0000000000..1bec3c6a90 --- /dev/null +++ b/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.restart; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; + +public class RestartApplicationIntegrationTest { + + private TestRestTemplate template = new TestRestTemplate(); + + @Test + public void givenBootApp_whenRestart_thenOk() throws Exception { + Application.main(new String[0]); + + ResponseEntity response = template.exchange("http://localhost:8080/restart", + HttpMethod.POST, null, Object.class); + + assertEquals(200, response.getStatusCode().value()); + } + + @Test + public void givenBootApp_whenRestartUsingActuator_thenOk() throws Exception { + Application.main(new String[] { "--server.port=8090" }); + + ResponseEntity response = template.exchange("http://localhost:8090/restartApp", + HttpMethod.POST, null, Object.class); + + assertEquals(200, response.getStatusCode().value()); + } + +} diff --git a/spring-boot-ops/src/test/resources/application.properties b/spring-boot-ops/src/test/resources/application.properties index 2095a82a14..0adf2998d7 100644 --- a/spring-boot-ops/src/test/resources/application.properties +++ b/spring-boot-ops/src/test/resources/application.properties @@ -4,4 +4,6 @@ spring.mail.properties.mail.smtp.auth=false management.endpoints.web.exposure.include=* management.endpoint.shutdown.enabled=true -endpoints.shutdown.enabled=true \ No newline at end of file +endpoints.shutdown.enabled=true + +management.endpoint.restart.enabled=true \ No newline at end of file From 5afdce78ead6d1854ef6d787cb70b10f9527a6b5 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Tue, 11 Dec 2018 09:52:10 +0200 Subject: [PATCH 26/76] quick compilation fix --- .../com/baeldung/jpa/stringcast/QueryExecutor.java | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java index 6f1e2ee5ca..2cb5679d4d 100644 --- a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/stringcast/QueryExecutor.java @@ -1,13 +1,12 @@ package com.baeldung.jpa.stringcast; -import com.sun.istack.internal.Nullable; - -import javax.persistence.EntityManager; -import javax.persistence.Query; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; +import javax.persistence.EntityManager; +import javax.persistence.Query; + public class QueryExecutor { public static List executeNativeQueryNoCastCheck(String statement, EntityManager em) { @@ -24,10 +23,7 @@ public class QueryExecutor { } if (results.get(0) instanceof String) { - return ((List) results) - .stream() - .map(s -> new String[] { s }) - .collect(Collectors.toList()); + return ((List) results).stream().map(s -> new String[] { s }).collect(Collectors.toList()); } else { return (List) results; } From 98d74af44ab4a338e6ea6dde074781080bab403f Mon Sep 17 00:00:00 2001 From: Ganesh Pagade Date: Tue, 11 Dec 2018 22:47:56 +0530 Subject: [PATCH 27/76] added shebang file --- core-java-11/src/main/java/com/baeldung/add | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100755 core-java-11/src/main/java/com/baeldung/add diff --git a/core-java-11/src/main/java/com/baeldung/add b/core-java-11/src/main/java/com/baeldung/add new file mode 100755 index 0000000000..539c1a43d4 --- /dev/null +++ b/core-java-11/src/main/java/com/baeldung/add @@ -0,0 +1,12 @@ +#!/usr/local/bin/java --source 11 + +import java.util.Arrays; + +public class Addition +{ + public static void main(String[] args) { + System.out.println(Arrays.stream(args) + .mapToInt(Integer::parseInt) + .sum()); + } +} \ No newline at end of file From cfab18ae96ef8342001466d541e4c04da5c952e2 Mon Sep 17 00:00:00 2001 From: Loredana Date: Tue, 11 Dec 2018 22:46:08 +0200 Subject: [PATCH 28/76] add code for jgrapht image gen --- algorithms-miscellaneous-2/pom.xml | 6 +++ .../jgrapht/GraphImageGenerationUnitTest.java | 47 ++++++++++++++++++ .../src/test/resources/graph.png | Bin 0 -> 9365 bytes 3 files changed, 53 insertions(+) create mode 100644 algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java create mode 100644 algorithms-miscellaneous-2/src/test/resources/graph.png diff --git a/algorithms-miscellaneous-2/pom.xml b/algorithms-miscellaneous-2/pom.xml index 25472d4888..5461f4ebe1 100644 --- a/algorithms-miscellaneous-2/pom.xml +++ b/algorithms-miscellaneous-2/pom.xml @@ -33,6 +33,11 @@ jgrapht-core ${org.jgrapht.core.version} + + org.jgrapht + jgrapht-ext + ${org.jgrapht.ext.version} + pl.allegro.finance tradukisto @@ -83,6 +88,7 @@ 3.6.1 1.0.1 1.0.1 + 1.0.1 3.9.0 1.11 diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java new file mode 100644 index 0000000000..3b841d574a --- /dev/null +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.jgrapht; + +import static org.junit.Assert.assertTrue; +import java.awt.Color; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import javax.imageio.ImageIO; +import org.jgrapht.ext.JGraphXAdapter; +import org.jgrapht.graph.DefaultDirectedGraph; +import org.jgrapht.graph.DefaultEdge; +import org.junit.Before; +import org.junit.Test; +import com.mxgraph.layout.mxCircleLayout; +import com.mxgraph.layout.mxIGraphLayout; +import com.mxgraph.util.mxCellRenderer; + +public class GraphImageGenerationUnitTest { + static DefaultDirectedGraph g; + + @Before + public void createGraph() throws IOException { + File imgFile = new File("src/test/resources/graph.png"); + imgFile.createNewFile(); + g = new DefaultDirectedGraph(DefaultEdge.class); + String x1 = "x1"; + String x2 = "x2"; + String x3 = "x3"; + g.addVertex(x1); + g.addVertex(x2); + g.addVertex(x3); + g.addEdge(x1, x2); + g.addEdge(x2, x3); + g.addEdge(x3, x1); + } + + @Test + public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException { + JGraphXAdapter graphAdapter = new JGraphXAdapter(g); + mxIGraphLayout layout = new mxCircleLayout(graphAdapter); + layout.execute(graphAdapter.getDefaultParent()); + File imgFile = new File("src/test/resources/graph.png"); + BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null); + ImageIO.write(image, "PNG", imgFile); + assertTrue(imgFile.exists()); + } +} \ No newline at end of file diff --git a/algorithms-miscellaneous-2/src/test/resources/graph.png b/algorithms-miscellaneous-2/src/test/resources/graph.png new file mode 100644 index 0000000000000000000000000000000000000000..56995b8dd9be23e173c365a616ac64123004d81c GIT binary patch literal 9365 zcmZ{Kc{r5O`}bHIJITI`EfTVhEyivrvP8BRNky_#WQGwU${*zVDHJ--XCJ z_F;y3AAP^?@A|!eyspc|bLN~g_jd04bAQhB#`q4Lj+&Di1On0N>uH;UKqO(nuLYPC z7-^|&zX<{f-PhOFF!P(*`fO!u8WO$X*=#t3urV8&W& zI`GI4a;SSix61zk~}r(F&{8?Ysj;OQA6dm4#!|q9XLV zLAam6bo0~1o*-J(S#9T!215I%ez6*EY^)4-v_fOeZtp->IRi1_+`MDu%fQ`scQ?ZT z*SmYKV@6a5!@?d_nyaKV0U4tdvt#1O9v`l+>jiI6F|asMEk|tUX1b zf3Rn_SBg@NQN?bSgUihi=$|AIiVwN;om@7i^ONs6CNM=$dDF!RTeciiN<+bm`qwYN z8Ct2`35?e{RIdn*8CbxXY$u*LhJ-YpJ()+vd-!po+B)5d149P`C%&hL13Q7=W{#BV zTxS!weEAl$(p!Ejey}TDKb+V%KT!66`e(3if8$^S@;oiK(&-WdSlkHwtKNTYMy z-KqValsYudspH3hZ0O)EHXv-MZNpJPY4`DCUtLo<1^dXv#3k3K25eH*vE)5ZBaXl|I<%bRkiluCB+z1$o5uY0d1h zpbGyE)Ln7Xn%DjlVe$-HG;h94x4J*m&)Isu6T7EP`bosh!eS@aMKNv}A5S^>9neQDCa<&zQY<iQ641&vFF*%_Au!y05 zaMzT7QLqBJ{DE$5N`!eZwHm=fz8R?JlKieFLQDbbin0of+u0kvzFpOQJZQ~4m~d|( zT79>uQMXq@ya8{*iXeeTrjKrbj%^;vHWB$=fGl3xc2IySjTFo;>;@OyPBI{b%w@Ls4n= zgKVs>DvjihLu^W;MiG=Z@c2GyqHyL`kWoU0XZa1@y)$jkcAkcC53i27QDRK8nu5(v z(Nxj5P5Bv5XpH030`eAVkJGHP%iPIY!QoNCHe@oI#<7?y z?)lA{6}AKAtzHG;fuN|Ot<~R|^v`g-TPd906IxW~tTu~oySLo9M=LOSRp}*1mG3z! ze0bc{OskHH$`Y*+(gThbrZGG7eM$eDb!b|FF zq)#dg^9vCSjYowH3E>HWwX)MEhw}vAlRInUl_|6A4SSKb-GyRSM;=z~mXnj-CS)er z^UwNyP8Q9`%or|YAXf5CqUD_xN>Eo`cq~N?uB8>7f`KU7@y+JJeaIXdi)Vf?a?1fV z6yzLUMGPRCnzYyGs(iGpH>GhobvdA(f_we2g-5Mv8g@C~pSHu5%zipa;9VVWy#Dum zwwQKR_`?%O(dp`WIcAwn6x#TRn9ntG>vzYMv&82UyjE4~>^TzBm7XW`J6Ss5*L)S2 z`E70f>M&ECKtFMa zJ+zDYx+K`0117^=YuXsCDZiYgx3Op6a`b0R?qRXTZFoJu5X;7B3%uD{4R3R=^c7{(Hyz`*~i)l47|>=gzC z!ZIPrK}d24$$vh^fnlTI#ITi$C7Xdnq=Rvw%m;1PMwRwsd<`fMn9@7_&|iP9t6(+vOv$-TPG zg-jUjZBR_GgP2(iAQVJBVon~Z`baT#SI~FLrg(u4T1GYr&7n{8&%AOnB`1PRs2~zI zl#V*$hj%}2PU70iS$?$&;3D$es*O6!@Y%kL-FH)-fy#Ra*0NM{ zzxD}Fd47#QpPqpVM_}|SAMBbFknj|DP&pNpt&ipTS03j%ruxmS;%0pfWZTdz;WyKS zWeNmD=T(Sbj9$vQA&Y?URtyBeJ0Vd^f&%=NVbSY8eG(}Fpz_wYuKaSvLt4Txp&+v^d`qRcjT!ynC^jD7cuy8>3{rPdNh$Aq47Dv9QYQkky z003mobLCp}bioti_BU=KX5xJoUnX|JGAS2-mB&dNOOJ!8ee{>irzBcni@ zG*Se12;sF%ZQ0c9%b(gjUYWisv*eLFp>CA@6-iO!0a&-EQyK zudZ<<>25e4ly5Xm*kL62fC z-=Y@RE);>N5|xi3oEC5ViJ)u#gVjB|TvPC)ldE>2IW;RVQVO)a;0kU!ptIuc_4m&s zTWqbKsyo{2pI}`4wRPD{?hjPsFn@N;d706il{1vFnVC(ZlaM%ob7MD#$6Gsvq*` zr{splHUw=CxZ#fuwA|m*c@RGGHoGIcC&v;vpR&@boeI3ibp1|cp~9}LQHcf9fxX|K z<|~8H{n&-C36QR*L(jSuk4t*5e*%FSR&mhtrk7i%c`hDth3-xVOs}XwK^}^!Jh#5u zRoqiUF7qI1oPA!B{RW2foOqvCUyM=6{s`OZ6gR^Zy?_X0gRpeYUQXWQA3LI+4*8w< zQSUWOPy;^4(lrF@vYpWu;q`u=xj3FFgAOQsWyWj^A+Wtyr_m;_A<)^)K!t=2uR!O!LYb(87upCeVOPP3@ch?8H}I+lZdZ1k!ZT zukW<#?lndWE3I|F0g*m;-mXwNqy%lL)Bg^5bWi~**M~n^p>PFE%{K+Y8lZW{#Dw}7Fl^(zoLgY=)2WOBtzRu(&a+`+MfzR?J72;DnaOA@hZVNJDDG8zMZ z%02igLa(^JNnT30-TbWXOBskkY@{BOy`so<6T&AKJjlq`DH)F;#|MI%#K^mLqy7kr z9%G=y;0#8=PRS%pYNOvriO($SRVK%D52$Hh`EC464poYq*nF(4KvgXPzH3kJxAhrt zya4J_)Kb>qZs)5CTN00OJ*7Zt)WMANGlpI2Hr)~KXk*xA@nb6V?Yxi<&pWpA&Gf&7 zCU*7axhw}*BW?kOjl$pOWr$z6a1us)%Yv*4TV~?Syf>LAyi2d2WTPmp8jhuS#eY<` zWT?r@qK42I@usAWict#OMG2_}6+Cg`)Szv%_v~h3Md+B=-XE1*mrl}Fm0CUzw!dN- zAeybUbe+QPr=}%@|CmAB!Qo}}QZ*1v3$1cg$Y+F2HeenIoU)`4iOI7HxK_$p9hCl} zt#6mB9p2xVdMxPyBV`Zn8c_~ejxub40I5@bT<*oY-4_K+sab*zm>B$}Qyps;to1K6 zQ}noFXh?6_47A0Pj}arrf=YRBb>FKA{>nZLF@+kszKnF@laj{^tm15TU~*mj$+TW6 zqY}rlz!n1a-$Gu=%hygShCjP8E^(v~A8_V*9`x3I>o$fb$B#$Os13k? zbH=$}J8TKl+=i?w$JnF8QJ!NTYuKT(nOCL&h+*COQ7I4yB&u|sJC1UumXELaa{iz+ zc&+LM80pK}X4=AzUNf%}4Wt_|qnnM{8>X=;(y7ixKi1g$F1_4p$Z}H2nCKZbV;&$Y zQ@7VkuTb`vvQNRIZbt*P2hhVegPwC0m*4XkTOh?jz$qO|9?3eQJE}eEX|{ZDP85A- zG=#UR>5pFPLc+9@6yP)I5MwUv;LldBA37fl4Ei(V(JgI{6^6$j6jyVZlR%1^Xb>DH z4GihOUt~0U6R?9%A3viRfwj~HrAra`vH%z4QRCKZu2>x2b<`Fb&%BP7!K$2p!(Auq zTMEaF1v@yn8&p47H75%zon%w$oS(ZHJ%z^HH=dSvnDBjqZUH7UbG)k>B!_v?tey|1 zUD9~ubTIfQf~)*pw3@DK6Wk4`MLE}~-pFw+PPVB_+*zH`gt5WmDEje6U9KADX!`+K zIm3DXo0vp_P6kL3L&aOg<9Vp!n<-FmJ7BiJFRwFuOoJFINFd#>m`ec+!|p;Jykh+e z6viq_rNoTWyD?Npoch5uLJ7X|pCs$_vK4L@0wroR>5Dma#${t;F&^6xW*!Z7cHT12 z_2u9$rn{P4wcLl`jDTd#>r4hYp;$dP0>m>1^7an<%C?#p0UNtxKc|LGYrhJ& zM6&3Z`1YViD3Qx-{t2~L^Z}Rwn9CjeP*C9Rh6f&uT$a3|mErl}iqTjH{|F^E>gavP-d=%#h>m9OMf(>sK80ONHU*s=lEm_RXBppqCS*GL956GmEyx?bSX8TwD ziRGdm`(3z^rMRioE}@>FZNl#l$M2oID@Ayq^>~1~K`tAy`kK*znWor6)U?)o*{Y|BHUr& z3A>-os-5rti?s67fnP7!KGkAa`y|AvxhYSN1}}ITPUV+KWXWrPd?{J$d!MI& zXG%~}-oz_UBCoow+~@i)J@deTgF=Ot^mms1GOjS`Ql7p0&QC@~TAxipm}>5j*u8q* zfQCrBT+nC#1E8n;JFd0~GjboK-_RBEof>awz%J*z@1LV?#HF}|*jzH>>NqfIYHbRF z7#j3f_wM33K8*wdR%i(YBx(~$uWN3%9tT|Wx5(BcF(=mf^ucN@X`o4;JvsEFDg*Vz zW|Uo6iMvkRKG0g-kkr%i9V2C@Y&hvULHKv=;+a3qBoc-jo&~q6cfwBBa4gCssGt|p zNwO}X3> zwf&~)LHa{Tea-IM)hhlXkDz3E2E$ZySSBV%_i)S3$SCXpNNtUJcD7u+uUSGx&<_@f zxY%Cq#!8*1HL8S;1hXlX@Ep(szVDcbVXIMYyL|t{jX=J`ab4cNKX&dYAOH>)54YSz zzM9-k@g@S<{-w>cl1OrhD1;J*kKoo8j{CHfh!Bd@l407i@^&%CNiqKT$7YyTrt~XA z{g;De=6`AMC@|nXG>?rPDlDjM-J^t7rz`<7Ln7wELK$Xx6}Q6nhP%!6n)feT!O-B3 zOOpnUabeFV{Ik(;##uV@(<5_16vs>G&iu4MceQ*TrBo_UlN9zBeA|m~ekC6uG-$lr zYtG*bwu8x}_y0pl6nXxKl4x{v`|^!X|k%v9C z&KMb03*tyjR$)UYt&AYvb2I>KM{9)!6piOUqaq`sv|R)^_3Q=3n%`jZlm1pZ%&c6)luVDaE+L*6p2t-%iAg?4#swBX*qe zY6D7wLP*Bh#_LdAU%Ev-^rRdJMwiBG@;tq^zEgi#Sx@ZXe{17wW}ZmO8;iYZ{Jz#$ z-nuKdQNR!{JHz;XvV8kRVv2x&fU7;Mi1=V37gIHTqw%U(uHM`!c;6XH(!T{(Lus|k z098#?c4z*orMvd56!v;2Mv8F;ZfavOE4yg3t!6x)(OaA|k;g(=w;ZyUYd0dr_@I7D zq4G<9t#Q74br3NlYmPB4^6=>>bx5f`9;i$OC8Lt2?Dnd}CNz{tr)Th(d2Br#BS&3w zVnpX>7RHn=&-B^tQG!`G20f0|WCj}xHYo)n&zj&#lnm1{U?90G4+7;XGk_lA%;xJ& zROjf@a1>DPNjMG2qr>S9=Y7CmifmRoAE>&O;(*iJ5Wk`1_bbTPJ%&uf!H3|fmpxgT zQvyO}lOFP9!PLNvPAM07vD%qp3n;~U3Rr=kdJPfdioYvPb04poaA9NJ)VC3O0NfZF zHwd(1C?JImade&0=mKzM8Mi1{FZ0kQrV%YVpa_5n08soiG6}_~Hvwzdi$`e}%v#_z zL{pt@1nA4-Ra9Ud3mPLw?nNYR(h4489wI?zKa9bTLt7vI_{F4jyC5*I>Slqa zBzB8a@ewu_t;pS-+6Vw>evdT4b%Px~JBGIV$W8bFElBG_ zd7y?n^5L9&YK^R2k90;}>o%zb;<~ClE{kO4F`H*lD0ViUeGIeK2i)1^@itoR%N&U< z*&2`2>PALY0R%u*9PwWZU#xLPbU)KH&$|tv0%az=gIElJnBLOpsI8t$huohnYf?Jz z=(}{W#{gDyH{jvV(w1oJWvlHW(Fo-LW&lQZt?BKb@5XDG$BeCaZslW{EMM19spQjr z;#txE>7tXs3?rStAVrEJ?|Um0XzJr`d;?ku_Kw$>CIvm0^M`Ydao9b{F2H8?P`2V1 zgB2QdSIxp?0H7gPe7SW3*zcX3KQ)7fIcPn73+9|N<+j5E2OwD!MGAhN&8D2VK zrEm9c5FMZs$#~3bJze%eu>8aK&v}bl4R~;1zgNmG%Yy4w{KpU##m+Q<6fQtxnv~ld zsI1&6xPr+NAZCDeaZvCz2F->|A`bqg)6==c>axTLU@0an zeKIO`^=#?E4-)c1Q9us3;&CH@yuZkhQ(r{#g5XF7SnaOXID@TD9vx8wa6M^Yb2TwW zPj-xO4C%AJK!_ysi#ngBcjk>QtgQ}O2)7%MS3YO2SoH2^yMX58uj2{wH3=6u(;P>6 z@wH%f(``uMFFfeqgVe}iQ(e$}*R^%+i~WPOt@j~nt@RAR$b75Bx1&t?1wqCuc^ewz6F|#q7WO2Y7WA0d4Ck{n z9uFxS|7H6ykM0HEg}geACk$8bEp5a8^B5MRtJ~`vlJ~9x`yQGfSVJiS9C0SFatc1T z(Cq@6T2egWj|Fr?4_WXCS5(VEFT_?a(H2v+x{xbfPUR`rC+qNFSIP@@^Ipe~7Q1q3 zxc;|`*$zcx&_5+!0g1o|%2{_EI0t#x0mf?3IuwIewr>mNNG=c8PRi${)P2mvf@LzM zONG`*6gWP8KKJcIOw6?AhnTqe*M1k9U<)|^hVi_H?g2T|(edARznP<6J*S(niGBIi z;`%8g6_#m$JOz(Y4j6XIss@gq&%)x9r{Cfvk>usC;_(V2NyO#!3rR*UXb;K-!E}CH zJ`6aa9nJzdY|pVzjW2>%-G<$DuCe@{T53EMghZm{!r^61H%x#IQ@#)kA>nDNCIT6< zl%cFF=#{nZe>(+|qGN}))MLzr-+Z)ESBfWOs}(zqZnb<>#eto8M2``JD&lj4u_20` zn6Nb9s~Lb`!)Kew3DA)Tu zwh;iEllp}GUN&yeTIb~uB^Rs9As}|5-U}&)cd*M}E?r;dQ$=HFNr3*r zQEvTAJ)2wYOF=VSy<}oF@p)SLI%-ahhoWTkqIvSB1{Bib;jZt;uU4G?^YeDBuAPta zP7sj)`q51GS7@8y_Wnnrw*AVVQ9qT=X~t_kcozlvz{c7-L4#+t3Cn7~eE<%ivRrI)I_X7(+%(zEgpXBy@=wiB z8xmZy;sg|09j}B-mZ)p<)bO3zigp^QEr^3~;IC3rGPT!_(_ZF(wxe37iv&`kb?PJy z5Qv-vAq>EeolZ_Ew#iVZVyt&y%l-swyA$#zxH?bXqxiUad1+Mzxl^ZMk@2e#ozL|g z*v6|XI9vKm;57ht9TX+SX29;FJPRyQaG%u0MK`dI$zxpO)-ATM&*Y%!UC z*3|}9uR)|+DF5ED$kDfpF`P0X0*eZrH<3*=8AY>IBrHw%5Wk|p-la=eCXb$$_qjll z5aaaX)H}t7VMr_NAG%J1`T^_4C0=e2SJm&ES$~S9iE2pC?q-zMztu4= z?+D*he=+s6>L$agn_Y9zGgp0bG8y)9BuMhQ$9}!6pR7eH;s`;hTW?(f2FGQe|2DAc z)OtRPWq^gNw3XpzR@UnJc*Dl%(QZ^l4MUrGHL^0mgE|+uTd}7I6iBw7UfHutAq7E# z-A}HGXYg-3>`ZNqB--9U90%Quu>`U+4qSz0qRRY^ua28u^{>Y=p)tTc&4S>+mn~qV z7td%Dq+^3p3hEpQTx!yvcdBg#v}7T67)@eO4NaLB-?P0Ce@xS9*jd+rJotsT?Kqu-7OtdTNQ?Hj#kL2|l zZUXh0$3aLUPN)20ZTx<0j{mDExKJVv%NQ6I=r`ze%2ZErA^f#f!Kuiit&EbOL_*yE zz8QBQfPrXoh72A(y2E?&h$u;nl|Ky*Z1`W z!VzXd26$P7_G0I}KUouJJK`cEFuymQKknY)4!sb?3~K`1!N%R5C}~6tNtya(rH04s z-CzY?Oo5R`o&uMr&(}8Q`Ky-$&A(;ljtGstuXY2jx_~m%1z+LWPpiW-%iMNoi>{ch z>^cs#n>%T1MNavyj4=qHvaF>f4uh3i~lnpjrs3~|KG{93t41u4u!y16;7l6`HlvXU-3_` o`2kf$9aCeMtj6fOpa|k6k6vV*^qxsH2>8+0xuadIY5(f~0EG)fM*si- literal 0 HcmV?d00001 From 652a7a3f46d4cb0e2a197ff5bdb6ffb9c0e7d79e Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Tue, 11 Dec 2018 20:43:13 -0600 Subject: [PATCH 29/76] BAEL-2174 update README.md (#5901) * BAEL-2246: add link back to article * BAEL-2174: rename core-java-net module to core-java-networking * BAEL-2174: add link back to article --- core-java-networking/README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/core-java-networking/README.md b/core-java-networking/README.md index b7a142ea27..626ea794e6 100644 --- a/core-java-networking/README.md +++ b/core-java-networking/README.md @@ -1,3 +1,7 @@ ========= -## Core Java Net +## Core Java Networking + +### Relevant Articles + +- [Connecting Through Proxy Servers in Core Java](https://www.baeldung.com/java-connect-via-proxy-server) From 9c9e32aa7c55afcc69ba6ebcacce59eb8a54d050 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Wed, 12 Dec 2018 04:44:11 +0000 Subject: [PATCH 30/76] Guide to ShedLock with Spring Issue: BAEL-2360 --- spring-all/pom.xml | 12 ++++++++++++ .../shedlock/SchedulerConfiguration.java | 12 ++++++++++++ .../scheduling/shedlock/TaskScheduler.java | 15 +++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 spring-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java create mode 100644 spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java diff --git a/spring-all/pom.xml b/spring-all/pom.xml index 2dc4915bab..77c7e74e08 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -155,6 +155,18 @@ org.apache.logging.log4j log4j-core + + + + net.javacrumbs.shedlock + shedlock-spring + 2.1.0 + + + net.javacrumbs.shedlock + shedlock-provider-jdbc-template + 2.1.0 + diff --git a/spring-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java b/spring-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java new file mode 100644 index 0000000000..74ea39683d --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/scheduling/shedlock/SchedulerConfiguration.java @@ -0,0 +1,12 @@ +package com.baeldung.scheduling.shedlock; + +import org.springframework.context.annotation.Configuration; +import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; +import org.springframework.scheduling.annotation.EnableScheduling; + +@Configuration +@EnableScheduling +@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") +public class SchedulerConfiguration { + +} \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java b/spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java new file mode 100644 index 0000000000..b1b1ad921f --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/scheduling/shedlock/TaskScheduler.java @@ -0,0 +1,15 @@ +package com.baeldung.scheduling.shedlock; + +import net.javacrumbs.shedlock.core.SchedulerLock; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +class TaskScheduler { + + @Scheduled(cron = "*/15 * * * * *") + @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastForString = "PT5M", lockAtMostForString = "PT14M") + public void scheduledTask() { + System.out.println("Running ShedLock task"); + } +} \ No newline at end of file From 7e3e9db288d8d02a11b437b1cbf80a6df0248af3 Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Wed, 12 Dec 2018 08:17:25 +0100 Subject: [PATCH 31/76] BAEL-2351 cleanup --- spring-boot-ops/pom.xml~ | 164 --------------------------------------- 1 file changed, 164 deletions(-) delete mode 100644 spring-boot-ops/pom.xml~ diff --git a/spring-boot-ops/pom.xml~ b/spring-boot-ops/pom.xml~ deleted file mode 100644 index 2c3b650c30..0000000000 --- a/spring-boot-ops/pom.xml~ +++ /dev/null @@ -1,164 +0,0 @@ - - - 4.0.0 - - spring-boot-ops - war - spring-boot-ops - Demo project for Spring Boot - - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-thymeleaf - provided - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.springframework.boot - spring-boot-starter-mail - - - - org.springframework.boot - spring-boot-starter-actuator - - - - com.h2database - h2 - runtime - - - - javax.persistence - javax.persistence-api - ${jpa.version} - - - - com.google.guava - guava - ${guava.version} - - - - org.subethamail - subethasmtp - ${subethasmtp.version} - test - - - - org.webjars - bootstrap - ${bootstrap.version} - - - - org.webjars - jquery - ${jquery.version} - - - - org.springframework.cloud - spring-cloud-context - ${springcloud.version} - - - - - - ${project.artifactId} - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - com.baeldung.webjar.WebjarsdemoApplication - - - - - - - - - - autoconfiguration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/*IntegrationTest.java - **/*IntTest.java - - - **/AutoconfigurationTest.java - - - - - - - json - - - - - - - - - - - org.baeldung.boot.Application - 3.1.1 - 3.3.7-1 - 2.2 - 18.0 - 3.1.7 - - - From 743949afe69b1dfc995b387ff1c8ebd195733cd0 Mon Sep 17 00:00:00 2001 From: Kacper Date: Wed, 12 Dec 2018 11:15:04 +0100 Subject: [PATCH 32/76] testing with StepVerifier (#5673) * testing with StepVerifier * Test publisher --- spring-5-reactive/pom.xml | 2 +- .../stepverifier/PostExecutionUnitTest.java | 34 +++++++++++++ .../stepverifier/StepByStepUnitTest.java | 39 ++++++++++++++ .../TestingTestPublisherUnitTest.java | 51 +++++++++++++++++++ .../stepverifier/TimeBasedUnitTest.java | 22 ++++++++ 5 files changed, 147 insertions(+), 1 deletion(-) create mode 100644 spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java create mode 100644 spring-5-reactive/src/test/java/com/baeldung/stepverifier/StepByStepUnitTest.java create mode 100644 spring-5-reactive/src/test/java/com/baeldung/stepverifier/TestingTestPublisherUnitTest.java create mode 100644 spring-5-reactive/src/test/java/com/baeldung/stepverifier/TimeBasedUnitTest.java diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index ab64d1e2fa..63cc185afe 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -143,7 +143,7 @@ 1.0 1.0 4.1 - 3.1.6.RELEASE + 3.2.3.RELEASE diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java new file mode 100644 index 0000000000..17fea6b50b --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/PostExecutionUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.stepverifier; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +import java.time.Duration; + +public class PostExecutionUnitTest { + + Flux source = Flux.create(emitter -> { + emitter.next(1); + emitter.next(2); + emitter.next(3); + emitter.complete(); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + emitter.next(4); + }).filter(number -> number % 2 == 0); + + @Test + public void droppedElements() { + StepVerifier.create(source) + .expectNext(2) + .expectComplete() + .verifyThenAssertThat() + .hasDropped(4) + .tookLessThan(Duration.ofMillis(1050)); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/StepByStepUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/StepByStepUnitTest.java new file mode 100644 index 0000000000..c7196d6b6c --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/StepByStepUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.stepverifier; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +public class StepByStepUnitTest { + + Flux source = Flux.just("John", "Monica", "Mark", "Cloe", "Frank", "Casper", "Olivia", "Emily", "Cate") + .filter(name -> name.length() == 4) + .map(String::toUpperCase); + + @Test + public void shouldReturnForLettersUpperCaseStrings() { + StepVerifier + .create(source) + .expectNext("JOHN") + .expectNextMatches(name -> name.startsWith("MA")) + .expectNext("CLOE", "CATE") + .expectComplete() + .verify(); + } + + @Test + public void shouldThrowExceptionAfterFourElements() { + Flux error = source.concatWith( + Mono.error(new IllegalArgumentException("Our message")) + ); + + StepVerifier + .create(error) + .expectNextCount(4) + .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && + throwable.getMessage().equals("Our message") + ).verify(); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TestingTestPublisherUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TestingTestPublisherUnitTest.java new file mode 100644 index 0000000000..fb65e2d315 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TestingTestPublisherUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.stepverifier; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; +import reactor.test.publisher.TestPublisher; + +public class TestingTestPublisherUnitTest { + + @Test + public void testPublisher() { + TestPublisher + .create() + .next("First", "Second", "Third") + .error(new RuntimeException("Message")); + } + + @Test + public void nonCompliant() { + TestPublisher + .createNoncompliant(TestPublisher.Violation.ALLOW_NULL) + .emit("1", "2", null, "3"); + } + + @Test + public void testPublisherInAction() { + final TestPublisher testPublisher = TestPublisher.create(); + + UppercaseConverter uppercaseConverter = new UppercaseConverter(testPublisher.flux()); + + StepVerifier.create(uppercaseConverter.getUpperCase()) + .then(() -> testPublisher.emit("aA", "bb", "ccc")) + .expectNext("AA", "BB", "CCC") + .verifyComplete(); + } + +} + +class UppercaseConverter { + private final Flux source; + + UppercaseConverter(Flux source) { + this.source = source; + } + + Flux getUpperCase() { + return source + .map(String::toUpperCase); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TimeBasedUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TimeBasedUnitTest.java new file mode 100644 index 0000000000..54e5e7882a --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/stepverifier/TimeBasedUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.stepverifier; + +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +import java.time.Duration; + +public class TimeBasedUnitTest { + + @Test + public void simpleExample() { + StepVerifier + .withVirtualTime(() -> Flux.interval(Duration.ofSeconds(1)).take(2)) + .expectSubscription() + .expectNoEvent(Duration.ofSeconds(1)) + .expectNext(0L) + .thenAwait(Duration.ofSeconds(1)) + .expectNext(1L) + .verifyComplete(); + } +} From 99dd82d2ff8f307fe4cf2bd7ae6b3c7c78b25e52 Mon Sep 17 00:00:00 2001 From: geroza Date: Tue, 11 Dec 2018 12:17:29 -0200 Subject: [PATCH 33/76] Migrated modules to parent-boot-2 usign spring-boot 2.1: spring-mvc-forms-thymeleaf spring-rest spring-rest-angular spring-rest-query-language spring-rest-shell spring-rest-simple spring-rest-template spring-resttemplate spring-security-mvc-boot spring-security-openid spring-security-sso spring-security-thymeleaf --- spring-mvc-forms-thymeleaf/pom.xml | 4 +-- spring-rest-angular/pom.xml | 4 +-- .../org/baeldung/web/main/Application.java | 4 +-- .../StudentServiceIntegrationTest.java | 34 +++++++++++-------- spring-rest-query-language/pom.xml | 4 +-- spring-rest-shell/pom.xml | 4 +-- spring-rest-simple/pom.xml | 4 +-- spring-rest-template/pom.xml | 4 +-- spring-rest/pom.xml | 4 +-- .../lists/client/EmployeeClient.java | 8 ++--- .../advice/JsonpControllerAdvice.java | 13 ------- ...pplication.java => UploadApplication.java} | 4 +-- .../SpringContextIntegrationTest.java | 2 +- spring-resttemplate/pom.xml | 4 +-- spring-security-mvc-boot/pom.xml | 6 ++-- .../src/main/resources/templates/private.html | 2 +- spring-security-openid/pom.xml | 4 +-- ...mple.properties => application.properties} | 0 spring-security-sso/pom.xml | 6 ++-- .../spring-security-sso-ui-2/pom.xml | 2 +- .../spring-security-sso-ui/pom.xml | 2 +- spring-security-thymeleaf/pom.xml | 6 ++-- 22 files changed, 58 insertions(+), 67 deletions(-) delete mode 100644 spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java rename spring-rest/src/main/java/com/baeldung/web/upload/app/{Application.java => UploadApplication.java} (79%) rename spring-security-openid/src/main/resources/{application.properties.sample.properties => application.properties} (100%) diff --git a/spring-mvc-forms-thymeleaf/pom.xml b/spring-mvc-forms-thymeleaf/pom.xml index 67a2696c8a..504ad1dcb2 100644 --- a/spring-mvc-forms-thymeleaf/pom.xml +++ b/spring-mvc-forms-thymeleaf/pom.xml @@ -9,10 +9,10 @@ spring forms examples using thymeleaf - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 22ddabb4ea..5240ae24e7 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -8,10 +8,10 @@ war - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java b/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java index d6fe719311..fd10643c53 100644 --- a/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java +++ b/spring-rest-angular/src/main/java/org/baeldung/web/main/Application.java @@ -6,12 +6,12 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import org.springframework.web.filter.ShallowEtagHeaderFilter; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @SpringBootApplication @EnableAutoConfiguration @Import(PersistenceConfig.class) -public class Application extends WebMvcConfigurerAdapter { +public class Application implements WebMvcConfigurer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java index 4d65c02fff..1473d44b92 100644 --- a/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java +++ b/spring-rest-angular/src/test/java/org/baeldung/web/service/StudentServiceIntegrationTest.java @@ -1,62 +1,66 @@ package org.baeldung.web.service; +import static io.restassured.RestAssured.given; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsCollectionContaining.hasItems; +import static org.hamcrest.core.IsEqual.equalTo; + import org.apache.commons.lang3.RandomStringUtils; import org.baeldung.web.main.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; -import static io.restassured.RestAssured.given; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsCollectionContaining.hasItems; -import static org.hamcrest.core.IsEqual.equalTo; - @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class StudentServiceIntegrationTest { + + @LocalServerPort + int port; - private static final String ENDPOINT = "http://localhost:8080/student/get"; + private static final String ENDPOINT = "http://localhost:%s/student/get"; @Test public void givenRequestForStudents_whenPageIsOne_expectContainsNames() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat() + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().assertThat() .body("content.name", hasItems("Bryan", "Ben")); } @Test public void givenRequestForStudents_whenSizeIsTwo_expectTwoItems() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("size", equalTo(2)); + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().assertThat().body("size", equalTo(2)); } @Test public void givenRequestForStudents_whenSizeIsTwo_expectNumberOfElementsTwo() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("numberOfElements", equalTo(2)); + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().assertThat().body("numberOfElements", equalTo(2)); } @Test public void givenRequestForStudents_whenResourcesAreRetrievedPaged_thenExpect200() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().statusCode(200); + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().statusCode(200); } @Test public void givenRequestForStudents_whenPageOfResourcesAreRetrievedOutOfBounds_thenExpect500() { - given().params("page", "1000", "size", "2").get(ENDPOINT).then().statusCode(500); + given().params("page", "1000", "size", "2").get(String.format(ENDPOINT, port)).then().statusCode(500); } @Test public void givenRequestForStudents_whenPageNotValid_thenExpect500() { - given().params("page", RandomStringUtils.randomNumeric(5), "size", "2").get(ENDPOINT).then().statusCode(500); + given().params("page", RandomStringUtils.randomNumeric(5), "size", "2").get(String.format(ENDPOINT, port)).then().statusCode(500); } @Test public void givenRequestForStudents_whenPageSizeIsFive_expectFiveItems() { - given().params("page", "0", "size", "5").get(ENDPOINT).then().body("content.size()", is(5)); + given().params("page", "0", "size", "5").get(String.format(ENDPOINT, port)).then().body("content.size()", is(5)); } @Test public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources() { - given().params("page", "0", "size", "2").get(ENDPOINT).then().assertThat().body("first", equalTo(true)); + given().params("page", "0", "size", "2").get(String.format(ENDPOINT, port)).then().assertThat().body("first", equalTo(true)); } } diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index 6f790f1f48..70fea91f31 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -7,10 +7,10 @@ war - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-rest-shell/pom.xml b/spring-rest-shell/pom.xml index 8b7ce1770d..540b3d08eb 100644 --- a/spring-rest-shell/pom.xml +++ b/spring-rest-shell/pom.xml @@ -8,10 +8,10 @@ A simple project to demonstrate Spring REST Shell features. - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index e5de463999..d301957eb9 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -8,10 +8,10 @@ war - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-rest-template/pom.xml b/spring-rest-template/pom.xml index d86e208987..fa93308cf5 100644 --- a/spring-rest-template/pom.xml +++ b/spring-rest-template/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index ea4cfc26d7..5c88697cef 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -7,10 +7,10 @@ war - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java index d811045733..191719b084 100644 --- a/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java +++ b/spring-rest/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java @@ -43,7 +43,7 @@ public class EmployeeClient ResponseEntity> response = restTemplate.exchange( - "http://localhost:8080/spring-rest/employees/", + "http://localhost:8082/spring-rest/employees/", HttpMethod.GET, null, new ParameterizedTypeReference>(){}); @@ -61,7 +61,7 @@ public class EmployeeClient EmployeeList response = restTemplate.getForObject( - "http://localhost:8080/spring-rest/employees/v2", + "http://localhost:8082/spring-rest/employees/v2", EmployeeList.class); List employees = response.getEmployees(); @@ -80,7 +80,7 @@ public class EmployeeClient newEmployees.add(new Employee(4, "CEO")); restTemplate.postForObject( - "http://localhost:8080/spring-rest/employees/", + "http://localhost:8082/spring-rest/employees/", newEmployees, ResponseEntity.class); } @@ -94,7 +94,7 @@ public class EmployeeClient newEmployees.add(new Employee(4, "CEO")); restTemplate.postForObject( - "http://localhost:8080/spring-rest/employees/v2/", + "http://localhost:8082/spring-rest/employees/v2/", new EmployeeList(newEmployees), ResponseEntity.class); } diff --git a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java b/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java deleted file mode 100644 index 853e417d46..0000000000 --- a/spring-rest/src/main/java/com/baeldung/sampleapp/web/controller/advice/JsonpControllerAdvice.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.sampleapp.web.controller.advice; - -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice; - -@ControllerAdvice -public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice { - - public JsonpControllerAdvice() { - super("callback"); - } - -} diff --git a/spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java b/spring-rest/src/main/java/com/baeldung/web/upload/app/UploadApplication.java similarity index 79% rename from spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java rename to spring-rest/src/main/java/com/baeldung/web/upload/app/UploadApplication.java index d6821196eb..f3b1c0dc6f 100644 --- a/spring-rest/src/main/java/com/baeldung/web/upload/app/Application.java +++ b/spring-rest/src/main/java/com/baeldung/web/upload/app/UploadApplication.java @@ -9,9 +9,9 @@ import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration @ComponentScan("com.baeldung.web.upload") @SpringBootApplication -public class Application extends SpringBootServletInitializer { +public class UploadApplication extends SpringBootServletInitializer { public static void main(final String[] args) { - SpringApplication.run(Application.class, args); + SpringApplication.run(UploadApplication.class, args); } } \ No newline at end of file diff --git a/spring-rest/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-rest/src/test/java/com/baeldung/SpringContextIntegrationTest.java index e659897303..f04106c1e1 100644 --- a/spring-rest/src/test/java/com/baeldung/SpringContextIntegrationTest.java +++ b/spring-rest/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -14,7 +14,7 @@ import com.baeldung.web.log.app.Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = { CustomApplication.class, ImageApplication.class, PropertyEditorApplication.class, - ResponseHeadersApplication.class, Application.class, com.baeldung.web.upload.app.Application.class, + ResponseHeadersApplication.class, Application.class, com.baeldung.web.upload.app.UploadApplication.class, MainApplication.class}) public class SpringContextIntegrationTest { diff --git a/spring-resttemplate/pom.xml b/spring-resttemplate/pom.xml index 2c404a7e8c..9a0978f120 100644 --- a/spring-resttemplate/pom.xml +++ b/spring-resttemplate/pom.xml @@ -8,10 +8,10 @@ war - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index c072bf0f99..0a40b0b324 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -11,10 +11,10 @@ Spring Security MVC Boot - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 @@ -36,7 +36,7 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 + thymeleaf-extras-springsecurity5 org.springframework.boot diff --git a/spring-security-mvc-boot/src/main/resources/templates/private.html b/spring-security-mvc-boot/src/main/resources/templates/private.html index 5af8c7a13e..035d84bbbd 100644 --- a/spring-security-mvc-boot/src/main/resources/templates/private.html +++ b/spring-security-mvc-boot/src/main/resources/templates/private.html @@ -1,6 +1,6 @@ + xmlns:sec="http://www.thymeleaf.org/extras/spring-security"> Private diff --git a/spring-security-openid/pom.xml b/spring-security-openid/pom.xml index 6a946792ba..4343996e02 100644 --- a/spring-security-openid/pom.xml +++ b/spring-security-openid/pom.xml @@ -9,10 +9,10 @@ Spring OpenID sample project - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-security-openid/src/main/resources/application.properties.sample.properties b/spring-security-openid/src/main/resources/application.properties similarity index 100% rename from spring-security-openid/src/main/resources/application.properties.sample.properties rename to spring-security-openid/src/main/resources/application.properties diff --git a/spring-security-sso/pom.xml b/spring-security-sso/pom.xml index 4deab01464..4b297a91b5 100644 --- a/spring-security-sso/pom.xml +++ b/spring-security-sso/pom.xml @@ -9,10 +9,10 @@ pom - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 @@ -24,7 +24,7 @@ 3.1.0 2.3.3.RELEASE - 2.0.1.RELEASE + 2.1.1.RELEASE diff --git a/spring-security-sso/spring-security-sso-ui-2/pom.xml b/spring-security-sso/spring-security-sso-ui-2/pom.xml index 1f9a5754ae..e4ccb82fea 100644 --- a/spring-security-sso/spring-security-sso-ui-2/pom.xml +++ b/spring-security-sso/spring-security-sso-ui-2/pom.xml @@ -37,7 +37,7 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 + thymeleaf-extras-springsecurity5 diff --git a/spring-security-sso/spring-security-sso-ui/pom.xml b/spring-security-sso/spring-security-sso-ui/pom.xml index 56131749ba..a946db4c3b 100644 --- a/spring-security-sso/spring-security-sso-ui/pom.xml +++ b/spring-security-sso/spring-security-sso-ui/pom.xml @@ -38,7 +38,7 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 + thymeleaf-extras-springsecurity5 diff --git a/spring-security-thymeleaf/pom.xml b/spring-security-thymeleaf/pom.xml index 314783ebf2..d8b476683a 100644 --- a/spring-security-thymeleaf/pom.xml +++ b/spring-security-thymeleaf/pom.xml @@ -11,10 +11,10 @@ Spring Security with Thymeleaf tutorial - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 @@ -43,7 +43,7 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 + thymeleaf-extras-springsecurity5 From 9ee33c151f8110c21027954deb50944f869ca030 Mon Sep 17 00:00:00 2001 From: geroza Date: Tue, 11 Dec 2018 20:39:09 -0200 Subject: [PATCH 34/76] migrated modules to parent-boot-2 with spring-boot 2.1: spring-session/spring-session-jdbc spring-vault spring-webflux-amqp vaadin vavr --- spring-session/spring-session-jdbc/pom.xml | 4 +-- spring-vault/pom.xml | 25 +++---------------- spring-webflux-amqp/pom.xml | 4 +-- .../src/main/resources/application.yml | 2 +- vaadin/pom.xml | 4 +-- .../src/main/resources/application.properties | 2 ++ vavr/pom.xml | 4 +-- 7 files changed, 14 insertions(+), 31 deletions(-) create mode 100644 vaadin/src/main/resources/application.properties diff --git a/spring-session/spring-session-jdbc/pom.xml b/spring-session/spring-session-jdbc/pom.xml index a595a94914..ce6b5f5908 100644 --- a/spring-session/spring-session-jdbc/pom.xml +++ b/spring-session/spring-session-jdbc/pom.xml @@ -15,10 +15,10 @@ - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-2.0-temp + ../../parent-boot-2 diff --git a/spring-vault/pom.xml b/spring-vault/pom.xml index 6a7db5dd71..aad6da1cc3 100644 --- a/spring-vault/pom.xml +++ b/spring-vault/pom.xml @@ -13,10 +13,10 @@ Spring Vault sample project - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 @@ -41,27 +41,8 @@ - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - **/*IntegrationTest.java - - - - - - UTF-8 - 2.0.1.RELEASE + 2.1.1.RELEASE diff --git a/spring-webflux-amqp/pom.xml b/spring-webflux-amqp/pom.xml index e4e0d55ce3..4faa165c50 100755 --- a/spring-webflux-amqp/pom.xml +++ b/spring-webflux-amqp/pom.xml @@ -11,10 +11,10 @@ Spring WebFlux AMQP Sample - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/spring-webflux-amqp/src/main/resources/application.yml b/spring-webflux-amqp/src/main/resources/application.yml index 3f527ce4c5..702aaba357 100755 --- a/spring-webflux-amqp/src/main/resources/application.yml +++ b/spring-webflux-amqp/src/main/resources/application.yml @@ -1,6 +1,6 @@ spring: rabbitmq: - host: 192.168.99.100 + host: localhost port: 5672 username: guest password: guest diff --git a/vaadin/pom.xml b/vaadin/pom.xml index 1111c0aa0c..c34ffa3636 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -10,10 +10,10 @@ Vaadin - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 diff --git a/vaadin/src/main/resources/application.properties b/vaadin/src/main/resources/application.properties new file mode 100644 index 0000000000..1cb7086b82 --- /dev/null +++ b/vaadin/src/main/resources/application.properties @@ -0,0 +1,2 @@ +#Vaadin supports spring-boot 2.1 properly from V8 onwards (according to this comment https://github.com/vaadin/spring/issues/331#issuecomment-435128475) +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/vavr/pom.xml b/vavr/pom.xml index fa8eff1ce7..ae495e9830 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -7,10 +7,10 @@ vavr - parent-boot-2.0-temp + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2.0-temp + ../parent-boot-2 From 2e6a5a35106f15c17187f886c8db2b58f0e260c4 Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Wed, 12 Dec 2018 06:32:57 -0500 Subject: [PATCH 35/76] removed eval article code --- hexagonal-architecture/.gitignore | 1 - hexagonal-architecture/pom.xml | 14 ----- .../com/baeldung/hexagonal/Application.java | 26 -------- .../baeldung/hexagonal/domain/Employee.java | 60 ------------------- .../hexagonal/domain/EmployeeService.java | 25 -------- .../hexagonal/output/EmployeeCsvWriter.java | 59 ------------------ .../hexagonal/output/EmployeeLogger.java | 17 ------ .../hexagonal/output/EmployeeOutput.java | 9 --- .../hexagonal/storage/EmployeeRepository.java | 13 ---- .../storage/InMemoryEmployeeRepository.java | 31 ---------- .../ui/EmployeeConsoleInputImpl.java | 43 ------------- .../baeldung/hexagonal/ui/EmployeeInput.java | 7 --- 12 files changed, 305 deletions(-) delete mode 100644 hexagonal-architecture/.gitignore delete mode 100644 hexagonal-architecture/pom.xml delete mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/Application.java delete mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java delete mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/EmployeeService.java delete mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java delete mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeLogger.java delete mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeOutput.java delete mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/EmployeeRepository.java delete mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/InMemoryEmployeeRepository.java delete mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java delete mode 100644 hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeInput.java diff --git a/hexagonal-architecture/.gitignore b/hexagonal-architecture/.gitignore deleted file mode 100644 index ae3c172604..0000000000 --- a/hexagonal-architecture/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/bin/ diff --git a/hexagonal-architecture/pom.xml b/hexagonal-architecture/pom.xml deleted file mode 100644 index d184576705..0000000000 --- a/hexagonal-architecture/pom.xml +++ /dev/null @@ -1,14 +0,0 @@ - - 4.0.0 - com.baeldung.hexagonal - hexagonal-architecture - jar - hexagonal-architecture - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/Application.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/Application.java deleted file mode 100644 index 237b664708..0000000000 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/Application.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.hexagonal; - -import java.io.File; - -import com.baeldung.hexagonal.domain.EmployeeService; -import com.baeldung.hexagonal.output.EmployeeCsvWriter; -import com.baeldung.hexagonal.output.EmployeeLogger; -import com.baeldung.hexagonal.output.EmployeeOutput; -import com.baeldung.hexagonal.storage.EmployeeRepository; -import com.baeldung.hexagonal.storage.InMemoryEmployeeRepository; -import com.baeldung.hexagonal.ui.EmployeeConsoleInputImpl; -import com.baeldung.hexagonal.ui.EmployeeInput; - -public class Application { - - public static void main(String[] args) { - EmployeeRepository repository = new InMemoryEmployeeRepository(); - EmployeeOutput output = new EmployeeLogger(); - EmployeeOutput csvOutput = new EmployeeCsvWriter(new File(".").getAbsolutePath(), "output.csv"); - EmployeeService service = new EmployeeService(repository, csvOutput); - EmployeeInput ui = new EmployeeConsoleInputImpl(); - ui.collectData(service); - service.generateOutput(); - } - -} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java deleted file mode 100644 index 0d883995b6..0000000000 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/Employee.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.hexagonal.domain; - -public class Employee { - private Long id; - private String name; - - public Employee(Long id, String name) { - this.id = id; - this.name = name; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - return "Employee [id=" + id + ", name=" + name + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Employee other = (Employee) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - - return true; - } - -} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/EmployeeService.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/EmployeeService.java deleted file mode 100644 index 2ab3ce9712..0000000000 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/domain/EmployeeService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.hexagonal.domain; - -import java.util.List; - -import com.baeldung.hexagonal.output.EmployeeOutput; -import com.baeldung.hexagonal.storage.EmployeeRepository; - -public class EmployeeService { - private EmployeeRepository employeeRepository; - private EmployeeOutput employeeOutput; - - public EmployeeService(EmployeeRepository employeeRepository, EmployeeOutput employeeOutput) { - this.employeeRepository = employeeRepository; - this.employeeOutput = employeeOutput; - } - - public Long add(Employee employee) { - return employeeRepository.save(employee); - } - - public void generateOutput() { - List employees = employeeRepository.findAll(); - employeeOutput.writeAll(employees); - } -} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java deleted file mode 100644 index 799fbc28ba..0000000000 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeCsvWriter.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.hexagonal.output; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; - -import com.baeldung.hexagonal.domain.Employee; - -public class EmployeeCsvWriter implements EmployeeOutput { - private File outputFile; - - public EmployeeCsvWriter(String path, String fileName) throws IllegalArgumentException { - if (fileName == null || path == null || fileName.length() == 0 || path.length() == 0) { - throw new IllegalArgumentException("Path and FileName are required"); - } else if (!fileName.endsWith(".csv")) { - throw new IllegalArgumentException("File name must be a .csv file"); - } - - System.out.println(path); - if (!path.endsWith("/")) { - path += "/"; - } - - outputFile = new File(path, fileName); - } - - @Override - public void writeAll(List employees) { - BufferedWriter writer = null; - - try { - writer = new BufferedWriter(new FileWriter(outputFile)); - for (Iterator it = employees.iterator(); it.hasNext();) { - Employee emp = it.next(); - StringBuffer empLine = new StringBuffer(); - empLine.append(emp.getId()); - empLine.append(","); - empLine.append(emp.getName()); - writer.newLine(); - } - writer.flush(); - } catch (IOException ioe) { - // handle the exception - } finally { - if (writer != null) { - try { - writer.close(); - } catch (IOException e) { - // handle the exception - } - } - } - - } - -} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeLogger.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeLogger.java deleted file mode 100644 index 5272d18961..0000000000 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeLogger.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.hexagonal.output; - -import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.baeldung.hexagonal.domain.Employee; - -public class EmployeeLogger implements EmployeeOutput { - private static final Logger LOG = LoggerFactory.getLogger(EmployeeLogger.class); - - @Override - public void writeAll(List employees) { - employees.forEach(employee -> LOG.info(employee.toString())); - } - -} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeOutput.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeOutput.java deleted file mode 100644 index 979c06e1f4..0000000000 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/output/EmployeeOutput.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.hexagonal.output; - -import java.util.List; - -import com.baeldung.hexagonal.domain.Employee; - -public interface EmployeeOutput { - public void writeAll(List employees); -} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/EmployeeRepository.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/EmployeeRepository.java deleted file mode 100644 index 2787601998..0000000000 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/EmployeeRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.hexagonal.storage; - -import java.util.List; - -import com.baeldung.hexagonal.domain.Employee; - -public interface EmployeeRepository { - public Long save(Employee employee); - - public Employee findById(Long id); - - public List findAll(); -} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/InMemoryEmployeeRepository.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/InMemoryEmployeeRepository.java deleted file mode 100644 index e860c16462..0000000000 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/storage/InMemoryEmployeeRepository.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.hexagonal.storage; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.baeldung.hexagonal.domain.Employee; - -public class InMemoryEmployeeRepository implements EmployeeRepository { - private static Map employees = new HashMap<>(); - - @Override - public Long save(Employee employee) { - Long id = employee.getId(); - employees.put(id, employee); - return id; - } - - @Override - public Employee findById(Long id) { - return employees.get(id); - } - - @Override - public List findAll() { - List all = new ArrayList(employees.values()); - return all; - } - -} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java deleted file mode 100644 index 77453da48f..0000000000 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeConsoleInputImpl.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.hexagonal.ui; - -import java.util.Scanner; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.baeldung.hexagonal.domain.Employee; -import com.baeldung.hexagonal.domain.EmployeeService; - -public class EmployeeConsoleInputImpl implements EmployeeInput { - private static final Logger LOG = LoggerFactory.getLogger(EmployeeConsoleInputImpl.class); - - public void enterEmployee(EmployeeService service, Scanner scanner) { - LOG.info("ID: "); - System.out.print("> "); - Long id = scanner.nextLong(); - LOG.info("Name: "); - System.out.print("> "); - String name = scanner.next(); - - Employee employee = new Employee(id, name); - service.add(employee); - } - - @Override - public void collectData(EmployeeService service) { - try (final Scanner scanner = new Scanner(System.in)) { - String keepGoing = "Y"; - do { - LOG.info("Enter information for an employee"); - enterEmployee(service, scanner); - LOG.info("Do you want to enter another employee? (Y/N)"); - System.out.print("> "); - keepGoing = scanner.next(); - if (keepGoing.length() > 1) { - keepGoing = keepGoing.substring(0, 1); - } - } while (keepGoing.equalsIgnoreCase("Y")); - } - } - -} diff --git a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeInput.java b/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeInput.java deleted file mode 100644 index adec2852cd..0000000000 --- a/hexagonal-architecture/src/main/java/com/baeldung/hexagonal/ui/EmployeeInput.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.hexagonal.ui; - -import com.baeldung.hexagonal.domain.EmployeeService; - -public interface EmployeeInput { - void collectData(EmployeeService service); -} From 1ad6d9c8720e94d87fdc74617326da4c216acd19 Mon Sep 17 00:00:00 2001 From: geroza Date: Wed, 12 Dec 2018 10:26:07 -0200 Subject: [PATCH 36/76] Deleted temporary parent-boot module using spring-boot 2.0.x --- parent-boot-2.0-temp/README.md | 2 - parent-boot-2.0-temp/pom.xml | 85 ---------------------------------- pom.xml | 6 --- 3 files changed, 93 deletions(-) delete mode 100644 parent-boot-2.0-temp/README.md delete mode 100644 parent-boot-2.0-temp/pom.xml diff --git a/parent-boot-2.0-temp/README.md b/parent-boot-2.0-temp/README.md deleted file mode 100644 index 8134c8eafe..0000000000 --- a/parent-boot-2.0-temp/README.md +++ /dev/null @@ -1,2 +0,0 @@ -This pom will be ued only temporary until we migrate parent-boot-2 to 2.1.0 for ticket BAEL-10354 - diff --git a/parent-boot-2.0-temp/pom.xml b/parent-boot-2.0-temp/pom.xml deleted file mode 100644 index 9284e4af13..0000000000 --- a/parent-boot-2.0-temp/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - 4.0.0 - parent-boot-2.0-temp - 0.0.1-SNAPSHOT - pom - Temporary Parent for all Spring Boot 2.0.x modules - - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - - - io.rest-assured - rest-assured - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - ${start-class} - - - - - - - - - - thin-jar - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.springframework.boot.experimental - spring-boot-thin-layout - ${thin.version} - - - - - - - - - - 3.1.0 - - 1.0.11.RELEASE - 2.0.5.RELEASE - - - - diff --git a/pom.xml b/pom.xml index 4e1e61961e..f6a56c895d 100644 --- a/pom.xml +++ b/pom.xml @@ -324,7 +324,6 @@ parent-boot-1 parent-boot-2 - parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java @@ -592,7 +591,6 @@ parent-boot-1 parent-boot-2 - parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java @@ -987,7 +985,6 @@ parent-boot-1 parent-boot-2 - parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java @@ -1038,7 +1035,6 @@ parent-boot-1 parent-boot-2 - parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java @@ -1302,7 +1298,6 @@ parent-boot-1 parent-boot-2 - parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java @@ -1538,7 +1533,6 @@ parent-boot-1 parent-boot-2 - parent-boot-2.0-temp parent-spring-4 parent-spring-5 parent-java From cb7e5157236c11d274a25fb434bb1b7f9dc28138 Mon Sep 17 00:00:00 2001 From: Surapaneni Venkata Kiran Date: Wed, 12 Dec 2018 14:19:45 -0500 Subject: [PATCH 37/76] BAEL-2421 * Changes for http://jira.baeldung.com/browse/BAEL-2421 * fixed formatting * Merged the test and main classes as per the suggestion. * Merged the source code with tests. --- .../baeldung/ConvertStringToListUnitTest.java | 135 ++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java diff --git a/java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java b/java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java new file mode 100644 index 0000000000..47357a99cc --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/ConvertStringToListUnitTest.java @@ -0,0 +1,135 @@ +package com.baeldung; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; + +import com.google.common.base.Function; +import com.google.common.base.Splitter; +import com.google.common.collect.Lists; + +public class ConvertStringToListUnitTest { + + private final String countries = "Russia,Germany,England,France,Italy"; + private final String ranks = "1,2,3,4,5, 6,7"; + private final String emptyStrings = ",,,,,"; + private final List expectedCountriesList = Arrays.asList("Russia", "Germany", "England", "France", "Italy"); + private final List expectedRanksList = Arrays.asList(1, 2, 3, 4, 5, 6, 7); + private final List expectedEmptyStringsList = Arrays.asList("", "", "", "", "", ""); + + @Test + public void givenString_thenGetListOfStringByJava() { + List convertedCountriesList = Arrays.asList(countries.split(",", -1)); + + assertEquals(expectedCountriesList, convertedCountriesList); + } + + @Test + public void givenString_thenGetListOfStringByApache() { + List convertedCountriesList = Arrays.asList(StringUtils.splitPreserveAllTokens(countries, ",")); + + assertEquals(expectedCountriesList, convertedCountriesList); + } + + @Test + public void givenString_thenGetListOfStringByGuava() { + List convertedCountriesList = Splitter.on(",") + .trimResults() + .splitToList(countries); + + assertEquals(expectedCountriesList, convertedCountriesList); + } + + @Test + public void givenString_thenGetListOfStringByJava8() { + List convertedCountriesList = Stream.of(countries.split(",", -1)) + .collect(Collectors.toList()); + + assertEquals(expectedCountriesList, convertedCountriesList); + } + + @Test + public void givenString_thenGetListOfIntegerByJava() { + String[] convertedRankArray = ranks.split(","); + List convertedRankList = new ArrayList(); + for (String number : convertedRankArray) { + convertedRankList.add(Integer.parseInt(number.trim())); + } + + assertEquals(expectedRanksList, convertedRankList); + } + + @Test + public void givenString_thenGetListOfIntegerByGuava() { + List convertedRankList = Lists.transform(Splitter.on(",") + .trimResults() + .splitToList(ranks), new Function() { + @Override + public Integer apply(String input) { + return Integer.parseInt(input.trim()); + } + }); + + assertEquals(expectedRanksList, convertedRankList); + } + + @Test + public void givenString_thenGetListOfIntegerByJava8() { + List convertedRankList = Stream.of(ranks.split(",")) + .map(String::trim) + .map(Integer::parseInt) + .collect(Collectors.toList()); + + assertEquals(expectedRanksList, convertedRankList); + } + + @Test + public void givenString_thenGetListOfIntegerByApache() { + String[] convertedRankArray = StringUtils.split(ranks, ","); + List convertedRankList = new ArrayList(); + for (String number : convertedRankArray) { + convertedRankList.add(Integer.parseInt(number.trim())); + } + + assertEquals(expectedRanksList, convertedRankList); + } + + @Test + public void givenEmptyStrings_thenGetListOfStringByJava() { + List convertedEmptyStringsList = Arrays.asList(emptyStrings.split(",", -1)); + + assertEquals(expectedEmptyStringsList, convertedEmptyStringsList); + } + + @Test + public void givenEmptyStrings_thenGetListOfStringByApache() { + List convertedEmptyStringsList = Arrays.asList(StringUtils.splitPreserveAllTokens(emptyStrings, ",")); + + assertEquals(expectedEmptyStringsList, convertedEmptyStringsList); + } + + @Test + public void givenEmptyStrings_thenGetListOfStringByGuava() { + List convertedEmptyStringsList = Splitter.on(",") + .trimResults() + .splitToList(emptyStrings); + + assertEquals(expectedEmptyStringsList, convertedEmptyStringsList); + } + + @Test + public void givenEmptyStrings_thenGetListOfStringByJava8() { + List convertedEmptyStringsList = Stream.of(emptyStrings.split(",", -1)) + .collect(Collectors.toList()); + + assertEquals(expectedEmptyStringsList, convertedEmptyStringsList); + } + +} From 5525c1277658edfd20de06e46a2dd61506484cf3 Mon Sep 17 00:00:00 2001 From: Paul van Gool Date: Wed, 12 Dec 2018 14:20:14 -0800 Subject: [PATCH 38/76] BAEL-1049: Re-merge changes. (#5895) * BAEL-1049: Re-merge changes. * Change to re-trigger build * Change to re-trigger the build * Change to re-trigger build * Change to re-trigger build --- .../baeldung/fj/FunctionalJavaUnitTest.java | 42 ++++++++----------- 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java index aa06ba4eb9..97ead07470 100644 --- a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java +++ b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java @@ -1,6 +1,8 @@ package com.baeldung.fj; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -30,7 +32,7 @@ public class FunctionalJavaUnitTest { List fList1 = fList.map(timesTwo); List fList2 = fList.map(i -> i * 2); - assertEquals(fList1.equals(fList2), true); + assertTrue(fList1.equals(fList2)); } @Test @@ -41,7 +43,7 @@ public class FunctionalJavaUnitTest { List fList2 = fList.map(plusOne).map(timesTwo); Show.listShow(Show.intShow).println(fList2); - assertEquals(fList1.equals(fList2), false); + assertFalse(fList1.equals(fList2)); } @Test @@ -49,10 +51,8 @@ public class FunctionalJavaUnitTest { List fList = List.list(3, 4, 5, 6); List evenList = fList.map(isEven); List evenListTrueResult = List.list(false, true, false, true); - List evenListFalseResult = List.list(true, false, false, true); - assertEquals(evenList.equals(evenListTrueResult), true); - assertEquals(evenList.equals(evenListFalseResult), false); + assertTrue(evenList.equals(evenListTrueResult)); } @Test @@ -60,10 +60,8 @@ public class FunctionalJavaUnitTest { List fList = List.list(3, 4, 5, 6); fList = fList.map(i -> i + 100); List resultList = List.list(103, 104, 105, 106); - List falseResultList = List.list(15, 504, 105, 106); - assertEquals(fList.equals(resultList), true); - assertEquals(fList.equals(falseResultList), false); + assertTrue(fList.equals(resultList)); } @Test @@ -71,23 +69,19 @@ public class FunctionalJavaUnitTest { Array array = Array.array(3, 4, 5, 6); Array filteredArray = array.filter(isEven); Array result = Array.array(4, 6); - Array wrongResult = Array.array(3, 5); - assertEquals(filteredArray.equals(result), true); - assertEquals(filteredArray.equals(wrongResult), false); + assertTrue(filteredArray.equals(result)); } @Test public void checkForLowerCase_givenStringArray_returnResult() { Array array = Array.array("Welcome", "To", "baeldung"); + assertTrue(array.exists(s -> List.fromString(s).forall(Characters.isLowerCase))); + Array array2 = Array.array("Welcome", "To", "Baeldung"); - Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); - Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase)); - Boolean isAll = array.forall(s -> List.fromString(s).forall(Characters.isLowerCase)); - - assertEquals(isExist, true); - assertEquals(isExist2, false); - assertEquals(isAll, false); + assertFalse(array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase))); + + assertFalse(array.forall(s -> List.fromString(s).forall(Characters.isLowerCase))); } @Test @@ -102,9 +96,9 @@ public class FunctionalJavaUnitTest { Option result2 = n2.bind(function); Option result3 = n3.bind(function); - assertEquals(result1, Option.none()); - assertEquals(result2, Option.some(102)); - assertEquals(result3, Option.none()); + assertEquals(Option.none(), result1); + assertEquals(Option.some(102), result2); + assertEquals(Option.none(), result3); } @Test @@ -112,11 +106,11 @@ public class FunctionalJavaUnitTest { Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27); int sumAll = intArray.foldLeft(Integers.add, 0); - assertEquals(sumAll, 260); + assertEquals(260, sumAll); int sumEven = intArray.filter(isEven).foldLeft(Integers.add, 0); - assertEquals(sumEven, 148); + assertEquals(148, sumEven); } - + } From 08eabaf2b8410c60a01c8beb1fdfdf12fbb3ed48 Mon Sep 17 00:00:00 2001 From: eric-martin Date: Wed, 12 Dec 2018 22:46:45 -0600 Subject: [PATCH 39/76] BAEL-2068: Using hibernate-c3p0 --- persistence-modules/hibernate5/pom.xml | 10 ++++++++++ .../hibernate5/src/test/resources/hibernate.properties | 7 ++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 7e9a0ddb29..f5a3a7e4c9 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -36,6 +36,11 @@ hibernate-spatial ${hibernate.version} + + org.hibernate + hibernate-c3p0 + ${hibernate.version} + mysql mysql-connector-java @@ -56,6 +61,11 @@ jackson-databind ${jackson.version} + + net.bytebuddy + byte-buddy + 1.9.5 + diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate.properties b/persistence-modules/hibernate5/src/test/resources/hibernate.properties index 7b8764637b..c14782ce0f 100644 --- a/persistence-modules/hibernate5/src/test/resources/hibernate.properties +++ b/persistence-modules/hibernate5/src/test/resources/hibernate.properties @@ -6,4 +6,9 @@ jdbc.password= hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop \ No newline at end of file +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 From 25854b89a800341a04c45473fb0cb97ba21f3dc8 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Thu, 13 Dec 2018 13:45:02 +0530 Subject: [PATCH 40/76] BAEL-10829 Cleanup parent pom.xml (#5907) * BAEL-10829 Cleanup parent pom.xml - Removed geotools module causing build to hang - Removed -q parameter from travis to see full logs while building * BAEL-10829 reverting -q flag in travis * BAEL-10829 Commented restx module due to failing tests --- pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 4e1e61961e..43b53690e0 100644 --- a/pom.xml +++ b/pom.xml @@ -401,7 +401,7 @@ flips flyway-cdi-extension - geotools + google-cloud google-web-toolkit @@ -550,7 +550,7 @@ reactor-core rest-with-spark-java resteasy - restx + rule-engines/easy-rules rule-engines/openl-tablets @@ -1115,7 +1115,7 @@ flips flyway-cdi-extension - geotools + google-cloud google-web-toolkit @@ -1264,7 +1264,7 @@ reactor-core rest-with-spark-java resteasy - restx + rule-engines/easy-rules rule-engines/openl-tablets From ac049837d9483bec98a66c3c818d57c23c1279fd Mon Sep 17 00:00:00 2001 From: clininger Date: Thu, 13 Dec 2018 15:38:53 +0700 Subject: [PATCH 41/76] Removed references to "wind" in sample code --- .../com/baeldung/rsocket/FireNForgetClient.java | 4 ++-- .../java/com/baeldung/rsocket/ReqStreamClient.java | 2 +- .../src/main/java/com/baeldung/rsocket/Server.java | 14 +++++++------- .../com/baeldung/rsocket/support/Constants.java | 4 ++-- .../{WindDataPublisher.java => DataPublisher.java} | 2 +- 5 files changed, 13 insertions(+), 13 deletions(-) rename rsocket/src/main/java/com/baeldung/rsocket/support/{WindDataPublisher.java => DataPublisher.java} (91%) diff --git a/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java index 496b3fc5c9..a67078db06 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/FireNForgetClient.java @@ -61,9 +61,9 @@ public class FireNForgetClient { * @return List of random floats */ private List generateData() { - List dataList = new ArrayList<>(WIND_DATA_LENGTH); + List dataList = new ArrayList<>(DATA_LENGTH); float velocity = 0; - for (int i = 0; i < WIND_DATA_LENGTH; i++) { + for (int i = 0; i < DATA_LENGTH; i++) { velocity += Math.random(); dataList.add(velocity); } diff --git a/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java index e97192bdf0..085f9874fa 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/ReqStreamClient.java @@ -21,7 +21,7 @@ public class ReqStreamClient { public Flux getDataStream() { return socket - .requestStream(DefaultPayload.create(WIND_DATA_STREAM_NAME)) + .requestStream(DefaultPayload.create(DATA_STREAM_NAME)) .map(Payload::getData) .map(buf -> buf.getFloat()) .onErrorReturn(null); diff --git a/rsocket/src/main/java/com/baeldung/rsocket/Server.java b/rsocket/src/main/java/com/baeldung/rsocket/Server.java index b5718ab36d..42243da39f 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/Server.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/Server.java @@ -1,6 +1,6 @@ package com.baeldung.rsocket; -import com.baeldung.rsocket.support.WindDataPublisher; +import com.baeldung.rsocket.support.DataPublisher; import static com.baeldung.rsocket.support.Constants.*; import com.baeldung.rsocket.support.GameController; import io.rsocket.AbstractRSocket; @@ -19,7 +19,7 @@ public class Server { private static final Logger LOG = LoggerFactory.getLogger(Server.class); private final Disposable server; - private final WindDataPublisher windDataPublisher = new WindDataPublisher(); + private final DataPublisher dataPublisher = new DataPublisher(); private final GameController gameController; public Server() { @@ -34,7 +34,7 @@ public class Server { } public void dispose() { - windDataPublisher.complete(); + dataPublisher.complete(); this.server.dispose(); } @@ -67,7 +67,7 @@ public class Server { @Override public Mono fireAndForget(Payload payload) { try { - windDataPublisher.publish(payload); // forward the payload + dataPublisher.publish(payload); // forward the payload return Mono.empty(); } catch (Exception x) { return Mono.error(x); @@ -78,13 +78,13 @@ public class Server { * Handle Request/Stream messages. Each request returns a new stream. * * @param payload Payload that can be used to determine which stream to return - * @return Flux stream containing simulated wind speed data + * @return Flux stream containing simulated measurement data */ @Override public Flux requestStream(Payload payload) { String streamName = payload.getDataUtf8(); - if (WIND_DATA_STREAM_NAME.equals(streamName)) { - return Flux.from(windDataPublisher); + if (DATA_STREAM_NAME.equals(streamName)) { + return Flux.from(dataPublisher); } return Flux.error(new IllegalArgumentException(streamName)); } diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java b/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java index 01bb374b4e..4ffc4f6483 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/Constants.java @@ -4,7 +4,7 @@ public interface Constants { int TCP_PORT = 7101; String ERROR_MSG = "error"; - int WIND_DATA_LENGTH = 30; - String WIND_DATA_STREAM_NAME = "wind-data"; + int DATA_LENGTH = 30; + String DATA_STREAM_NAME = "data"; int SHOT_COUNT = 10; } diff --git a/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java b/rsocket/src/main/java/com/baeldung/rsocket/support/DataPublisher.java similarity index 91% rename from rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java rename to rsocket/src/main/java/com/baeldung/rsocket/support/DataPublisher.java index 2ad5b5144b..3e74da8317 100644 --- a/rsocket/src/main/java/com/baeldung/rsocket/support/WindDataPublisher.java +++ b/rsocket/src/main/java/com/baeldung/rsocket/support/DataPublisher.java @@ -7,7 +7,7 @@ import org.reactivestreams.Subscriber; /** * Simple PUblisher to provide async data to Flux stream */ -public class WindDataPublisher implements Publisher { +public class DataPublisher implements Publisher { private Subscriber subscriber; From 92c7248a57bd823fc7bcbb5afbde4c5c5f5fdb4f Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Tue, 11 Dec 2018 22:49:55 +0330 Subject: [PATCH 42/76] Added two tests for time difference calculation in terms of seconds! --- .../com/baeldung/date/DateDiffUnitTest.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java index 92da22cc95..1234a700de 100644 --- a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java @@ -8,6 +8,7 @@ import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Period; +import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.Locale; import java.util.TimeZone; @@ -51,6 +52,16 @@ public class DateDiffUnitTest { assertEquals(diff, 6); } + @Test + public void givenTwoDateTimesInJava8_whenDifferentiatingInSeconds_thenWeGetTen() { + LocalDateTime now = LocalDateTime.now(); + LocalDateTime tenSecondsLater = now.plusSeconds(10); + + long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater); + + assertEquals(diff, 10); + } + @Test public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() { LocalDateTime ldt = LocalDateTime.now(); @@ -60,6 +71,16 @@ public class DateDiffUnitTest { assertEquals(diff, 6); } + @Test + public void givenTwoDateTimesInJava8_whenDifferentiatingInSecondsUsingUntil_thenWeGetTen() { + LocalDateTime now = LocalDateTime.now(); + LocalDateTime tenSecondsLater = now.plusSeconds(10); + + long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS); + + assertEquals(diff, 10); + } + @Test public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() { org.joda.time.LocalDate now = org.joda.time.LocalDate.now(); From 7a23ac4f5301a45b74e992b8e730ff7c7dab1d89 Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Thu, 13 Dec 2018 15:12:23 +0100 Subject: [PATCH 43/76] BAEL-2351 fixed integration tests --- .../src/main/resources/application.properties | 5 ++++- .../RestartApplicationIntegrationTest.java | 19 ++++++++++++------- .../src/test/resources/application.properties | 5 ++++- 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/spring-boot-ops/src/main/resources/application.properties b/spring-boot-ops/src/main/resources/application.properties index 644a3edabc..27b7915cff 100644 --- a/spring-boot-ops/src/main/resources/application.properties +++ b/spring-boot-ops/src/main/resources/application.properties @@ -1,4 +1,7 @@ management.endpoints.web.exposure.include=* management.metrics.enable.root=true management.metrics.enable.jvm=true -management.endpoint.restart.enabled=true \ No newline at end of file +management.endpoint.restart.enabled=true +spring.datasource.jmx-enabled=false +spring.main.allow-bean-definition-overriding=true +management.endpoint.shutdown.enabled=true \ No newline at end of file diff --git a/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java index 1bec3c6a90..14e80c3ac7 100644 --- a/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java +++ b/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java @@ -2,20 +2,25 @@ package com.baeldung.restart; import static org.junit.Assert.assertEquals; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; +import java.time.Duration; + public class RestartApplicationIntegrationTest { - - private TestRestTemplate template = new TestRestTemplate(); + + private TestRestTemplate restTemplate = new TestRestTemplate(); @Test public void givenBootApp_whenRestart_thenOk() throws Exception { Application.main(new String[0]); - - ResponseEntity response = template.exchange("http://localhost:8080/restart", + + ResponseEntity response = restTemplate.exchange("http://localhost:8080/restart", HttpMethod.POST, null, Object.class); assertEquals(200, response.getStatusCode().value()); @@ -24,11 +29,11 @@ public class RestartApplicationIntegrationTest { @Test public void givenBootApp_whenRestartUsingActuator_thenOk() throws Exception { Application.main(new String[] { "--server.port=8090" }); - - ResponseEntity response = template.exchange("http://localhost:8090/restartApp", + + ResponseEntity response = restTemplate.exchange("http://localhost:8090/restartApp", HttpMethod.POST, null, Object.class); assertEquals(200, response.getStatusCode().value()); } -} +} \ No newline at end of file diff --git a/spring-boot-ops/src/test/resources/application.properties b/spring-boot-ops/src/test/resources/application.properties index 0adf2998d7..cf0f0ab74c 100644 --- a/spring-boot-ops/src/test/resources/application.properties +++ b/spring-boot-ops/src/test/resources/application.properties @@ -6,4 +6,7 @@ management.endpoints.web.exposure.include=* management.endpoint.shutdown.enabled=true endpoints.shutdown.enabled=true -management.endpoint.restart.enabled=true \ No newline at end of file +management.endpoint.restart.enabled=true + +spring.main.allow-bean-definition-overriding=true +spring.jmx.unique-names=true \ No newline at end of file From 8b63e6d7f46b59b66c8611589ead7da1883e6e24 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Fri, 14 Dec 2018 00:53:14 +0530 Subject: [PATCH 44/76] BAEL-10829 Clean up the parent pom of the tutorials project (#5911) - Moved jhipster and java-mongodb modules to heavy profiles --- pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 43b53690e0..99dae9decb 100644 --- a/pom.xml +++ b/pom.xml @@ -448,7 +448,6 @@ jersey JGit jgroups - jhipster jib jjwt jmeter @@ -516,7 +515,6 @@ persistence-modules/java-cockroachdb persistence-modules/java-jdbi persistence-modules/java-jpa - persistence-modules/java-mongodb persistence-modules/jnosql persistence-modules/liquibase persistence-modules/orientdb @@ -998,12 +996,14 @@ core-kotlin jenkins/hello-world + jhipster jws libraries persistence-modules/hibernate5 persistence-modules/java-jpa + persistence-modules/java-mongodb persistence-modules/jnosql spring-5-data-reactive @@ -1162,7 +1162,6 @@ jersey JGit jgroups - jhipster jib jjwt jmeter @@ -1230,7 +1229,6 @@ persistence-modules/java-cockroachdb persistence-modules/java-jdbi persistence-modules/java-jpa - persistence-modules/java-mongodb persistence-modules/jnosql persistence-modules/liquibase persistence-modules/orientdb @@ -1549,18 +1547,20 @@ core-kotlin jenkins/hello-world + jhipster jws libraries persistence-modules/hibernate5 persistence-modules/java-jpa + persistence-modules/java-mongodb persistence-modules/jnosql spring-5-data-reactive spring-amqp-simple - vaadin + vaadin From 28de875e872e9cbfa6b4aec6bc9e9af4394be35c Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Thu, 13 Dec 2018 20:23:55 +0100 Subject: [PATCH 45/76] added link --- rxjava-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/rxjava-2/README.md b/rxjava-2/README.md index f9528bb1d5..d0bdeec684 100644 --- a/rxjava-2/README.md +++ b/rxjava-2/README.md @@ -6,3 +6,4 @@ - [RxJava Maybe](http://www.baeldung.com/rxjava-maybe) - [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay) - [Combining RxJava Completables](https://www.baeldung.com/rxjava-completable) +- [Converting Synchronous and Asynchronous APIs to Observables using RxJava2](https://www.baeldung.com/rxjava-apis-to-observables) From 3235804ebfe0ed86ec71a69a5dcd0cebf0722d2f Mon Sep 17 00:00:00 2001 From: Loredana Date: Fri, 14 Dec 2018 00:01:53 +0200 Subject: [PATCH 46/76] small fix in merge sort --- .../main/java/com/baeldung/algorithms/mergesort/MergeSort.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java index 0deb48b6a0..945b4ffd7e 100644 --- a/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java +++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java @@ -34,7 +34,7 @@ public class MergeSort { while (i < left && j < right) { - if (l[i] < r[j]) + if (l[i] <= r[j]) a[k++] = l[i++]; else a[k++] = r[j++]; From 291abe3dee5284140df5a2c0ede606c2737d2b8a Mon Sep 17 00:00:00 2001 From: Ger Roza Date: Fri, 14 Dec 2018 09:02:17 -0200 Subject: [PATCH 47/76] change in README just to kick off a Travis build --- spring-mvc-forms-thymeleaf/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-mvc-forms-thymeleaf/README.md b/spring-mvc-forms-thymeleaf/README.md index f0f7e35a98..22f12afbca 100644 --- a/spring-mvc-forms-thymeleaf/README.md +++ b/spring-mvc-forms-thymeleaf/README.md @@ -2,3 +2,4 @@ - [Session Attributes in Spring MVC](http://www.baeldung.com/spring-mvc-session-attributes) - [Binding a List in Thymeleaf](http://www.baeldung.com/thymeleaf-list) + From 50f23889012685d6ca1820f414ebad2ad570ed30 Mon Sep 17 00:00:00 2001 From: Shubhra Srivastava Date: Fri, 14 Dec 2018 22:56:10 +0530 Subject: [PATCH 48/76] BAEL-2411 Spring Data Jpa Pagingg and Sorting (#5912) --- .../product/ProductRepository.java | 9 +- .../com/baeldung/domain/product/Product.java | 17 ++- .../ProductRepositoryIntegrationTest.java | 142 ++++++++++++++++++ 3 files changed, 165 insertions(+), 3 deletions(-) mode change 100644 => 100755 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java mode change 100644 => 100755 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java create mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/product/ProductRepositoryIntegrationTest.java diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java old mode 100644 new mode 100755 index 7044d57e53..1f9f5f9195 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/product/ProductRepository.java @@ -1,8 +1,13 @@ package com.baeldung.dao.repositories.product; import com.baeldung.domain.product.Product; -import org.springframework.data.jpa.repository.JpaRepository; -public interface ProductRepository extends JpaRepository { +import java.util.List; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.PagingAndSortingRepository; + +public interface ProductRepository extends PagingAndSortingRepository { + + List findAllByPrice(double price, Pageable pageable); } diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java old mode 100644 new mode 100755 index 42e6dd8f45..2f82e3e318 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/domain/product/Product.java @@ -19,6 +19,17 @@ public class Product { super(); } + private Product(int id, String name, double price) { + super(); + this.id = id; + this.name = name; + this.price = price; + } + + public static Product from(int id, String name, double price) { + return new Product(id, name, price); + } + public int getId() { return id; } @@ -46,7 +57,11 @@ public class Product { @Override public String toString() { final StringBuilder builder = new StringBuilder(); - builder.append("Product [name=").append(name).append(", id=").append(id).append("]"); + builder.append("Product [name=") + .append(name) + .append(", id=") + .append(id) + .append("]"); return builder.toString(); } } diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/product/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/product/ProductRepositoryIntegrationTest.java new file mode 100644 index 0000000000..4caa0f0ca4 --- /dev/null +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/dao/repositories/product/ProductRepositoryIntegrationTest.java @@ -0,0 +1,142 @@ +package com.baeldung.dao.repositories.product; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.config.PersistenceProductConfiguration; +import com.baeldung.domain.product.Product; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { PersistenceProductConfiguration.class }) +@EnableTransactionManagement +public class ProductRepositoryIntegrationTest { + + @Autowired + private ProductRepository productRepository; + + @Before + @Transactional("productTransactionManager") + public void setUp() { + productRepository.save(Product.from(1001, "Book", 21)); + productRepository.save(Product.from(1002, "Coffee", 10)); + productRepository.save(Product.from(1003, "Jeans", 30)); + productRepository.save(Product.from(1004, "Shirt", 32)); + productRepository.save(Product.from(1005, "Bacon", 10)); + } + + @Test + public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { + Pageable pageRequest = PageRequest.of(0, 2); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(2)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1001, 1002) + .contains(id))); + } + + @Test + public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { + Pageable pageRequest = PageRequest.of(1, 2); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(2)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1003, 1004) + .contains(id))); + } + + @Test + public void whenRequestingLastPage_ThenReturnLastPageWithRemData() { + Pageable pageRequest = PageRequest.of(2, 2); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(1)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1005) + .contains(id))); + } + + @Test + public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { + Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name")); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(3)); + assertThat(result.getContent() + .stream() + .map(Product::getId) + .collect(Collectors.toList()), equalTo(Arrays.asList(1005, 1001, 1002))); + + } + + @Test + public void whenSortingByPriceDescAndPaging_ThenReturnSortedPagedResult() { + Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price") + .descending()); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(3)); + assertThat(result.getContent() + .stream() + .map(Product::getId) + .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001))); + + } + + @Test + public void whenSortingByPriceDescAndNameAscAndPaging_ThenReturnSortedPagedResult() { + Pageable pageRequest = PageRequest.of(0, 5, Sort.by("price") + .descending() + .and(Sort.by("name"))); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(5)); + assertThat(result.getContent() + .stream() + .map(Product::getId) + .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001, 1005, 1002))); + + } + + @Test + public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { + Pageable pageRequest = PageRequest.of(0, 2); + + List result = productRepository.findAllByPrice(10, pageRequest); + + assertThat(result, hasSize(2)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1002, 1005) + .contains(id))); + } +} From dc46da61064f8bde322f1210790aee48875c0312 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:04:19 +0800 Subject: [PATCH 49/76] Update README.md --- spring-mvc-xml/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index 442a533d1b..3199118281 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -8,7 +8,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- [Spring MVC Tutorial](http://www.baeldung.com/spring-mvc-tutorial) - [Servlet Session Timeout](http://www.baeldung.com/servlet-session-timeout) - [Returning Image/Media Data with Spring MVC](http://www.baeldung.com/spring-mvc-image-media-data) - [Geolocation by IP in Java](http://www.baeldung.com/geolocation-by-ip-with-maxmind) From 4b388e986ad0d76a440937bc4adc67dce0bde839 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:05:17 +0800 Subject: [PATCH 50/76] Update README.md --- deeplearning4j/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deeplearning4j/README.md b/deeplearning4j/README.md index 7f9c92ec73..14e585cd97 100644 --- a/deeplearning4j/README.md +++ b/deeplearning4j/README.md @@ -2,4 +2,4 @@ This is a sample project for the [deeplearning4j](https://deeplearning4j.org) library. ### Relevant Articles: -- [A Guide to deeplearning4j](http://www.baeldung.com/deeplearning4j) +- [A Guide to Deeplearning4j](http://www.baeldung.com/deeplearning4j) From a7d6bb8e09738c5b11d3c2902e814d1243af1500 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:06:10 +0800 Subject: [PATCH 51/76] Update README.md --- persistence-modules/spring-hibernate-5/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index b4d73708c3..75d23f7532 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -1,6 +1,6 @@ ### Relevant articles -- [Guide to @Immutable Annotation in Hibernate](http://www.baeldung.com/hibernate-immutable) +- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) - [Hibernate Many to Many Annotation Tutorial](http://www.baeldung.com/hibernate-many-to-many) - [Programmatic Transactions in the Spring TestContext Framework](http://www.baeldung.com/spring-test-programmatic-transactions) - [Hibernate Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) From 4ecc955bd44fc4da4a10d1fbe1c50ebf57503248 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:08:04 +0800 Subject: [PATCH 52/76] Update README.md --- spring-4/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-4/README.md b/spring-4/README.md index 4600a603ef..402557eb41 100644 --- a/spring-4/README.md +++ b/spring-4/README.md @@ -1,4 +1,3 @@ ### Relevant Articles: -- [Guide to Flips For Spring](http://www.baeldung.com/guide-to-flips-for-spring/) - [A Guide to Flips for Spring](http://www.baeldung.com/flips-spring) - [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) From 5ec6c03d94d4400de44aad85e7f14d35be0b7134 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:08:41 +0800 Subject: [PATCH 53/76] Update README.md --- flips/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/flips/README.md b/flips/README.md index 0c62173b6a..7d843af9ea 100644 --- a/flips/README.md +++ b/flips/README.md @@ -1,2 +1 @@ ### Relevant Articles: -- [Guide to Flips For Spring](http://www.baeldung.com/guide-to-flips-for-spring/) From ac7af751a63529de7ede59a8bcfa3d535929100e Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:11:31 +0800 Subject: [PATCH 54/76] Update README.md --- spring-security-rest/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-security-rest/README.md b/spring-security-rest/README.md index d9b6a760b2..e3124516ae 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -15,6 +15,5 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Spring Security Context Propagation with @Async](http://www.baeldung.com/spring-security-async-principal-propagation) - [Servlet 3 Async Support with Spring MVC and Spring Security](http://www.baeldung.com/spring-mvc-async-security) - [Intro to Spring Security Expressions](http://www.baeldung.com/spring-security-expressions) -- [Spring Security Expressions - hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) - [Error Handling for REST with Spring 3](http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/) - [Spring Security for a REST API](http://www.baeldung.com/securing-a-restful-web-service-with-spring-security) From cb055db7f6902a8153a1fd8cb6205c04ef39def2 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:12:54 +0800 Subject: [PATCH 55/76] Update README.md --- spring-rest-full/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index a5d72372f7..d429e17671 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -19,7 +19,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) - [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration) - [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring) - +- [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic) ### Build the Project From ac2ad2256ab6706dc8e1b1aa2dc676bbcc0af043 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:15:30 +0800 Subject: [PATCH 56/76] Update README.md --- spring-security-rest/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-rest/README.md b/spring-security-rest/README.md index e3124516ae..c396948a59 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -15,5 +15,5 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Spring Security Context Propagation with @Async](http://www.baeldung.com/spring-security-async-principal-propagation) - [Servlet 3 Async Support with Spring MVC and Spring Security](http://www.baeldung.com/spring-mvc-async-security) - [Intro to Spring Security Expressions](http://www.baeldung.com/spring-security-expressions) -- [Error Handling for REST with Spring 3](http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/) +- [Error Handling for REST with Spring](https://www.baeldung.com/exception-handling-for-rest-with-spring) - [Spring Security for a REST API](http://www.baeldung.com/securing-a-restful-web-service-with-spring-security) From c9539281107a0944aa553a3297dba93540f9a9f2 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:16:47 +0800 Subject: [PATCH 57/76] Update README.md --- spring-session/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-session/README.md b/spring-session/README.md index 30f70996cf..505d043e75 100644 --- a/spring-session/README.md +++ b/spring-session/README.md @@ -3,5 +3,5 @@ ## Spring Session Examples ### Relevant Articles: -- [Introduction to Spring Session](http://www.baeldung.com/spring-session) -- [Spring Session with JDBC](http://www.baeldung.com/spring-session-jdbc) +- [Guide to Spring Session](https://www.baeldung.com/spring-session) +- [Spring Session with JDBC](https://www.baeldung.com/spring-session-jdbc) From f74383407b6f3f332816a2c7da920f42b887a721 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:17:36 +0800 Subject: [PATCH 58/76] Update README.md --- core-java-concurrency/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-concurrency/README.md b/core-java-concurrency/README.md index 682c9b8ef0..2db7b91cde 100644 --- a/core-java-concurrency/README.md +++ b/core-java-concurrency/README.md @@ -26,7 +26,6 @@ - [ExecutorService - Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads) - [wait and notify() Methods in Java](http://www.baeldung.com/java-wait-notify) - [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule) -- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer) - [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle) - [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable) - [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield) From e117d81aa06a89b830bf10ab6f334ce1fdf7f759 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:18:38 +0800 Subject: [PATCH 59/76] Update README.md --- jhipster/jhipster-monolithic/README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/jhipster/jhipster-monolithic/README.md b/jhipster/jhipster-monolithic/README.md index d321e9e81e..a2c267b74d 100644 --- a/jhipster/jhipster-monolithic/README.md +++ b/jhipster/jhipster-monolithic/README.md @@ -1,7 +1,5 @@ ### Relevant articles -- [Intro to JHipster](http://www.baeldung.com/jhipster) - # baeldung This application was generated using JHipster 4.0.8, you can find documentation and help at [https://jhipster.github.io/documentation-archive/v4.0.8](https://jhipster.github.io/documentation-archive/v4.0.8). From d8290433f871749a6b086375b0c249e4c236d7f0 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:23:51 +0800 Subject: [PATCH 60/76] Update README.md --- persistence-modules/java-jdbi/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/persistence-modules/java-jdbi/README.md b/persistence-modules/java-jdbi/README.md index 3bab6faa29..7d843af9ea 100644 --- a/persistence-modules/java-jdbi/README.md +++ b/persistence-modules/java-jdbi/README.md @@ -1,2 +1 @@ ### Relevant Articles: -- [Guide to CockroachDB in Java](http://www.baeldung.com/cockroachdb-java) From 78d4c3d618776bb48f9bc122a6f7ef3fb0a913a1 Mon Sep 17 00:00:00 2001 From: charlesgonzales <39999268+charlesgonzales@users.noreply.github.com> Date: Sat, 15 Dec 2018 05:25:09 +0800 Subject: [PATCH 61/76] Update README.md --- persistence-modules/redis/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/persistence-modules/redis/README.md b/persistence-modules/redis/README.md index dd655ca7aa..21cd048693 100644 --- a/persistence-modules/redis/README.md +++ b/persistence-modules/redis/README.md @@ -1,5 +1,4 @@ ### Relevant Articles: - [Intro to Jedis – the Java Redis Client Library](http://www.baeldung.com/jedis-java-redis-client-library) - [A Guide to Redis with Redisson](http://www.baeldung.com/redis-redisson) -- [Intro to Lettuce – the Java Redis Client Library](http://www.baeldung.com/lettuce-java-redis-client-library) - +- [Introduction to Lettuce – the Java Redis Client](https://www.baeldung.com/java-redis-lettuce) From 6acf513fdbc447bd5e164802dcbdd483007cd620 Mon Sep 17 00:00:00 2001 From: rahusriv Date: Sat, 15 Dec 2018 09:36:42 +0530 Subject: [PATCH 62/76] Multidimentional ArrayList (#5795) * Multidimentional ArrayList * Adding code for 3-D ArrayList * Removing comment * Fixing indentation * Spellcheck --- .../ArrayListOfArrayList.java | 37 +++++++++++++++ .../ThreeDimensionalArrayList.java | 45 +++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 core-java-collections/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java create mode 100644 core-java-collections/src/main/java/com/baeldung/list/multidimensional/ThreeDimensionalArrayList.java diff --git a/core-java-collections/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java b/core-java-collections/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java new file mode 100644 index 0000000000..72045d6761 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/list/multidimensional/ArrayListOfArrayList.java @@ -0,0 +1,37 @@ +package com.baeldung.list.multidimensional; + +import java.util.ArrayList; + +public class ArrayListOfArrayList { + + public static void main(String args[]) { + + int vertex = 5; + ArrayList> graph = new ArrayList<>(vertex); + + //Initializing each element of ArrayList with ArrayList + for(int i=0; i< vertex; i++) { + graph.add(new ArrayList()); + } + + //We can add any number of columns to each row + graph.get(0).add(1); + graph.get(0).add(5); + graph.get(1).add(0); + graph.get(1).add(2); + graph.get(2).add(1); + graph.get(2).add(3); + graph.get(3).add(2); + graph.get(3).add(4); + graph.get(4).add(3); + graph.get(4).add(5); + + //Printing all the edges + for(int i=0; i > > space = new ArrayList<>(x_axis_length); + + //Initializing each element of ArrayList with ArrayList< ArrayList > + for(int i=0; i< x_axis_length; i++) { + space.add(new ArrayList< ArrayList >(y_axis_length)); + for(int j =0; j< y_axis_length; j++) { + space.get(i).add(new ArrayList(z_axis_length)); + } + } + + //Set Red color for points (0,0,0) and (0,0,1) + space.get(0).get(0).add("Red"); + space.get(0).get(0).add("Red"); + //Set Blue color for points (0,1,0) and (0,1,1) + space.get(0).get(1).add("Blue"); + space.get(0).get(1).add("Blue"); + //Set Green color for points (1,0,0) and (1,0,1) + space.get(1).get(0).add("Green"); + space.get(1).get(0).add("Green"); + //Set Yellow color for points (1,1,0) and (1,1,1) + space.get(1).get(1).add("Yellow"); + space.get(1).get(1).add("Yellow"); + + //Printing colors for all the points + for(int i=0; i Date: Sat, 15 Dec 2018 10:01:26 +0530 Subject: [PATCH 63/76] BAEL-2337: Moved code from java-strings to algorithm-miscellaneous-1 (#5905) --- .../com/baeldung/algorithms}/string/SubstringPalindrome.java | 2 +- .../algorithms}/string/SubstringPalindromeUnitTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename {java-strings/src/main/java/com/baeldung => algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms}/string/SubstringPalindrome.java (98%) rename {java-strings/src/test/java/com/baeldung => algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms}/string/SubstringPalindromeUnitTest.java (98%) diff --git a/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java similarity index 98% rename from java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java index 688bf43b3c..b3d142eb07 100644 --- a/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java +++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.algorithms.string; import java.util.HashSet; import java.util.Set; diff --git a/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java similarity index 98% rename from java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java index b18a8d4a5f..8d225f67fa 100644 --- a/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java +++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.algorithms.string; import static org.junit.Assert.assertEquals; import java.util.HashSet; From 0ab513eb1d634a1c34d4cf0821b1fd073a6da53d Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 15 Dec 2018 18:45:17 +0200 Subject: [PATCH 64/76] small fixes for BAEL-10845 --- spring-rest-template/.gitignore | 14 ---- spring-rest-template/README.md | 8 -- spring-rest-template/checkstyle.xml | 11 --- spring-rest-template/pom.xml | 83 ------------------- .../client/MultipartFileUploadClient.java | 62 -------------- .../src/main/resources/logback.xml | 13 --- spring-rest/README.md | 1 + spring-resttemplate/README.md | 3 +- ...pringDataWithSecurityIntegrationTest.java} | 2 +- 9 files changed, 4 insertions(+), 193 deletions(-) delete mode 100644 spring-rest-template/.gitignore delete mode 100644 spring-rest-template/README.md delete mode 100644 spring-rest-template/checkstyle.xml delete mode 100644 spring-rest-template/pom.xml delete mode 100644 spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java delete mode 100644 spring-rest-template/src/main/resources/logback.xml rename spring-security-mvc-boot/src/test/java/com/baeldung/relationships/{SpringDataWithSecurityUnitTest.java => SpringDataWithSecurityIntegrationTest.java} (98%) diff --git a/spring-rest-template/.gitignore b/spring-rest-template/.gitignore deleted file mode 100644 index afdfaa6ded..0000000000 --- a/spring-rest-template/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* -*/.idea/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/spring-rest-template/README.md b/spring-rest-template/README.md deleted file mode 100644 index 2c31796080..0000000000 --- a/spring-rest-template/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Spring REST Template Example Project - -### The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles: -- [Uploading MultipartFile with Spring RestTemplate](http://www.baeldung.com/spring-rest-template-multipart-upload) -- [Mocking a RestTemplate in Spring](https://www.baeldung.com/spring-mock-rest-template) diff --git a/spring-rest-template/checkstyle.xml b/spring-rest-template/checkstyle.xml deleted file mode 100644 index 85063a7570..0000000000 --- a/spring-rest-template/checkstyle.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/spring-rest-template/pom.xml b/spring-rest-template/pom.xml deleted file mode 100644 index fa93308cf5..0000000000 --- a/spring-rest-template/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - 4.0.0 - com.baeldung - spring-rest-template - 0.1-SNAPSHOT - spring-rest-template - jar - - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - - - org.springframework - spring-web - - - commons-logging - commons-logging - - - - - - - spring-rest-template - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${checkstyle-maven-plugin.version} - - checkstyle.xml - - - - - check - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - **/*LongRunningUnitTest.java - **/*ManualTest.java - **/*LiveTest.java - - - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${checkstyle-maven-plugin.version} - - checkstyle.xml - - - - - - - - 3.0.0 - - diff --git a/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java b/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java deleted file mode 100644 index 804013d4dc..0000000000 --- a/spring-rest-template/src/main/java/com/baeldung/web/upload/client/MultipartFileUploadClient.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.web.upload.client; - -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.client.RestTemplate; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; - -public class MultipartFileUploadClient { - - public static void main(String[] args) throws IOException { - uploadSingleFile(); - uploadMultipleFile(); - } - - private static void uploadSingleFile() throws IOException { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - - MultiValueMap body = new LinkedMultiValueMap<>(); - body.add("file", getTestFile()); - - - HttpEntity> requestEntity = new HttpEntity<>(body, headers); - String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/"; - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); - System.out.println("Response code: " + response.getStatusCode()); - } - - private static void uploadMultipleFile() throws IOException { - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - - MultiValueMap body = new LinkedMultiValueMap<>(); - body.add("files", getTestFile()); - body.add("files", getTestFile()); - body.add("files", getTestFile()); - - HttpEntity> requestEntity = new HttpEntity<>(body, headers); - String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/"; - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity response = restTemplate.postForEntity(serverUrl, requestEntity, String.class); - System.out.println("Response code: " + response.getStatusCode()); - } - - public static Resource getTestFile() throws IOException { - Path testFile = Files.createTempFile("test-file", ".txt"); - System.out.println("Creating and Uploading Test File: " + testFile); - Files.write(testFile, "Hello World !!, This is a test file.".getBytes()); - return new FileSystemResource(testFile.toFile()); - } - -} diff --git a/spring-rest-template/src/main/resources/logback.xml b/spring-rest-template/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-rest-template/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-rest/README.md b/spring-rest/README.md index 5b8a35a4a5..efa0dbab60 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -24,3 +24,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Get and Post Lists of Objects with RestTemplate](http://www.baeldung.com/spring-rest-template-list) - [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) - [Spring’s RequestBody and ResponseBody Annotations](https://www.baeldung.com/spring-request-response-body) +- [Uploading MultipartFile with Spring RestTemplate](http://www.baeldung.com/spring-rest-template-multipart-upload) diff --git a/spring-resttemplate/README.md b/spring-resttemplate/README.md index bf8c56e6ec..1c8ddf73f9 100644 --- a/spring-resttemplate/README.md +++ b/spring-resttemplate/README.md @@ -7,4 +7,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template) - [Exploring the Spring Boot TestRestTemplate](http://www.baeldung.com/spring-boot-testresttemplate) - [Spring RestTemplate Error Handling](http://www.baeldung.com/spring-rest-template-error-handling) -- [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) \ No newline at end of file +- [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) +- [Mocking a RestTemplate in Spring](https://www.baeldung.com/spring-mock-rest-template) diff --git a/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityUnitTest.java b/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java similarity index 98% rename from spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityUnitTest.java rename to spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java index 8207363a70..bd0c14ca1f 100644 --- a/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityUnitTest.java +++ b/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java @@ -36,7 +36,7 @@ import com.baeldung.util.DummyContentUtil; @WebAppConfiguration @ContextConfiguration @DirtiesContext -public class SpringDataWithSecurityUnitTest { +public class SpringDataWithSecurityIntegrationTest { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); @Autowired private ServletContext servletContext; From 7ae533c5eea6eef7860ee3cb358554e6f53c0d90 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 15 Dec 2018 18:49:49 +0200 Subject: [PATCH 65/76] fix main pom --- pom.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/pom.xml b/pom.xml index bab3fc2317..8705321be1 100644 --- a/pom.xml +++ b/pom.xml @@ -700,7 +700,6 @@ spring-rest-query-language spring-rest-shell spring-rest-simple - spring-rest-template spring-resttemplate spring-roo @@ -1407,7 +1406,6 @@ spring-rest-query-language spring-rest-shell spring-rest-simple - spring-rest-template spring-resttemplate spring-roo From 432643f115a4682c290ecd07b125e7b5c6045779 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 15 Dec 2018 18:59:23 +0200 Subject: [PATCH 66/76] remove flips module --- flips/README.md | 1 - flips/pom.xml | 65 ---------------- .../com/baeldung/flips/ApplicationConfig.java | 15 ---- .../flips/controller/FlipController.java | 65 ---------------- .../java/com/baeldung/flips/model/Foo.java | 12 --- .../baeldung/flips/service/FlipService.java | 50 ------------- .../flips/service/NewFlipService.java | 13 ---- .../src/main/resources/application.properties | 5 -- flips/src/main/resources/logback.xml | 13 ---- .../FlipControllerIntegrationTest.java | 74 ------------------- pom.xml | 2 - 11 files changed, 315 deletions(-) delete mode 100644 flips/README.md delete mode 100644 flips/pom.xml delete mode 100644 flips/src/main/java/com/baeldung/flips/ApplicationConfig.java delete mode 100644 flips/src/main/java/com/baeldung/flips/controller/FlipController.java delete mode 100644 flips/src/main/java/com/baeldung/flips/model/Foo.java delete mode 100644 flips/src/main/java/com/baeldung/flips/service/FlipService.java delete mode 100644 flips/src/main/java/com/baeldung/flips/service/NewFlipService.java delete mode 100644 flips/src/main/resources/application.properties delete mode 100644 flips/src/main/resources/logback.xml delete mode 100644 flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java diff --git a/flips/README.md b/flips/README.md deleted file mode 100644 index 7d843af9ea..0000000000 --- a/flips/README.md +++ /dev/null @@ -1 +0,0 @@ -### Relevant Articles: diff --git a/flips/pom.xml b/flips/pom.xml deleted file mode 100644 index 75dc8bb579..0000000000 --- a/flips/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - 4.0.0 - flips - flips - 0.0.1-SNAPSHOT - jar - flips - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter-web - ${spring-boot-starter-web.version} - - - org.springframework.boot - spring-boot-starter-test - ${spring-boot-starter-test.version} - - - com.github.feature-flip - flips-web - ${flips-web.version} - - - org.projectlombok - lombok - - ${lombok.version} - provided - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - - - - - - - 1.5.10.RELEASE - 1.5.9.RELEASE - 1.0.1 - 1.16.18 - - - diff --git a/flips/src/main/java/com/baeldung/flips/ApplicationConfig.java b/flips/src/main/java/com/baeldung/flips/ApplicationConfig.java deleted file mode 100644 index 7001aeb991..0000000000 --- a/flips/src/main/java/com/baeldung/flips/ApplicationConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.flips; - -import org.flips.describe.config.FlipWebContextConfiguration; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Import; - -@SpringBootApplication -@Import(FlipWebContextConfiguration.class) -public class ApplicationConfig { - - public static void main(String[] args) { - SpringApplication.run(ApplicationConfig.class, args); - } -} \ No newline at end of file diff --git a/flips/src/main/java/com/baeldung/flips/controller/FlipController.java b/flips/src/main/java/com/baeldung/flips/controller/FlipController.java deleted file mode 100644 index 50458023b3..0000000000 --- a/flips/src/main/java/com/baeldung/flips/controller/FlipController.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.baeldung.flips.controller; - -import com.baeldung.flips.model.Foo; -import com.baeldung.flips.service.FlipService; -import org.flips.annotation.FlipOnDateTime; -import org.flips.annotation.FlipOnDaysOfWeek; -import org.flips.annotation.FlipOnEnvironmentProperty; -import org.flips.annotation.FlipOnProfiles; -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.RestController; - -import java.time.DayOfWeek; -import java.util.List; - -@RestController -public class FlipController { - - private FlipService flipService; - - @Autowired - public FlipController(FlipService flipService) { - this.flipService = flipService; - } - - @RequestMapping(value = "/foos", method = RequestMethod.GET) - @FlipOnProfiles(activeProfiles = "dev") - public List getAllFoos() { - return flipService.getAllFoos(); - } - - @RequestMapping(value = "/foo/{id}", method = RequestMethod.GET) - @FlipOnDaysOfWeek(daysOfWeek = { - DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, - DayOfWeek.FRIDAY, DayOfWeek.SATURDAY, DayOfWeek.SUNDAY - }) - public Foo getFooByNewId(@PathVariable int id) { - return flipService.getFooById(id).orElse(new Foo("Not Found", -1)); - } - - @RequestMapping(value = "/foo/last", method = RequestMethod.GET) - @FlipOnDateTime(cutoffDateTimeProperty = "last.active.after") - public Foo getLastFoo() { - return flipService.getLastFoo(); - } - - @RequestMapping(value = "/foo/first", method = RequestMethod.GET) - @FlipOnDateTime(cutoffDateTimeProperty = "first.active.after") - public Foo getFirstFoo() { - return flipService.getLastFoo(); - } - - @RequestMapping(value = "/foos/{id}", method = RequestMethod.GET) - @FlipOnEnvironmentProperty(property = "feature.foo.by.id", expectedValue = "Y") - public Foo getFooById(@PathVariable int id) { - return flipService.getFooById(id).orElse(new Foo("Not Found", -1)); - } - - @RequestMapping(value = "/foo/new", method = RequestMethod.GET) - public Foo getNewThing() { - return flipService.getNewFoo(); - } -} \ No newline at end of file diff --git a/flips/src/main/java/com/baeldung/flips/model/Foo.java b/flips/src/main/java/com/baeldung/flips/model/Foo.java deleted file mode 100644 index be15bee15c..0000000000 --- a/flips/src/main/java/com/baeldung/flips/model/Foo.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.flips.model; - -import lombok.Data; -import lombok.NonNull; -import lombok.RequiredArgsConstructor; - -@Data -@RequiredArgsConstructor -public class Foo { - @NonNull private final String name; - @NonNull private final int id; -} diff --git a/flips/src/main/java/com/baeldung/flips/service/FlipService.java b/flips/src/main/java/com/baeldung/flips/service/FlipService.java deleted file mode 100644 index 9f7fb325a5..0000000000 --- a/flips/src/main/java/com/baeldung/flips/service/FlipService.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.flips.service; - -import com.baeldung.flips.model.Foo; -import org.flips.annotation.FlipBean; -import org.flips.annotation.FlipOnSpringExpression; -import org.springframework.stereotype.Service; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -@Service -public class FlipService { - - private final List foos; - - public FlipService() { - foos = new ArrayList<>(); - foos.add(new Foo("Foo1", 1)); - foos.add(new Foo("Foo2", 2)); - foos.add(new Foo("Foo3", 3)); - foos.add(new Foo("Foo4", 4)); - foos.add(new Foo("Foo5", 5)); - foos.add(new Foo("Foo6", 6)); - - } - - public List getAllFoos() { - return foos; - } - - public Optional getFooById(int id) { - return foos.stream().filter(foo -> (foo.getId() == id)).findFirst(); - } - - @FlipBean(with = NewFlipService.class) - @FlipOnSpringExpression(expression = "(2 + 2) == 4") - public Foo getNewFoo() { - return new Foo("New Foo!", 99); - } - - public Foo getLastFoo() { - return foos.get(foos.size() - 1); - } - - public Foo getFirstFoo() { - return foos.get(0); - } - -} \ No newline at end of file diff --git a/flips/src/main/java/com/baeldung/flips/service/NewFlipService.java b/flips/src/main/java/com/baeldung/flips/service/NewFlipService.java deleted file mode 100644 index 1dcda9b6ca..0000000000 --- a/flips/src/main/java/com/baeldung/flips/service/NewFlipService.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.flips.service; - -import com.baeldung.flips.model.Foo; -import org.springframework.stereotype.Service; - -@Service -public class NewFlipService { - - public Foo getNewFoo() { - return new Foo("Shiny New Foo!", 100); - } - -} \ No newline at end of file diff --git a/flips/src/main/resources/application.properties b/flips/src/main/resources/application.properties deleted file mode 100644 index 274896be15..0000000000 --- a/flips/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -feature.foo.by.id=Y -feature.new.foo=Y -last.active.after=2018-03-14T00:00:00Z -first.active.after=2999-03-15T00:00:00Z -logging.level.org.flips=info \ No newline at end of file diff --git a/flips/src/main/resources/logback.xml b/flips/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/flips/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java b/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java deleted file mode 100644 index 9dd4ef064a..0000000000 --- a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.flips.controller; - -import org.hamcrest.Matchers; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; - -@RunWith(SpringRunner.class) -@SpringBootTest(properties = { - "feature.foo.by.id=Y", - "feature.new.foo=Y", - "last.active.after=2018-03-14T00:00:00Z", - "first.active.after=2999-03-15T00:00:00Z", - "logging.level.org.flips=info" - -}, webEnvironment = SpringBootTest.WebEnvironment.MOCK) -@AutoConfigureMockMvc -@ActiveProfiles("dev") -public class FlipControllerIntegrationTest { - - @Autowired private MockMvc mvc; - - @Test - public void givenValidDayOfWeek_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/1")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); - } - - @Test - public void givenValidDate_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/last")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo6"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(6))); - } - - @Test - public void givenInvalidDate_APINotAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/first")) - .andExpect(MockMvcResultMatchers.status().is(501)); - } - - @Test - public void givenCorrectProfile_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foos")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(6))); - } - - @Test - public void givenPropertySet_APIAvailable() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foos/1")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Foo1"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(1))); - } - - @Test - public void getValidExpression_FlipBean() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/foo/new")) - .andExpect(MockMvcResultMatchers.status().is(200)) - .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo("Shiny New Foo!"))) - .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(100))); - } -} \ No newline at end of file diff --git a/pom.xml b/pom.xml index bab3fc2317..643496e482 100644 --- a/pom.xml +++ b/pom.xml @@ -397,7 +397,6 @@ ethereum feign - flips flyway-cdi-extension @@ -1108,7 +1107,6 @@ ethereum feign - flips flyway-cdi-extension From 9271f1094181278deb536dbbf6e01fabd220acfc Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Sat, 15 Dec 2018 22:40:55 +0530 Subject: [PATCH 67/76] Adding files for the tutorial BAEL-1877: A Guide to Hibernate OGM (#5909) * Adding files for the tutorial BAEL-1877: A Guide to Hibernate OGM * Removing test for MongoDB as there may not be MongoDB running on integration platform. * Reapplied the standard Java formatter. * Incorporatd the review comments on the tutorial. * Commented out the integration test for MongoDB. * Removed implicit dependencies from pom.xml --- persistence-modules/hibernate-ogm/README.md | 4 + persistence-modules/hibernate-ogm/pom.xml | 60 ++++++++++++ .../com/baeldung/hibernate/ogm/Article.java | 54 +++++++++++ .../com/baeldung/hibernate/ogm/Author.java | 70 ++++++++++++++ .../com/baeldung/hibernate/ogm/Editor.java | 58 ++++++++++++ .../main/resources/META-INF/persistence.xml | 24 +++++ .../hibernate/ogm/EditorUnitTest.java | 92 +++++++++++++++++++ pom.xml | 2 + 8 files changed, 364 insertions(+) create mode 100644 persistence-modules/hibernate-ogm/README.md create mode 100644 persistence-modules/hibernate-ogm/pom.xml create mode 100644 persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Article.java create mode 100644 persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Author.java create mode 100644 persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java create mode 100644 persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml create mode 100644 persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java diff --git a/persistence-modules/hibernate-ogm/README.md b/persistence-modules/hibernate-ogm/README.md new file mode 100644 index 0000000000..f4a5bb6c3b --- /dev/null +++ b/persistence-modules/hibernate-ogm/README.md @@ -0,0 +1,4 @@ +## Relevant articles: + +- [Guide to Hibernate OGM](http://www.baeldung.com/xxxx) + diff --git a/persistence-modules/hibernate-ogm/pom.xml b/persistence-modules/hibernate-ogm/pom.xml new file mode 100644 index 0000000000..2ccac03bd3 --- /dev/null +++ b/persistence-modules/hibernate-ogm/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + com.baeldung + hibernate-ogm + 0.0.1-SNAPSHOT + hibernate-ogm + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + + org.hibernate.ogm + hibernate-ogm-mongodb + 5.4.0.Final + + + + org.hibernate.ogm + hibernate-ogm-neo4j + 5.4.0.Final + + + + org.jboss.narayana.jta + narayana-jta + 5.5.23.Final + + + + junit + junit + 4.12 + test + + + org.easytesting + fest-assert + 1.4 + test + + + + + hibernate-ogm + + + src/main/resources + true + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Article.java b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Article.java new file mode 100644 index 0000000000..29f01ecde7 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Article.java @@ -0,0 +1,54 @@ +package com.baeldung.hibernate.ogm; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Article { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + private String articleId; + + private String articleTitle; + + @ManyToOne + private Author author; + + // constructors, getters and setters... + + Article() { + } + + public Article(String articleTitle) { + this.articleTitle = articleTitle; + } + + public String getArticleId() { + return articleId; + } + + public void setArticleId(String articleId) { + this.articleId = articleId; + } + + public String getArticleTitle() { + return articleTitle; + } + + public void setArticleTitle(String articleTitle) { + this.articleTitle = articleTitle; + } + + public Author getAuthor() { + return author; + } + + public void setAuthor(Author author) { + this.author = author; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Author.java b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Author.java new file mode 100644 index 0000000000..9e60c9f934 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Author.java @@ -0,0 +1,70 @@ +package com.baeldung.hibernate.ogm; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Author { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + private String authorId; + + private String authorName; + + @ManyToOne + private Editor editor; + + @OneToMany(mappedBy = "author", cascade = CascadeType.PERSIST) + private Set
authoredArticles = new HashSet<>(); + + // constructors, getters and setters... + + Author() { + } + + public Author(String authorName) { + this.authorName = authorName; + } + + public String getAuthorId() { + return authorId; + } + + public void setAuthorId(String authorId) { + this.authorId = authorId; + } + + public String getAuthorName() { + return authorName; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public Editor getEditor() { + return editor; + } + + public void setEditor(Editor editor) { + this.editor = editor; + } + + public Set
getAuthoredArticles() { + return authoredArticles; + } + + public void setAuthoredArticles(Set
authoredArticles) { + this.authoredArticles = authoredArticles; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java new file mode 100644 index 0000000000..2c3f720e91 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/java/com/baeldung/hibernate/ogm/Editor.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.ogm; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +import org.hibernate.annotations.GenericGenerator; + +@Entity +public class Editor { + @Id + @GeneratedValue(generator = "uuid") + @GenericGenerator(name = "uuid", strategy = "uuid2") + private String editorId; + + private String editorName; + + @OneToMany(mappedBy = "editor", cascade = CascadeType.PERSIST) + private Set assignedAuthors = new HashSet<>(); + + // constructors, getters and setters... + + Editor() { + } + + public Editor(String editorName) { + this.editorName = editorName; + } + + public String getEditorId() { + return editorId; + } + + public void setEditorId(String editorId) { + this.editorId = editorId; + } + + public String getEditorName() { + return editorName; + } + + public void setEditorName(String editorName) { + this.editorName = editorName; + } + + public Set getAssignedAuthors() { + return assignedAuthors; + } + + public void setAssignedAuthors(Set assignedAuthors) { + this.assignedAuthors = assignedAuthors; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..43c86fb55b --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,24 @@ + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + + + + + + + + + org.hibernate.ogm.jpa.HibernateOgmPersistence + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java new file mode 100644 index 0000000000..d7fd49d917 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.hibernate.ogm; + +import static org.fest.assertions.Assertions.assertThat; + +import java.util.Map; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.transaction.TransactionManager; + +import org.junit.Test; + +public class EditorUnitTest { + /* + @Test + public void givenMongoDB_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { + EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-mongodb"); + Editor editor = generateTestData(); + persistTestData(entityManagerFactory, editor); + loadAndVerifyTestData(entityManagerFactory, editor); + } + */ + @Test + public void givenNeo4j_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { + EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-neo4j"); + Editor editor = generateTestData(); + persistTestData(entityManagerFactory, editor); + loadAndVerifyTestData(entityManagerFactory, editor); + } + + private void persistTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { + TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); + EntityManager entityManager; + + transactionManager.begin(); + entityManager = entityManagerFactory.createEntityManager(); + entityManager.persist(editor); + entityManager.close(); + transactionManager.commit(); + } + + private void loadAndVerifyTestData(EntityManagerFactory entityManagerFactory, Editor editor) throws Exception { + TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager(); + EntityManager entityManager; + + transactionManager.begin(); + entityManager = entityManagerFactory.createEntityManager(); + Editor loadedEditor = entityManager.find(Editor.class, editor.getEditorId()); + assertThat(loadedEditor).isNotNull(); + assertThat(loadedEditor.getEditorName()).isEqualTo("Tom"); + assertThat(loadedEditor.getAssignedAuthors()).onProperty("authorName") + .containsOnly("Maria", "Mike"); + Map loadedAuthors = loadedEditor.getAssignedAuthors() + .stream() + .collect(Collectors.toMap(Author::getAuthorName, e -> e)); + assertThat(loadedAuthors.get("Maria") + .getAuthoredArticles()).onProperty("articleTitle") + .containsOnly("Basic of Hibernate OGM"); + assertThat(loadedAuthors.get("Mike") + .getAuthoredArticles()).onProperty("articleTitle") + .containsOnly("Intermediate of Hibernate OGM", "Advanced of Hibernate OGM"); + entityManager.close(); + transactionManager.commit(); + } + + private Editor generateTestData() { + Editor tom = new Editor("Tom"); + Author maria = new Author("Maria"); + Author mike = new Author("Mike"); + Article basic = new Article("Basic of Hibernate OGM"); + Article intermediate = new Article("Intermediate of Hibernate OGM"); + Article advanced = new Article("Advanced of Hibernate OGM"); + maria.getAuthoredArticles() + .add(basic); + basic.setAuthor(maria); + mike.getAuthoredArticles() + .add(intermediate); + intermediate.setAuthor(mike); + mike.getAuthoredArticles() + .add(advanced); + advanced.setAuthor(mike); + tom.getAssignedAuthors() + .add(maria); + maria.setEditor(tom); + tom.getAssignedAuthors() + .add(mike); + mike.setEditor(tom); + return tom; + } +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index bab3fc2317..f1005c7053 100644 --- a/pom.xml +++ b/pom.xml @@ -509,6 +509,7 @@ persistence-modules/flyway persistence-modules/hbase persistence-modules/hibernate5 + persistence-modules/hibernate-ogm persistence-modules/influxdb persistence-modules/java-cassandra persistence-modules/java-cockroachdb @@ -1220,6 +1221,7 @@ persistence-modules/flyway persistence-modules/hbase persistence-modules/hibernate5 + persistence-modules/hibernate-ogm persistence-modules/influxdb persistence-modules/java-cassandra persistence-modules/java-cockroachdb From 94f40923141cf6481e810a38483f6b83bfee43f7 Mon Sep 17 00:00:00 2001 From: kyleandari <44148335+kyleandari@users.noreply.github.com> Date: Sat, 15 Dec 2018 17:35:09 -0500 Subject: [PATCH 68/76] BAEL-2431 Implementing multi-inheritance and Polymorphism using interfaces (#5924) * Implementing Hexagonal Architecture in java * Implementing multi-inheritance and Polymorphism using interfaces * Removing hexagonal code * Deleting hexagonal architecture code * fix for unit test names --- .../interfaces/multiinheritance/Fly.java | 5 ++++ .../multiinheritance/Transform.java | 5 ++++ .../interfaces/multiinheritance/Vehicle.java | 13 ++++++++++ .../interfaces/polymorphysim/Circle.java | 21 +++++++++++++++ .../polymorphysim/DisplayShape.java | 22 ++++++++++++++++ .../polymorphysim/MainPolymorphic.java | 15 +++++++++++ .../interfaces/polymorphysim/Shape.java | 6 +++++ .../interfaces/polymorphysim/Square.java | 20 ++++++++++++++ .../interfaces/PolymorphysimUnitTest.java | 26 +++++++++++++++++++ 9 files changed, 133 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java create mode 100644 core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java create mode 100644 core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java create mode 100644 core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java create mode 100644 core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/DisplayShape.java create mode 100644 core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/MainPolymorphic.java create mode 100644 core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java create mode 100644 core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java create mode 100644 core-java-8/src/test/java/com/baeldung/interfaces/PolymorphysimUnitTest.java diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java new file mode 100644 index 0000000000..d84182aec6 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Fly.java @@ -0,0 +1,5 @@ +package com.baeldung.interfaces.multiinheritance; + +public abstract interface Fly{ + void fly(); +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java new file mode 100644 index 0000000000..a18bbafdc1 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Transform.java @@ -0,0 +1,5 @@ +package com.baeldung.interfaces.multiinheritance; + +public interface Transform { + void transform(); +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java new file mode 100644 index 0000000000..fb0d36e3e0 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/multiinheritance/Vehicle.java @@ -0,0 +1,13 @@ +package com.baeldung.interfaces.multiinheritance; + +public class Vehicle implements Fly, Transform { + @Override + public void fly() { + System.out.println("I can Fly!!"); + } + + @Override + public void transform() { + System.out.println("I can Transform!!"); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java new file mode 100644 index 0000000000..bf0e613567 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Circle.java @@ -0,0 +1,21 @@ +package com.baeldung.interfaces.polymorphysim; + +public class Circle implements Shape { + + private double radius; + + public Circle(double radius){ + this.radius = radius; + } + + @Override + public String name() { + return "Circle"; + } + + @Override + public double area() { + return Math.PI * (radius * radius); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/DisplayShape.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/DisplayShape.java new file mode 100644 index 0000000000..2cf4fafee1 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/DisplayShape.java @@ -0,0 +1,22 @@ +package com.baeldung.interfaces.polymorphysim; + +import java.util.ArrayList; + +public class DisplayShape { + + private ArrayList shapes; + + public DisplayShape() { + shapes = new ArrayList<>(); + } + + public void add(Shape shape) { + shapes.add(shape); + } + + public void display() { + for (Shape shape : shapes) { + System.out.println(shape.name() + " area: " + shape.area()); + } + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/MainPolymorphic.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/MainPolymorphic.java new file mode 100644 index 0000000000..cc43c1300b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/MainPolymorphic.java @@ -0,0 +1,15 @@ +package com.baeldung.interfaces.polymorphysim; + +public class MainPolymorphic { + public static void main(String[] args){ + + Shape circleShape = new Circle(2); + Shape squareShape = new Square(2); + + DisplayShape displayShape = new DisplayShape(); + displayShape.add(circleShape); + displayShape.add(squareShape); + + displayShape.display(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java new file mode 100644 index 0000000000..fcb0c65e7b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Shape.java @@ -0,0 +1,6 @@ +package com.baeldung.interfaces.polymorphysim; + +public interface Shape { + public abstract String name(); + public abstract double area(); +} diff --git a/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java new file mode 100644 index 0000000000..9c440150b5 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/interfaces/polymorphysim/Square.java @@ -0,0 +1,20 @@ +package com.baeldung.interfaces.polymorphysim; + +public class Square implements Shape { + + private double width; + + public Square(double width) { + this.width = width; + } + + @Override + public String name() { + return "Square"; + } + + @Override + public double area() { + return width * width; + } +} diff --git a/core-java-8/src/test/java/com/baeldung/interfaces/PolymorphysimUnitTest.java b/core-java-8/src/test/java/com/baeldung/interfaces/PolymorphysimUnitTest.java new file mode 100644 index 0000000000..7ded5e6621 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/interfaces/PolymorphysimUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.interfaces; + +import com.baeldung.interfaces.polymorphysim.Circle; +import com.baeldung.interfaces.polymorphysim.Shape; +import com.baeldung.interfaces.polymorphysim.Square; +import org.assertj.core.api.Assertions; +import org.junit.Test; + +public class PolymorphysimUnitTest { + + @Test + public void whenInterfacePointsToCircle_CircleAreaMethodisBeingCalled(){ + double expectedArea = 12.566370614359172; + Shape circle = new Circle(2); + double actualArea = circle.area(); + Assertions.assertThat(actualArea).isEqualTo(expectedArea); + } + + @Test + public void whenInterfacePointsToSquare_SquareAreaMethodisBeingCalled(){ + double expectedArea = 4; + Shape square = new Square(2); + double actualArea = square.area(); + Assertions.assertThat(actualArea).isEqualTo(expectedArea); + } +} From 6ede1b74407483df1d29034de3fefef86a5b81a9 Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Sun, 16 Dec 2018 07:21:41 +0000 Subject: [PATCH 69/76] Kovert examples (#5831) --- core-kotlin/pom.xml | 11 +++ .../com/baeldung/kovert/AnnotatedServer.kt | 73 ++++++++++++++++++ .../kotlin/com/baeldung/kovert/ErrorServer.kt | 75 ++++++++++++++++++ .../kotlin/com/baeldung/kovert/JsonServer.kt | 76 +++++++++++++++++++ .../kotlin/com/baeldung/kovert/NoopServer.kt | 57 ++++++++++++++ .../com/baeldung/kovert/SecuredServer.kt | 68 +++++++++++++++++ .../com/baeldung/kovert/SimpleServer.kt | 65 ++++++++++++++++ core-kotlin/src/main/resources/kovert.conf | 15 ++++ 8 files changed, 440 insertions(+) create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt create mode 100644 core-kotlin/src/main/resources/kovert.conf diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index ed79ebc01b..8b871f28ee 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -72,6 +72,17 @@ injekt-core 1.16.1 + + uy.kohesive.kovert + kovert-vertx + [1.5.0,1.6.0) + + + nl.komponents.kovenant + kovenant + + + diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt new file mode 100644 index 0000000000..da2bbe4208 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt @@ -0,0 +1,73 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.core.HttpVerb +import uy.kohesive.kovert.core.Location +import uy.kohesive.kovert.core.Verb +import uy.kohesive.kovert.core.VerbAlias +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + + +class AnnotatedServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(AnnotatedServer::class.java) + + @JvmStatic + fun main(args: Array) { + AnnotatedServer().start() + } + } + + @VerbAlias("show", HttpVerb.GET) + class AnnotatedController { + fun RoutingContext.showStringById(id: String) = id + + @Verb(HttpVerb.GET) + @Location("/ping/:id") + fun RoutingContext.ping(id: String) = id + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", AnnotatedServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(AnnotatedController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt new file mode 100644 index 0000000000..a596391ed8 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt @@ -0,0 +1,75 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.core.HttpErrorCode +import uy.kohesive.kovert.core.HttpErrorCodeWithBody +import uy.kohesive.kovert.core.HttpErrorForbidden +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + + +class ErrorServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(ErrorServer::class.java) + + @JvmStatic + fun main(args: Array) { + ErrorServer().start() + } + } + + class ErrorController { + fun RoutingContext.getForbidden() { + throw HttpErrorForbidden() + } + fun RoutingContext.getError() { + throw HttpErrorCode("Something went wrong", 590) + } + fun RoutingContext.getErrorbody() { + throw HttpErrorCodeWithBody("Something went wrong", 591, "Body here") + } + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", ErrorServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(ErrorController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt new file mode 100644 index 0000000000..310fe2a7a0 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/JsonServer.kt @@ -0,0 +1,76 @@ +package com.baeldung.kovert + +import com.fasterxml.jackson.annotation.JsonProperty +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + +class JsonServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(JsonServer::class.java) + + @JvmStatic + fun main(args: Array) { + JsonServer().start() + } + } + + data class Person( + @JsonProperty("_id") + val id: String, + val name: String, + val job: String + ) + + class JsonController { + fun RoutingContext.getPersonById(id: String) = Person( + id = id, + name = "Tony Stark", + job = "Iron Man" + ) + fun RoutingContext.putPersonById(id: String, person: Person) = person + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", JsonServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(JsonController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt new file mode 100644 index 0000000000..98ce775e66 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/NoopServer.kt @@ -0,0 +1,57 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + +class NoopServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(NoopServer::class.java) + + @JvmStatic + fun main(args: Array) { + NoopServer().start() + } + } + + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", NoopServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt new file mode 100644 index 0000000000..86ca482808 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt @@ -0,0 +1,68 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + + +class SecuredServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(SecuredServer::class.java) + + @JvmStatic + fun main(args: Array) { + SecuredServer().start() + } + } + + class SecuredContext(private val routingContext: RoutingContext) { + val authenticated = routingContext.request().getHeader("Authorization") == "Secure" + } + + class SecuredController { + fun SecuredContext.getSecured() = this.authenticated + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", SecuredServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(SecuredController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt b/core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt new file mode 100644 index 0000000000..172469ab46 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt @@ -0,0 +1,65 @@ +package com.baeldung.kovert + +import io.vertx.ext.web.Router +import io.vertx.ext.web.RoutingContext +import nl.komponents.kovenant.functional.bind +import org.kodein.di.Kodein +import org.kodein.di.conf.global +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import uy.klutter.config.typesafe.ClassResourceConfig +import uy.klutter.config.typesafe.ReferenceConfig +import uy.klutter.config.typesafe.kodein.importConfig +import uy.klutter.config.typesafe.loadConfig +import uy.klutter.vertx.kodein.KodeinVertx +import uy.kohesive.kovert.vertx.bindController +import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx +import uy.kohesive.kovert.vertx.boot.KovertVerticle +import uy.kohesive.kovert.vertx.boot.KovertVerticleModule +import uy.kohesive.kovert.vertx.boot.KovertVertx + + +class SimpleServer { + companion object { + private val LOG: Logger = LoggerFactory.getLogger(SimpleServer::class.java) + + @JvmStatic + fun main(args: Array) { + SimpleServer().start() + } + } + + class SimpleController { + fun RoutingContext.getStringById(id: String) = id + fun RoutingContext.get_truncatedString_by_id(id: String, length: Int = 1) = id.subSequence(0, length) + } + + fun start() { + Kodein.global.addImport(Kodein.Module { + importConfig(loadConfig(ClassResourceConfig("/kovert.conf", SimpleServer::class.java), ReferenceConfig())) { + import("kovert.vertx", KodeinKovertVertx.configModule) + import("kovert.server", KovertVerticleModule.configModule) + } + + // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j + import(KodeinVertx.moduleWithLoggingToSlf4j) + // Kovert boot + import(KodeinKovertVertx.module) + import(KovertVerticleModule.module) + }) + + val initControllers = fun Router.() { + bindController(SimpleController(), "api") + } + + // startup asynchronously... + KovertVertx.start() bind { vertx -> + KovertVerticle.deploy(vertx, routerInit = initControllers) + } success { deploymentId -> + LOG.warn("Deployment complete.") + } fail { error -> + LOG.error("Deployment failed!", error) + } + + } +} diff --git a/core-kotlin/src/main/resources/kovert.conf b/core-kotlin/src/main/resources/kovert.conf new file mode 100644 index 0000000000..3b08641693 --- /dev/null +++ b/core-kotlin/src/main/resources/kovert.conf @@ -0,0 +1,15 @@ +{ + kovert: { + vertx: { + clustered: false + } + server: { + listeners: [ + { + host: "0.0.0.0" + port: "8000" + } + ] + } + } +} From 0f443d300683b64f9ca3c749a3bc6b02f2aaf8b8 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sun, 16 Dec 2018 14:54:35 +0530 Subject: [PATCH 70/76] Task/bael 10829 4 (#5925) * BAEL-10829 Commented out spring-data-elasticsearc * BAEL-10829 commented out spring-data-elasticsearch project * Revert "BAEL-10829 Commented out spring-data-elasticsearc" This reverts commit 84b7b4086435ac25a14841199145cc5d9e5c4beb. --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index fce724b907..f22aeea5e6 100644 --- a/pom.xml +++ b/pom.xml @@ -528,7 +528,7 @@ persistence-modules/spring-data-couchbase-2 persistence-modules/spring-data-dynamodb persistence-modules/spring-data-eclipselink - persistence-modules/spring-data-elasticsearch + persistence-modules/spring-data-gemfire persistence-modules/spring-data-jpa persistence-modules/spring-data-keyvalue @@ -1238,7 +1238,7 @@ persistence-modules/spring-data-couchbase-2 persistence-modules/spring-data-dynamodb persistence-modules/spring-data-eclipselink - persistence-modules/spring-data-elasticsearch + persistence-modules/spring-data-gemfire persistence-modules/spring-data-jpa persistence-modules/spring-data-keyvalue From b4e1d7779f29a46472034250a9929f1a203569c0 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 16 Dec 2018 12:48:55 +0200 Subject: [PATCH 71/76] Create README.md --- rsocket/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 rsocket/README.md diff --git a/rsocket/README.md b/rsocket/README.md new file mode 100644 index 0000000000..fa232bc515 --- /dev/null +++ b/rsocket/README.md @@ -0,0 +1,3 @@ +Relevant articles + +- [Introduction to RSocket](https://www.baeldung.com/rsocket) From d9ac59cd132f72af339fb0ff0036743e66378383 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 16 Dec 2018 16:37:45 +0530 Subject: [PATCH 72/76] [BAEL-10127] - Added code for modelmapper article --- spring-boot/pom.xml | 7 ++ .../baeldung/modelmapper/PostApplication.java | 20 ++++ .../controller/PostRestController.java | 91 +++++++++++++++++ .../com/baeldung/modelmapper/dto/PostDto.java | 71 ++++++++++++++ .../com/baeldung/modelmapper/dto/UserDto.java | 14 +++ .../com/baeldung/modelmapper/model/Post.java | 98 +++++++++++++++++++ .../modelmapper/model/Preference.java | 32 ++++++ .../com/baeldung/modelmapper/model/User.java | 44 +++++++++ .../repository/PostRepository.java | 21 ++++ .../modelmapper/service/IPostService.java | 17 ++++ .../modelmapper/service/IUserService.java | 9 ++ .../modelmapper/service/PostService.java | 47 +++++++++ .../modelmapper/service/UserService.java | 25 +++++ .../baeldung/modelmapper/PostDtoUnitTest.java | 40 ++++++++ 14 files changed, 536 insertions(+) create mode 100644 spring-boot/src/main/java/com/baeldung/modelmapper/PostApplication.java create mode 100644 spring-boot/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java create mode 100644 spring-boot/src/main/java/com/baeldung/modelmapper/dto/PostDto.java create mode 100644 spring-boot/src/main/java/com/baeldung/modelmapper/dto/UserDto.java create mode 100644 spring-boot/src/main/java/com/baeldung/modelmapper/model/Post.java create mode 100644 spring-boot/src/main/java/com/baeldung/modelmapper/model/Preference.java create mode 100644 spring-boot/src/main/java/com/baeldung/modelmapper/model/User.java create mode 100644 spring-boot/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java create mode 100644 spring-boot/src/main/java/com/baeldung/modelmapper/service/IPostService.java create mode 100644 spring-boot/src/main/java/com/baeldung/modelmapper/service/IUserService.java create mode 100644 spring-boot/src/main/java/com/baeldung/modelmapper/service/PostService.java create mode 100644 spring-boot/src/main/java/com/baeldung/modelmapper/service/UserService.java create mode 100644 spring-boot/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 87c782b044..e6866b5a8f 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -162,6 +162,12 @@ javax.validation validation-api + + + org.modelmapper + modelmapper + ${modelmapper.version} + @@ -259,6 +265,7 @@ 5.2.4 18.0 2.2.4 + 2.3.2 diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/PostApplication.java b/spring-boot/src/main/java/com/baeldung/modelmapper/PostApplication.java new file mode 100644 index 0000000000..7684c43648 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/PostApplication.java @@ -0,0 +1,20 @@ +package com.baeldung.modelmapper; + +import org.modelmapper.ModelMapper; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +public class PostApplication { + + public static void main(String[] args) { + SpringApplication.run(PostApplication.class, args); + } + + @Bean + public ModelMapper modelMapper() { + return new ModelMapper(); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java b/spring-boot/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java new file mode 100644 index 0000000000..c0cbca5220 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/controller/PostRestController.java @@ -0,0 +1,91 @@ +package com.baeldung.modelmapper.controller; + +import java.text.ParseException; +import java.util.List; +import java.util.stream.Collectors; + +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +import com.baeldung.modelmapper.dto.PostDto; +import com.baeldung.modelmapper.model.Post; +import com.baeldung.modelmapper.service.IPostService; +import com.baeldung.modelmapper.service.IUserService; + +@Controller +public class PostRestController { + + @Autowired + private IPostService postService; + + @Autowired + private IUserService userService; + + @Autowired + private ModelMapper modelMapper; + + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public List getPosts( + @PathVariable("page") int page, + @PathVariable("size") int size, + @PathVariable("sortDir") String sortDir, + @PathVariable("sort") String sort) { + + List posts = postService.getPostsList(page, size, sortDir, sort); + return posts.stream() + .map(post -> convertToDto(post)) + .collect(Collectors.toList()); + } + + @RequestMapping(method = RequestMethod.POST) + @ResponseStatus(HttpStatus.CREATED) + @ResponseBody + public PostDto createPost(@RequestBody PostDto postDto) throws ParseException { + Post post = convertToEntity(postDto); + Post postCreated = postService.createPost(post); + return convertToDto(postCreated); + } + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + public PostDto getPost(@PathVariable("id") Long id) { + return convertToDto(postService.getPostById(id)); + } + + @RequestMapping(value = "/{id}", method = RequestMethod.PUT) + @ResponseStatus(HttpStatus.OK) + public void updatePost(@RequestBody PostDto postDto) throws ParseException { + Post post = convertToEntity(postDto); + postService.updatePost(post); + } + + + private PostDto convertToDto(Post post) { + PostDto postDto = modelMapper.map(post, PostDto.class); + postDto.setSubmissionDate(post.getSubmissionDate(), + userService.getCurrentUser().getPreference().getTimezone()); + return postDto; + } + + private Post convertToEntity(PostDto postDto) throws ParseException { + Post post = modelMapper.map(postDto, Post.class); + post.setSubmissionDate(postDto.getSubmissionDateConverted( + userService.getCurrentUser().getPreference().getTimezone())); + + if (postDto.getId() != null) { + Post oldPost = postService.getPostById(postDto.getId()); + post.setRedditID(oldPost.getRedditID()); + post.setSent(oldPost.isSent()); + } + return post; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/dto/PostDto.java b/spring-boot/src/main/java/com/baeldung/modelmapper/dto/PostDto.java new file mode 100644 index 0000000000..6fe2b23888 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/dto/PostDto.java @@ -0,0 +1,71 @@ +package com.baeldung.modelmapper.dto; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +public class PostDto { + + private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + + private Long id; + + private String title; + + private String url; + + private String date; + + private UserDto user; + + public Date getSubmissionDateConverted(String timezone) throws ParseException { + dateFormat.setTimeZone(TimeZone.getTimeZone(timezone)); + return dateFormat.parse(this.date); + } + + public void setSubmissionDate(Date date, String timezone) { + dateFormat.setTimeZone(TimeZone.getTimeZone(timezone)); + this.date = dateFormat.format(date); + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public UserDto getUser() { + return user; + } + + public void setUser(UserDto user) { + this.user = user; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/dto/UserDto.java b/spring-boot/src/main/java/com/baeldung/modelmapper/dto/UserDto.java new file mode 100644 index 0000000000..23110ecbaa --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/dto/UserDto.java @@ -0,0 +1,14 @@ +package com.baeldung.modelmapper.dto; + +public class UserDto { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/model/Post.java b/spring-boot/src/main/java/com/baeldung/modelmapper/model/Post.java new file mode 100644 index 0000000000..be65ce34a2 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/model/Post.java @@ -0,0 +1,98 @@ +package com.baeldung.modelmapper.model; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Post { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String title; + + private String url; + + private String date; + + private String redditID; + + private Date submissionDate; + + private boolean sent; + + private String userName; + + public Post() { + + } + + public boolean isSent() { + return sent; + } + + public void setSent(boolean sent) { + this.sent = sent; + } + + public String getRedditID() { + return redditID; + } + + public void setRedditID(String redditID) { + this.redditID = redditID; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public Date getSubmissionDate() { + return submissionDate; + } + + public void setSubmissionDate(Date submissionDate) { + this.submissionDate = submissionDate; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/model/Preference.java b/spring-boot/src/main/java/com/baeldung/modelmapper/model/Preference.java new file mode 100644 index 0000000000..0ab5b1eddf --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/model/Preference.java @@ -0,0 +1,32 @@ +package com.baeldung.modelmapper.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Preference { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String timezone; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/model/User.java b/spring-boot/src/main/java/com/baeldung/modelmapper/model/User.java new file mode 100644 index 0000000000..a458b26f4a --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/model/User.java @@ -0,0 +1,44 @@ +package com.baeldung.modelmapper.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String name; + + @OneToOne + Preference preference; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Preference getPreference() { + return preference; + } + + public void setPreference(Preference preference) { + this.preference = preference; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java b/spring-boot/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java new file mode 100644 index 0000000000..fc3f5733c3 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/repository/PostRepository.java @@ -0,0 +1,21 @@ +package com.baeldung.modelmapper.repository; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.data.repository.query.Param; + +import com.baeldung.modelmapper.model.Post; +import com.baeldung.modelmapper.model.User; + +public interface PostRepository extends JpaRepository, PagingAndSortingRepository { + + @Query("select u from Post u where u.userName=:userName") + Page findByUser(@Param("userName") String userName, Pageable pageReq); + + default Page findByUser(User user, Pageable pageReq) { + return findByUser(user.getName(), pageReq); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/service/IPostService.java b/spring-boot/src/main/java/com/baeldung/modelmapper/service/IPostService.java new file mode 100644 index 0000000000..0182a0da41 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/service/IPostService.java @@ -0,0 +1,17 @@ +package com.baeldung.modelmapper.service; + +import java.util.List; + +import com.baeldung.modelmapper.model.Post; + +public interface IPostService { + + List getPostsList(int page, int size, String sortDir, String sort); + + void updatePost(Post post); + + Post createPost(Post post); + + Post getPostById(Long id); + +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/service/IUserService.java b/spring-boot/src/main/java/com/baeldung/modelmapper/service/IUserService.java new file mode 100644 index 0000000000..79934114c1 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/service/IUserService.java @@ -0,0 +1,9 @@ +package com.baeldung.modelmapper.service; + +import com.baeldung.modelmapper.model.User; + +public interface IUserService { + + User getCurrentUser(); + +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/service/PostService.java b/spring-boot/src/main/java/com/baeldung/modelmapper/service/PostService.java new file mode 100644 index 0000000000..5980c30837 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/service/PostService.java @@ -0,0 +1,47 @@ +package com.baeldung.modelmapper.service; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; + +import com.baeldung.modelmapper.model.Post; +import com.baeldung.modelmapper.repository.PostRepository; + +@Service +public class PostService implements IPostService { + + @Autowired + private PostRepository postRepository; + + @Autowired + private IUserService userService; + + @Override + public List getPostsList(int page, int size, String sortDir, String sort) { + + PageRequest pageReq + = PageRequest.of(page, size, Sort.Direction.fromString(sortDir), sort); + + Page posts = postRepository.findByUser(userService.getCurrentUser(), pageReq); + return posts.getContent(); + } + + @Override + public void updatePost(Post post) { + postRepository.save(post); + } + + @Override + public Post createPost(Post post) { + return postRepository.save(post); + } + + @Override + public Post getPostById(Long id) { + return postRepository.getOne(id); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/modelmapper/service/UserService.java b/spring-boot/src/main/java/com/baeldung/modelmapper/service/UserService.java new file mode 100644 index 0000000000..e445f836a4 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/modelmapper/service/UserService.java @@ -0,0 +1,25 @@ +package com.baeldung.modelmapper.service; + +import org.springframework.stereotype.Service; + +import com.baeldung.modelmapper.model.Preference; +import com.baeldung.modelmapper.model.User; + +@Service +public class UserService implements IUserService { + + @Override + public User getCurrentUser() { + + Preference preference = new Preference(); + preference.setId(1L); + preference.setTimezone("Asia/Calcutta"); + + User user = new User(); + user.setId(1L); + user.setName("Micheal"); + user.setPreference(preference); + + return user; + } +} \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java b/spring-boot/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java new file mode 100644 index 0000000000..34ec4db783 --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/modelmapper/PostDtoUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.modelmapper; + +import static org.junit.Assert.assertEquals; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import org.junit.Test; +import org.modelmapper.ModelMapper; + +import com.baeldung.modelmapper.dto.PostDto; +import com.baeldung.modelmapper.model.Post; + +public class PostDtoUnitTest { + + private ModelMapper modelMapper = new ModelMapper(); + + @Test + public void whenConvertPostEntityToPostDto_thenCorrect() { + Post post = new Post(); + post.setId(Long.valueOf(1)); + post.setTitle(randomAlphabetic(6)); + post.setUrl("www.test.com"); + + PostDto postDto = modelMapper.map(post, PostDto.class); + assertEquals(post.getId(), postDto.getId()); + assertEquals(post.getTitle(), postDto.getTitle()); + assertEquals(post.getUrl(), postDto.getUrl()); + } + + @Test + public void whenConvertPostDtoToPostEntity_thenCorrect() { + PostDto postDto = new PostDto(); + postDto.setId(Long.valueOf(1)); + postDto.setTitle(randomAlphabetic(6)); + postDto.setUrl("www.test.com"); + + Post post = modelMapper.map(postDto, Post.class); + assertEquals(postDto.getId(), post.getId()); + assertEquals(postDto.getTitle(), post.getTitle()); + assertEquals(postDto.getUrl(), post.getUrl()); + } +} \ No newline at end of file From 5174d9495bfd515ee2af9bbfb10eac9a2c79bfec Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 16 Dec 2018 17:11:21 +0530 Subject: [PATCH 73/76] [BAEL-10840] - Moved FTP related code back to libraries module --- libraries-apache-commons/README.md | 3 +-- libraries-apache-commons/pom.xml | 7 ------- libraries/README.md | 1 + libraries/pom.xml | 13 +++++++++++++ .../src/main/java/com/baeldung/ftp/FtpClient.java | 0 .../com/baeldung/ftp/FtpClientIntegrationTest.java | 0 .../baeldung/ftp/JdkFtpClientIntegrationTest.java | 0 7 files changed, 15 insertions(+), 9 deletions(-) rename {libraries-apache-commons => libraries}/src/main/java/com/baeldung/ftp/FtpClient.java (100%) rename {libraries-apache-commons => libraries}/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java (100%) rename {libraries-apache-commons => libraries}/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java (100%) diff --git a/libraries-apache-commons/README.md b/libraries-apache-commons/README.md index 66090e3709..01f2379588 100644 --- a/libraries-apache-commons/README.md +++ b/libraries-apache-commons/README.md @@ -17,5 +17,4 @@ - [Apache Commons Collections BidiMap](http://www.baeldung.com/commons-collections-bidi-map) - [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) - [Histograms with Apache Commons Frequency](http://www.baeldung.com/apache-commons-frequency) -- [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3) -- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client) \ No newline at end of file +- [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3) \ No newline at end of file diff --git a/libraries-apache-commons/pom.xml b/libraries-apache-commons/pom.xml index f61a7a4a9a..c7ff918af9 100644 --- a/libraries-apache-commons/pom.xml +++ b/libraries-apache-commons/pom.xml @@ -83,12 +83,6 @@ ${org.hamcrest.java-hamcrest.version} test - - org.mockftpserver - MockFtpServer - ${mockftpserver.version} - test - @@ -110,7 +104,6 @@ 3.6 1.3 3.6.1 - 2.7.1 diff --git a/libraries/README.md b/libraries/README.md index 28184c161b..ce2445f3e0 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -65,6 +65,7 @@ - [Guide to JMapper](http://www.baeldung.com/jmapper) - [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once) - [An Introduction to SuanShu](https://www.baeldung.com/suanshu) +- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-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 16d79a59b1..2ad4871e3f 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -55,6 +55,11 @@ commons-lang3 ${commons-lang.version} + + commons-net + commons-net + ${commons-net.version} + tec.units unit-ri @@ -664,6 +669,12 @@ ${derive4j.version} true + + org.mockftpserver + MockFtpServer + ${mockftpserver.version} + test + @@ -888,6 +899,8 @@ 3.3.0 3.0.2 1.1.0 + 2.7.1 + 3.6 diff --git a/libraries-apache-commons/src/main/java/com/baeldung/ftp/FtpClient.java b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java similarity index 100% rename from libraries-apache-commons/src/main/java/com/baeldung/ftp/FtpClient.java rename to libraries/src/main/java/com/baeldung/ftp/FtpClient.java diff --git a/libraries-apache-commons/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java b/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java similarity index 100% rename from libraries-apache-commons/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java rename to libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java diff --git a/libraries-apache-commons/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java b/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java similarity index 100% rename from libraries-apache-commons/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java rename to libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java From 1e29af79ffaf70c65fad2652d4f5da1dec7a95e5 Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Sun, 16 Dec 2018 06:58:45 -0500 Subject: [PATCH 74/76] Example code for Guide to Packages --- .../java/com/baeldung/packages/TodoApp.java | 22 +++++++++++ .../java/com/baeldung/packages/TodoList.java | 27 +++++++++++++ .../baeldung/packages/domain/TodoItem.java | 39 +++++++++++++++++++ .../baeldung/packages/PackagesUnitTest.java | 23 +++++++++++ 4 files changed, 111 insertions(+) create mode 100644 core-java-lang/src/main/java/com/baeldung/packages/TodoApp.java create mode 100644 core-java-lang/src/main/java/com/baeldung/packages/TodoList.java create mode 100644 core-java-lang/src/main/java/com/baeldung/packages/domain/TodoItem.java create mode 100644 core-java-lang/src/test/java/com/baeldung/packages/PackagesUnitTest.java diff --git a/core-java-lang/src/main/java/com/baeldung/packages/TodoApp.java b/core-java-lang/src/main/java/com/baeldung/packages/TodoApp.java new file mode 100644 index 0000000000..0f4a56f708 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/packages/TodoApp.java @@ -0,0 +1,22 @@ +package com.baeldung.packages; + +import java.time.LocalDate; + +import com.baeldung.packages.domain.TodoItem; + +public class TodoApp { + + public static void main(String[] args) { + TodoList todoList = new TodoList(); + for (int i = 0; i < 3; i++) { + TodoItem item = new TodoItem(); + item.setId(Long.valueOf((long)i)); + item.setDescription("Todo item " + (i + 1)); + item.setDueDate(LocalDate.now().plusDays((long)(i + 1))); + todoList.addTodoItem(item); + } + + todoList.getTodoItems().forEach((TodoItem todoItem) -> System.out.println(todoItem.toString())); + } + +} diff --git a/core-java-lang/src/main/java/com/baeldung/packages/TodoList.java b/core-java-lang/src/main/java/com/baeldung/packages/TodoList.java new file mode 100644 index 0000000000..6ed6cd4ec1 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/packages/TodoList.java @@ -0,0 +1,27 @@ +package com.baeldung.packages; + +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.packages.domain.TodoItem; + +public class TodoList { + private List todoItems; + + public void addTodoItem(TodoItem todoItem) { + if (todoItems == null) { + todoItems = new ArrayList(); + } + + todoItems.add(todoItem); + } + + public List getTodoItems() { + return todoItems; + } + + public void setTodoItems(List todoItems) { + this.todoItems = todoItems; + } + +} diff --git a/core-java-lang/src/main/java/com/baeldung/packages/domain/TodoItem.java b/core-java-lang/src/main/java/com/baeldung/packages/domain/TodoItem.java new file mode 100644 index 0000000000..972e574a7f --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/packages/domain/TodoItem.java @@ -0,0 +1,39 @@ +package com.baeldung.packages.domain; + +import java.time.LocalDate; + +public class TodoItem { + private Long id; + private String description; + private LocalDate dueDate; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public LocalDate getDueDate() { + return dueDate; + } + + public void setDueDate(LocalDate dueDate) { + this.dueDate = dueDate; + } + + @Override + public String toString() { + return "TodoItem [id=" + id + ", description=" + description + ", dueDate=" + dueDate + "]"; + } + +} diff --git a/core-java-lang/src/test/java/com/baeldung/packages/PackagesUnitTest.java b/core-java-lang/src/test/java/com/baeldung/packages/PackagesUnitTest.java new file mode 100644 index 0000000000..212fb7b3c7 --- /dev/null +++ b/core-java-lang/src/test/java/com/baeldung/packages/PackagesUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.packages; + +import static org.junit.Assert.assertEquals; + +import java.time.LocalDate; + +import org.junit.Test; + +import com.baeldung.packages.domain.TodoItem; + +public class PackagesUnitTest { + + @Test + public void whenTodoItemAdded_ThenSizeIncreases() { + TodoItem todoItem = new TodoItem(); + todoItem.setId(1L); + todoItem.setDescription("Test the Todo List"); + todoItem.setDueDate(LocalDate.now()); + TodoList todoList = new TodoList(); + todoList.addTodoItem(todoItem); + assertEquals(1, todoList.getTodoItems().size()); + } +} From ca3a38aa0adaea158a69a29594206b14bf2ea941 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 16 Dec 2018 17:20:58 +0200 Subject: [PATCH 75/76] move ftp file --- .../src/test/resources/ftp/baz.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {libraries-apache-commons => libraries}/src/test/resources/ftp/baz.txt (100%) diff --git a/libraries-apache-commons/src/test/resources/ftp/baz.txt b/libraries/src/test/resources/ftp/baz.txt similarity index 100% rename from libraries-apache-commons/src/test/resources/ftp/baz.txt rename to libraries/src/test/resources/ftp/baz.txt From d8e34dc9f2c8c5fabbf3172974d9da80bfd21117 Mon Sep 17 00:00:00 2001 From: Laurentiu Delcea Date: Sun, 16 Dec 2018 18:22:22 +0200 Subject: [PATCH 76/76] BAEL-2376 Inline classes in kotlin (#5842) * BAEL-2376 Inline classes in kotlin * BAEL-2376 Move classes --- .../baeldung/inline/classes/CircleRadius.kt | 14 ++++++++++++++ .../inline/classes/InlineDoubleWrapper.kt | 3 +++ .../inline/classes/CircleRadiusTest.kt | 19 +++++++++++++++++++ .../inline/classes/InlineDoubleWrapperTest.kt | 13 +++++++++++++ 4 files changed, 49 insertions(+) create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt b/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt new file mode 100644 index 0000000000..5b46b9570f --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt @@ -0,0 +1,14 @@ +package com.baeldung.inline.classes + +interface Drawable { + fun draw() +} + +inline class CircleRadius(private val circleRadius : Double) : Drawable { + val diameterOfCircle get() = 2 * circleRadius + fun areaOfCircle() = 3.14 * circleRadius * circleRadius + + override fun draw() { + println("Draw my circle") + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt b/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt new file mode 100644 index 0000000000..430fa509da --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt @@ -0,0 +1,3 @@ +package com.baeldung.inline.classes + +inline class InlineDoubleWrapper(val doubleValue : Double) \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt new file mode 100644 index 0000000000..8de378b6dd --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt @@ -0,0 +1,19 @@ +package com.baeldung.inline.classes + +import org.junit.Test +import kotlin.test.assertEquals + +class CircleRadiusTest { + + @Test + fun givenRadius_ThenDiameterIsCorrectlyCalculated() { + val radius = CircleRadius(5.0) + assertEquals(10.0, radius.diameterOfCircle) + } + + @Test + fun givenRadius_ThenAreaIsCorrectlyCalculated() { + val radius = CircleRadius(5.0) + assertEquals(78.5, radius.areaOfCircle()) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt new file mode 100644 index 0000000000..349c90d6f4 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt @@ -0,0 +1,13 @@ +package com.baeldung.inline.classes + +import org.junit.Test +import kotlin.test.assertEquals + +class InlineDoubleWrapperTest { + + @Test + fun whenInclineClassIsUsed_ThenPropertyIsReadCorrectly() { + val piDoubleValue = InlineDoubleWrapper(3.14) + assertEquals(3.14, piDoubleValue.doubleValue) + } +} \ No newline at end of file