From e2a675b348bcf52f551a83de059613da65a04045 Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Tue, 16 Oct 2018 00:44:02 +0200 Subject: [PATCH 01/11] [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/11] [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/11] [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/11] [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/11] [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/11] [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/11] [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/11] [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 3e685aa12d47f428a3dcb11bb6073d297078dd5c Mon Sep 17 00:00:00 2001 From: mprevisic Date: Tue, 11 Dec 2018 01:30:10 +0100 Subject: [PATCH 09/11] 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 7e3e9db288d8d02a11b437b1cbf80a6df0248af3 Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Wed, 12 Dec 2018 08:17:25 +0100 Subject: [PATCH 10/11] 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 7a23ac4f5301a45b74e992b8e730ff7c7dab1d89 Mon Sep 17 00:00:00 2001 From: markoprevisic Date: Thu, 13 Dec 2018 15:12:23 +0100 Subject: [PATCH 11/11] 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