diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..40f5c88746 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Eugen Paraschiv + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index d94a786bc2..271aea0767 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,14 @@ The "REST with Spring" Classes ============================== + After 5 months of work, here's the Master Class of REST With Spring:
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)** +And here's the Master Class of Learn Spring Security:
+**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)** + + Spring Tutorials ================ diff --git a/apache-poi/src/main/java/com/baeldung/poi/powerpoint/PowerPointHelper.java b/apache-poi/src/main/java/com/baeldung/poi/powerpoint/PowerPointHelper.java new file mode 100644 index 0000000000..e2af4f8808 --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/poi/powerpoint/PowerPointHelper.java @@ -0,0 +1,224 @@ +package com.baeldung.poi.powerpoint; + +import org.apache.poi.sl.usermodel.AutoNumberingScheme; +import org.apache.poi.sl.usermodel.PictureData; +import org.apache.poi.sl.usermodel.TableCell; +import org.apache.poi.sl.usermodel.TextParagraph; +import org.apache.poi.util.IOUtils; +import org.apache.poi.xslf.usermodel.*; + +import java.awt.*; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Helper class for the PowerPoint presentation creation + */ +public class PowerPointHelper { + + /** + * Read an existing presentation + * + * @param fileLocation + * File location of the presentation + * @return instance of {@link XMLSlideShow} + * @throws IOException + */ + public XMLSlideShow readingExistingSlideShow(String fileLocation) throws IOException { + return new XMLSlideShow(new FileInputStream(fileLocation)); + } + + /** + * Create a sample presentation + * + * @param fileLocation + * File location of the presentation + * @throws IOException + */ + public void createPresentation(String fileLocation) throws IOException { + // Create presentation + XMLSlideShow ppt = new XMLSlideShow(); + + XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0); + + // Retriving the slide layout + XSLFSlideLayout layout = defaultMaster.getLayout(SlideLayout.TITLE_ONLY); + + // Creating the 1st slide + XSLFSlide slide1 = ppt.createSlide(layout); + XSLFTextShape title = slide1.getPlaceholder(0); + // Clearing text to remove the predefined one in the template + title.clearText(); + XSLFTextParagraph p = title.addNewTextParagraph(); + + XSLFTextRun r1 = p.addNewTextRun(); + r1.setText("Baeldung"); + r1.setFontColor(new Color(78, 147, 89)); + r1.setFontSize(48.); + + // Add Image + ClassLoader classLoader = getClass().getClassLoader(); + byte[] pictureData = IOUtils.toByteArray(new FileInputStream(classLoader.getResource("logo-leaf.png").getFile())); + + XSLFPictureData pd = ppt.addPicture(pictureData, PictureData.PictureType.PNG); + XSLFPictureShape picture = slide1.createPicture(pd); + picture.setAnchor(new Rectangle(320, 230, 100, 92)); + + // Creating 2nd slide + layout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT); + XSLFSlide slide2 = ppt.createSlide(layout); + + // setting the tile + title = slide2.getPlaceholder(0); + title.clearText(); + XSLFTextRun r = title.addNewTextParagraph().addNewTextRun(); + r.setText("Baeldung"); + + // Adding the link + XSLFHyperlink link = r.createHyperlink(); + link.setAddress("http://www.baeldung.com"); + + // setting the content + XSLFTextShape content = slide2.getPlaceholder(1); + content.clearText(); // unset any existing text + content.addNewTextParagraph().addNewTextRun().setText("First paragraph"); + content.addNewTextParagraph().addNewTextRun().setText("Second paragraph"); + content.addNewTextParagraph().addNewTextRun().setText("Third paragraph"); + + // Creating 3rd slide - List + layout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT); + XSLFSlide slide3 = ppt.createSlide(layout); + title = slide3.getPlaceholder(0); + title.clearText(); + r = title.addNewTextParagraph().addNewTextRun(); + r.setText("Lists"); + + content = slide3.getPlaceholder(1); + content.clearText(); + XSLFTextParagraph p1 = content.addNewTextParagraph(); + p1.setIndentLevel(0); + p1.setBullet(true); + r1 = p1.addNewTextRun(); + r1.setText("Bullet"); + + // the next three paragraphs form an auto-numbered list + XSLFTextParagraph p2 = content.addNewTextParagraph(); + p2.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1); + p2.setIndentLevel(1); + XSLFTextRun r2 = p2.addNewTextRun(); + r2.setText("Numbered List Item - 1"); + + // Creating 4th slide + XSLFSlide slide4 = ppt.createSlide(); + createTable(slide4); + + // Save presentation + FileOutputStream out = new FileOutputStream(fileLocation); + ppt.write(out); + out.close(); + + // Closing presentation + ppt.close(); + } + + /** + * Delete a slide from the presentation + * + * @param ppt + * The presentation + * @param slideNumber + * The number of the slide to be deleted (0-based) + */ + public void deleteSlide(XMLSlideShow ppt, int slideNumber) { + ppt.removeSlide(slideNumber); + } + + /** + * Re-order the slides inside a presentation + * + * @param ppt + * The presentation + * @param slideNumber + * The number of the slide to move + * @param newSlideNumber + * The new position of the slide (0-base) + */ + public void reorderSlide(XMLSlideShow ppt, int slideNumber, int newSlideNumber) { + List slides = ppt.getSlides(); + + XSLFSlide secondSlide = slides.get(slideNumber); + ppt.setSlideOrder(secondSlide, newSlideNumber); + } + + /** + * Retrieve the placeholder inside a slide + * + * @param slide + * The slide + * @return List of placeholder inside a slide + */ + public List retrieveTemplatePlaceholders(XSLFSlide slide) { + List placeholders = new ArrayList<>(); + + for (XSLFShape shape : slide.getShapes()) { + if (shape instanceof XSLFAutoShape) { + placeholders.add(shape); + } + } + return placeholders; + } + + /** + * Create a table + * + * @param slide + * Slide + */ + private void createTable(XSLFSlide slide) { + + XSLFTable tbl = slide.createTable(); + tbl.setAnchor(new Rectangle(50, 50, 450, 300)); + + int numColumns = 3; + int numRows = 5; + + // header + XSLFTableRow headerRow = tbl.addRow(); + headerRow.setHeight(50); + for (int i = 0; i < numColumns; i++) { + XSLFTableCell th = headerRow.addCell(); + XSLFTextParagraph p = th.addNewTextParagraph(); + p.setTextAlign(TextParagraph.TextAlign.CENTER); + XSLFTextRun r = p.addNewTextRun(); + r.setText("Header " + (i + 1)); + r.setBold(true); + r.setFontColor(Color.white); + th.setFillColor(new Color(79, 129, 189)); + th.setBorderWidth(TableCell.BorderEdge.bottom, 2.0); + th.setBorderColor(TableCell.BorderEdge.bottom, Color.white); + // all columns are equally sized + tbl.setColumnWidth(i, 150); + } + + // data + for (int rownum = 0; rownum < numRows; rownum++) { + XSLFTableRow tr = tbl.addRow(); + tr.setHeight(50); + for (int i = 0; i < numColumns; i++) { + XSLFTableCell cell = tr.addCell(); + XSLFTextParagraph p = cell.addNewTextParagraph(); + XSLFTextRun r = p.addNewTextRun(); + + r.setText("Cell " + (i * rownum + 1)); + if (rownum % 2 == 0) { + cell.setFillColor(new Color(208, 216, 232)); + } else { + cell.setFillColor(new Color(233, 247, 244)); + } + } + } + } +} diff --git a/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java new file mode 100644 index 0000000000..5319208e85 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java @@ -0,0 +1,77 @@ +package com.baeldung.poi.powerpoint; + +import org.apache.poi.xslf.usermodel.XMLSlideShow; +import org.apache.poi.xslf.usermodel.XSLFShape; +import org.apache.poi.xslf.usermodel.XSLFSlide; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.util.List; + +public class PowerPointIntegrationTest { + + private PowerPointHelper pph; + private String fileLocation; + private static final String FILE_NAME = "presentation.pptx"; + + @Before + public void setUp() throws Exception { + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; + + pph = new PowerPointHelper(); + pph.createPresentation(fileLocation); + } + + @Test + public void whenReadingAPresentation_thenOK() throws Exception { + XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation); + + Assert.assertNotNull(xmlSlideShow); + Assert.assertEquals(4, xmlSlideShow.getSlides().size()); + } + + @Test + public void whenRetrievingThePlaceholdersForEachSlide_thenOK() throws Exception { + XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation); + + List onlyTitleSlidePlaceholders = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(0)); + List titleAndBodySlidePlaceholders = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(1)); + List emptySlidePlaceholdes = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(3)); + + Assert.assertEquals(1, onlyTitleSlidePlaceholders.size()); + Assert.assertEquals(2, titleAndBodySlidePlaceholders.size()); + Assert.assertEquals(0, emptySlidePlaceholdes.size()); + + } + + @Test + public void whenSortingSlides_thenOK() throws Exception { + XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation); + XSLFSlide slide4 = xmlSlideShow.getSlides().get(3); + pph.reorderSlide(xmlSlideShow, 3, 1); + + Assert.assertEquals(slide4, xmlSlideShow.getSlides().get(1)); + } + + @Test + public void givenPresentation_whenDeletingASlide_thenOK() throws Exception { + XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation); + pph.deleteSlide(xmlSlideShow, 3); + + Assert.assertEquals(3, xmlSlideShow.getSlides().size()); + } + + @After + public void tearDown() throws Exception { + File testFile = new File(fileLocation); + if (testFile.exists()) { + testFile.delete(); + } + pph = null; + } +} diff --git a/bootique/dependency-reduced-pom.xml b/bootique/dependency-reduced-pom.xml index ed18f4e42a..ab09cfb7b1 100644 --- a/bootique/dependency-reduced-pom.xml +++ b/bootique/dependency-reduced-pom.xml @@ -28,8 +28,14 @@ junit junit - 3.8.1 + 4.12 test + + + hamcrest-core + org.hamcrest + + diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Data.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Data.java new file mode 100644 index 0000000000..9b850c4153 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Data.java @@ -0,0 +1,33 @@ +package com.baeldung.concurrent.waitandnotify; + +public class Data { + private String packet; + + // True if receiver should wait + // False if sender should wait + private boolean transfer = true; + + public synchronized String receive() { + while (transfer) { + try { + wait(); + } catch (InterruptedException e) {} + } + transfer = true; + + notifyAll(); + return packet; + } + + public synchronized void send(String packet) { + while (!transfer) { + try { + wait(); + } catch (InterruptedException e) {} + } + transfer = false; + + this.packet = packet; + notifyAll(); + } +} \ No newline at end of file diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/NetworkDriver.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/NetworkDriver.java new file mode 100644 index 0000000000..d4fd1574c6 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/NetworkDriver.java @@ -0,0 +1,12 @@ +package com.baeldung.concurrent.waitandnotify; + +public class NetworkDriver { + public static void main(String[] args) { + Data data = new Data(); + Thread sender = new Thread(new Sender(data)); + Thread receiver = new Thread(new Receiver(data)); + + sender.start(); + receiver.start(); + } +} \ No newline at end of file diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Receiver.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Receiver.java new file mode 100644 index 0000000000..63f48b8031 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Receiver.java @@ -0,0 +1,25 @@ +package com.baeldung.concurrent.waitandnotify; + +import java.util.concurrent.ThreadLocalRandom; + +public class Receiver implements Runnable { + private Data load; + + public Receiver(Data load) { + this.load = load; + } + + public void run() { + for(String receivedMessage = load.receive(); + !"End".equals(receivedMessage) ; + receivedMessage = load.receive()) { + + System.out.println(receivedMessage); + + //Thread.sleep() to mimic heavy server-side processing + try { + Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000)); + } catch (InterruptedException e) {} + } + } +} \ No newline at end of file diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Sender.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Sender.java new file mode 100644 index 0000000000..b7d782c3f5 --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/waitandnotify/Sender.java @@ -0,0 +1,30 @@ +package com.baeldung.concurrent.waitandnotify; + +import java.util.concurrent.ThreadLocalRandom; + +public class Sender implements Runnable { + private Data data; + + public Sender(Data data) { + this.data = data; + } + + public void run() { + String packets[] = { + "First packet", + "Second packet", + "Third packet", + "Fourth packet", + "End" + }; + + for (String packet : packets) { + data.send(packet); + + //Thread.sleep() to mimic heavy server-side processing + try { + Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000)); + } catch (InterruptedException e) {} + } + } +} \ No newline at end of file diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java index 8c1bdbf787..70854f013f 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/stopping/StopThreadTest.java @@ -1,7 +1,11 @@ package com.baeldung.concurrent.stopping; +import com.jayway.awaitility.Awaitility; import org.junit.Test; +import java.util.concurrent.TimeUnit; + +import static com.jayway.awaitility.Awaitility.await; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -22,11 +26,10 @@ public class StopThreadTest { // Stop it and make sure the flags have been reversed controlSubThread.stop(); - Thread.sleep(interval); - assertTrue(controlSubThread.isStopped()); + await() + .until(() -> assertTrue(controlSubThread.isStopped())); } - @Test public void whenInterruptedThreadIsStopped() throws InterruptedException { @@ -44,7 +47,8 @@ public class StopThreadTest { controlSubThread.interrupt(); // Wait less than the time we would normally sleep, and make sure we exited. - Thread.sleep(interval/10); - assertTrue(controlSubThread.isStopped()); + Awaitility.await() + .atMost(interval/ 10, TimeUnit.MILLISECONDS) + .until(controlSubThread::isStopped); } } diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/waitandnotify/NetworkIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/waitandnotify/NetworkIntegrationTest.java new file mode 100644 index 0000000000..49f4313e9d --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/waitandnotify/NetworkIntegrationTest.java @@ -0,0 +1,65 @@ +package com.baeldung.concurrent.waitandnotify; + +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class NetworkIntegrationTest { + + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + private String expected; + + @Before + public void setUpStreams() { + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + } + + @Before + public void setUpExpectedOutput() { + StringWriter expectedStringWriter = new StringWriter(); + + PrintWriter printWriter = new PrintWriter(expectedStringWriter); + printWriter.println("First packet"); + printWriter.println("Second packet"); + printWriter.println("Third packet"); + printWriter.println("Fourth packet"); + printWriter.close(); + + expected = expectedStringWriter.toString(); + } + + @After + public void cleanUpStreams() { + System.setOut(null); + System.setErr(null); + } + + @Test + public void givenSenderAndReceiver_whenSendingPackets_thenNetworkSynchronized() { + Data data = new Data(); + Thread sender = new Thread(new Sender(data)); + Thread receiver = new Thread(new Receiver(data)); + + sender.start(); + receiver.start(); + + //wait for sender and receiver to finish before we test against expected + try { + sender.join(); + receiver.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + assertEquals(expected, outContent.toString()); + } +} diff --git a/core-java-sun/.gitignore b/core-java-sun/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/core-java-sun/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-sun/README.md b/core-java-sun/README.md new file mode 100644 index 0000000000..9cf8b26f1b --- /dev/null +++ b/core-java-sun/README.md @@ -0,0 +1,6 @@ +========= + +## Core Java Cookbooks and Examples + +### Relevant Articles: +- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) diff --git a/core-java-sun/pom.xml b/core-java-sun/pom.xml new file mode 100644 index 0000000000..3997f47d19 --- /dev/null +++ b/core-java-sun/pom.xml @@ -0,0 +1,489 @@ + + 4.0.0 + com.baeldung + core-java-sun + 0.1.0-SNAPSHOT + jar + + core-java-sun + + + + + + net.sourceforge.collections + collections-generic + ${collections-generic.version} + + + com.google.guava + guava + ${guava.version} + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + + commons-io + commons-io + ${commons-io.version} + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + + org.decimal4j + decimal4j + ${decimal4j.version} + + + + org.bouncycastle + bcprov-jdk15on + ${bouncycastle.version} + + + + org.unix4j + unix4j-command + ${unix4j.version} + + + + com.googlecode.grep4j + grep4j + ${grep4j.version} + + + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + + log4j + log4j + 1.2.17 + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + + + org.hamcrest + hamcrest-all + 1.3 + test + + + + junit + junit + ${junit.version} + test + + + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + org.mockito + mockito-core + ${mockito.version} + test + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + + commons-codec + commons-codec + ${commons-codec.version} + + + + org.javamoney + moneta + 1.1 + + + + org.owasp.esapi + esapi + 2.1.0.1 + + + + com.sun.messaging.mq + fscontext + ${fscontext.version} + + + com.codepoetics + protonpack + ${protonpack.version} + + + one.util + streamex + ${streamex.version} + + + io.vavr + vavr + ${vavr.version} + + + org.openjdk.jmh + jmh-core + 1.19 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.19 + + + org.springframework + spring-web + 4.3.4.RELEASE + + + com.sun + tools + 1.8.0 + system + ${java.home}/../lib/tools.jar + + + + + core-java + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + libs/ + org.baeldung.executable.ExecutableMavenJar + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + package + + single + + + ${project.basedir} + + + org.baeldung.executable.ExecutableMavenJar + + + + jar-with-dependencies + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + shade + + + true + + + org.baeldung.executable.ExecutableMavenJar + + + + + + + + + com.jolira + onejar-maven-plugin + + + + org.baeldung.executable.ExecutableMavenJar + true + ${project.build.finalName}-onejar.${project.packaging} + + + one-jar + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + spring-boot + org.baeldung.executable.ExecutableMavenJar + + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + java + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed + + -Xmx300m + -XX:+UseParallelGC + -classpath + + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed + + + + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + org.codehaus.mojo + exec-maven-plugin + + + + run-benchmarks + + none + + exec + + + test + java + + -classpath + + org.openjdk.jmh.Main + .* + + + + + + + + + + + + + 2.8.5 + + + 1.7.21 + 1.1.7 + + + 23.0 + 3.5 + 1.55 + 1.10 + 3.6.1 + 1.0.3 + 2.5 + 4.1 + 4.01 + 0.4 + 1.8.7 + 1.16.12 + 4.6-b01 + 1.13 + 0.6.5 + 0.9.0 + + + 1.3 + 4.12 + 2.8.9 + 3.6.1 + 1.7.0 + + + 3.6.0 + 2.19.1 + + \ No newline at end of file diff --git a/core-java-sun/src/main/java/com/baeldung/.gitignore b/core-java-sun/src/main/java/com/baeldung/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-sun/src/main/java/com/baeldung/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/core-java-sun/src/main/java/com/baeldung/README.md b/core-java-sun/src/main/java/com/baeldung/README.md new file mode 100644 index 0000000000..51809b2882 --- /dev/null +++ b/core-java-sun/src/main/java/com/baeldung/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java) diff --git a/core-java/src/main/java/com/baeldung/javac/Positive.java b/core-java-sun/src/main/java/com/baeldung/javac/Positive.java similarity index 100% rename from core-java/src/main/java/com/baeldung/javac/Positive.java rename to core-java-sun/src/main/java/com/baeldung/javac/Positive.java diff --git a/core-java/src/main/java/com/baeldung/javac/SampleJavacPlugin.java b/core-java-sun/src/main/java/com/baeldung/javac/SampleJavacPlugin.java similarity index 100% rename from core-java/src/main/java/com/baeldung/javac/SampleJavacPlugin.java rename to core-java-sun/src/main/java/com/baeldung/javac/SampleJavacPlugin.java diff --git a/core-java-sun/src/main/resources/log4j.properties b/core-java-sun/src/main/resources/log4j.properties new file mode 100644 index 0000000000..621cf01735 --- /dev/null +++ b/core-java-sun/src/main/resources/log4j.properties @@ -0,0 +1,6 @@ +log4j.rootLogger=DEBUG, A1 + +log4j.appender.A1=org.apache.log4j.ConsoleAppender + +log4j.appender.A1.layout=org.apache.log4j.PatternLayout +log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n \ No newline at end of file diff --git a/core-java-sun/src/main/resources/logback.xml b/core-java-sun/src/main/resources/logback.xml new file mode 100644 index 0000000000..ec0dc2469a --- /dev/null +++ b/core-java-sun/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/javac/SampleJavacPluginIntegrationTest.java b/core-java-sun/src/test/java/com/baeldung/javac/SampleJavacPluginIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/javac/SampleJavacPluginIntegrationTest.java rename to core-java-sun/src/test/java/com/baeldung/javac/SampleJavacPluginIntegrationTest.java diff --git a/core-java/src/test/java/com/baeldung/javac/SimpleClassFile.java b/core-java-sun/src/test/java/com/baeldung/javac/SimpleClassFile.java similarity index 100% rename from core-java/src/test/java/com/baeldung/javac/SimpleClassFile.java rename to core-java-sun/src/test/java/com/baeldung/javac/SimpleClassFile.java diff --git a/core-java/src/test/java/com/baeldung/javac/SimpleFileManager.java b/core-java-sun/src/test/java/com/baeldung/javac/SimpleFileManager.java similarity index 100% rename from core-java/src/test/java/com/baeldung/javac/SimpleFileManager.java rename to core-java-sun/src/test/java/com/baeldung/javac/SimpleFileManager.java diff --git a/core-java/src/test/java/com/baeldung/javac/SimpleSourceFile.java b/core-java-sun/src/test/java/com/baeldung/javac/SimpleSourceFile.java similarity index 100% rename from core-java/src/test/java/com/baeldung/javac/SimpleSourceFile.java rename to core-java-sun/src/test/java/com/baeldung/javac/SimpleSourceFile.java diff --git a/core-java/src/test/java/com/baeldung/javac/TestCompiler.java b/core-java-sun/src/test/java/com/baeldung/javac/TestCompiler.java similarity index 100% rename from core-java/src/test/java/com/baeldung/javac/TestCompiler.java rename to core-java-sun/src/test/java/com/baeldung/javac/TestCompiler.java diff --git a/core-java/src/test/java/com/baeldung/javac/TestRunner.java b/core-java-sun/src/test/java/com/baeldung/javac/TestRunner.java similarity index 100% rename from core-java/src/test/java/com/baeldung/javac/TestRunner.java rename to core-java-sun/src/test/java/com/baeldung/javac/TestRunner.java diff --git a/core-java-sun/src/test/resources/.gitignore b/core-java-sun/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-sun/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/core-java/pom.xml b/core-java/pom.xml index 77000b8741..2c4cbfc37b 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -181,11 +181,6 @@ 2.1.0.1 - - com.sun.messaging.mq - fscontext - ${fscontext.version} - com.codepoetics protonpack @@ -216,13 +211,6 @@ spring-web 4.3.4.RELEASE - - com.sun - tools - 1.8.0 - system - ${java.home}/../lib/tools.jar - diff --git a/core-java/src/main/java/com/baeldung/comparable/Player.java b/core-java/src/main/java/com/baeldung/comparable/Player.java new file mode 100644 index 0000000000..68a78980f3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparable/Player.java @@ -0,0 +1,51 @@ +package com.baeldung.comparable; + +public class Player implements Comparable { + + private int ranking; + + private String name; + + private int age; + + public Player(int ranking, String name, int age) { + this.ranking = ranking; + this.name = name; + this.age = age; + } + + public int getRanking() { + return ranking; + } + + public void setRanking(int ranking) { + this.ranking = ranking; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return this.name; + } + + @Override + public int compareTo(Player otherPlayer) { + return (this.getRanking() - otherPlayer.getRanking()); + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparable/PlayerSorter.java b/core-java/src/main/java/com/baeldung/comparable/PlayerSorter.java new file mode 100644 index 0000000000..a9b883f579 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparable/PlayerSorter.java @@ -0,0 +1,25 @@ +package com.baeldung.comparable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class PlayerSorter { + + public static void main(String[] args) { + + List footballTeam = new ArrayList(); + Player player1 = new Player(59, "John", 20); + Player player2 = new Player(67, "Roger", 22); + Player player3 = new Player(45, "Steven", 24); + footballTeam.add(player1); + footballTeam.add(player2); + footballTeam.add(player3); + + System.out.println("Before Sorting : " + footballTeam); + Collections.sort(footballTeam); + System.out.println("After Sorting : " + footballTeam); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparator/Player.java b/core-java/src/main/java/com/baeldung/comparator/Player.java new file mode 100644 index 0000000000..e6e9ee0db6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparator/Player.java @@ -0,0 +1,46 @@ +package com.baeldung.comparator; + +public class Player { + + private int ranking; + + private String name; + + private int age; + + public Player(int ranking, String name, int age) { + this.ranking = ranking; + this.name = name; + this.age = age; + } + + public int getRanking() { + return ranking; + } + + public void setRanking(int ranking) { + this.ranking = ranking; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return this.name; + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparator/PlayerAgeComparator.java b/core-java/src/main/java/com/baeldung/comparator/PlayerAgeComparator.java new file mode 100644 index 0000000000..d2e7ca1f42 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparator/PlayerAgeComparator.java @@ -0,0 +1,12 @@ +package com.baeldung.comparator; + +import java.util.Comparator; + +public class PlayerAgeComparator implements Comparator { + + @Override + public int compare(Player firstPlayer, Player secondPlayer) { + return (firstPlayer.getAge() - secondPlayer.getAge()); + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparator/PlayerAgeSorter.java b/core-java/src/main/java/com/baeldung/comparator/PlayerAgeSorter.java new file mode 100644 index 0000000000..3bbbcddb80 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparator/PlayerAgeSorter.java @@ -0,0 +1,27 @@ +package com.baeldung.comparator; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class PlayerAgeSorter { + + public static void main(String[] args) { + + List footballTeam = new ArrayList(); + Player player1 = new Player(59, "John", 22); + Player player2 = new Player(67, "Roger", 20); + Player player3 = new Player(45, "Steven", 24); + footballTeam.add(player1); + footballTeam.add(player2); + footballTeam.add(player3); + + System.out.println("Before Sorting : " + footballTeam); + //Instance of PlayerAgeComparator + PlayerAgeComparator playerComparator = new PlayerAgeComparator(); + Collections.sort(footballTeam, playerComparator); + System.out.println("After Sorting by age : " + footballTeam); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparator/PlayerRankingComparator.java b/core-java/src/main/java/com/baeldung/comparator/PlayerRankingComparator.java new file mode 100644 index 0000000000..2d42698843 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparator/PlayerRankingComparator.java @@ -0,0 +1,12 @@ +package com.baeldung.comparator; + +import java.util.Comparator; + +public class PlayerRankingComparator implements Comparator { + + @Override + public int compare(Player firstPlayer, Player secondPlayer) { + return (firstPlayer.getRanking() - secondPlayer.getRanking()); + } + +} diff --git a/core-java/src/main/java/com/baeldung/comparator/PlayerRankingSorter.java b/core-java/src/main/java/com/baeldung/comparator/PlayerRankingSorter.java new file mode 100644 index 0000000000..581585fb7e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/comparator/PlayerRankingSorter.java @@ -0,0 +1,27 @@ +package com.baeldung.comparator; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class PlayerRankingSorter { + + public static void main(String[] args) { + + List footballTeam = new ArrayList(); + Player player1 = new Player(59, "John", 22); + Player player2 = new Player(67, "Roger", 20); + Player player3 = new Player(45, "Steven", 40); + footballTeam.add(player1); + footballTeam.add(player2); + footballTeam.add(player3); + + System.out.println("Before Sorting : " + footballTeam); + //Instance of PlayerRankingComparator + PlayerRankingComparator playerComparator = new PlayerRankingComparator(); + Collections.sort(footballTeam, playerComparator); + System.out.println("After Sorting by ranking : " + footballTeam); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/PolygonFactory.java b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/PolygonFactory.java index 406f0f5274..9f34fe77b9 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/PolygonFactory.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/creational/factory/PolygonFactory.java @@ -11,7 +11,7 @@ public class PolygonFactory { if(numberOfSides == 5) { return new Pentagon(); } - if(numberOfSides == 4) { + if(numberOfSides == 7) { return new Heptagon(); } else if(numberOfSides == 8) { @@ -19,4 +19,4 @@ public class PolygonFactory { } return null; } -} \ No newline at end of file +} diff --git a/core-java/src/main/java/com/baeldung/polymorphism/FileManager.java b/core-java/src/main/java/com/baeldung/polymorphism/FileManager.java new file mode 100644 index 0000000000..7f2665ff2d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/polymorphism/FileManager.java @@ -0,0 +1,38 @@ +package com.baeldung.polymorphism; + +import java.awt.image.BufferedImage; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class FileManager { + + final static Logger logger = LoggerFactory.getLogger(FileManager.class); + + public static void main(String[] args) { + GenericFile file1 = new TextFile("SampleTextFile", "This is a sample text content", "v1.0.0"); + logger.info("File Info: \n" + file1.getFileInfo() + "\n"); + ImageFile imageFile = new ImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString() + .getBytes(), "v1.0.0"); + logger.info("File Info: \n" + imageFile.getFileInfo()); + } + + public static ImageFile createImageFile(String name, int height, int width, byte[] content, String version) { + ImageFile imageFile = new ImageFile(name, height, width, content, version); + logger.info("File 2 Info: \n" + imageFile.getFileInfo()); + return imageFile; + } + + public static GenericFile createTextFile(String name, String content, String version) { + GenericFile file1 = new TextFile(name, content, version); + logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n"); + return file1; + } + + public static TextFile createTextFile2(String name, String content, String version) { + TextFile file1 = new TextFile(name, content, version); + logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n"); + return file1; + } + +} diff --git a/core-java/src/main/java/com/baeldung/polymorphism/GenericFile.java b/core-java/src/main/java/com/baeldung/polymorphism/GenericFile.java new file mode 100644 index 0000000000..4075083c49 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/polymorphism/GenericFile.java @@ -0,0 +1,63 @@ +package com.baeldung.polymorphism; + +import java.util.Date; + +public class GenericFile { + private String name; + private String extension; + private Date dateCreated; + private String version; + private byte[] content; + + public GenericFile() { + this.setDateCreated(new Date()); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + public Date getDateCreated() { + return dateCreated; + } + + public void setDateCreated(Date dateCreated) { + this.dateCreated = dateCreated; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public byte[] getContent() { + return content; + } + + public void setContent(byte[] content) { + this.content = content; + } + + public String getFileInfo() { + return "File Name: " + this.getName() + "\n" + "Extension: " + this.getExtension() + "\n" + "Date Created: " + this.getDateCreated() + "\n" + "Version: " + this.getVersion() + "\n"; + } + + public Object read() { + return content; + } +} diff --git a/core-java/src/main/java/com/baeldung/polymorphism/ImageFile.java b/core-java/src/main/java/com/baeldung/polymorphism/ImageFile.java new file mode 100644 index 0000000000..ac72a40993 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/polymorphism/ImageFile.java @@ -0,0 +1,41 @@ +package com.baeldung.polymorphism; + +public class ImageFile extends GenericFile { + private int height; + private int width; + + public ImageFile(String name, int height, int width, byte[] content, String version) { + this.setHeight(height); + this.setWidth(width); + this.setContent(content); + this.setName(name); + this.setVersion(version); + this.setExtension(".jpg"); + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = height; + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = width; + } + + public String getFileInfo() { + return super.getFileInfo() + "Height: " + this.getHeight() + "\n" + "Width: " + this.getWidth(); + } + + public String read() { + return this.getContent() + .toString(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/polymorphism/TextFile.java b/core-java/src/main/java/com/baeldung/polymorphism/TextFile.java new file mode 100644 index 0000000000..8280b4ee95 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/polymorphism/TextFile.java @@ -0,0 +1,44 @@ +package com.baeldung.polymorphism; + +public class TextFile extends GenericFile { + private int wordCount; + + public TextFile(String name, String content, String version) { + String[] words = content.split(" "); + this.setWordCount(words.length > 0 ? words.length : 1); + this.setContent(content.getBytes()); + this.setName(name); + this.setVersion(version); + this.setExtension(".txt"); + } + + public int getWordCount() { + return wordCount; + } + + public void setWordCount(int wordCount) { + this.wordCount = wordCount; + } + + public String getFileInfo() { + return super.getFileInfo() + "Word Count: " + wordCount; + } + + public String read() { + return this.getContent() + .toString(); + } + + public String read(int limit) { + return this.getContent() + .toString() + .substring(0, limit); + } + + public String read(int start, int stop) { + return this.getContent() + .toString() + .substring(start, stop); + } + +} diff --git a/core-java/src/test/java/com/baeldung/comparable/ComparableUnitTest.java b/core-java/src/test/java/com/baeldung/comparable/ComparableUnitTest.java new file mode 100644 index 0000000000..e8745884b8 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/comparable/ComparableUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.comparable; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.Test; + +public class ComparableUnitTest { + + @Test + public void whenUsingComparable_thenSortedList() { + List footballTeam = new ArrayList(); + Player player1 = new Player(59, "John", 20); + Player player2 = new Player(67, "Roger", 22); + Player player3 = new Player(45, "Steven", 24); + footballTeam.add(player1); + footballTeam.add(player2); + footballTeam.add(player3); + Collections.sort(footballTeam); + assertEquals(footballTeam.get(0) + .getName(), "Steven"); + assertEquals(footballTeam.get(2) + .getRanking(), 67); + } + +} diff --git a/core-java/src/test/java/com/baeldung/comparator/ComparatorUnitTest.java b/core-java/src/test/java/com/baeldung/comparator/ComparatorUnitTest.java new file mode 100644 index 0000000000..5b7ec3bfe4 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/comparator/ComparatorUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.comparator; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class ComparatorUnitTest { + + List footballTeam; + + @Before + public void setUp() { + footballTeam = new ArrayList(); + Player player1 = new Player(59, "John", 20); + Player player2 = new Player(67, "Roger", 22); + Player player3 = new Player(45, "Steven", 24); + footballTeam.add(player1); + footballTeam.add(player2); + footballTeam.add(player3); + } + + @Test + public void whenUsingRankingComparator_thenSortedList() { + PlayerRankingComparator playerComparator = new PlayerRankingComparator(); + Collections.sort(footballTeam, playerComparator); + assertEquals(footballTeam.get(0) + .getName(), "Steven"); + assertEquals(footballTeam.get(2) + .getRanking(), 67); + } + + @Test + public void whenUsingAgeComparator_thenSortedList() { + PlayerAgeComparator playerComparator = new PlayerAgeComparator(); + Collections.sort(footballTeam, playerComparator); + assertEquals(footballTeam.get(0) + .getName(), "John"); + assertEquals(footballTeam.get(2) + .getRanking(), 45); + } + +} diff --git a/core-java/src/test/java/com/baeldung/comparator/Java8ComparatorUnitTest.java b/core-java/src/test/java/com/baeldung/comparator/Java8ComparatorUnitTest.java new file mode 100644 index 0000000000..49c8749309 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/comparator/Java8ComparatorUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.comparator; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class Java8ComparatorUnitTest { + + List footballTeam; + + @Before + public void setUp() { + footballTeam = new ArrayList(); + Player player1 = new Player(59, "John", 22); + Player player2 = new Player(67, "Roger", 20); + Player player3 = new Player(45, "Steven", 24); + footballTeam.add(player1); + footballTeam.add(player2); + footballTeam.add(player3); + } + + @Test + public void whenComparing_UsingLambda_thenSorted() { + System.out.println("************** Java 8 Comaparator **************"); + Comparator byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking(); + + System.out.println("Before Sorting : " + footballTeam); + Collections.sort(footballTeam, byRanking); + System.out.println("After Sorting : " + footballTeam); + assertEquals(footballTeam.get(0) + .getName(), "Steven"); + assertEquals(footballTeam.get(2) + .getRanking(), 67); + } + + @Test + public void whenComparing_UsingComparatorComparing_thenSorted() { + System.out.println("********* Comaparator.comparing method *********"); + System.out.println("********* byRanking *********"); + Comparator byRanking = Comparator.comparing(Player::getRanking); + + System.out.println("Before Sorting : " + footballTeam); + Collections.sort(footballTeam, byRanking); + System.out.println("After Sorting : " + footballTeam); + assertEquals(footballTeam.get(0) + .getName(), "Steven"); + assertEquals(footballTeam.get(2) + .getRanking(), 67); + + System.out.println("********* byAge *********"); + Comparator byAge = Comparator.comparing(Player::getAge); + + System.out.println("Before Sorting : " + footballTeam); + Collections.sort(footballTeam, byAge); + System.out.println("After Sorting : " + footballTeam); + assertEquals(footballTeam.get(0) + .getName(), "Roger"); + assertEquals(footballTeam.get(2) + .getRanking(), 45); + } + +} diff --git a/core-java/src/test/java/com/baeldung/file/FileOutputStreamTest.java b/core-java/src/test/java/com/baeldung/file/FileOutputStreamTest.java deleted file mode 100644 index 451c1b4c4d..0000000000 --- a/core-java/src/test/java/com/baeldung/file/FileOutputStreamTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.file; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintWriter; - -import org.junit.After; -import org.junit.Test; - -import com.baeldung.util.StreamUtils; - -public class FileOutputStreamTest { - - public static final String fileName = "src/main/resources/countries.properties"; - - @Test - public void whenAppendToFileUsingFileOutputStream_thenCorrect() throws Exception { - FileOutputStream fos = new FileOutputStream(fileName, true); - fos.write("Spain\r\n".getBytes()); - fos.close(); - - assertThat(StreamUtils.getStringFromInputStream( - new FileInputStream(fileName))) - .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); - } - - @After - public void revertFile() throws IOException { - PrintWriter writer = new PrintWriter(fileName); - writer.print("UK\r\n" + "US\r\n" + "Germany\r\n"); - writer.close(); - } -} diff --git a/core-java/src/test/java/com/baeldung/file/FileUtilsTest.java b/core-java/src/test/java/com/baeldung/file/FileUtilsTest.java deleted file mode 100644 index 9ee8726575..0000000000 --- a/core-java/src/test/java/com/baeldung/file/FileUtilsTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.file; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; - -import org.apache.commons.io.FileUtils; -import org.junit.After; -import org.junit.Test; - -import com.baeldung.util.StreamUtils; - -public class FileUtilsTest { - - public static final String fileName = "src/main/resources/countries.properties"; - - @Test - public void whenAppendToFileUsingFiles_thenCorrect() throws IOException { - File file = new File(fileName); - FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true); - - assertThat(StreamUtils.getStringFromInputStream( - new FileInputStream(fileName))) - .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); - } - - @After - public void revertFile() throws IOException { - PrintWriter writer = new PrintWriter(fileName); - writer.print("UK\r\n" + "US\r\n" + "Germany\r\n"); - writer.close(); - } -} diff --git a/core-java/src/test/java/com/baeldung/file/FileWriterTest.java b/core-java/src/test/java/com/baeldung/file/FileWriterTest.java deleted file mode 100644 index 8d2ce4310e..0000000000 --- a/core-java/src/test/java/com/baeldung/file/FileWriterTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.file; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.BufferedWriter; -import java.io.FileInputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; - -import org.junit.After; -import org.junit.Test; - -import com.baeldung.util.StreamUtils; - -public class FileWriterTest { - - public static final String fileName = "src/main/resources/countries.properties"; - - @Test - public void whenAppendToFileUsingFileWriter_thenCorrect() throws IOException { - FileWriter fw = new FileWriter(fileName, true); - BufferedWriter bw = new BufferedWriter(fw); - bw.write("Spain"); - bw.newLine(); - bw.close(); - - assertThat( - StreamUtils.getStringFromInputStream( - new FileInputStream(fileName))) - .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n"); - } - - @After - public void revertFile() throws IOException { - PrintWriter writer = new PrintWriter(fileName); - writer.print("UK\r\n" + "US\r\n" + "Germany\r\n"); - writer.close(); - } -} diff --git a/core-java/src/test/java/com/baeldung/file/FilesTest.java b/core-java/src/test/java/com/baeldung/file/FilesTest.java index bd39d004d3..e17e8580aa 100644 --- a/core-java/src/test/java/com/baeldung/file/FilesTest.java +++ b/core-java/src/test/java/com/baeldung/file/FilesTest.java @@ -2,14 +2,24 @@ package com.baeldung.file; import static org.assertj.core.api.Assertions.assertThat; +import java.io.BufferedWriter; +import java.io.File; import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; +import com.google.common.base.Charsets; +import com.google.common.io.CharSink; +import com.google.common.io.FileWriteMode; +import org.apache.commons.io.FileUtils; import org.junit.After; +import org.junit.Before; import org.junit.Test; import com.baeldung.util.StreamUtils; @@ -18,6 +28,26 @@ public class FilesTest { public static final String fileName = "src/main/resources/countries.properties"; + @Before + @After + public void setup() throws Exception { + PrintWriter writer = new PrintWriter(fileName); + writer.print("UK\r\n" + "US\r\n" + "Germany\r\n"); + writer.close(); + } + + @Test + public void whenAppendToFileUsingGuava_thenCorrect() throws IOException { + File file = new File(fileName); + CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND); + chs.write("Spain\r\n"); + + assertThat(StreamUtils.getStringFromInputStream( + new FileInputStream(fileName))) + .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + } + + @Test public void whenAppendToFileUsingFiles_thenCorrect() throws IOException { Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND); @@ -27,10 +57,38 @@ public class FilesTest { .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); } - @After - public void revertFile() throws IOException { - PrintWriter writer = new PrintWriter(fileName); - writer.print("UK\r\n" + "US\r\n" + "Germany\r\n"); - writer.close(); + @Test + public void whenAppendToFileUsingFileUtils_thenCorrect() throws IOException { + File file = new File(fileName); + FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true); + + assertThat(StreamUtils.getStringFromInputStream( + new FileInputStream(fileName))) + .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + } + + @Test + public void whenAppendToFileUsingFileOutputStream_thenCorrect() throws Exception { + FileOutputStream fos = new FileOutputStream(fileName, true); + fos.write("Spain\r\n".getBytes()); + fos.close(); + + assertThat(StreamUtils.getStringFromInputStream( + new FileInputStream(fileName))) + .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); + } + + @Test + public void whenAppendToFileUsingFileWriter_thenCorrect() throws IOException { + FileWriter fw = new FileWriter(fileName, true); + BufferedWriter bw = new BufferedWriter(fw); + bw.write("Spain"); + bw.newLine(); + bw.close(); + + assertThat( + StreamUtils.getStringFromInputStream( + new FileInputStream(fileName))) + .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n"); } } diff --git a/core-java/src/test/java/com/baeldung/file/GuavaTest.java b/core-java/src/test/java/com/baeldung/file/GuavaTest.java deleted file mode 100644 index 5a7ec6c4a8..0000000000 --- a/core-java/src/test/java/com/baeldung/file/GuavaTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.file; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.PrintWriter; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.baeldung.util.StreamUtils; -import com.google.common.base.Charsets; -import com.google.common.io.CharSink; -import com.google.common.io.FileWriteMode; -import com.google.common.io.Files; - -public class GuavaTest { - - public static final String fileName = "src/main/resources/countries.properties"; - - @Before - public void setup() throws Exception { - PrintWriter writer = new PrintWriter(fileName); - writer.print("UK\r\n" + "US\r\n" + "Germany\r\n"); - writer.close(); - } - - @Test - public void whenAppendToFileUsingGuava_thenCorrect() throws IOException { - File file = new File(fileName); - CharSink chs = Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND); - chs.write("Spain\r\n"); - - assertThat(StreamUtils.getStringFromInputStream( - new FileInputStream(fileName))) - .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); - } - - @After - public void revertFile() throws IOException { - PrintWriter writer = new PrintWriter(fileName); - writer.print("UK\r\n" + "US\r\n" + "Germany\r\n"); - writer.close(); - } -} diff --git a/core-java/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java b/core-java/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java new file mode 100644 index 0000000000..8fb606c2fc --- /dev/null +++ b/core-java/src/test/java/com/baeldung/polymorphism/PolymorphismUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.polymorphism; + +import static org.junit.Assert.*; + +import java.awt.image.BufferedImage; + +import org.junit.Ignore; +import org.junit.Test; + +public class PolymorphismUnitTest { + + @Test + public void givenImageFile_whenFileCreated_shouldSucceed() { + ImageFile imageFile = FileManager.createImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString() + .getBytes(), "v1.0.0"); + assertEquals(200, imageFile.getHeight()); + } + + // Downcasting then Upcasting + @Test + public void givenTextFile_whenTextFileCreatedAndAssignedToGenericFileAndCastBackToTextFileOnGetWordCount_shouldSucceed() { + GenericFile textFile = FileManager.createTextFile("SampleTextFile", "This is a sample text content", "v1.0.0"); + TextFile textFile2 = (TextFile) textFile; + assertEquals(6, textFile2.getWordCount()); + } + + // Downcasting + @Test(expected = ClassCastException.class) + public void givenGenericFile_whenCastToTextFileAndInvokeGetWordCount_shouldFail() { + GenericFile genericFile = new GenericFile(); + TextFile textFile = (TextFile) genericFile; + System.out.println(textFile.getWordCount()); + } +} diff --git a/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java b/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java new file mode 100644 index 0000000000..509c8764d2 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java @@ -0,0 +1,60 @@ +package com.baeldung.varargs; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class FormatterTest { + + private final static String FORMAT = "%s %s %s"; + + @Test + public void givenNoArgument_thenEmptyAndTwoSpacesAreReturned() { + String actualResult = format(); + + assertThat(actualResult, is("empty ")); + } + + @Test + public void givenOneArgument_thenResultHasTwoTrailingSpace() { + String actualResult = format("baeldung"); + + assertThat(actualResult, is("baeldung ")); + } + + @Test + public void givenTwoArguments_thenOneTrailingSpaceExists() { + String actualResult = format("baeldung", "rocks"); + + assertThat(actualResult, is("baeldung rocks ")); + } + + @Test + public void givenMoreThanThreeArguments_thenTheFirstThreeAreUsed() { + String actualResult = formatWithVarArgs("baeldung", "rocks", "java", "and", "spring"); + + assertThat(actualResult, is("baeldung rocks java")); + } + + public String format() { + return format("empty", ""); + } + + public String format(String value) { + return format(value, ""); + } + + public String format(String val1, String val2) { + return String.format(FORMAT, val1, val2, ""); + } + + public String formatWithVarArgs(String... values) { + if (values.length == 0) { + return "no arguments given"; + } + + return String.format(FORMAT, values); + } + +} \ No newline at end of file diff --git a/logging-modules/log4j/README.md b/logging-modules/log4j/README.md index 3c0258142c..8aae1b5826 100644 --- a/logging-modules/log4j/README.md +++ b/logging-modules/log4j/README.md @@ -2,6 +2,5 @@ - [Introduction to Java Logging](http://www.baeldung.com/java-logging-intro) - [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback) - [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode) -- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java) - [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback) - [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders) diff --git a/lucene/pom.xml b/lucene/pom.xml index 42b81a7d4a..6659d9ac32 100644 --- a/lucene/pom.xml +++ b/lucene/pom.xml @@ -31,7 +31,5 @@ 4.12 test - - \ No newline at end of file diff --git a/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java b/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java index 40a35fad86..97b1ec7b5d 100644 --- a/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java +++ b/lucene/src/main/java/com/baeldung/lucene/InMemoryLuceneIndex.java @@ -7,18 +7,22 @@ import java.util.List; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; +import org.apache.lucene.document.SortedDocValuesField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; +import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; +import org.apache.lucene.search.Sort; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; +import org.apache.lucene.util.BytesRef; public class InMemoryLuceneIndex { @@ -45,6 +49,7 @@ public class InMemoryLuceneIndex { document.add(new TextField("title", title, Field.Store.YES)); document.add(new TextField("body", body, Field.Store.YES)); + document.add(new SortedDocValuesField("title", new BytesRef(title))); writter.addDocument(document); writter.close(); @@ -73,6 +78,51 @@ public class InMemoryLuceneIndex { } + public void deleteDocument(Term term) { + try { + IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); + IndexWriter writter = new IndexWriter(memoryIndex, indexWriterConfig); + writter.deleteDocuments(term); + writter.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public List searchIndex(Query query) { + try { + IndexReader indexReader = DirectoryReader.open(memoryIndex); + IndexSearcher searcher = new IndexSearcher(indexReader); + TopDocs topDocs = searcher.search(query, 10); + List documents = new ArrayList<>(); + for (ScoreDoc scoreDoc : topDocs.scoreDocs) { + documents.add(searcher.doc(scoreDoc.doc)); + } + + return documents; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + + } + + public List searchIndex(Query query, Sort sort) { + try { + IndexReader indexReader = DirectoryReader.open(memoryIndex); + IndexSearcher searcher = new IndexSearcher(indexReader); + TopDocs topDocs = searcher.search(query, 10, sort); + List documents = new ArrayList<>(); + for (ScoreDoc scoreDoc : topDocs.scoreDocs) { + documents.add(searcher.doc(scoreDoc.doc)); + } + + return documents; + } catch (IOException e) { + e.printStackTrace(); + } + return null; + + } + } - - diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java index c3a498a4b8..acf688cb99 100644 --- a/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java +++ b/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java @@ -4,7 +4,19 @@ import java.util.List; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.BooleanClause; +import org.apache.lucene.search.BooleanQuery; +import org.apache.lucene.search.FuzzyQuery; +import org.apache.lucene.search.PhraseQuery; +import org.apache.lucene.search.PrefixQuery; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.Sort; +import org.apache.lucene.search.SortField; +import org.apache.lucene.search.TermQuery; +import org.apache.lucene.search.WildcardQuery; import org.apache.lucene.store.RAMDirectory; +import org.apache.lucene.util.BytesRef; import org.junit.Assert; import org.junit.Test; @@ -20,4 +32,121 @@ public class LuceneInMemorySearchTest { Assert.assertEquals("Hello world", documents.get(0).get("title")); } -} + @Test + public void givenTermQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("activity", "running in track"); + inMemoryLuceneIndex.indexDocument("activity", "Cars are running on road"); + + Term term = new Term("body", "running"); + Query query = new TermQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(2, documents.size()); + } + + @Test + public void givenPrefixQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("article", "Lucene introduction"); + inMemoryLuceneIndex.indexDocument("article", "Introduction to Lucene"); + + Term term = new Term("body", "intro"); + Query query = new PrefixQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(2, documents.size()); + } + + @Test + public void givenBooleanQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("Destination", "Las Vegas singapore car"); + inMemoryLuceneIndex.indexDocument("Commutes in singapore", "Bus Car Bikes"); + + Term term1 = new Term("body", "singapore"); + Term term2 = new Term("body", "car"); + + TermQuery query1 = new TermQuery(term1); + TermQuery query2 = new TermQuery(term2); + + BooleanQuery booleanQuery = new BooleanQuery.Builder().add(query1, BooleanClause.Occur.MUST) + .add(query2, BooleanClause.Occur.MUST).build(); + + List documents = inMemoryLuceneIndex.searchIndex(booleanQuery); + Assert.assertEquals(1, documents.size()); + } + + @Test + public void givenPhraseQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("quotes", "A rose by any other name would smell as sweet."); + + Query query = new PhraseQuery(1, "body", new BytesRef("smell"), new BytesRef("sweet")); + List documents = inMemoryLuceneIndex.searchIndex(query); + + Assert.assertEquals(1, documents.size()); + } + + @Test + public void givenFuzzyQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("article", "Halloween Festival"); + inMemoryLuceneIndex.indexDocument("decoration", "Decorations for Halloween"); + + Term term = new Term("body", "hallowen"); + Query query = new FuzzyQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(2, documents.size()); + } + + @Test + public void givenWildCardQueryWhenFetchedDocumentThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("article", "Lucene introduction"); + inMemoryLuceneIndex.indexDocument("article", "Introducing Lucene with Spring"); + + Term term = new Term("body", "intro*"); + Query query = new WildcardQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(2, documents.size()); + } + + @Test + public void givenSortFieldWhenSortedThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("Ganges", "River in India"); + inMemoryLuceneIndex.indexDocument("Mekong", "This river flows in south Asia"); + inMemoryLuceneIndex.indexDocument("Amazon", "Rain forest river"); + inMemoryLuceneIndex.indexDocument("Rhine", "Belongs to Europe"); + inMemoryLuceneIndex.indexDocument("Nile", "Longest River"); + + Term term = new Term("body", "river"); + Query query = new WildcardQuery(term); + + SortField sortField = new SortField("title", SortField.Type.STRING_VAL, false); + Sort sortByTitle = new Sort(sortField); + + List documents = inMemoryLuceneIndex.searchIndex(query, sortByTitle); + Assert.assertEquals(4, documents.size()); + Assert.assertEquals("Amazon", documents.get(0).getField("title").stringValue()); + } + + @Test + public void whenDocumentDeletedThenCorrect() { + InMemoryLuceneIndex inMemoryLuceneIndex = new InMemoryLuceneIndex(new RAMDirectory(), new StandardAnalyzer()); + inMemoryLuceneIndex.indexDocument("Ganges", "River in India"); + inMemoryLuceneIndex.indexDocument("Mekong", "This river flows in south Asia"); + + Term term = new Term("title", "ganges"); + inMemoryLuceneIndex.deleteDocument(term); + + Query query = new TermQuery(term); + + List documents = inMemoryLuceneIndex.searchIndex(query); + Assert.assertEquals(0, documents.size()); + } + +} \ No newline at end of file diff --git a/muleesb/.gitignore b/muleesb/.gitignore new file mode 100644 index 0000000000..541f92c42e --- /dev/null +++ b/muleesb/.gitignore @@ -0,0 +1 @@ +# Add any directories, files, or patterns you don't want to be tracked by version control \ No newline at end of file diff --git a/muleesb/.mule/objectstore/b2fe1a90-c473-11e7-8eb5-98e7f44e8ac8/partition-descriptor b/muleesb/.mule/objectstore/b2fe1a90-c473-11e7-8eb5-98e7f44e8ac8/partition-descriptor new file mode 100644 index 0000000000..0b8060f303 --- /dev/null +++ b/muleesb/.mule/objectstore/b2fe1a90-c473-11e7-8eb5-98e7f44e8ac8/partition-descriptor @@ -0,0 +1 @@ +DEFAULT_PARTITION \ No newline at end of file diff --git a/muleesb/.mule/queue-tx-log/tx1.log b/muleesb/.mule/queue-tx-log/tx1.log new file mode 100644 index 0000000000..e69de29bb2 diff --git a/muleesb/.mule/queue-tx-log/tx2.log b/muleesb/.mule/queue-tx-log/tx2.log new file mode 100644 index 0000000000..e69de29bb2 diff --git a/muleesb/.mule/queue-xa-tx-log/tx1.log b/muleesb/.mule/queue-xa-tx-log/tx1.log new file mode 100644 index 0000000000..e69de29bb2 diff --git a/muleesb/.mule/queue-xa-tx-log/tx2.log b/muleesb/.mule/queue-xa-tx-log/tx2.log new file mode 100644 index 0000000000..e69de29bb2 diff --git a/muleesb/mule-project.xml b/muleesb/mule-project.xml new file mode 100644 index 0000000000..0d522b0141 --- /dev/null +++ b/muleesb/mule-project.xml @@ -0,0 +1,5 @@ + + + muleesb + + diff --git a/muleesb/pom.xml b/muleesb/pom.xml new file mode 100644 index 0000000000..2c88bf83da --- /dev/null +++ b/muleesb/pom.xml @@ -0,0 +1,214 @@ + + + + 4.0.0 + com.mycompany + muleesb + 1.0.0-SNAPSHOT + mule + Mule muleesb Application + + + UTF-8 + UTF-8 + + 3.8.1 + 1.2 + 1.3.6 + 3.9.0 + + + + + + org.mule.tools.maven + mule-app-maven-plugin + ${mule.tools.version} + true + + true + + + + org.mule.tools + muleesb-maven-plugin + 1.0 + + 3.7.0 + /home/abir/AnypointStudio/workspace/variablescopetest + + + + deploy + + start + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.7 + + + add-resource + generate-resources + + add-resource + + + + + src/main/app/ + + + mappings/ + + + src/main/api/ + + + + + + + + com.mulesoft.munit.tools + munit-maven-plugin + ${munit.version} + + + test + test + + test + + + + + + true + + html + + + + + + + + src/test/munit + + + src/test/resources + + + + + + + + + org.mule.modules + mule-module-spring-config + ${mule.version} + provided + + + + org.mule.transports + mule-transport-file + ${mule.version} + provided + + + org.mule.transports + mule-transport-http + ${mule.version} + provided + + + org.mule.transports + mule-transport-jdbc + ${mule.version} + provided + + + org.mule.transports + mule-transport-jms + ${mule.version} + provided + + + org.mule.transports + mule-transport-vm + ${mule.version} + provided + + + + org.mule.modules + mule-module-scripting + ${mule.version} + provided + + + org.mule.modules + mule-module-xml + ${mule.version} + provided + + + + org.mule.tests + mule-tests-functional + ${mule.version} + test + + + org.mule.modules + mule-module-apikit + ${mule.version} + provided + + + com.mulesoft.munit + mule-munit-support + ${mule.munit.support.version} + test + + + com.mulesoft.munit + munit-runner + ${munit.version} + test + + + + + + Central + Central + http://repo1.maven.org/maven2/ + default + + + mulesoft-releases + MuleSoft Releases Repository + http://repository.mulesoft.org/releases/ + default + + + + + mulesoft-release + mulesoft release repository + default + http://repository.mulesoft.org/releases/ + + false + + + + diff --git a/muleesb/src/main/app/mule-app.properties b/muleesb/src/main/app/mule-app.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/muleesb/src/main/app/mule-deploy.properties b/muleesb/src/main/app/mule-deploy.properties new file mode 100644 index 0000000000..07eabe9cc6 --- /dev/null +++ b/muleesb/src/main/app/mule-deploy.properties @@ -0,0 +1,6 @@ +#** GENERATED CONTENT ** Mule Application Deployment Descriptor +#Mon Nov 06 15:54:37 BDT 2017 +redeployment.enabled=true +encoding=UTF-8 +domain=default +config.resources=variablescopetest.xml diff --git a/muleesb/src/main/app/variablescopetest.xml b/muleesb/src/main/app/variablescopetest.xml new file mode 100644 index 0000000000..518b901084 --- /dev/null +++ b/muleesb/src/main/app/variablescopetest.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/muleesb/src/main/java/com/baeldung/transformer/FromFlow2Component.java b/muleesb/src/main/java/com/baeldung/transformer/FromFlow2Component.java new file mode 100644 index 0000000000..0e180062a7 --- /dev/null +++ b/muleesb/src/main/java/com/baeldung/transformer/FromFlow2Component.java @@ -0,0 +1,18 @@ +package com.baeldung.transformer; + +import org.mule.api.MuleEventContext; +import org.mule.api.MuleMessage; +import org.mule.api.lifecycle.Callable; + +public class FromFlow2Component implements Callable { + + @Override + public Object onCall(MuleEventContext eventContext) throws Exception { + + MuleMessage message = eventContext.getMessage(); + message.setPayload("Converted in flow 2"); + + return message; + } + +} diff --git a/muleesb/src/main/java/com/baeldung/transformer/InitializationTransformer.java b/muleesb/src/main/java/com/baeldung/transformer/InitializationTransformer.java new file mode 100644 index 0000000000..1e1ad15be8 --- /dev/null +++ b/muleesb/src/main/java/com/baeldung/transformer/InitializationTransformer.java @@ -0,0 +1,29 @@ +package com.baeldung.transformer; + +import org.mule.api.MuleMessage; +import org.mule.api.transformer.TransformerException; +import org.mule.api.transport.PropertyScope; +import org.mule.transformer.AbstractMessageTransformer; + +public class InitializationTransformer extends AbstractMessageTransformer { + + @Override + public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException { + // TODO Auto-generated method stub + + String payload = null; + + try { + payload = message.getPayloadAsString(); + }catch (Exception e) { + e.printStackTrace(); + } + + System.out.println("Logged Payload: "+payload); + message.setPayload("Payload from Initialization"); + message.setProperty("outboundKey", "outboundpropertyvalue",PropertyScope.OUTBOUND); + + + return message; + } +} \ No newline at end of file diff --git a/muleesb/src/main/java/com/baeldung/transformer/InvokingMessageComponent.java b/muleesb/src/main/java/com/baeldung/transformer/InvokingMessageComponent.java new file mode 100644 index 0000000000..105522e5b4 --- /dev/null +++ b/muleesb/src/main/java/com/baeldung/transformer/InvokingMessageComponent.java @@ -0,0 +1,16 @@ +package com.baeldung.transformer; + +import org.mule.api.MuleMessage; +import org.mule.api.transformer.TransformerException; +import org.mule.transformer.AbstractMessageTransformer; + +public class InvokingMessageComponent extends AbstractMessageTransformer { + + @Override + public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException { + // TODO Auto-generated method stub + String InboundProp = (String) message.getInboundProperty("outboundKey"); + System.out.println("InboundProp:" + InboundProp); + return InboundProp; + } +} \ No newline at end of file diff --git a/muleesb/src/main/resources/log4j2.xml b/muleesb/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..98c4b02433 --- /dev/null +++ b/muleesb/src/main/resources/log4j2.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/muleesb/src/test/munit/variablescopetest-test-suite.xml b/muleesb/src/test/munit/variablescopetest-test-suite.xml new file mode 100644 index 0000000000..43e410a327 --- /dev/null +++ b/muleesb/src/test/munit/variablescopetest-test-suite.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/muleesb/src/test/resources/log4j2-test.xml b/muleesb/src/test/resources/log4j2-test.xml new file mode 100644 index 0000000000..6351ae041c --- /dev/null +++ b/muleesb/src/test/resources/log4j2-test.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/noexception/README.md b/noexception/README.md index d840191369..9dd4c11190 100644 --- a/noexception/README.md +++ b/noexception/README.md @@ -1,2 +1,2 @@ ### Relevant Articles: -- [Introduction to NoException](http://www.baeldung.com/intrduction-to-noexception) +- [Introduction to NoException](http://www.baeldung.com/introduction-to-noexception) diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java index 61d821e85e..614de6d3ad 100644 --- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.hibernate.manytomany; - import java.util.HashSet; import java.util.Set; import org.hibernate.Session; @@ -17,10 +16,8 @@ import com.baeldung.hibernate.manytomany.model.Employee; import com.baeldung.hibernate.manytomany.model.Project; import com.baeldung.manytomany.spring.PersistenceConfig; - - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest { @Autowired @@ -28,7 +25,6 @@ public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest { private Session session; - @Before public final void before() { session = sessionFactory.openSession(); @@ -43,11 +39,11 @@ public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest { @Test public final void whenEntitiesAreCreated_thenNoExceptions() { - Set projects = new HashSet(); - projects.add(new Project("IT Project")); - projects.add(new Project("Networking Project")); - session.persist(new Employee("Peter", "Oven", projects)); - session.persist(new Employee("Allan", "Norman", projects)); + Set projects = new HashSet(); + projects.add(new Project("IT Project")); + projects.add(new Project("Networking Project")); + session.persist(new Employee("Peter", "Oven", projects)); + session.persist(new Employee("Allan", "Norman", projects)); } } diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java new file mode 100644 index 0000000000..6b0a6f9808 --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java @@ -0,0 +1,33 @@ +package com.baeldung.jupiter; + +import static org.junit.Assert.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +/** + * @SpringJUnitConfig(SpringJUnitConfigTest.Config.class) is equivalent to: + * + * @ExtendWith(SpringExtension.class) + * @ContextConfiguration(classes = SpringJUnitConfigTest.Config.class ) + * + */ +@SpringJUnitConfig(SpringJUnitConfigTest.Config.class) +public class SpringJUnitConfigTest { + + @Configuration + static class Config { + } + + @Autowired + private ApplicationContext applicationContext; + + @Test + void givenAppContext_WhenInjected_ThenItShouldNotBeNull() { + assertNotNull(applicationContext); + } + +} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java new file mode 100644 index 0000000000..c679dce77f --- /dev/null +++ b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java @@ -0,0 +1,34 @@ +package com.baeldung.jupiter; + +import static org.junit.Assert.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; +import org.springframework.web.context.WebApplicationContext; + +/** + * @SpringJUnitWebConfig(SpringJUnitWebConfigTest.Config.class) is equivalent to: + * + * @ExtendWith(SpringExtension.class) + * @WebAppConfiguration + * @ContextConfiguration(classes = SpringJUnitWebConfigTest.Config.class ) + * + */ +@SpringJUnitWebConfig(SpringJUnitWebConfigTest.Config.class) +public class SpringJUnitWebConfigTest { + + @Configuration + static class Config { + } + + @Autowired + private WebApplicationContext webAppContext; + + @Test + void givenWebAppContext_WhenInjected_ThenItShouldNotBeNull() { + assertNotNull(webAppContext); + } + +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/Application.java b/spring-security-mvc-boot/src/main/java/org/baeldung/Application.java index b3c98c3e71..8a40744bdc 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/Application.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/Application.java @@ -5,12 +5,13 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.FilterType; @Configuration @EnableAutoConfiguration -@ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*"), @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.multipleauthproviders.*"), - @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.multiplelogin.*"), @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.multipleentrypoints.*") }) +@ComponentScan({ "org.baeldung.config", "org.baeldung.persistence", "org.baeldung.security", "org.baeldung.web" }) +// @ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*"), @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.multipleauthproviders.*"), +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.multiplelogin.*"), @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.multipleentrypoints.*"), +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.rolesauthorities.*"), @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.acl.*") }) public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..cf1ac7de89 --- /dev/null +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,15 @@ +package org.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/undertow/dependency-reduced-pom.xml b/undertow/dependency-reduced-pom.xml new file mode 100644 index 0000000000..0654c82b74 --- /dev/null +++ b/undertow/dependency-reduced-pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + com.baeldung.undertow + undertow + undertow + 1.0-SNAPSHOT + http://maven.apache.org + + ${project.artifactId} + + + maven-shade-plugin + + + package + + shade + + + + + + maven-jar-plugin + + + + com.baeldung.undertow.SimpleServer + + + + + + + + 1.8 + 1.8 + + +