diff --git a/bootique/config.yml b/bootique/config.yml new file mode 100644 index 0000000000..269b4ab867 --- /dev/null +++ b/bootique/config.yml @@ -0,0 +1,11 @@ +log: + level: warn + appenders: + - type: file + logFormat: '%c{20}: %m%n' + file: /home/logger.log + +jetty: + context: /hello + connector: + port: 10001 diff --git a/bootique/dependency-reduced-pom.xml b/bootique/dependency-reduced-pom.xml new file mode 100644 index 0000000000..ed18f4e42a --- /dev/null +++ b/bootique/dependency-reduced-pom.xml @@ -0,0 +1,50 @@ + + + + bootique-parent + io.bootique.parent + 0.12 + + 4.0.0 + com.baeldung.bootique + bootique + bootique + 1.0-SNAPSHOT + http://maven.apache.org + + + + maven-shade-plugin + + + + + + io.bootique + bootique-test + 0.23 + test + + + junit + junit + 3.8.1 + test + + + + + + io.bootique.bom + bootique-bom + 0.23 + pom + import + + + + + com.baeldung.bootique.App + + + diff --git a/bootique/pom.xml b/bootique/pom.xml new file mode 100644 index 0000000000..28b716e104 --- /dev/null +++ b/bootique/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + com.baeldung.bootique + bootique + jar + 1.0-SNAPSHOT + bootique + http://maven.apache.org + + + com.baeldung.bootique.App + + + + io.bootique.parent + bootique-parent + 0.12 + + + + + + io.bootique.bom + bootique-bom + 0.23 + pom + import + + + + + + + io.bootique.jersey + bootique-jersey + compile + + + io.bootique.logback + bootique-logback + compile + + + io.bootique + bootique-test + test + + + junit + junit + 4.12 + test + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + + \ No newline at end of file diff --git a/bootique/src/main/java/com/baeldung/bootique/App.java b/bootique/src/main/java/com/baeldung/bootique/App.java new file mode 100644 index 0000000000..cc1b90ce7d --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/App.java @@ -0,0 +1,41 @@ +package com.baeldung.bootique; + +import com.baeldung.bootique.module.ModuleBinder; +import com.baeldung.bootique.router.IndexController; +import com.baeldung.bootique.router.SaveController; +import com.google.inject.Module; +import io.bootique.Bootique; +import io.bootique.jersey.JerseyModule; +import io.bootique.log.BootLogger; + +import java.util.function.Supplier; + +public class App { + + public static void main(String[] args) { + Module module = binder -> JerseyModule.extend(binder).addResource(IndexController.class) + .addResource(SaveController.class); + Bootique.app(args).module(module).module(ModuleBinder.class).bootLogger(new BootLogger() { + @Override + public void trace(Supplier arg0) { + // ... + } + + @Override + public void stdout(String arg0) { + // ... + } + + @Override + public void stderr(String arg0, Throwable arg1) { + // ... + } + + @Override + public void stderr(String arg0) { + // ... + } + }).autoLoadModules().exec(); + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java b/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java new file mode 100644 index 0000000000..8811d48652 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/module/ModuleBinder.java @@ -0,0 +1,15 @@ +package com.baeldung.bootique.module; + +import com.baeldung.bootique.service.HelloService; +import com.baeldung.bootique.service.impl.HelloServiceImpl; +import com.google.inject.Binder; +import com.google.inject.Module; + +public class ModuleBinder implements Module { + + @Override + public void configure(Binder binder) { + binder.bind(HelloService.class).to(HelloServiceImpl.class); + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java b/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java new file mode 100644 index 0000000000..cf78177e6d --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/module/ModuleProvider.java @@ -0,0 +1,13 @@ +package com.baeldung.bootique.module; + +import com.google.inject.Module; +import io.bootique.BQModuleProvider; + +public class ModuleProvider implements BQModuleProvider { + + @Override + public Module module() { + return new ModuleBinder(); + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java b/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java new file mode 100644 index 0000000000..6e3b31df41 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/router/IndexController.java @@ -0,0 +1,14 @@ +package com.baeldung.bootique.router; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/") +public class IndexController { + + @GET + public String index() { + return "Hello, baeldung!"; + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java b/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java new file mode 100644 index 0000000000..f38f59708c --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/router/SaveController.java @@ -0,0 +1,20 @@ +package com.baeldung.bootique.router; + +import com.baeldung.bootique.service.HelloService; +import com.google.inject.Inject; + +import javax.ws.rs.POST; +import javax.ws.rs.Path; + +@Path("/save") +public class SaveController { + + @Inject + HelloService helloService; + + @POST + public String save() { + return "Data Saved!"; + } + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/service/HelloService.java b/bootique/src/main/java/com/baeldung/bootique/service/HelloService.java new file mode 100644 index 0000000000..74c0401cc3 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/service/HelloService.java @@ -0,0 +1,7 @@ +package com.baeldung.bootique.service; + +public interface HelloService { + + boolean save(); + +} diff --git a/bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java b/bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java new file mode 100644 index 0000000000..d2c0b5b838 --- /dev/null +++ b/bootique/src/main/java/com/baeldung/bootique/service/impl/HelloServiceImpl.java @@ -0,0 +1,12 @@ +package com.baeldung.bootique.service.impl; + +import com.baeldung.bootique.service.HelloService; + +public class HelloServiceImpl implements HelloService { + + @Override + public boolean save() { + return true; + } + +} diff --git a/bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider b/bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider new file mode 100644 index 0000000000..714cf3a2df --- /dev/null +++ b/bootique/src/main/resources/META-INF/services/io.bootique.BQModuleProvider @@ -0,0 +1 @@ +com.baeldung.bootique.module.ModuleProvider \ No newline at end of file diff --git a/bootique/src/test/java/com/baeldung/bootique/AppTest.java b/bootique/src/test/java/com/baeldung/bootique/AppTest.java new file mode 100644 index 0000000000..8856780ed4 --- /dev/null +++ b/bootique/src/test/java/com/baeldung/bootique/AppTest.java @@ -0,0 +1,27 @@ +package com.baeldung.bootique; + +import com.baeldung.bootique.service.HelloService; +import io.bootique.BQRuntime; +import io.bootique.test.junit.BQDaemonTestFactory; +import io.bootique.test.junit.BQTestFactory; +import org.junit.Rule; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AppTest { + + @Rule + public BQTestFactory bqTestFactory = new BQTestFactory(); + + @Rule + public BQDaemonTestFactory bqDaemonTestFactory = new BQDaemonTestFactory(); + + @Test + public void givenService_expectBoolen() { + BQRuntime runtime = bqTestFactory.app("--server").autoLoadModules().createRuntime(); + HelloService service = runtime.getInstance(HelloService.class); + assertEquals(true, service.save()); + } + +} diff --git a/core-java/hashcode/pom.xml b/core-java/hashcode/pom.xml deleted file mode 100644 index 393aa69153..0000000000 --- a/core-java/hashcode/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - com.baeldung.hashcode - hashcode - 1.0 - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - - - junit - junit - 4.12 - test - - - org.slf4j - slf4j-api - 1.7.25 - - - org.slf4j - slf4j-simple - 1.7.25 - - - \ No newline at end of file diff --git a/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java b/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java deleted file mode 100644 index dcd853f451..0000000000 --- a/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.application; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import static org.junit.Assert.assertEquals; - -public class ApplicationTest { - - private ByteArrayOutputStream outContent; - - @Before - public void setUpPrintStreamInstance() throws Exception { - this.outContent = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outContent)); - } - - @After - public void tearDownByteArrayOutputStream() throws Exception { - outContent = null; - } - - @Test - public void main_NoInputState_TextPrintedToConsole() throws Exception { - Application.main(new String[]{}); - assertEquals("User found in the collection", outContent.toString()); - } -} \ No newline at end of file diff --git a/core-java/pom.xml b/core-java/pom.xml index 78338fc439..422965a0ed 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -80,7 +80,11 @@ - + + log4j + log4j + 1.2.17 + org.slf4j slf4j-api @@ -391,7 +395,7 @@ 1.1.7 - 21.0 + 22.0 3.5 1.55 1.10 diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java index 977dae4fdb..758bdecd0c 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierDemo.java @@ -15,14 +15,12 @@ public class CyclicBarrierDemo { private int NUM_PARTIAL_RESULTS; private int NUM_WORKERS; - private void runSimulation(int numWorkers, int numberOfPartialResults) { NUM_PARTIAL_RESULTS = numberOfPartialResults; NUM_WORKERS = numWorkers; cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread()); - System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " - + NUM_PARTIAL_RESULTS + " partial results each"); + System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " + NUM_PARTIAL_RESULTS + " partial results each"); for (int i = 0; i < NUM_WORKERS; i++) { Thread worker = new Thread(new NumberCruncherThread()); worker.setName("Thread " + i); @@ -38,8 +36,7 @@ public class CyclicBarrierDemo { List partialResult = new ArrayList<>(); for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) { Integer num = random.nextInt(10); - System.out.println(thisThreadName - + ": Crunching some numbers! Final result - " + num); + System.out.println(thisThreadName + ": Crunching some numbers! Final result - " + num); partialResult.add(num); } partialResults.add(partialResult); @@ -57,13 +54,12 @@ public class CyclicBarrierDemo { @Override public void run() { String thisThreadName = Thread.currentThread().getName(); - System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS - + " workers, having " + NUM_PARTIAL_RESULTS + " results each."); + System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS + " workers, having " + NUM_PARTIAL_RESULTS + " results each."); int sum = 0; for (List threadResult : partialResults) { System.out.print("Adding "); for (Integer partialResult : threadResult) { - System.out.print(partialResult+" "); + System.out.print(partialResult + " "); sum += partialResult; } System.out.println(); diff --git a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java b/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java index c5672706ad..4de420900a 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java +++ b/core-java/src/main/java/com/baeldung/concurrent/diningphilosophers/Philosopher.java @@ -15,7 +15,8 @@ public class Philosopher implements Runnable { Thread.sleep(((int) (Math.random() * 100))); } - @Override public void run() { + @Override + public void run() { try { while (true) { doAction(System.nanoTime() + ": Thinking"); // thinking diff --git a/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java index ae2b279d9a..83a9fb6692 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java @@ -6,22 +6,22 @@ import java.util.concurrent.TimeUnit; public class ExecutorServiceDemo { - ExecutorService executor = Executors.newFixedThreadPool(10); + ExecutorService executor = Executors.newFixedThreadPool(10); - public void execute() { + public void execute() { - executor.submit(() -> { - new Task(); - }); + executor.submit(() -> { + new Task(); + }); - executor.shutdown(); - executor.shutdownNow(); - try { - executor.awaitTermination(20l, TimeUnit.NANOSECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } + executor.shutdown(); + executor.shutdownNow(); + try { + executor.awaitTermination(20l, TimeUnit.NANOSECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } - } + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java index 7cb611be0f..4794d5cb61 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java +++ b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java @@ -9,36 +9,36 @@ import java.util.concurrent.TimeoutException; public class FutureDemo { - public String invoke() { + public String invoke() { - String str = null; + String str = null; - ExecutorService executorService = Executors.newFixedThreadPool(10); + ExecutorService executorService = Executors.newFixedThreadPool(10); - Future future = executorService.submit(() -> { - // Task - Thread.sleep(10000l); - return "Hellow world"; - }); + Future future = executorService.submit(() -> { + // Task + Thread.sleep(10000l); + return "Hellow world"; + }); - future.cancel(false); + future.cancel(false); - try { - future.get(20, TimeUnit.SECONDS); - } catch (InterruptedException | ExecutionException | TimeoutException e1) { - e1.printStackTrace(); - } + try { + future.get(20, TimeUnit.SECONDS); + } catch (InterruptedException | ExecutionException | TimeoutException e1) { + e1.printStackTrace(); + } - if (future.isDone() && !future.isCancelled()) { - try { - str = future.get(); - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - } - } + if (future.isDone() && !future.isCancelled()) { + try { + str = future.get(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + } - return str; + return str; - } + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java index 8744027e40..f708804cae 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java +++ b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java @@ -4,20 +4,20 @@ import java.util.concurrent.ThreadFactory; public class BaeldungThreadFactory implements ThreadFactory { - private int threadId; - private String name; + private int threadId; + private String name; - public BaeldungThreadFactory(String name) { - threadId = 1; - this.name = name; - } + public BaeldungThreadFactory(String name) { + threadId = 1; + this.name = name; + } - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r, name + "-Thread_" + threadId); - System.out.println("created new thread with id : " + threadId + " and name : " + t.getName()); - threadId++; - return t; - } + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r, name + "-Thread_" + threadId); + System.out.println("created new thread with id : " + threadId + " and name : " + t.getName()); + threadId++; + return t; + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java index 04ba62d457..a69623c667 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java +++ b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java @@ -2,9 +2,9 @@ package com.baeldung.concurrent.threadfactory; public class Task implements Runnable { - @Override - public void run() { - // task details - } - + @Override + public void run() { + // task details + } + } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java new file mode 100644 index 0000000000..0d69d0e7ec --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java @@ -0,0 +1,13 @@ +package com.baeldung.designpatterns.adapter; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class AdapterPatternDriver { + + public static void main(String args[]) { + LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl(); + LOG.info("Bugatti Veyron Super Sport's top speed is " + luxuryCars.bugattiVeyronInKMPH() + " Kmph."); + LOG.info("McLaren F1 top speed is " + luxuryCars.mcLarenInKMPH() + " Kmph."); + LOG.info("Aston Martin One-77 top speed is " + luxuryCars.astonMartinInKMPH() + " Kmph."); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java new file mode 100644 index 0000000000..278329b994 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.adapter; + +public class LuxuryCarsSpeed { + public double bugattiVeyronInMPH() { + return 268; + } + + public double mcLarenInMPH() { + return 241; + } + + public double astonMartinInMPH() { + return 220; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java new file mode 100644 index 0000000000..84f7be2729 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java @@ -0,0 +1,7 @@ +package com.baeldung.designpatterns.adapter; + +public interface LuxuryCarsSpeedAdapter { + public double bugattiVeyronInKMPH(); + public double mcLarenInKMPH(); + public double astonMartinInKMPH(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java new file mode 100644 index 0000000000..2767b78e38 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java @@ -0,0 +1,26 @@ +package com.baeldung.designpatterns.adapter; + +public class LuxuryCarsSpeedAdapterImpl extends LuxuryCarsSpeed implements LuxuryCarsSpeedAdapter { + + @Override + public double bugattiVeyronInKMPH() { + double mph = super.bugattiVeyronInMPH(); + return convertMPHtoKMPH(mph); + } + + @Override + public double mcLarenInKMPH() { + double mph = super.mcLarenInMPH(); + return convertMPHtoKMPH(mph); + } + + @Override + public double astonMartinInKMPH() { + double mph = super.astonMartinInMPH(); + return convertMPHtoKMPH(mph); + } + + private double convertMPHtoKMPH(double mph) { + return mph * 1.60934; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java new file mode 100644 index 0000000000..97a4a9508c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Blue.java @@ -0,0 +1,12 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Blue implements Color { + + @Override + public void fillColor() { + LOG.info("Color : Blue"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java new file mode 100644 index 0000000000..921deadcac --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/BridgePatternDriver.java @@ -0,0 +1,14 @@ +package com.baeldung.designpatterns.bridge; + +public class BridgePatternDriver { + + public static void main(String[] args) { + //a square with red color + Shape square = new Square(new Red()); + square.drawShape(); + + //a triangle with blue color + Shape triangle = new Triangle(new Blue()); + triangle.drawShape(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java new file mode 100644 index 0000000000..91d2b01609 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Color.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.bridge; + +public interface Color { + public void fillColor(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java new file mode 100644 index 0000000000..8c22a94f00 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Red.java @@ -0,0 +1,12 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Red implements Color { + + @Override + public void fillColor() { + LOG.info("Color : Red"); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java new file mode 100644 index 0000000000..c4daf7a821 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Shape.java @@ -0,0 +1,11 @@ +package com.baeldung.designpatterns.bridge; + +public abstract class Shape { + protected Color color; + + public Shape(Color color) { + this.color = color; + } + + abstract public void drawShape(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java new file mode 100644 index 0000000000..6b377197eb --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Square.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Square extends Shape { + + public Square(Color color) { + super(color); + } + + @Override + public void drawShape() { + LOG.info("Square drawn. "); + color.fillColor(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java new file mode 100644 index 0000000000..900e78cf2b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/bridge/Triangle.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.bridge; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class Triangle extends Shape { + + public Triangle(Color color) { + super(color); + } + + @Override + public void drawShape() { + LOG.info("Triangle drawn. "); + color.fillColor(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java new file mode 100644 index 0000000000..881add8b21 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/BubbleLights.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.decorator; + +public class BubbleLights extends TreeDecorator { + + public BubbleLights(ChristmasTree tree) { + super(tree); + } + + public String decorate() { + return super.decorate() + decorateWithBubbleLights(); + } + + private String decorateWithBubbleLights() { + return " with Bubble Lights"; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java new file mode 100644 index 0000000000..80a0865567 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTree.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.decorator; + +public interface ChristmasTree { + public String decorate(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java new file mode 100644 index 0000000000..9241fd59db --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/ChristmasTreeImpl.java @@ -0,0 +1,10 @@ +package com.baeldung.designpatterns.decorator; + +public class ChristmasTreeImpl implements ChristmasTree { + + @Override + public String decorate() { + return "Christmas tree"; + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java new file mode 100644 index 0000000000..f70991da6b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/DecoratorPatternDriver.java @@ -0,0 +1,20 @@ +package com.baeldung.designpatterns.decorator; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; + +public class DecoratorPatternDriver { + + public static void main(String[] args) { + //christmas tree with just one Garland + ChristmasTree tree1 = new Garland(new ChristmasTreeImpl()); + LOG.info(tree1.decorate()); + + //christmas tree with two Garlands and one Bubble lights + ChristmasTree tree2 = new BubbleLights(new Garland( + new Garland(new ChristmasTreeImpl())) + ); + LOG.info(tree2.decorate()); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java new file mode 100644 index 0000000000..d2efd6e451 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/Garland.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.decorator; + +public class Garland extends TreeDecorator { + + public Garland(ChristmasTree tree) { + super(tree); + } + + public String decorate() { + return super.decorate() + decorateWithGarland(); + } + + private String decorateWithGarland() { + return " with Garland"; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java b/core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java new file mode 100644 index 0000000000..5427d2ac7e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/decorator/TreeDecorator.java @@ -0,0 +1,15 @@ +package com.baeldung.designpatterns.decorator; + +public abstract class TreeDecorator implements ChristmasTree { + private ChristmasTree tree; + + public TreeDecorator(ChristmasTree tree) { + this.tree = tree; + } + + @Override + public String decorate() { + return tree.decorate(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java new file mode 100644 index 0000000000..96a6bfb878 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObject.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.proxy; + +public interface ExpensiveObject { + public void process(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java new file mode 100644 index 0000000000..7014d3811c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectImpl.java @@ -0,0 +1,20 @@ +package com.baeldung.designpatterns.proxy; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG;; + +public class ExpensiveObjectImpl implements ExpensiveObject { + + public ExpensiveObjectImpl() { + heavyInitialConfiguration(); + } + + @Override + public void process() { + LOG.info("processing complete."); + } + + private void heavyInitialConfiguration() { + LOG.info("Loading initial configuration..."); + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java new file mode 100644 index 0000000000..f36e688c90 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ExpensiveObjectProxy.java @@ -0,0 +1,13 @@ +package com.baeldung.designpatterns.proxy; + +public class ExpensiveObjectProxy implements ExpensiveObject{ + private static ExpensiveObject object; + + @Override + public void process() { + if(object == null) { + object = new ExpensiveObjectImpl(); + } + object.process(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java new file mode 100644 index 0000000000..088b069e28 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/proxy/ProxyPatternDriver.java @@ -0,0 +1,9 @@ +package com.baeldung.designpatterns.proxy; + +public class ProxyPatternDriver { + public static void main(String[] args) { + ExpensiveObject object = new ExpensiveObjectProxy(); + object.process(); + object.process(); + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java new file mode 100644 index 0000000000..0fc86e30a7 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/ClassSingleton.java @@ -0,0 +1,28 @@ +package com.baeldung.designpatterns.singleton; + +public class ClassSingleton { + + private static ClassSingleton INSTANCE; + private String info = "Initial class info"; + + private ClassSingleton(){ + } + + public static ClassSingleton getInstance(){ + if(INSTANCE == null){ + INSTANCE = new ClassSingleton(); + } + + return INSTANCE; + } + + // getters and setters + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java new file mode 100644 index 0000000000..f75484477b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/EnumSingleton.java @@ -0,0 +1,26 @@ +package com.baeldung.designpatterns.singleton; + +public enum EnumSingleton { + + INSTANCE("Initial enum info"); //Name of the single instance + + private String info; + + private EnumSingleton(String info) { + this.info = info; + } + + public EnumSingleton getInstance(){ + return INSTANCE; + } + + //getters and setters + + public String getInfo() { + return info; + } + + public void setInfo(String info) { + this.info = info; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java new file mode 100644 index 0000000000..f8ca2ffa78 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/Sandbox.java @@ -0,0 +1,32 @@ +package com.baeldung.designpatterns.singleton; + +public class Sandbox { + + public static void main(String[] args) { + + //Class singleton + + ClassSingleton classSingleton1 = ClassSingleton.getInstance(); + //OurSingleton object1 = new OurSingleton(); // The constructor OurSingleton() is not visible + + System.out.println(classSingleton1.getInfo()); //Initial class info + + ClassSingleton classSingleton2 = ClassSingleton.getInstance(); + classSingleton2.setInfo("New class info"); + + System.out.println(classSingleton1.getInfo()); //New class info + System.out.println(classSingleton2.getInfo()); //New class info + + //Enum singleton + + EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE.getInstance(); + + System.out.println(enumSingleton1.getInfo()); //Initial enum info + + EnumSingleton enumSingleton2 = EnumSingleton.INSTANCE.getInstance(); + enumSingleton2.setInfo("New enum info"); + + System.out.println(enumSingleton1.getInfo()); //New enum info + System.out.println(enumSingleton2.getInfo()); //New enum info + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java b/core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java new file mode 100644 index 0000000000..f7b6e4f3e9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/util/LogerUtil.java @@ -0,0 +1,35 @@ +package com.baeldung.designpatterns.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Properties; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; + +public class LogerUtil { + + public final static Logger LOG = Logger.getLogger("GLOBAL"); + + static { + configuration(); + } + + private static void configuration() { + Properties props = new Properties(); + try { + props.load( + new BufferedReader( + new InputStreamReader( + LogerUtil.class.getResourceAsStream("/log4jstructuraldp.properties") + ) + ) + ); + } catch (IOException e) { + System.out.println("log4jstructuraldp.properties file not configured properly"); + System.exit(0); + } + PropertyConfigurator.configure(props); + } +} diff --git a/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java b/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java index 4afce56e39..7e6bb5d3b2 100644 --- a/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java +++ b/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java @@ -14,26 +14,25 @@ public class LookupFSJNDI { super(); init(); } - + private void init() throws NamingException { Hashtable env = new Hashtable(); - - env.put (Context.INITIAL_CONTEXT_FACTORY, - "com.sun.jndi.fscontext.RefFSContextFactory"); + + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); // URI to namespace (actual directory) env.put(Context.PROVIDER_URL, "file:./src/test/resources"); - + ctx = new InitialContext(env); } public InitialContext getCtx() { return ctx; } - + public File getFile(String fileName) { File file; try { - file = (File)getCtx().lookup(fileName); + file = (File) getCtx().lookup(fileName); } catch (NamingException e) { file = null; } diff --git a/core-java/hashcode/src/main/java/com/baeldung/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java similarity index 81% rename from core-java/hashcode/src/main/java/com/baeldung/entities/User.java rename to core-java/src/main/java/com/baeldung/hashcode/entities/User.java index a976233562..c46c3de65a 100644 --- a/core-java/hashcode/src/main/java/com/baeldung/entities/User.java +++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java @@ -1,4 +1,4 @@ -package com.baeldung.entities; +package com.baeldung.hashcode.entities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -18,13 +18,16 @@ public class User { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null) return false; - if (this.getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null) + return false; + if (this.getClass() != o.getClass()) + return false; User user = (User) o; return id != user.id && (!name.equals(user.name) && !email.equals(user.email)); } - + @Override public int hashCode() { int hash = 7; diff --git a/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java b/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java index 220b9a8ec6..21044f82c4 100644 --- a/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java +++ b/core-java/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java @@ -10,7 +10,6 @@ public class JMXTutorialMainlauncher { private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class); - public static void main(String[] args) { // TODO Auto-generated method stub diff --git a/core-java/src/main/java/com/baeldung/socket/EchoClient.java b/core-java/src/main/java/com/baeldung/socket/EchoClient.java index cf5c253276..fa3901d5da 100644 --- a/core-java/src/main/java/com/baeldung/socket/EchoClient.java +++ b/core-java/src/main/java/com/baeldung/socket/EchoClient.java @@ -8,9 +8,8 @@ import java.net.*; public class EchoClient { - private static final Logger LOG = LoggerFactory.getLogger(EchoClient.class); - + private Socket clientSocket; private PrintWriter out; private BufferedReader in; diff --git a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java index ae00fc7cb4..d79a7c3ecb 100644 --- a/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java +++ b/core-java/src/main/java/com/baeldung/stream/InfiniteStreams.java @@ -1,6 +1,5 @@ package com.baeldung.stream; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java/src/main/java/com/baeldung/string/StringHelper.java b/core-java/src/main/java/com/baeldung/string/StringHelper.java index dac0d1272e..a9cc71d36a 100644 --- a/core-java/src/main/java/com/baeldung/string/StringHelper.java +++ b/core-java/src/main/java/com/baeldung/string/StringHelper.java @@ -12,15 +12,10 @@ class StringHelper { } static String removeLastCharOptional(String s) { - return Optional.ofNullable(s) - .filter(str -> str.length() != 0) - .map(str -> str.substring(0, str.length() - 1)) - .orElse(s); + return Optional.ofNullable(s).filter(str -> str.length() != 0).map(str -> str.substring(0, str.length() - 1)).orElse(s); } static String removeLastCharRegexOptional(String s) { - return Optional.ofNullable(s) - .map(str -> str.replaceAll(".$", "")) - .orElse(s); + return Optional.ofNullable(s).map(str -> str.replaceAll(".$", "")).orElse(s); } } diff --git a/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java b/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java index 130218acc2..21164a976c 100644 --- a/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java +++ b/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java @@ -25,11 +25,7 @@ public class MyTokenizer { } public List getTokensWithCollection(String str) { - return Collections - .list(new StringTokenizer(str, ",")) - .stream() - .map(token -> (String) token) - .collect(Collectors.toList()); + return Collections.list(new StringTokenizer(str, ",")).stream().map(token -> (String) token).collect(Collectors.toList()); } public List getTokensFromFile(String path, String delim) { diff --git a/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java index bfb6681f7c..5631616ea8 100644 --- a/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java +++ b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java @@ -11,12 +11,12 @@ public class CustomTemporalAdjuster implements TemporalAdjuster { @Override public Temporal adjustInto(Temporal temporal) { switch (DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK))) { - case FRIDAY: - return temporal.plus(3, ChronoUnit.DAYS); - case SATURDAY: - return temporal.plus(2, ChronoUnit.DAYS); - default: - return temporal.plus(1, ChronoUnit.DAYS); + case FRIDAY: + return temporal.plus(3, ChronoUnit.DAYS); + case SATURDAY: + return temporal.plus(2, ChronoUnit.DAYS); + default: + return temporal.plus(1, ChronoUnit.DAYS); } } } diff --git a/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java b/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java index 69d7ff2390..a5f70d9df5 100644 --- a/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java +++ b/core-java/src/main/java/com/baeldung/transferqueue/Consumer.java @@ -9,7 +9,6 @@ import java.util.concurrent.atomic.AtomicInteger; public class Consumer implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(Consumer.class); - private final TransferQueue transferQueue; private final String name; private final int numberOfMessagesToConsume; diff --git a/core-java/src/main/resources/log4jstructuraldp.properties b/core-java/src/main/resources/log4jstructuraldp.properties new file mode 100644 index 0000000000..5bc2bfe4b9 --- /dev/null +++ b/core-java/src/main/resources/log4jstructuraldp.properties @@ -0,0 +1,9 @@ + +# Root logger +log4j.rootLogger=INFO, file, stdout + +# Write to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java index 2f1abef64e..8cddf31245 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/accumulator/LongAccumulatorUnitTest.java @@ -15,28 +15,24 @@ public class LongAccumulatorUnitTest { @Test public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException { - //given + // given ExecutorService executorService = Executors.newFixedThreadPool(8); LongBinaryOperator sum = Long::sum; LongAccumulator accumulator = new LongAccumulator(sum, 0L); int numberOfThreads = 4; int numberOfIncrements = 100; - //when - Runnable accumulateAction = () -> IntStream - .rangeClosed(0, numberOfIncrements) - .forEach(accumulator::accumulate); + // when + Runnable accumulateAction = () -> IntStream.rangeClosed(0, numberOfIncrements).forEach(accumulator::accumulate); for (int i = 0; i < numberOfThreads; i++) { executorService.execute(accumulateAction); } - - //then + // then executorService.awaitTermination(500, TimeUnit.MILLISECONDS); executorService.shutdown(); assertEquals(accumulator.get(), 20200); - } } diff --git a/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java new file mode 100644 index 0000000000..fb483a8a68 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java @@ -0,0 +1,20 @@ +package com.baeldung.designpatterns; + + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapter; +import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapterImpl; + +public class AdapterPatternIntegrationTest { + @Test + public void givenLuxuryCarsAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() { + LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl(); + assertEquals(luxuryCars.bugattiVeyronInKMPH(), 431.30312, 0.00001); + assertEquals(luxuryCars.mcLarenInKMPH(), 387.85094, 0.00001); + assertEquals(luxuryCars.astonMartinInKMPH(), 354.0548, 0.00001); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java new file mode 100644 index 0000000000..56a7a704f2 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/BridgePatternIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.designpatterns; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.apache.log4j.spi.LoggingEvent; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.designpatterns.bridge.Blue; +import com.baeldung.designpatterns.bridge.Red; +import com.baeldung.designpatterns.bridge.Shape; +import com.baeldung.designpatterns.bridge.Square; +import com.baeldung.designpatterns.bridge.Triangle; + +public class BridgePatternIntegrationTest { + public static TestAppenderDP appender; + + @Before + public void setUp() { + appender = new TestAppenderDP(); + LOG.addAppender(appender); + } + + @Test + public void whenBridgePatternInvoked_thenConfigSuccess() { + //a square with red color + Shape square = new Square(new Red()); + square.drawShape(); + + //a triangle with blue color + Shape triangle = new Triangle(new Blue()); + triangle.drawShape(); + + final List log = appender.getLog(); + + assertThat((String) log.get(0).getMessage(), is("Square drawn. ")); + assertThat((String) log.get(1).getMessage(), is("Color : Red")); + assertThat((String) log.get(2).getMessage(), is("Triangle drawn. ")); + assertThat((String) log.get(3).getMessage(), is("Color : Blue")); + } + + @After + public void tearDown() { + LOG.removeAppender(appender); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java new file mode 100644 index 0000000000..b3b3f988f1 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/DecoratorPatternIntegrationTest.java @@ -0,0 +1,28 @@ +package com.baeldung.designpatterns; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.baeldung.designpatterns.decorator.BubbleLights; +import com.baeldung.designpatterns.decorator.ChristmasTree; +import com.baeldung.designpatterns.decorator.ChristmasTreeImpl; +import com.baeldung.designpatterns.decorator.Garland; + +public class DecoratorPatternIntegrationTest { + private ChristmasTree tree; + + @Test + public void givenDecoratorPattern_WhenDecoratorsInjectedAtRuntime_thenConfigSuccess() { + //christmas tree with just one Garland + tree = new Garland(new ChristmasTreeImpl()); + assertEquals(tree.decorate(), "Christmas tree with Garland"); + + //christmas tree with two Garlands and one Bubble lights + tree = new BubbleLights(new Garland( + new Garland(new ChristmasTreeImpl())) + ); + assertEquals(tree.decorate(), "Christmas tree with Garland with Garland with Bubble Lights"); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java new file mode 100644 index 0000000000..7fa95b31d7 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/ProxyPatternIntegrationTest.java @@ -0,0 +1,44 @@ +package com.baeldung.designpatterns; + +import static com.baeldung.designpatterns.util.LogerUtil.LOG; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.apache.log4j.spi.LoggingEvent; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.designpatterns.proxy.ExpensiveObject; +import com.baeldung.designpatterns.proxy.ExpensiveObjectProxy; + +public class ProxyPatternIntegrationTest { + public static TestAppenderDP appender; + + @Before + public void setUp() { + appender = new TestAppenderDP(); + LOG.addAppender(appender); + } + + @Test + public void givenExpensiveObjectProxy_WhenObjectInitialized_thenInitializedOnlyOnce() { + ExpensiveObject object = new ExpensiveObjectProxy(); + object.process(); + object.process(); + + final List log = appender.getLog(); + + assertThat((String) log.get(0).getMessage(), is("Loading initial configuration...")); + assertThat((String) log.get(1).getMessage(), is("processing complete.")); + assertThat((String) log.get(2).getMessage(), is("processing complete.")); + } + + @After + public void tearDown() { + LOG.removeAppender(appender); + } +} + diff --git a/core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java b/core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java new file mode 100644 index 0000000000..613c26fa13 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/TestAppenderDP.java @@ -0,0 +1,29 @@ +package com.baeldung.designpatterns; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; + +public class TestAppenderDP extends AppenderSkeleton { + private final List log = new ArrayList(); + + @Override + public boolean requiresLayout() { + return false; + } + + @Override + protected void append(final LoggingEvent loggingEvent) { + log.add(loggingEvent); + } + + @Override + public void close() { + } + + public List getLog() { + return new ArrayList(log); + } +} \ No newline at end of file diff --git a/core-java/hashcode/src/main/java/com/baeldung/application/Application.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java similarity index 55% rename from core-java/hashcode/src/main/java/com/baeldung/application/Application.java rename to core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java index 08c670c82f..60950fae7a 100644 --- a/core-java/hashcode/src/main/java/com/baeldung/application/Application.java +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java @@ -1,12 +1,17 @@ -package com.baeldung.application; +package com.baeldung.hashcode.application; + +import com.baeldung.hashcode.entities.User; +import org.junit.Test; -import com.baeldung.entities.User; import java.util.HashMap; import java.util.Map; -public class Application { +import static org.junit.Assert.assertTrue; - public static void main(String[] args) { +public class ApplicationTest { + + @Test + public void main_NoInputState_TextPrintedToConsole() throws Exception { Map users = new HashMap<>(); User user1 = new User(1L, "John", "john@domain.com"); User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); @@ -16,8 +21,6 @@ public class Application { users.put(user2, user2); users.put(user3, user3); - if (users.containsKey(user1)) { - System.out.print("User found in the collection"); - } + assertTrue(users.containsKey(user1)); } -} +} \ No newline at end of file diff --git a/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java similarity index 86% rename from core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java rename to core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java index 01f6085d7e..e356b4beef 100644 --- a/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java @@ -1,4 +1,4 @@ -package com.baeldung.entities; +package com.baeldung.hashcode.entities; import org.junit.After; import org.junit.Assert; @@ -23,7 +23,7 @@ public class UserTest { } @Test - public void equals_EqualUserInstance_TrueAssertion(){ + public void equals_EqualUserInstance_TrueAssertion() { Assert.assertTrue(user.equals(comparisonUser)); } diff --git a/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java b/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java index 0fd6f7dfe8..fe10266043 100644 --- a/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java +++ b/core-java/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java @@ -15,7 +15,6 @@ public class LambdaExceptionWrappersUnitTest { private static final Logger LOG = LoggerFactory.getLogger(LambdaExceptionWrappersUnitTest.class); - private List integers; @Before diff --git a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java b/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java index 7a23afa12f..5327e5f4f0 100644 --- a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java +++ b/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java @@ -29,12 +29,9 @@ public class ListOfListsUnitTest { @Test public void givenListOfLists_thenCheckNames() { - assertEquals("Pen 1", ((Pen) listOfLists.get(0) - .get(0)).getName()); - assertEquals("Pencil 1", ((Pencil) listOfLists.get(1) - .get(0)).getName()); - assertEquals("Rubber 1", ((Rubber) listOfLists.get(2) - .get(0)).getName()); + assertEquals("Pen 1", ((Pen) listOfLists.get(0).get(0)).getName()); + assertEquals("Pencil 1", ((Pencil) listOfLists.get(1).get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(2).get(0)).getName()); } @SuppressWarnings("unchecked") @@ -43,11 +40,9 @@ public class ListOfListsUnitTest { ((ArrayList) listOfLists.get(1)).remove(0); listOfLists.remove(1); - assertEquals("Rubber 1", ((Rubber) listOfLists.get(1) - .get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(1).get(0)).getName()); listOfLists.remove(0); - assertEquals("Rubber 1", ((Rubber) listOfLists.get(0) - .get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) listOfLists.get(0).get(0)).getName()); } @Test @@ -67,11 +62,8 @@ public class ListOfListsUnitTest { list.add(pencils); list.add(rubbers); - assertEquals("Pen 1", ((Pen) list.get(0) - .get(0)).getName()); - assertEquals("Pencil 1", ((Pencil) list.get(1) - .get(0)).getName()); - assertEquals("Rubber 1", ((Rubber) list.get(2) - .get(0)).getName()); + assertEquals("Pen 1", ((Pen) list.get(0).get(0)).getName()); + assertEquals("Pencil 1", ((Pencil) list.get(1).get(0)).getName()); + assertEquals("Rubber 1", ((Rubber) list.get(2).get(0)).getName()); } } diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java rename to core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java index 3d52a9eea9..fe2747bcee 100644 --- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java +++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java @@ -1,190 +1,190 @@ -package com.baeldung.money; - -import org.javamoney.moneta.FastMoney; -import org.javamoney.moneta.Money; -import org.javamoney.moneta.format.CurrencyStyle; -import org.junit.Ignore; -import org.junit.Test; - -import javax.money.CurrencyUnit; -import javax.money.Monetary; -import javax.money.MonetaryAmount; -import javax.money.UnknownCurrencyException; -import javax.money.convert.CurrencyConversion; -import javax.money.convert.MonetaryConversions; -import javax.money.format.AmountFormatQueryBuilder; -import javax.money.format.MonetaryAmountFormat; -import javax.money.format.MonetaryFormats; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class JavaMoneyUnitTest { - - @Test - public void givenCurrencyCode_whenString_thanExist() { - CurrencyUnit usd = Monetary.getCurrency("USD"); - - assertNotNull(usd); - assertEquals(usd.getCurrencyCode(), "USD"); - assertEquals(usd.getNumericCode(), 840); - assertEquals(usd.getDefaultFractionDigits(), 2); - } - - @Test(expected = UnknownCurrencyException.class) - public void givenCurrencyCode_whenNoExist_thanThrowsError() { - Monetary.getCurrency("AAA"); - } - - @Test - public void givenAmounts_whenStringified_thanEquals() { - CurrencyUnit usd = Monetary.getCurrency("USD"); - MonetaryAmount fstAmtUSD = Monetary - .getDefaultAmountFactory() - .setCurrency(usd) - .setNumber(200) - .create(); - Money moneyof = Money.of(12, usd); - FastMoney fastmoneyof = FastMoney.of(2, usd); - - assertEquals("USD", usd.toString()); - assertEquals("USD 200", fstAmtUSD.toString()); - assertEquals("USD 12", moneyof.toString()); - assertEquals("USD 2.00000", fastmoneyof.toString()); - } - - @Test - public void givenCurrencies_whenCompared_thanNotequal() { - MonetaryAmount oneDolar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - Money oneEuro = Money.of(1, "EUR"); - - assertFalse(oneEuro.equals(FastMoney.of(1, "EUR"))); - assertTrue(oneDolar.equals(Money.of(1, "USD"))); - } - - @Test(expected = ArithmeticException.class) - public void givenAmount_whenDivided_thanThrowsException() { - MonetaryAmount oneDolar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - oneDolar.divide(3); - fail(); // if no exception - } - - @Test - public void givenAmounts_whenSummed_thanCorrect() { - List monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF")); - - Money sumAmtCHF = (Money) monetaryAmounts - .stream() - .reduce(Money.of(0, "CHF"), MonetaryAmount::add); - - assertEquals("CHF 111.35", sumAmtCHF.toString()); - } - - @Test - public void givenArithmetic_whenStringified_thanEqualsAmount() { - CurrencyUnit usd = Monetary.getCurrency("USD"); - - Money moneyof = Money.of(12, usd); - MonetaryAmount fstAmtUSD = Monetary - .getDefaultAmountFactory() - .setCurrency(usd) - .setNumber(200.50) - .create(); - MonetaryAmount oneDolar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - Money subtractedAmount = Money - .of(1, "USD") - .subtract(fstAmtUSD); - MonetaryAmount multiplyAmount = oneDolar.multiply(0.25); - MonetaryAmount divideAmount = oneDolar.divide(0.25); - - assertEquals("USD", usd.toString()); - assertEquals("USD 1", oneDolar.toString()); - assertEquals("USD 200.5", fstAmtUSD.toString()); - assertEquals("USD 12", moneyof.toString()); - assertEquals("USD -199.5", subtractedAmount.toString()); - assertEquals("USD 0.25", multiplyAmount.toString()); - assertEquals("USD 4", divideAmount.toString()); - } - - @Test - public void givenAmount_whenRounded_thanEquals() { - MonetaryAmount fstAmtEUR = Monetary - .getDefaultAmountFactory() - .setCurrency("EUR") - .setNumber(1.30473908) - .create(); - MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding()); - assertEquals("EUR 1.30473908", fstAmtEUR.toString()); - assertEquals("EUR 1.3", roundEUR.toString()); - } - - @Test - @Ignore("Currency providers are not always available") - public void givenAmount_whenConversion_thenNotNull() { - MonetaryAmount oneDollar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - - CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR"); - - MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR); - - assertEquals("USD 1", oneDollar.toString()); - assertNotNull(convertedAmountUSDtoEUR); - } - - @Test - public void givenLocale_whenFormatted_thanEquals() { - MonetaryAmount oneDollar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US); - String usFormatted = formatUSD.format(oneDollar); - - assertEquals("USD 1", oneDollar.toString()); - assertNotNull(formatUSD); - assertEquals("USD1.00", usFormatted); - } - - @Test - public void givenAmount_whenCustomFormat_thanEquals() { - MonetaryAmount oneDollar = Monetary - .getDefaultAmountFactory() - .setCurrency("USD") - .setNumber(1) - .create(); - - MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder - .of(Locale.US) - .set(CurrencyStyle.NAME) - .set("pattern", "00000.00 ¤") - .build()); - String customFormatted = customFormat.format(oneDollar); - - assertNotNull(customFormat); - assertEquals("USD 1", oneDollar.toString()); - assertEquals("00001.00 US Dollar", customFormatted); - } -} +package com.baeldung.money; + +import org.javamoney.moneta.FastMoney; +import org.javamoney.moneta.Money; +import org.javamoney.moneta.format.CurrencyStyle; +import org.junit.Ignore; +import org.junit.Test; + +import javax.money.CurrencyUnit; +import javax.money.Monetary; +import javax.money.MonetaryAmount; +import javax.money.UnknownCurrencyException; +import javax.money.convert.CurrencyConversion; +import javax.money.convert.MonetaryConversions; +import javax.money.format.AmountFormatQueryBuilder; +import javax.money.format.MonetaryAmountFormat; +import javax.money.format.MonetaryFormats; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class JavaMoneyUnitManualTest { + + @Test + public void givenCurrencyCode_whenString_thanExist() { + CurrencyUnit usd = Monetary.getCurrency("USD"); + + assertNotNull(usd); + assertEquals(usd.getCurrencyCode(), "USD"); + assertEquals(usd.getNumericCode(), 840); + assertEquals(usd.getDefaultFractionDigits(), 2); + } + + @Test(expected = UnknownCurrencyException.class) + public void givenCurrencyCode_whenNoExist_thanThrowsError() { + Monetary.getCurrency("AAA"); + } + + @Test + public void givenAmounts_whenStringified_thanEquals() { + CurrencyUnit usd = Monetary.getCurrency("USD"); + MonetaryAmount fstAmtUSD = Monetary + .getDefaultAmountFactory() + .setCurrency(usd) + .setNumber(200) + .create(); + Money moneyof = Money.of(12, usd); + FastMoney fastmoneyof = FastMoney.of(2, usd); + + assertEquals("USD", usd.toString()); + assertEquals("USD 200", fstAmtUSD.toString()); + assertEquals("USD 12", moneyof.toString()); + assertEquals("USD 2.00000", fastmoneyof.toString()); + } + + @Test + public void givenCurrencies_whenCompared_thanNotequal() { + MonetaryAmount oneDolar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + Money oneEuro = Money.of(1, "EUR"); + + assertFalse(oneEuro.equals(FastMoney.of(1, "EUR"))); + assertTrue(oneDolar.equals(Money.of(1, "USD"))); + } + + @Test(expected = ArithmeticException.class) + public void givenAmount_whenDivided_thanThrowsException() { + MonetaryAmount oneDolar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + oneDolar.divide(3); + fail(); // if no exception + } + + @Test + public void givenAmounts_whenSummed_thanCorrect() { + List monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF")); + + Money sumAmtCHF = (Money) monetaryAmounts + .stream() + .reduce(Money.of(0, "CHF"), MonetaryAmount::add); + + assertEquals("CHF 111.35", sumAmtCHF.toString()); + } + + @Test + public void givenArithmetic_whenStringified_thanEqualsAmount() { + CurrencyUnit usd = Monetary.getCurrency("USD"); + + Money moneyof = Money.of(12, usd); + MonetaryAmount fstAmtUSD = Monetary + .getDefaultAmountFactory() + .setCurrency(usd) + .setNumber(200.50) + .create(); + MonetaryAmount oneDolar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + Money subtractedAmount = Money + .of(1, "USD") + .subtract(fstAmtUSD); + MonetaryAmount multiplyAmount = oneDolar.multiply(0.25); + MonetaryAmount divideAmount = oneDolar.divide(0.25); + + assertEquals("USD", usd.toString()); + assertEquals("USD 1", oneDolar.toString()); + assertEquals("USD 200.5", fstAmtUSD.toString()); + assertEquals("USD 12", moneyof.toString()); + assertEquals("USD -199.5", subtractedAmount.toString()); + assertEquals("USD 0.25", multiplyAmount.toString()); + assertEquals("USD 4", divideAmount.toString()); + } + + @Test + public void givenAmount_whenRounded_thanEquals() { + MonetaryAmount fstAmtEUR = Monetary + .getDefaultAmountFactory() + .setCurrency("EUR") + .setNumber(1.30473908) + .create(); + MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding()); + assertEquals("EUR 1.30473908", fstAmtEUR.toString()); + assertEquals("EUR 1.3", roundEUR.toString()); + } + + @Test + @Ignore("Currency providers are not always available") + public void givenAmount_whenConversion_thenNotNull() { + MonetaryAmount oneDollar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + + CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR"); + + MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR); + + assertEquals("USD 1", oneDollar.toString()); + assertNotNull(convertedAmountUSDtoEUR); + } + + @Test + public void givenLocale_whenFormatted_thanEquals() { + MonetaryAmount oneDollar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US); + String usFormatted = formatUSD.format(oneDollar); + + assertEquals("USD 1", oneDollar.toString()); + assertNotNull(formatUSD); + assertEquals("USD1.00", usFormatted); + } + + @Test + public void givenAmount_whenCustomFormat_thanEquals() { + MonetaryAmount oneDollar = Monetary + .getDefaultAmountFactory() + .setCurrency("USD") + .setNumber(1) + .create(); + + MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder + .of(Locale.US) + .set(CurrencyStyle.NAME) + .set("pattern", "00000.00 �") + .build()); + String customFormatted = customFormat.format(oneDollar); + + assertNotNull(customFormat); + assertEquals("USD 1", oneDollar.toString()); + assertEquals("00001.00 US Dollar", customFormatted); + } +} diff --git a/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java b/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java new file mode 100644 index 0000000000..69b0b6d3ef --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java @@ -0,0 +1,65 @@ +package com.baeldung.stream; + +import static java.util.stream.Collectors.collectingAndThen; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.IntStream; + +import org.junit.Test; + +import com.baeldung.stream.mycollectors.MyImmutableListCollector; +import com.google.common.collect.ImmutableList; + +public class StreamToImmutableTest { + + @Test + public void whenUsingCollectingToImmutableSet_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c"); + List result = givenList.stream() + .collect(collectingAndThen(toSet(), ImmutableList::copyOf)); + + System.out.println(result.getClass()); + } + + @Test + public void whenUsingCollectingToUnmodifiableList_thenSuccess() { + List givenList = new ArrayList<>(Arrays.asList("a", "b", "c")); + List result = givenList.stream() + .collect(collectingAndThen(toList(), Collections::unmodifiableList)); + + System.out.println(result.getClass()); + } + + @Test + public void whenCollectToImmutableList_thenSuccess() { + List list = IntStream.range(0, 9) + .boxed() + .collect(ImmutableList.toImmutableList()); + + System.out.println(list.getClass()); + } + + @Test + public void whenCollectToMyImmutableListCollector_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c", "d"); + List result = givenList.stream() + .collect(MyImmutableListCollector.toImmutableList()); + + System.out.println(result.getClass()); + } + + @Test + public void whenPassingSupplier_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c", "d"); + List result = givenList.stream() + .collect(MyImmutableListCollector.toImmutableList(LinkedList::new)); + + System.out.println(result.getClass()); + } +} diff --git a/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java b/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java new file mode 100644 index 0000000000..cf6b3601c3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java @@ -0,0 +1,22 @@ +package com.baeldung.stream.mycollectors; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Collector; + +public class MyImmutableListCollector { + + public static > Collector> toImmutableList(Supplier supplier) { + return Collector.of(supplier, List::add, (left, right) -> { + left.addAll(right); + return left; + }, Collections::unmodifiableList); + } + + public static Collector, List> toImmutableList() { + return toImmutableList(ArrayList::new); + } + +} diff --git a/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java index 9d8d3c884b..5fb85bb2c4 100644 --- a/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java @@ -13,7 +13,6 @@ public class CoreThreadPoolIntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class); - @Test(timeout = 1000) public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException { diff --git a/feign/README.md b/feign/README.md index 149f7320d9..4d6964a73a 100644 --- a/feign/README.md +++ b/feign/README.md @@ -4,5 +4,5 @@ This is the implementation of a [spring-hypermedia-api][1] client using Feign. [1]: https://github.com/eugenp/spring-hypermedia-api -###Relevant Articles: +### Relevant Articles: - [Intro to Feign](http://www.baeldung.com/intro-to-feign) diff --git a/grpc/pom.xml b/grpc/pom.xml new file mode 100644 index 0000000000..074075b5cc --- /dev/null +++ b/grpc/pom.xml @@ -0,0 +1,74 @@ + + 4.0.0 + + grpc + grpc-demo + 0.0.1-SNAPSHOT + jar + + grpc-demo + http://maven.apache.org + + + UTF-8 + 1.5.0 + + + + + io.grpc + grpc-netty + ${io.grpc.version} + + + io.grpc + grpc-protobuf + ${io.grpc.version} + + + io.grpc + grpc-stub + ${io.grpc.version} + + + junit + junit + 4.12 + test + + + + + + kr.motd.maven + os-maven-plugin + 1.5.0.Final + + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + 0.5.0 + + + com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier} + + grpc-java + + io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier} + + + + + + compile + compile-custom + + + + + + + diff --git a/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java b/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java new file mode 100644 index 0000000000..1a1809387f --- /dev/null +++ b/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java @@ -0,0 +1,28 @@ +package org.baeldung.grpc.client; + +import org.baeldung.grpc.HelloRequest; +import org.baeldung.grpc.HelloResponse; +import org.baeldung.grpc.HelloServiceGrpc; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; + +public class GrpcClient { + public static void main(String[] args) throws InterruptedException { + ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080) + .usePlaintext(true) + .build(); + + HelloServiceGrpc.HelloServiceBlockingStub stub + = HelloServiceGrpc.newBlockingStub(channel); + + HelloResponse helloResponse = stub.hello(HelloRequest.newBuilder() + .setFirstName("Baeldung") + .setLastName("gRPC") + .build()); + + System.out.println("Response received from server:\n" + helloResponse); + + channel.shutdown(); + } +} diff --git a/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java b/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java new file mode 100644 index 0000000000..8a2b94e53b --- /dev/null +++ b/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java @@ -0,0 +1,18 @@ +package org.baeldung.grpc.server; + +import java.io.IOException; + +import io.grpc.Server; +import io.grpc.ServerBuilder; + +public class GrpcServer { + public static void main(String[] args) throws IOException, InterruptedException { + Server server = ServerBuilder.forPort(8080) + .addService(new HelloServiceImpl()).build(); + + System.out.println("Starting server..."); + server.start(); + System.out.println("Server started!"); + server.awaitTermination(); + } +} diff --git a/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java b/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java new file mode 100644 index 0000000000..b08ad02c97 --- /dev/null +++ b/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java @@ -0,0 +1,29 @@ +package org.baeldung.grpc.server; + +import org.baeldung.grpc.HelloRequest; +import org.baeldung.grpc.HelloResponse; +import org.baeldung.grpc.HelloServiceGrpc.HelloServiceImplBase; + +import io.grpc.stub.StreamObserver; + +public class HelloServiceImpl extends HelloServiceImplBase { + + @Override + public void hello( + HelloRequest request, StreamObserver responseObserver) { + System.out.println("Request received from client:\n" + request); + + String greeting = new StringBuilder().append("Hello, ") + .append(request.getFirstName()) + .append(" ") + .append(request.getLastName()) + .toString(); + + HelloResponse response = HelloResponse.newBuilder() + .setGreeting(greeting) + .build(); + + responseObserver.onNext(response); + responseObserver.onCompleted(); + } +} diff --git a/grpc/src/main/proto/HelloService.proto b/grpc/src/main/proto/HelloService.proto new file mode 100644 index 0000000000..4f53191ab9 --- /dev/null +++ b/grpc/src/main/proto/HelloService.proto @@ -0,0 +1,16 @@ +syntax = "proto3"; +option java_multiple_files = true; +package org.baeldung.grpc; + +message HelloRequest { + string firstName = 1; + string lastName = 2; +} + +message HelloResponse { + string greeting = 1; +} + +service HelloService { + rpc hello(HelloRequest) returns (HelloResponse); +} diff --git a/jee7/.gitignore b/jee7/.gitignore new file mode 100644 index 0000000000..067348b3f4 --- /dev/null +++ b/jee7/.gitignore @@ -0,0 +1,5 @@ + +/classes/ +/.idea/ +/target/ +/jee7.iml diff --git a/jee7/pom.xml b/jee7/pom.xml index b5e0d80b6c..6858a05d17 100644 --- a/jee7/pom.xml +++ b/jee7/pom.xml @@ -6,8 +6,10 @@ com.baeldung jee7 1.0-SNAPSHOT + war JavaEE 7 Arquillian Archetype Sample + com.baeldung parent-modules @@ -174,6 +176,7 @@ maven-war-plugin ${maven-war-plugin.version} + webapp false diff --git a/jee7/src/main/webapp/WEB-INF/spring/security.xml b/jee7/src/main/webapp/WEB-INF/spring/security.xml new file mode 100644 index 0000000000..777cd9461f --- /dev/null +++ b/jee7/src/main/webapp/WEB-INF/spring/security.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee7/src/main/webapp/WEB-INF/web.xml b/jee7/src/main/webapp/WEB-INF/web.xml index 11bd87cf99..1bcbb96e24 100644 --- a/jee7/src/main/webapp/WEB-INF/web.xml +++ b/jee7/src/main/webapp/WEB-INF/web.xml @@ -32,6 +32,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + index.jsf welcome.jsf diff --git a/jee7/src/main/webapp/index.jsp b/jee7/src/main/webapp/index.jsp new file mode 100644 index 0000000000..93fef9713d --- /dev/null +++ b/jee7/src/main/webapp/index.jsp @@ -0,0 +1,11 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Index Page + + + Non-secured Index Page +
+
Login + + \ No newline at end of file diff --git a/jee7/src/main/webapp/secure.jsp b/jee7/src/main/webapp/secure.jsp new file mode 100644 index 0000000000..0cadd2cd4f --- /dev/null +++ b/jee7/src/main/webapp/secure.jsp @@ -0,0 +1,24 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %> + + + + + Home Page + + +

Home Page

+ +

+ Hello
+ Roles: +

+ +
+ + +
+ + \ No newline at end of file diff --git a/jooq/README.md b/jooq/README.md deleted file mode 100644 index 2f09cab46b..0000000000 --- a/jooq/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [Introduction to jOOL](http://www.baeldung.com/jool) diff --git a/jooq/pom.xml b/jooq/pom.xml deleted file mode 100644 index 667640d085..0000000000 --- a/jooq/pom.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - - 4.0.0 - - jooq - - - - org.jooq - jool - ${jool.version} - - - - - 0.9.12 - - - \ No newline at end of file diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt new file mode 100644 index 0000000000..96e54716b3 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/Sealed.kt @@ -0,0 +1,19 @@ +package com.baeldung.kotlin + +sealed class Result { + abstract fun map(func: (S) -> R) : Result + abstract fun mapFailure(func: (F) -> R) : Result + abstract fun get() : S? +} + +data class Success(val success: S) : Result() { + override fun map(func: (S) -> R) : Result = Success(func(success)) + override fun mapFailure(func: (F) -> R): Result = Success(success) + override fun get(): S? = success +} + +data class Failure(val failure: F) : Result() { + override fun map(func: (S) -> R) : Result = Failure(failure) + override fun mapFailure(func: (F) -> R): Result = Failure(func(failure)) + override fun get(): S? = null +} diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt new file mode 100644 index 0000000000..9ea9f027fc --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt @@ -0,0 +1,35 @@ +package com.baeldung.kotlin.delegates + +val data = arrayOf>( + mutableMapOf( + "id" to 1, + "name" to "George", + "age" to 4 + ), + mutableMapOf( + "id" to 2, + "name" to "Charlotte", + "age" to 2 + ) +) + +class NoRecordFoundException(id: Int) : Exception("No record found for id $id") { + init { + println("No record found for ID $id") + } +} + +fun queryForValue(field: String, id: Int): Any { + println("Loading record $id from the fake database") + val value = data.firstOrNull { it["id"] == id } + ?.get(field) ?: throw NoRecordFoundException(id) + println("Loaded value $value for field $field of record $id") + return value +} + +fun update(field: String, id: Int, value: Any?) { + println("Updating field $field of record $id to value $value in the fake database") + data.firstOrNull { it["id"] == id } + ?.put(field, value) + ?: throw NoRecordFoundException(id) +} diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt new file mode 100644 index 0000000000..c1c0f8823c --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt @@ -0,0 +1,13 @@ +package com.baeldung.kotlin.delegates + +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty + +class DatabaseDelegate(private val field: String, private val id: Int) : ReadWriteProperty { + override fun getValue(thisRef: R, property: KProperty<*>): T = + queryForValue(field, id) as T + + override fun setValue(thisRef: R, property: KProperty<*>, value: T) { + update(field, id, value) + } +} diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt new file mode 100644 index 0000000000..7788305ea1 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt @@ -0,0 +1,6 @@ +package com.baeldung.kotlin.delegates + +class User(val id: Int) { + var name: String by DatabaseDelegate("name", id) + var age: Int by DatabaseDelegate("age", id) +} diff --git a/kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt new file mode 100644 index 0000000000..8c7509f653 --- /dev/null +++ b/kotlin/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt @@ -0,0 +1,84 @@ +package com.baeldung.kotlin + +import org.junit.Assert +import org.junit.Test + +class SealedTest { + fun divide(a: Int, b: Int) : Result = when (b) { + 0 -> Failure("Division by zero") + else -> Success(a.toFloat() / b) + } + + @Test + fun testSuccess() { + val result = divide(10, 5) + Assert.assertEquals(Success(2.0f), result) + } + + @Test + fun testError() { + val result = divide(10, 0) + Assert.assertEquals(Failure("Division by zero"), result) + } + + @Test + fun testMatchOnSuccess() { + val result = divide(10, 5) + when (result) { + is Success -> { + // Expected + } + is Failure -> Assert.fail("Expected Success") + } + } + + @Test + fun testMatchOnError() { + val result = divide(10, 0) + when (result) { + is Failure -> { + // Expected + } + } + } + + @Test + fun testGetSuccess() { + val result = divide(10, 5) + Assert.assertEquals(2.0f, result.get()) + } + + @Test + fun testGetError() { + val result = divide(10, 0) + Assert.assertNull(result.get()) + } + + @Test + fun testMapOnSuccess() { + val result = divide(10, 5) + .map { "Result: $it" } + Assert.assertEquals(Success("Result: 2.0"), result) + } + + @Test + fun testMapOnError() { + val result = divide(10, 0) + .map { "Result: $it" } + Assert.assertEquals(Failure("Division by zero"), result) + } + + @Test + fun testMapFailureOnSuccess() { + val result = divide(10, 5) + .mapFailure { "Failure: $it" } + Assert.assertEquals(Success(2.0f), result) + } + + @Test + fun testMapFailureOnError() { + val result = divide(10, 0) + .mapFailure { "Failure: $it" } + Assert.assertEquals(Failure("Failure: Division by zero"), result) + } +} diff --git a/kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt new file mode 100644 index 0000000000..fc50730dfa --- /dev/null +++ b/kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt @@ -0,0 +1,26 @@ +package com.baeldung.kotlin.delegates + +import org.junit.Test +import kotlin.test.assertEquals + +class DatabaseDelegatesTest { + @Test + fun testGetKnownFields() { + val user = User(1) + assertEquals("George", user.name) + assertEquals(4, user.age) + } + + @Test + fun testSetKnownFields() { + val user = User(2) + user.age = 3 + assertEquals(3, user.age) + } + + @Test(expected = NoRecordFoundException::class) + fun testGetKnownField() { + val user = User(3) + user.name + } +} diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml new file mode 100644 index 0000000000..94a9ca43f4 --- /dev/null +++ b/libraries-data/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + libraries-data + libraries-data + jar + + + com.esotericsoftware + kryo + ${kryo.version} + + + + 4.0.1 + + \ No newline at end of file diff --git a/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java b/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java new file mode 100644 index 0000000000..0e125e48a9 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java @@ -0,0 +1,16 @@ +package com.baeldung.kryo; + +import java.io.Serializable; + +public class ComplexClass implements Serializable{ + private static final long serialVersionUID = 123456L; + private String name = "Bael"; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/kryo/Person.java b/libraries-data/src/main/java/com/baeldung/kryo/Person.java new file mode 100644 index 0000000000..f9be5cfd62 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/kryo/Person.java @@ -0,0 +1,54 @@ +package com.baeldung.kryo; + +import com.esotericsoftware.kryo.DefaultSerializer; +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.KryoSerializable; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; +import java.util.Date; + +@DefaultSerializer(PersonSerializer.class) +public class Person implements KryoSerializable { + private String name = "John Doe"; + private int age = 18; + private Date birthDate = new Date(933191282821L); + + 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; + } + + public Date getBirthDate() { + return birthDate; + } + + public void setBirthDate(Date birthDate) { + this.birthDate = birthDate; + } + + @Override + public void write(Kryo kryo, Output output) { + output.writeString(name); + output.writeLong(birthDate.getTime()); + output.writeInt(age); + } + + @Override + public void read(Kryo kryo, Input input) { + name = input.readString(); + birthDate = new Date(input.readLong()); + age = input.readInt(); + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java b/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java new file mode 100644 index 0000000000..f5d01509a6 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java @@ -0,0 +1,33 @@ +package com.baeldung.kryo; + +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.Serializer; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; +import java.util.Date; + +public class PersonSerializer extends Serializer { + + @Override + public void write(Kryo kryo, Output output, Person object) { + output.writeString(object.getName()); + output.writeLong(object.getBirthDate() + .getTime()); + } + + @Override + public Person read(Kryo kryo, Input input, Class type) { + Person person = new Person(); + person.setName(input.readString()); + long birthDate = input.readLong(); + person.setBirthDate(new Date(birthDate)); + person.setAge(calculateAge(birthDate)); + return person; + } + + private int calculateAge(long birthDate) { + // Some custom logic + return 18; + } + +} diff --git a/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java b/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java new file mode 100644 index 0000000000..c124ca618d --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java @@ -0,0 +1,125 @@ +package com.baeldung.kryo; + +import static org.junit.Assert.assertEquals; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.util.Date; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.junit.Before; +import org.junit.Test; + +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; +import com.esotericsoftware.kryo.serializers.JavaSerializer; + +public class KryoUnitTest { + + private Kryo kryo; + private Output output; + private Input input; + + @Before + public void init() { + kryo = new Kryo(); + try { + output = new Output(new FileOutputStream("file.dat")); + input = new Input(new FileInputStream("file.dat")); + } catch (FileNotFoundException ex) { + Logger.getLogger(KryoUnitTest.class.getName()) + .log(Level.SEVERE, null, ex); + } + } + + @Test + public void givenObject_whenSerializing_thenReadCorrectly() { + Object someObject = "Some string"; + + kryo.writeClassAndObject(output, someObject); + output.close(); + + Object theObject = kryo.readClassAndObject(input); + input.close(); + + assertEquals(theObject, "Some string"); + } + + @Test + public void givenObjects_whenSerializing_thenReadCorrectly() { + String someString = "Multiple Objects"; + Date someDate = new Date(915170400000L); + + kryo.writeObject(output, someString); + kryo.writeObject(output, someDate); + output.close(); + + String readString = kryo.readObject(input, String.class); + Date readDate = kryo.readObject(input, Date.class); + input.close(); + + assertEquals(readString, "Multiple Objects"); + assertEquals(readDate.getTime(), 915170400000L); + } + + @Test + public void givenPerson_whenSerializing_thenReadCorrectly() { + Person person = new Person(); + + kryo.writeObject(output, person); + output.close(); + + Person readPerson = kryo.readObject(input, Person.class); + input.close(); + + assertEquals(readPerson.getName(), "John Doe"); + } + + @Test + public void givenPerson_whenUsingCustomSerializer_thenReadCorrectly() { + Person person = new Person(); + person.setAge(0); + kryo.register(Person.class, new PersonSerializer()); + + kryo.writeObject(output, person); + output.close(); + + Person readPerson = kryo.readObject(input, Person.class); + input.close(); + + assertEquals(readPerson.getName(), "John Doe"); + assertEquals(readPerson.getAge(), 18); + } + + @Test + public void givenPerson_whenCustomSerialization_thenReadCorrectly() { + Person person = new Person(); + + kryo.writeObject(output, person); + output.close(); + + Person readPerson = kryo.readObject(input, Person.class); + input.close(); + + assertEquals(readPerson.getName(), "John Doe"); + assertEquals(readPerson.getAge(), 18); + } + + @Test + public void givenJavaSerializable_whenSerializing_thenReadCorrectly() { + ComplexClass complexClass = new ComplexClass(); + kryo.register(ComplexClass.class, new JavaSerializer()); + + kryo.writeObject(output, complexClass); + output.close(); + + ComplexClass readComplexObject = kryo.readObject(input, ComplexClass.class); + input.close(); + + assertEquals(readComplexObject.getName(), "Bael"); + } + +} diff --git a/libraries/README.md b/libraries/README.md index f0484ec710..0e58628118 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -27,6 +27,8 @@ - [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) - [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph) +- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue) +- [Quick Guide to RSS with Rome](http://www.baeldung.com/rome-rss) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index 3d00a61cf0..8f28a23d75 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -20,7 +20,6 @@ maven-bundle-plugin 3.3.0 maven-plugin -
true @@ -182,6 +181,16 @@ jetty-servlet ${jetty.version} + + rome + rome + ${rome.version} + + + io.specto + hoverfly-java + 0.8.0 + org.apache.httpcomponents httpclient @@ -453,12 +462,11 @@ pcollections ${pcollections.version} - + org.eclipse.collections eclipse-collections ${eclipse-collections.version} - 0.7.0 @@ -499,6 +507,7 @@ 1.6.0 1.7.1 2.1.2 - 8.2.0 + 1.0 + 8.2.0 - + \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java b/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java new file mode 100644 index 0000000000..66a9e0ebce --- /dev/null +++ b/libraries/src/main/java/com/baeldung/rome/RSSRomeExample.java @@ -0,0 +1,76 @@ +package com.baeldung.rome; + +import com.sun.syndication.feed.synd.*; +import com.sun.syndication.io.FeedException; +import com.sun.syndication.io.SyndFeedInput; +import com.sun.syndication.io.SyndFeedOutput; +import com.sun.syndication.io.XmlReader; + +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class RSSRomeExample { + + public static void main(String[] args) throws IOException, FeedException { + SyndFeed feed = createFeed(); + addEntryToFeed(feed); + publishFeed(feed); + readFeed(); + } + + private static SyndFeed createFeed() { + SyndFeed feed = new SyndFeedImpl(); + feed.setFeedType("rss_1.0"); + feed.setTitle("Test title"); + feed.setLink("http://www.somelink.com"); + feed.setDescription("Basic description"); + + return feed; + } + + private static void addEntryToFeed(SyndFeed feed) { + SyndEntry entry = new SyndEntryImpl(); + entry.setTitle("Entry title"); + entry.setLink("http://www.somelink.com/entry1"); + + addDescriptionToEntry(entry); + addCategoryToEntry(entry); + + feed.setEntries(Arrays.asList(entry)); + } + + private static void addDescriptionToEntry(SyndEntry entry) { + SyndContent description = new SyndContentImpl(); + description.setType("text/html"); + description.setValue("First entry"); + + entry.setDescription(description); + } + + private static void addCategoryToEntry(SyndEntry entry) { + List categories = new ArrayList<>(); + SyndCategory category = new SyndCategoryImpl(); + category.setName("Sophisticated category"); + categories.add(category); + + entry.setCategories(categories); + } + + private static void publishFeed(SyndFeed feed) throws IOException, FeedException { + Writer writer = new FileWriter("xyz.txt"); + SyndFeedOutput syndFeedOutput = new SyndFeedOutput(); + syndFeedOutput.output(feed, writer); + writer.close(); + } + + private static SyndFeed readFeed() throws IOException, FeedException { + URL feedSource = new URL("http://rssblog.whatisrss.com/feed/"); + SyndFeedInput input = new SyndFeedInput(); + return input.build(new XmlReader(feedSource)); + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java new file mode 100644 index 0000000000..430759f3a0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java @@ -0,0 +1,22 @@ +package com.baeldung.streamutils; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import org.apache.commons.io.IOUtils; +import org.springframework.util.StreamUtils; + +public class CopyStream { + public static String getStringFromInputStream(InputStream input) throws IOException { + StringWriter writer = new StringWriter(); + IOUtils.copy(input, writer, "UTF-8"); + return writer.toString(); + } + + public InputStream getNonClosingInputStream() throws IOException { + InputStream in = new FileInputStream("src/test/resources/input.txt"); + return StreamUtils.nonClosing(in); + } +} diff --git a/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java new file mode 100644 index 0000000000..6ee4a1ef3a --- /dev/null +++ b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java @@ -0,0 +1,11 @@ +package com.baeldung.streamutils; + +import java.io.InputStream; + +import org.springframework.util.StreamUtils; + +public class DrainStream { + public InputStream getInputStream() { + return StreamUtils.emptyInput(); + } +} diff --git a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java new file mode 100644 index 0000000000..bdaf4d7bd9 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java @@ -0,0 +1,140 @@ +package com.baeldung.hoverfly; + +import static io.specto.hoverfly.junit.core.SimulationSource.dsl; +import static io.specto.hoverfly.junit.dsl.HoverflyDsl.service; +import static io.specto.hoverfly.junit.dsl.HttpBodyConverter.jsonWithSingleQuotes; +import static io.specto.hoverfly.junit.dsl.ResponseCreators.success; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.any; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsTo; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToJson; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToXml; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matches; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.startsWith; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesJsonPath; +import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesXPath; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.lang3.time.StopWatch; +import org.junit.ClassRule; +import org.junit.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import io.specto.hoverfly.junit.core.SimulationSource; +import io.specto.hoverfly.junit.rule.HoverflyRule; + +public class HoverflyApiTest { + + private static final SimulationSource source = dsl( + service("http://www.baeldung.com") + .get("/api/courses/1") + .willReturn(success().body( + jsonWithSingleQuotes("{'id':'1','name':'HCI'}"))) + + .post("/api/courses") + .willReturn(success()) + + .andDelay(3, TimeUnit.SECONDS) + .forMethod("POST"), + + service(matches("www.*dung.com")) + .get(startsWith("/api/student")) + .queryParam("page", any()) + .willReturn(success()) + + .post(equalsTo("/api/student")) + .body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}"))) + .willReturn(success()) + + .put("/api/student/1") + .body(matchesJsonPath("$.name")) + .willReturn(success()) + + .post("/api/student") + .body(equalsToXml("2John")) + .willReturn(success()) + + .put("/api/student/2") + .body(matchesXPath("/student/name")) + .willReturn(success())); + + @ClassRule + public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source); + private final RestTemplate restTemplate = new RestTemplate(); + + @Test + public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException { + final ResponseEntity courseResponse = restTemplate.getForEntity( + "http://www.baeldung.com/api/courses/1", String.class); + + assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); + assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody()); + } + + @Test + public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException { + StopWatch stopWatch = new StopWatch(); + stopWatch.start(); + final ResponseEntity postResponse = restTemplate.postForEntity( + "http://www.baeldung.com/api/courses", null, Void.class); + stopWatch.stop(); + long postTime = stopWatch.getTime(); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + assertTrue(3L <= TimeUnit.MILLISECONDS.toSeconds(postTime)); + } + + @Test + public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException { + final ResponseEntity courseResponse = restTemplate.getForEntity( + "http://www.baeldung.com/api/student?page=3", Void.class); + + assertEquals(HttpStatus.OK, courseResponse.getStatusCode()); + } + + @Test + public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException { + final ResponseEntity postResponse = restTemplate.postForEntity( + "http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + } + + @Test + public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException { + RequestEntity putRequest = RequestEntity + .put(new URI("http://www.baeldung.com/api/student/1")) + .body("{\"id\":\"1\",\"name\":\"Trevor\"}"); + + ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); + assertEquals(HttpStatus.OK, putResponse.getStatusCode()); + } + + @Test + public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException { + final ResponseEntity postResponse = restTemplate.postForEntity( + "http://www.baeldung.com/api/student", "2John", Void.class); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + } + + + @Test + public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException { + RequestEntity putRequest = RequestEntity + .put(new URI("http://www.baeldung.com/api/student/2")) + .body("" + + "2Monica"); + + ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); + assertEquals(HttpStatus.OK, putResponse.getStatusCode()); + } +} diff --git a/jooq/src/test/java/com/baeldung/JOOLUnitTest.java b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java similarity index 64% rename from jooq/src/test/java/com/baeldung/JOOLUnitTest.java rename to libraries/src/test/java/com/baeldung/jool/JOOLTest.java index 17873db50a..ba20e153fd 100644 --- a/jooq/src/test/java/com/baeldung/JOOLUnitTest.java +++ b/libraries/src/test/java/com/baeldung/jool/JOOLTest.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.jool; import org.jooq.lambda.Seq; import org.jooq.lambda.Unchecked; @@ -13,6 +13,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -20,7 +21,7 @@ import static junit.framework.Assert.assertTrue; import static junit.framework.TestCase.assertEquals; import static org.jooq.lambda.tuple.Tuple.tuple; -public class JOOLUnitTest { +public class JOOLTest { @Test public void givenSeq_whenCheckContains_shouldReturnTrue() { List concat = Seq.of(1, 2, 3).concat(Seq.of(4, 5, 6)).toList(); @@ -54,58 +55,58 @@ public class JOOLUnitTest { @Test public void givenSeq_whenJoin_shouldHaveElementsFromBothSeq() { assertEquals( - Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2)) + Seq.of(1, 2, 4).innerJoin(Seq.of(1, 2, 3), Objects::equals).toList(), + Arrays.asList(tuple(1, 1), tuple(2, 2)) ); assertEquals( - Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)) + Seq.of(1, 2, 4).leftOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), + Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(4, null)) ); assertEquals( - Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), (a, b) -> a == b).toList(), - Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)) + Seq.of(1, 2, 4).rightOuterJoin(Seq.of(1, 2, 3), Objects::equals).toList(), + Arrays.asList(tuple(1, 1), tuple(2, 2), tuple(null, 3)) ); assertEquals( - Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), - Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")) + Seq.of(1, 2).crossJoin(Seq.of("A", "B")).toList(), + Arrays.asList(tuple(1, "A"), tuple(1, "B"), tuple(2, "A"), tuple(2, "B")) ); } @Test public void givenSeq_whenManipulateSeq_seqShouldHaveNewElementsInIt() { assertEquals( - Seq.of(1, 2, 3).cycle().limit(9).toList(), - Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3) + Seq.of(1, 2, 3).cycle().limit(9).toList(), + Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3) ); assertEquals( - Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), - tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)) + Seq.of(1, 2, 3).duplicate().map((first, second) -> tuple(first.toList(), second.toList())), + tuple(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)) ); assertEquals( - Seq.of(1, 2, 3, 4).intersperse(0).toList(), - Arrays.asList(1, 0, 2, 0, 3, 0, 4) + Seq.of(1, 2, 3, 4).intersperse(0).toList(), + Arrays.asList(1, 0, 2, 0, 3, 0, 4) ); assertEquals( - Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), - 5 + Seq.of(1, 2, 3, 4, 5).shuffle().toList().size(), + 5 ); assertEquals( - Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), - tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) + Seq.of(1, 2, 3, 4).partition(i -> i > 2).map((first, second) -> tuple(first.toList(), second.toList())), + tuple(Arrays.asList(3, 4), Arrays.asList(1, 2)) ); assertEquals( - Seq.of(1, 2, 3, 4).reverse().toList(), - Arrays.asList(4, 3, 2, 1) + Seq.of(1, 2, 3, 4).reverse().toList(), + Arrays.asList(4, 3, 2, 1) ); } @@ -117,20 +118,20 @@ public class JOOLUnitTest { expectedAfterGroupBy.put(0, Arrays.asList(2, 4)); assertEquals( - Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), - expectedAfterGroupBy + Seq.of(1, 2, 3, 4).groupBy(i -> i % 2), + expectedAfterGroupBy ); assertEquals( - Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), - "!abc" + Seq.of("a", "b", "c").foldLeft("!", (u, t) -> u + t), + "!abc" ); assertEquals( - Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), - "abc!" + Seq.of("a", "b", "c").foldRight("!", (t, u) -> t + u), + "abc!" ); } @@ -138,13 +139,13 @@ public class JOOLUnitTest { public void givenSeq_whenUsingSeqWhile_shouldBehaveAsWhileLoop() { assertEquals( - Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), - Arrays.asList(3, 4, 5) + Seq.of(1, 2, 3, 4, 5).skipWhile(i -> i < 3).toList(), + Arrays.asList(3, 4, 5) ); assertEquals( - Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), - Arrays.asList(3, 4, 5) + Seq.of(1, 2, 3, 4, 5).skipUntil(i -> i == 3).toList(), + Arrays.asList(3, 4, 5) ); } @@ -152,19 +153,19 @@ public class JOOLUnitTest { public void givenSeq_whenZip_shouldHaveZippedSeq() { assertEquals( - Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), - Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")) + Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c")).toList(), + Arrays.asList(tuple(1, "a"), tuple(2, "b"), tuple(3, "c")) ); assertEquals( - Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), - Arrays.asList("1:a", "2:b", "3:c") + Seq.of(1, 2, 3).zip(Seq.of("a", "b", "c"), (x, y) -> x + ":" + y).toList(), + Arrays.asList("1:a", "2:b", "3:c") ); assertEquals( - Seq.of("a", "b", "c").zipWithIndex().toList(), - Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)) + Seq.of("a", "b", "c").zipWithIndex().toList(), + Arrays.asList(tuple("a", 0L), tuple("b", 1L), tuple("c", 2L)) ); } @@ -187,8 +188,8 @@ public class JOOLUnitTest { //then assertEquals( - collect, - Arrays.asList(1, 1, 1) + collect, + Arrays.asList(1, 1, 1) ); } @@ -197,13 +198,13 @@ public class JOOLUnitTest { public void givenOperationThatThrowsCheckedException_whenExecuteUsingUncheckedFuction_shouldPass() { //when List collect = Stream.of("a", "b", "c") - .map(Unchecked.function(elem -> methodThatThrowsChecked(elem))) - .collect(Collectors.toList()); + .map(Unchecked.function(this::methodThatThrowsChecked)) + .collect(Collectors.toList()); //then assertEquals( - collect, - Arrays.asList(1, 1, 1) + collect, + Arrays.asList(1, 1, 1) ); } @@ -236,5 +237,4 @@ public class JOOLUnitTest { Arrays.asList(tuple("michael", "similar", "winter", "summer"), tuple("jodie", "variable", "winter", "summer")) ); } - } diff --git a/libraries/src/test/java/com/baeldung/neuroph/XORTest.java b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java index 063c57195b..4a6ecf8e46 100644 --- a/libraries/src/test/java/com/baeldung/neuroph/XORTest.java +++ b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java @@ -10,6 +10,10 @@ import static org.junit.Assert.*; public class XORTest { private NeuralNetwork ann = null; + private void print(String input, double output, double actual) { + System.out.println("Testing: " + input + " Expected: " + actual + " Result: " + output); + } + @Before public void annInit() { ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork()); @@ -19,32 +23,36 @@ public class XORTest { public void leftDisjunctTest() { ann.setInput(0, 1); ann.calculate(); - assertEquals(ann.getOutput()[0], 1.0,0.0); + print("0, 1", ann.getOutput()[0], 1.0); + assertEquals(ann.getOutput()[0], 1.0, 0.0); } @Test public void rightDisjunctTest() { ann.setInput(1, 0); ann.calculate(); - assertEquals(ann.getOutput()[0], 1.0,0.0); + print("1, 0", ann.getOutput()[0], 1.0); + assertEquals(ann.getOutput()[0], 1.0, 0.0); } @Test public void bothFalseConjunctTest() { ann.setInput(0, 0); ann.calculate(); - assertEquals(ann.getOutput()[0], 0.0,0.0); + print("0, 0", ann.getOutput()[0], 0.0); + assertEquals(ann.getOutput()[0], 0.0, 0.0); } @Test public void bothTrueConjunctTest() { ann.setInput(1, 1); ann.calculate(); - assertEquals(ann.getOutput()[0], 0.0,0.0); + print("1, 1", ann.getOutput()[0], 0.0); + assertEquals(ann.getOutput()[0], 0.0, 0.0); } @After public void annClose() { ann = null; } -} +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java new file mode 100644 index 0000000000..9a65075e5b --- /dev/null +++ b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java @@ -0,0 +1,100 @@ +package com.baeldung.streamutils; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.util.StreamUtils; + +import static com.baeldung.streamutils.CopyStream.getStringFromInputStream; + +public class CopyStreamTest { + + @Test + public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copy(in, out); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(inputFileContent, outputFileContent); + } + + @Test + public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + InputStream in = new FileInputStream(inputFileName); + OutputStream out = new FileOutputStream(outputFileName); + + StreamUtils.copyRange(in, out, 1, 10); + + assertTrue(outputFile.exists()); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent); + } + + @Test + public void whenCopyStringToOutputStream_thenCorrect() throws IOException { + String string = "Should be copied to OutputStream."; + String outputFileName = "src/test/resources/output.txt"; + File outputFile = new File(outputFileName); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(string, StandardCharsets.UTF_8, out); + + assertTrue(outputFile.exists()); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToString_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream is = new FileInputStream(inputFileName); + String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8); + + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + Assert.assertEquals(inputFileContent, content); + } + + @Test + public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException { + String outputFileName = "src/test/resources/output.txt"; + String string = "Should be copied to OutputStream."; + byte[] byteArray = string.getBytes(); + OutputStream out = new FileOutputStream("src/test/resources/output.txt"); + + StreamUtils.copy(byteArray, out); + String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName)); + Assert.assertEquals(outputFileContent, string); + } + + @Test + public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException { + String inputFileName = "src/test/resources/input.txt"; + InputStream in = new FileInputStream(inputFileName); + byte[] out = StreamUtils.copyToByteArray(in); + + String content = new String(out); + String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName)); + Assert.assertEquals(inputFileContent, content); + } + +} diff --git a/libraries/src/test/resources/input.txt b/libraries/src/test/resources/input.txt new file mode 100644 index 0000000000..811232fa1f --- /dev/null +++ b/libraries/src/test/resources/input.txt @@ -0,0 +1 @@ +This file is merely for testing. \ No newline at end of file diff --git a/libraries/src/test/resources/output.txt b/libraries/src/test/resources/output.txt new file mode 100644 index 0000000000..34e1e27d5a --- /dev/null +++ b/libraries/src/test/resources/output.txt @@ -0,0 +1 @@ +Should be copied to OutputStream. \ No newline at end of file diff --git a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java index 8f8918ab22..9d47b2f5d4 100644 --- a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java +++ b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java @@ -8,6 +8,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; +import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; @@ -120,7 +121,7 @@ public class LoginControllerIntegrationTest { .login(userForm); // complex matcher Mockito.verify(loginService) - .setCurrentUser(Mockito.argThat(new ArgumentMatcher() { + .setCurrentUser(ArgumentMatchers.argThat(new ArgumentMatcher() { @Override public boolean matches(String argument) { return argument.startsWith("foo"); diff --git a/patterns/intercepting-filter/pom.xml b/patterns/intercepting-filter/pom.xml index 550409b643..5b7eb48a86 100644 --- a/patterns/intercepting-filter/pom.xml +++ b/patterns/intercepting-filter/pom.xml @@ -22,7 +22,6 @@ org.slf4j slf4j-api ${slf4j.version} - provided diff --git a/pom.xml b/pom.xml index 6641155044..f33d63bc48 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,6 @@ - spring-activiti aws akka-streams algorithms @@ -39,6 +38,7 @@ apache-thrift autovalue axon + bootique cdi @@ -81,10 +81,9 @@ javax-servlets javaxval jaxb - + jee7 jjwt - jooq jpa-storedprocedure jsf json-path @@ -94,6 +93,7 @@ jws libraries + libraries-data log-mdc log4j log4j2 @@ -128,6 +128,7 @@ spark-java spring-5-mvc + spring-activiti spring-akka spring-amqp spring-all diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java b/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java new file mode 100644 index 0000000000..f6cf9fba68 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java @@ -0,0 +1,43 @@ +package com.baelding.rxjava.operator; + +import rx.Observable.Operator; +import rx.Subscriber; + +public class ToCleanString implements Operator { + + public static ToCleanString toCleanString() { + return new ToCleanString(); + } + + private ToCleanString() { + super(); + } + + @Override + public Subscriber call(final Subscriber subscriber) { + return new Subscriber(subscriber) { + @Override + public void onCompleted() { + if (!subscriber.isUnsubscribed()) { + subscriber.onCompleted(); + } + } + + @Override + public void onError(Throwable t) { + if (!subscriber.isUnsubscribed()) { + subscriber.onError(t); + } + } + + @Override + public void onNext(String item) { + if (!subscriber.isUnsubscribed()) { + final String result = item.replaceAll("[^A-Za-z0-9]", ""); + subscriber.onNext(result); + } + } + }; + } + +} \ No newline at end of file diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java b/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java new file mode 100644 index 0000000000..006d59de36 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java @@ -0,0 +1,20 @@ +package com.baelding.rxjava.operator; + +import rx.Observable; +import rx.Observable.Transformer; + +public class ToLength implements Transformer { + + public static ToLength toLength() { + return new ToLength(); + } + + private ToLength() { + super(); + } + + @Override + public Observable call(Observable source) { + return source.map(String::length); + } +} \ No newline at end of file diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java index 040936a67a..458091fd1c 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java @@ -34,7 +34,7 @@ public class RxJavaBackpressureLongRunningUnitTest { public void givenHotObservable_whenBackpressureNotDefined_shouldTrowException() { // given TestSubscriber testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); source.observeOn(Schedulers.computation()).subscribe(testSubscriber); @@ -50,7 +50,7 @@ public class RxJavaBackpressureLongRunningUnitTest { public void givenHotObservable_whenWindowIsDefined_shouldNotThrowException() { // given TestSubscriber> testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); // when source.window(500).observeOn(Schedulers.computation()).subscribe(testSubscriber); @@ -67,7 +67,7 @@ public class RxJavaBackpressureLongRunningUnitTest { public void givenHotObservable_whenBufferIsDefined_shouldNotThrowException() { // given TestSubscriber> testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); // when source.buffer(1024).observeOn(Schedulers.computation()).subscribe(testSubscriber); @@ -84,7 +84,7 @@ public class RxJavaBackpressureLongRunningUnitTest { public void givenHotObservable_whenSkippingOperationIsDefined_shouldNotThrowException() { // given TestSubscriber testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); // when source.sample(100, TimeUnit.MILLISECONDS) diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java new file mode 100644 index 0000000000..a49103196c --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java @@ -0,0 +1,109 @@ +package com.baeldung.rxjava; + +import static com.baelding.rxjava.operator.ToCleanString.toCleanString; +import static com.baelding.rxjava.operator.ToLength.toLength; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import rx.Observable; +import rx.Observable.Operator; +import rx.Observable.Transformer; +import rx.Subscriber; + +import com.baelding.rxjava.operator.ToCleanString; +import com.baelding.rxjava.operator.ToLength; + +public class RxJavaCustomOperatorUnitTest { + + @Test + public void whenUseCleanStringOperator_thenSuccess() { + final List list = Arrays.asList("john_1", "tom-3"); + final List results = new ArrayList<>(); + + final Observable observable = Observable.from(list) + .lift(toCleanString()); + + // when + observable.subscribe(results::add); + + // then + assertThat(results, notNullValue()); + assertThat(results, hasSize(2)); + assertThat(results, hasItems("john1", "tom3")); + } + + @Test + public void whenUseToLengthOperator_thenSuccess() { + final List list = Arrays.asList("john", "tom"); + final List results = new ArrayList<>(); + + final Observable observable = Observable.from(list) + .compose(toLength()); + + // when + observable.subscribe(results::add); + + // then + assertThat(results, notNullValue()); + assertThat(results, hasSize(2)); + assertThat(results, hasItems(4, 3)); + } + + @Test + public void whenUseFunctionOperator_thenSuccess() { + final Operator cleanStringFn = subscriber -> new Subscriber(subscriber) { + @Override + public void onCompleted() { + if (!subscriber.isUnsubscribed()) { + subscriber.onCompleted(); + } + } + + @Override + public void onError(Throwable t) { + if (!subscriber.isUnsubscribed()) { + subscriber.onError(t); + } + } + + @Override + public void onNext(String str) { + if (!subscriber.isUnsubscribed()) { + final String result = str.replaceAll("[^A-Za-z0-9]", ""); + subscriber.onNext(result); + } + } + }; + + final List results = new ArrayList<>(); + Observable.from(Arrays.asList("ap_p-l@e", "or-an?ge")) + .lift(cleanStringFn) + .subscribe(results::add); + + assertThat(results, notNullValue()); + assertThat(results, hasSize(2)); + assertThat(results, hasItems("apple", "orange")); + } + + @Test + public void whenUseFunctionTransformer_thenSuccess() { + final Transformer toLengthFn = source -> source.map(String::length); + + final List results = new ArrayList<>(); + Observable.from(Arrays.asList("apple", "orange")) + .compose(toLengthFn) + .subscribe(results::add); + + assertThat(results, notNullValue()); + assertThat(results, hasSize(2)); + assertThat(results, hasItems(5, 6)); + } +} diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index 3d2f1386df..c5289b20a6 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -53,6 +53,23 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + true + + diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java index 3924d31f68..96b551c03c 100644 --- a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java @@ -1,9 +1,5 @@ package com.example.activitiwithspring; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - import org.activiti.engine.RuntimeService; import org.activiti.engine.TaskService; import org.activiti.engine.task.Task; @@ -12,12 +8,15 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.List; +import java.util.stream.Collectors; + @RestController public class ActivitiController { private static final Logger logger = LoggerFactory.getLogger(ActivitiController.class); + @Autowired private RuntimeService runtimeService; @@ -28,33 +27,26 @@ public class ActivitiController { public String startProcess() { runtimeService.startProcessInstanceByKey("my-process"); return "Process started. Number of currently running process instances = " + runtimeService.createProcessInstanceQuery() - .count(); + .count(); } @GetMapping("/get-tasks/{processInstanceId}") public List getTasks(@PathVariable String processInstanceId) { List usertasks = taskService.createTaskQuery() - .processInstanceId(processInstanceId) - .list(); + .processInstanceId(processInstanceId) + .list(); - List tasks = usertasks.stream().map(task -> { - TaskRepresentation taskRepresentation = new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId()); - return taskRepresentation; - }).collect(Collectors.toList()); - return tasks; + return usertasks.stream() + .map(task -> new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId())) + .collect(Collectors.toList()); } @GetMapping("/complete-task-A/{processInstanceId}") - public TaskRepresentation completeTaskA(@PathVariable String processInstanceId) { + public void completeTaskA(@PathVariable String processInstanceId) { Task task = taskService.createTaskQuery() - .processInstanceId(processInstanceId) - .singleResult(); + .processInstanceId(processInstanceId) + .singleResult(); taskService.complete(task.getId()); logger.info("Task completed"); - task = taskService.createTaskQuery() - .processInstanceId(processInstanceId) - .singleResult(); - - return new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId()); } } diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java index e98b8ad7ca..2cfacdcf0d 100644 --- a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java @@ -5,7 +5,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ActivitiWithSpringApplication { - public static void main(String[] args) { SpringApplication.run(ActivitiWithSpringApplication.class, args); } diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java b/spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java new file mode 100644 index 0000000000..c11b48f37a --- /dev/null +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/servicetasks/SendEmailServiceTask.java @@ -0,0 +1,12 @@ +package com.example.activitiwithspring.servicetasks; + +import org.activiti.engine.delegate.DelegateExecution; +import org.activiti.engine.delegate.JavaDelegate; + +public class SendEmailServiceTask implements JavaDelegate { + + public void execute(DelegateExecution execution) { + //logic to sent email confirmation + } + +} diff --git a/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml b/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml index 3ced8d6b7c..6f151af458 100644 --- a/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml +++ b/spring-activiti/src/main/resources/processes/my-process.bpmn20.xml @@ -1,66 +1,35 @@ - - + + - - - + + + - - - - - + - + - + - + - - + + - - - - - - + + + - - - - - - - + + + diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerTest.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java similarity index 73% rename from spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerTest.java rename to spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java index 3176207664..65fd33bfc6 100644 --- a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerTest.java +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java @@ -1,10 +1,6 @@ package com.example.activitiwithspring; -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.List; - +import com.fasterxml.jackson.databind.ObjectMapper; import org.activiti.engine.RuntimeService; import org.activiti.engine.runtime.ProcessInstance; import org.junit.Before; @@ -21,13 +17,16 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @SpringBootTest -public class ActivitiControllerTest { - private static final Logger logger = LoggerFactory.getLogger(ActivitiControllerTest.class); +public class ActivitiControllerIntegrationTest { + private static final Logger logger = LoggerFactory.getLogger(ActivitiControllerIntegrationTest.class); private MockMvc mockMvc; @Autowired @@ -39,10 +38,10 @@ public class ActivitiControllerTest { @Before public void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) - .build(); + .build(); for (ProcessInstance instance : runtimeService.createProcessInstanceQuery() - .list()) { + .list()) { runtimeService.deleteProcessInstance(instance.getId(), "Reset Processes"); } } @@ -51,21 +50,21 @@ public class ActivitiControllerTest { public void givenProcess_whenStartProcess_thenIncreaseInProcessInstanceCount() throws Exception { String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) - .andReturn() - .getResponse() - .getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); assertEquals("Process started. Number of currently running process instances = 1", responseBody); responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) - .andReturn() - .getResponse() - .getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); assertEquals("Process started. Number of currently running process instances = 2", responseBody); responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) - .andReturn() - .getResponse() - .getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); assertEquals("Process started. Number of currently running process instances = 3", responseBody); } @@ -73,19 +72,19 @@ public class ActivitiControllerTest { public void givenProcess_whenProcessInstance_thenReceivedRunningTask() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) - .andReturn() - .getResponse(); + .andReturn() + .getResponse(); ProcessInstance pi = runtimeService.createProcessInstanceQuery() - .orderByProcessInstanceId() - .desc() - .list() - .get(0); + .orderByProcessInstanceId() + .desc() + .list() + .get(0); logger.info("process instance = " + pi.getId()); String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/get-tasks/" + pi.getId())) - .andReturn() - .getResponse() - .getContentAsString(); + .andReturn() + .getResponse() + .getContentAsString(); ObjectMapper mapper = new ObjectMapper(); List tasks = Arrays.asList(mapper.readValue(responseBody, TaskRepresentation[].class)); @@ -98,23 +97,21 @@ public class ActivitiControllerTest { public void givenProcess_whenCompleteTaskA_thenReceivedNextTask() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) - .andReturn() - .getResponse(); + .andReturn() + .getResponse(); ProcessInstance pi = runtimeService.createProcessInstanceQuery() - .orderByProcessInstanceId() - .desc() - .list() - .get(0); + .orderByProcessInstanceId() + .desc() + .list() + .get(0); logger.info("process instance = " + pi.getId()); - String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/complete-task-A/" + pi.getId())) + this.mockMvc.perform(MockMvcRequestBuilders.get("/complete-task-A/" + pi.getId())) .andReturn() .getResponse() .getContentAsString(); - ObjectMapper mapper = new ObjectMapper(); - TaskRepresentation task = mapper.readValue(responseBody, TaskRepresentation.class); - assertEquals("B", task.getName()); - + List list = runtimeService.createProcessInstanceQuery().list(); + assertEquals(0, list.size()); } } diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java similarity index 84% rename from spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationTests.java rename to spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java index da22c6c7fa..7460c302d8 100644 --- a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationTests.java +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class ActivitiWithSpringApplicationTests { +public class ActivitiWithSpringApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java new file mode 100644 index 0000000000..7f07191cde --- /dev/null +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessEngineCreationTests.java @@ -0,0 +1,64 @@ +package com.example.activitiwithspring; + +import org.activiti.engine.ProcessEngine; +import org.activiti.engine.ProcessEngineConfiguration; +import org.activiti.engine.ProcessEngines; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import org.junit.Test; + +public class ProcessEngineCreationTests { + + @Test + public void givenXMLConfig_whenGetDefault_thenGotProcessEngine() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + assertNotNull(processEngine); + assertEquals("root", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenXMLConfig_whenCreateDefaultConfiguration_thenGotProcessEngine() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createProcessEngineConfigurationFromResourceDefault(); + ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("root", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenDifferentNameXMLConfig_whenGetProcessEngineConfig_thenGotResult() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("my.activiti.cfg.xml"); + ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("baeldung", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenDifferentBeanNameInXMLConfig_whenGetProcessEngineConfig_thenGotResult() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration + .createProcessEngineConfigurationFromResource("my.activiti.cfg.xml", "myProcessEngineConfiguration"); + ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("baeldung", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenNoXMLConfig_whenCreateInMemProcessEngineConfig_thenCreated() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration(); + ProcessEngine processEngine = processEngineConfiguration + .setJdbcUrl("jdbc:h2:mem:my-own-in-mem-db;DB_CLOSE_DELAY=1000") + .buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } + + @Test + public void givenNoXMLConfig_whenCreateProcessEngineConfig_thenCreated() { + ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration(); + ProcessEngine processEngine = processEngineConfiguration + .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE) + .setJdbcUrl("jdbc:h2:mem:my-own-db;DB_CLOSE_DELAY=1000") + .buildProcessEngine(); + assertNotNull(processEngine); + assertEquals("sa", processEngine.getProcessEngineConfiguration().getJdbcUsername()); + } +} diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java new file mode 100644 index 0000000000..cae28d5281 --- /dev/null +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ProcessExecutionTests.java @@ -0,0 +1,97 @@ +package com.example.activitiwithspring; + + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.activiti.engine.ActivitiException; +import org.activiti.engine.ProcessEngine; +import org.activiti.engine.ProcessEngines; +import org.activiti.engine.RepositoryService; +import org.activiti.engine.RuntimeService; +import org.activiti.engine.TaskService; +import org.activiti.engine.runtime.ProcessInstance; +import org.activiti.engine.task.Task; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class ProcessExecutionTests { + + @Test + public void givenBPMN_whenDeployProcess_thenDeployed() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + Long count = repositoryService.createProcessDefinitionQuery().count(); + assertTrue(count >= 1); + } + + @Test + public void givenProcessDefinition_whenStartProcessInstance_thenProcessRunning() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + + Map variables = new HashMap(); + variables.put("employeeName", "Kermit"); + variables.put("numberOfDays", new Integer(4)); + variables.put("vacationMotivation", "I'm really tired!"); + + RuntimeService runtimeService = processEngine.getRuntimeService(); + ProcessInstance processInstance = runtimeService + .startProcessInstanceByKey("vacationRequest", variables); + + Long count = runtimeService.createProcessInstanceQuery().count(); + assertTrue(count >= 1); + } + + @Test + public void givenProcessInstance_whenCompleteTask_thenProcessExecutionContinues() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + + Map variables = new HashMap(); + variables.put("employeeName", "Kermit"); + variables.put("numberOfDays", new Integer(4)); + variables.put("vacationMotivation", "I'm really tired!"); + + RuntimeService runtimeService = processEngine.getRuntimeService(); + ProcessInstance processInstance = runtimeService + .startProcessInstanceByKey("vacationRequest", variables); + + TaskService taskService = processEngine.getTaskService(); + List tasks = taskService.createTaskQuery().taskCandidateGroup("management").list(); + + Task task = tasks.get(0); + + Map taskVariables = new HashMap(); + taskVariables.put("vacationApproved", "false"); + taskVariables.put("comments", "We have a tight deadline!"); + taskService.complete(task.getId(), taskVariables); + + Task currentTask = taskService.createTaskQuery().taskName("Modify vacation request").singleResult(); + assertNotNull(currentTask); + } + + @Test(expected = ActivitiException.class) + public void givenProcessDefinition_whenSuspend_thenNoProcessInstanceCreated() { + ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine(); + RepositoryService repositoryService = processEngine.getRepositoryService(); + repositoryService.createDeployment() + .addClasspathResource("org/activiti/test/vacationRequest.bpmn20.xml") + .deploy(); + + RuntimeService runtimeService = processEngine.getRuntimeService(); + repositoryService.suspendProcessDefinitionByKey("vacationRequest"); + runtimeService.startProcessInstanceByKey("vacationRequest"); + } +} diff --git a/spring-activiti/src/test/resources/activiti.cfg.xml b/spring-activiti/src/test/resources/activiti.cfg.xml new file mode 100644 index 0000000000..1ee117d936 --- /dev/null +++ b/spring-activiti/src/test/resources/activiti.cfg.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + diff --git a/spring-activiti/src/test/resources/my.activiti.cfg.xml b/spring-activiti/src/test/resources/my.activiti.cfg.xml new file mode 100644 index 0000000000..07e4206dad --- /dev/null +++ b/spring-activiti/src/test/resources/my.activiti.cfg.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml b/spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml new file mode 100644 index 0000000000..354c633385 --- /dev/null +++ b/spring-activiti/src/test/resources/org/activiti/test/vacationRequest.bpmn20.xml @@ -0,0 +1,149 @@ + + + + + + + + + + + + + ${employeeName} would like to take ${numberOfDays} day(s) of vacation (Motivation: ${reason}). + + + + + + + + + + management + + + + + + + + + + Your manager has disapproved your vacation request for ${numberOfDays} days. + Reason: ${comments} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-property-exp/pom.xml b/spring-boot-property-exp/pom.xml index f554bb5b99..0c54d57db1 100644 --- a/spring-boot-property-exp/pom.xml +++ b/spring-boot-property-exp/pom.xml @@ -24,8 +24,8 @@ - property-exp-default - property-exp-custom + property-exp-default-config + property-exp-custom-config diff --git a/spring-boot-property-exp/property-exp-custom/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml similarity index 72% rename from spring-boot-property-exp/property-exp-custom/pom.xml rename to spring-boot-property-exp/property-exp-custom-config/pom.xml index 234404a6c0..cfce323eab 100644 --- a/spring-boot-property-exp/property-exp-custom/pom.xml +++ b/spring-boot-property-exp/property-exp-custom-config/pom.xml @@ -40,6 +40,15 @@ **/application*.properties + + ${basedir}/src/main/resources + true + + **/application*.yml + **/application*.yaml + **/application*.properties + + @@ -53,6 +62,14 @@ true + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp + + diff --git a/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java b/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java rename to spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java diff --git a/spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java b/spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java rename to spring-boot-property-exp/property-exp-custom-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java diff --git a/spring-boot-property-exp/property-exp-custom/src/main/resources/application.properties b/spring-boot-property-exp/property-exp-custom-config/src/main/resources/application.properties similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/resources/application.properties rename to spring-boot-property-exp/property-exp-custom-config/src/main/resources/application.properties diff --git a/spring-boot-property-exp/property-exp-custom/src/main/resources/banner.txt b/spring-boot-property-exp/property-exp-custom-config/src/main/resources/banner.txt similarity index 100% rename from spring-boot-property-exp/property-exp-custom/src/main/resources/banner.txt rename to spring-boot-property-exp/property-exp-custom-config/src/main/resources/banner.txt diff --git a/spring-boot-property-exp/property-exp-default/build.gradle b/spring-boot-property-exp/property-exp-default-config/build.gradle similarity index 96% rename from spring-boot-property-exp/property-exp-default/build.gradle rename to spring-boot-property-exp/property-exp-default-config/build.gradle index f3c5f4a378..ec27de7c41 100644 --- a/spring-boot-property-exp/property-exp-default/build.gradle +++ b/spring-boot-property-exp/property-exp-default-config/build.gradle @@ -27,6 +27,10 @@ repositories { mavenCentral() } +springBoot { + executable = true +} + import org.apache.tools.ant.filters.ReplaceTokens processResources { with copySpec { diff --git a/spring-boot-property-exp/property-exp-default/gradle.properties b/spring-boot-property-exp/property-exp-default-config/gradle.properties similarity index 100% rename from spring-boot-property-exp/property-exp-default/gradle.properties rename to spring-boot-property-exp/property-exp-default-config/gradle.properties diff --git a/spring-boot-property-exp/property-exp-default/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml similarity index 75% rename from spring-boot-property-exp/property-exp-default/pom.xml rename to spring-boot-property-exp/property-exp-default-config/pom.xml index 3629e56111..2544800e6a 100644 --- a/spring-boot-property-exp/property-exp-default/pom.xml +++ b/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -30,4 +30,16 @@ + + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + + diff --git a/spring-boot-property-exp/property-exp-default/settings.gradle b/spring-boot-property-exp/property-exp-default-config/settings.gradle similarity index 100% rename from spring-boot-property-exp/property-exp-default/settings.gradle rename to spring-boot-property-exp/property-exp-default-config/settings.gradle diff --git a/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java b/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java rename to spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/SpringBootPropertyExpansionApp.java diff --git a/spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java b/spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java rename to spring-boot-property-exp/property-exp-default-config/src/main/java/com/baeldung/propertyexpansion/components/PropertyLoggerBean.java diff --git a/spring-boot-property-exp/property-exp-default/src/main/resources/application.properties b/spring-boot-property-exp/property-exp-default-config/src/main/resources/application.properties similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/resources/application.properties rename to spring-boot-property-exp/property-exp-default-config/src/main/resources/application.properties diff --git a/spring-boot-property-exp/property-exp-default/src/main/resources/banner.txt b/spring-boot-property-exp/property-exp-default-config/src/main/resources/banner.txt similarity index 100% rename from spring-boot-property-exp/property-exp-default/src/main/resources/banner.txt rename to spring-boot-property-exp/property-exp-default-config/src/main/resources/banner.txt diff --git a/spring-core/README.md b/spring-core/README.md index 380b3138fe..b0d0b8408c 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -6,3 +6,4 @@ - [Constructor Injection in Spring with Lombok](http://www.baeldung.com/spring-injection-lombok) - [A Quick Guide to Spring @Value](http://www.baeldung.com/spring-value-annotation) - [Spring YAML Configuration](http://www.baeldung.com/spring-yaml) +- [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) diff --git a/spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java b/spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java new file mode 100644 index 0000000000..d2cda19ae6 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java @@ -0,0 +1,75 @@ +package com.baeldung.valuewithdefaults; + +import java.util.Arrays; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.util.Assert; + +import com.google.common.collect.Lists; +import com.google.common.primitives.Ints; + +/** + * Demonstrates setting defaults for @Value annotation. Note that there are no properties + * defined in the specified property source. We also assume that the user here + * does not have a system property named some.key. + * + */ +@Configuration +@PropertySource(name = "myProperties", value = "valueswithdefaults.properties") +public class ValuesWithDefaultsApp { + + @Value("${some.key:my default value}") + private String stringWithDefaultValue; + + @Value("${some.key:}") + private String stringWithBlankDefaultValue; + + @Value("${some.key:true}") + private boolean booleanWithDefaultValue; + + @Value("${some.key:42}") + private int intWithDefaultValue; + + @Value("${some.key:one,two,three}") + private String[] stringArrayWithDefaults; + + @Value("${some.key:1,2,3}") + private int[] intArrayWithDefaults; + + @Value("#{systemProperties['some.key'] ?: 'my default system property value'}") + private String spelWithDefaultValue; + + + public static void main(String[] args) { + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesWithDefaultsApp.class); + } + + @PostConstruct + public void afterInitialize() { + // strings + Assert.isTrue(stringWithDefaultValue.equals("my default value")); + Assert.isTrue(stringWithBlankDefaultValue.equals("")); + + // other primitives + Assert.isTrue(booleanWithDefaultValue); + Assert.isTrue(intWithDefaultValue == 42); + + // arrays + List stringListValues = Lists.newArrayList("one", "two", "three"); + Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues)); + + List intListValues = Lists.newArrayList(1, 2, 3); + Assert.isTrue(Ints.asList(intArrayWithDefaults).containsAll(intListValues)); + + // SpEL + Assert.isTrue(spelWithDefaultValue.equals("my default system property value")); + + } +} diff --git a/spring-core/src/main/resources/valueswithdefaults.properties b/spring-core/src/main/resources/valueswithdefaults.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-mvc-email/pom.xml b/spring-mvc-email/pom.xml index c40abdb4bf..9228054878 100644 --- a/spring-mvc-email/pom.xml +++ b/spring-mvc-email/pom.xml @@ -21,16 +21,17 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-tomcat + provided + org.springframework.boot spring-boot-starter-mail - + - - org.apache.tomcat.embed - tomcat-embed-jasper - javax.servlet jstl diff --git a/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java b/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java index f146ee1d04..bc5d6b3151 100644 --- a/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java +++ b/spring-mvc-email/src/main/java/com/baeldung/spring/Application.java @@ -2,10 +2,11 @@ package com.baeldung.spring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); } diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 0cfb3e6dee..8a51c04113 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -15,14 +15,19 @@ - 4.3.4.RELEASE - 2.6 + 4.3.10.RELEASE + 3.1.0 1.2 2.3.1 3.1.0 - 5.3.3.Final + 5.4.1.Final enter-location-of-server 1.3.2 + 1.8 + 3.0.7.RELEASE + 2.4.12 + 2.3.23 + 1.2.5 @@ -79,6 +84,45 @@ commons-fileupload ${fileupload.version} + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring4 + ${org.thymeleaf-version} + + + + + org.freemarker + freemarker + ${freemarker.version} + + + org.springframework + spring-context-support + ${springframework.version} + + + + + org.codehaus.groovy + groovy-templates + ${groovy.version} + + + + + de.neuland-bfi + spring-jade4j + ${jade.version} + + @@ -94,6 +138,14 @@ ${deploy-path} + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + springMvcSimple diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java index 9ace968bbe..b62ccae465 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java @@ -12,7 +12,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc -@ComponentScan(basePackages = "com.baeldung.springmvcforms") +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) class ApplicationConfiguration extends WebMvcConfigurerAdapter { @Override diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java new file mode 100644 index 0000000000..e43238f8a6 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; +import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) +public class FreemarkerConfiguration { + @Bean + public FreeMarkerConfigurer freemarkerConfig() { + FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); + freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/"); + return freeMarkerConfigurer; + } + + @Bean + public FreeMarkerViewResolver freemarkerViewResolver() { + FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); + resolver.setCache(true); + resolver.setPrefix(""); + resolver.setSuffix(".ftl"); + return resolver; + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java new file mode 100644 index 0000000000..b7a9256fc0 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer; +import org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) +public class GroovyConfiguration { + + @Bean + public GroovyMarkupConfigurer groovyMarkupConfigurer() { + GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer(); + configurer.setResourceLoaderPath("/WEB-INF/views/"); + return configurer; + } + + @Bean + public GroovyMarkupViewResolver thymeleafViewResolver() { + GroovyMarkupViewResolver viewResolver = new GroovyMarkupViewResolver(); + viewResolver.setSuffix(".tpl"); + return viewResolver; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java new file mode 100644 index 0000000000..10345bac58 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/JadeTemplateConfiguration.java @@ -0,0 +1,39 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +import de.neuland.jade4j.JadeConfiguration; +import de.neuland.jade4j.spring.template.SpringTemplateLoader; +import de.neuland.jade4j.spring.view.JadeViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) +public class JadeTemplateConfiguration { + @Bean + public SpringTemplateLoader templateLoader() { + SpringTemplateLoader templateLoader = new SpringTemplateLoader(); + templateLoader.setBasePath("/WEB-INF/views/"); + templateLoader.setSuffix(".jade"); + return templateLoader; + } + + @Bean + public JadeConfiguration jadeConfiguration() { + JadeConfiguration configuration = new JadeConfiguration(); + configuration.setCaching(false); + configuration.setTemplateLoader(templateLoader()); + return configuration; + } + + @Bean + public ViewResolver viewResolver() { + JadeViewResolver viewResolver = new JadeViewResolver(); + viewResolver.setConfiguration(jadeConfiguration()); + return viewResolver; + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java new file mode 100644 index 0000000000..257dbc718a --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java @@ -0,0 +1,38 @@ +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) +public class ThymeleafConfiguration { + @Bean + public SpringTemplateEngine templateEngine() { + SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(thymeleafTemplateResolver()); + return templateEngine; + } + + @Bean + public SpringResourceTemplateResolver thymeleafTemplateResolver() { + SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/views/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } + + @Bean + public ThymeleafViewResolver thymeleafViewResolver() { + ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + return viewResolver; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java index d6bbf5eabd..d57d2c621a 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java @@ -15,6 +15,10 @@ public class WebInitializer implements WebApplicationInitializer { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(ApplicationConfiguration.class); + //ctx.register(ThymeleafConfiguration.class); + //ctx.register(FreemarkerConfiguration.class); + //ctx.register(GroovyConfiguration.class); + //ctx.register(JadeTemplateConfiguration.class); ctx.setServletContext(container); // Manage the lifecycle of the root application context diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java new file mode 100644 index 0000000000..b402a376c0 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java @@ -0,0 +1,50 @@ +package com.baeldung.spring.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.spring.domain.User; + +@Controller +public class UserController { + + @GetMapping("/registration") + public String getRegistration(Model model) { + model.addAttribute("user", new User()); + return "registration"; + } + + @GetMapping("/registration-thymeleaf") + public String getRegistrationThymeleaf(Model model) { + model.addAttribute("user", new User()); + return "registration-thymeleaf"; + } + + @GetMapping("/registration-freemarker") + public String getRegistrationFreemarker(Model model) { + model.addAttribute("user", new User()); + return "registration-freemarker"; + } + + @GetMapping("/registration-groovy") + public String getRegistrationGroovy(Model model) { + model.addAttribute("user", new User()); + return "registration-groovy"; + } + + @GetMapping("/registration-jade") + public String getRegistrationJade(Model model) { + model.addAttribute("user", new User()); + return "registration-jade"; + } + + @PostMapping("/register") + @ResponseBody + public void register(User user){ + System.out.println(user.getEmail()); + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java new file mode 100644 index 0000000000..8016f98d85 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.domain; + +public class User { + private String email; + private String password; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl new file mode 100644 index 0000000000..8dce9a88c9 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl @@ -0,0 +1,15 @@ +<#import "/spring.ftl" as spring/> + + + +User Registration + + +
+ <@spring.bind path="user" /> + Email:<@spring.formInput "user.email"/>
+ Password:<@spring.formPasswordInput "user.password"/>
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl new file mode 100644 index 0000000000..291077fc2e --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl @@ -0,0 +1,18 @@ +yieldUnescaped '' +html(lang:'en') { + head { + meta('http-equiv':'"Content-Type" content="text/html; charset=utf-8"') + title('User Registration') + } + body { + form (id:'userForm', action:'register', method:'post') { + label (for:'email', 'Email') + input (name:'email', type:'text', value:user.email?:'') + label (for:'password', 'Password') + input (name:'password', type:'password', value:user.password?:'') + div (class:'form-actions') { + input (type:'submit', value:'Submit') + } + } + } +} \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-jade.jade b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-jade.jade new file mode 100644 index 0000000000..44b6293ff0 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-jade.jade @@ -0,0 +1,11 @@ +doctype html +html + head + title User Registration + body + form(action="register" method="post" ) + label(for="email") Emailaaaaaaaa: + input(type="text" name="email") + label(for="password") Password: + input(type="password" name="password") + input(type="submit" value="Submit") \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html new file mode 100644 index 0000000000..c98f3283c0 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html @@ -0,0 +1,13 @@ + + + +User Registration + + +
+ Email:
+ Password:
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp new file mode 100644 index 0000000000..7c2d9c73b1 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp @@ -0,0 +1,18 @@ +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +User Registration + + + + Email: + +
+ Password: + +
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/web.xml b/spring-mvc-simple/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index b6f1065cad..0000000000 --- a/spring-mvc-simple/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - spring - org.springframework.web.servlet.DispatcherServlet - - contextConfigLocation - classpath*:spring-servlet_RequestMappingHandlerAdapter.xml - - 1 - - - spring - / - - \ No newline at end of file diff --git a/spring-rest/src/main/webapp/WEB-INF/web.xml b/spring-rest/src/main/webapp/WEB-INF/web.xml index a439de8a05..1b8b767ae3 100644 --- a/spring-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest/src/main/webapp/WEB-INF/web.xml @@ -19,10 +19,10 @@ org.baeldung.config - + api diff --git a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java index 4057a85f13..c2c5939676 100644 --- a/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-jsp-authentication/src/main/java/org/baeldung/config/Application.java @@ -2,10 +2,11 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.boot.web.support.SpringBootServletInitializer; -@SpringBootApplication +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class Application extends SpringBootServletInitializer { @Override diff --git a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java index 4057a85f13..c2c5939676 100644 --- a/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-jsp-authorize/src/main/java/org/baeldung/config/Application.java @@ -2,10 +2,11 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.boot.web.support.SpringBootServletInitializer; -@SpringBootApplication +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class Application extends SpringBootServletInitializer { @Override diff --git a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java index 4057a85f13..c2c5939676 100644 --- a/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-jsp-config/src/main/java/org/baeldung/config/Application.java @@ -2,10 +2,11 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.boot.web.support.SpringBootServletInitializer; -@SpringBootApplication +@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class Application extends SpringBootServletInitializer { @Override diff --git a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java index bea0194b40..329b104143 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/Application.java @@ -2,9 +2,10 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java index bea0194b40..329b104143 100644 --- a/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-thymeleaf-authorize/src/main/java/org/baeldung/config/Application.java @@ -2,9 +2,10 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java index bea0194b40..329b104143 100644 --- a/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java +++ b/spring-security-client/spring-security-thymeleaf-config/src/main/java/org/baeldung/config/Application.java @@ -2,9 +2,10 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class Application { +public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-core/src/main/java/org/baeldung/app/App.java b/spring-security-core/src/main/java/org/baeldung/app/App.java index 06c295fcd7..37d8c34c5a 100644 --- a/spring-security-core/src/main/java/org/baeldung/app/App.java +++ b/spring-security-core/src/main/java/org/baeldung/app/App.java @@ -3,6 +3,7 @@ package org.baeldung.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @@ -10,7 +11,7 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @EnableJpaRepositories("org.baeldung.repository") @ComponentScan("org.baeldung") @EntityScan("org.baeldung.entity") -public class App { +public class App extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(App.class, args); } diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index f2b6b766eb..e6452ea70b 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -57,7 +57,7 @@
- 1.5.7 + 1.5.5 diff --git a/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java b/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java index 4bcb255046..5936aa30ef 100644 --- a/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java +++ b/spring-security-mvc-ldap/src/main/java/org/baeldung/SampleLDAPApplication.java @@ -1,8 +1,9 @@ package org.baeldung; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -11,17 +12,22 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter * class to run up a Jetty Server (on http://localhost:8080) * */ -@EnableAutoConfiguration -@ComponentScan("org.baeldung") -public class SampleLDAPApplication extends WebMvcConfigurerAdapter { +@SpringBootApplication +public class SampleLDAPApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SampleLDAPApplication.class, args); } - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/login").setViewName("login"); + @Bean + public WebMvcConfigurerAdapter adapter() { + return new WebMvcConfigurerAdapter() { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/login") + .setViewName("login"); + } + }; } } \ No newline at end of file diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java index b68e7eab50..1472a1f89c 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java @@ -1,17 +1,14 @@ package org.baeldung.spring; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; -@Configuration +//@Configuration //@ImportResource({ "classpath:RedirectionWebSecurityConfig.xml" }) -@EnableWebSecurity -@Profile("!https") +//@EnableWebSecurity +//@Profile("!https") public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter { public RedirectionSecurityConfig() { @@ -20,25 +17,23 @@ public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth - .inMemoryAuthentication() - .withUser("user1") - .password("user1Pass") - .roles("USER"); + auth.inMemoryAuthentication() + .withUser("user1") + .password("user1Pass") + .roles("USER"); } @Override protected void configure(final HttpSecurity http) throws Exception { - http - .authorizeRequests() - .antMatchers("/login*") - .permitAll() - .anyRequest() - .authenticated() - .and() - .formLogin() - .successHandler(new SavedRequestAwareAuthenticationSuccessHandler()); - //.successHandler(new RefererAuthenticationSuccessHandler()) + http.authorizeRequests() + .antMatchers("/login*") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin() + .successHandler(new SavedRequestAwareAuthenticationSuccessHandler()); + // .successHandler(new RefererAuthenticationSuccessHandler()) } } diff --git a/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java b/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java index 608e8a6819..ed57088c56 100644 --- a/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java +++ b/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java @@ -2,9 +2,10 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication -public class SpringOpenidApplication { +public class SpringOpenidApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SpringOpenidApplication.class, args); diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index c329bd1cb8..77a58a56d8 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -33,12 +33,6 @@ org.springframework spring-core - - - commons-logging - commons-logging - - org.springframework @@ -79,6 +73,12 @@ spring-oxm + + commons-logging + commons-logging + ${commons-logging.version} + + @@ -105,24 +105,11 @@ org.apache.httpcomponents httpcore - ${httpcore.version} - - - commons-logging - commons-logging - - org.apache.httpcomponents httpclient - - - commons-logging - commons-logging - - @@ -213,7 +200,7 @@ 19.0 3.5 - + 1.2 4.4.5 4.5.2 diff --git a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java index 5ef699d264..c0ad5eb690 100644 --- a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiApplication.java @@ -3,24 +3,14 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.context.request.RequestContextListener; @EnableOAuth2Sso @SpringBootApplication -public class UiApplication extends WebSecurityConfigurerAdapter { +public class UiApplication extends SpringBootServletInitializer { - @Override - public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers("/", "/login**") - .permitAll() - .anyRequest() - .authenticated(); - } @Bean public RequestContextListener requestContextListener() { diff --git a/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java new file mode 100644 index 0000000000..5dbe9ada34 --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui-2/src/main/java/org/baeldung/config/UiSecurityConfig.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class UiSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/", "/login**") + .permitAll() + .anyRequest() + .authenticated(); + } + +} diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java index 5ef699d264..6e29879cb3 100644 --- a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiApplication.java @@ -3,24 +3,13 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.context.request.RequestContextListener; @EnableOAuth2Sso @SpringBootApplication -public class UiApplication extends WebSecurityConfigurerAdapter { - - @Override - public void configure(HttpSecurity http) throws Exception { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers("/", "/login**") - .permitAll() - .anyRequest() - .authenticated(); - } +public class UiApplication extends SpringBootServletInitializer { @Bean public RequestContextListener requestContextListener() { diff --git a/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java new file mode 100644 index 0000000000..5dbe9ada34 --- /dev/null +++ b/spring-security-sso/spring-security-sso-ui/src/main/java/org/baeldung/config/UiSecurityConfig.java @@ -0,0 +1,20 @@ +package org.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class UiSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + public void configure(HttpSecurity http) throws Exception { + http.antMatcher("/**") + .authorizeRequests() + .antMatchers("/", "/login**") + .permitAll() + .anyRequest() + .authenticated(); + } + +} diff --git a/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java b/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java index 625e5439ee..b8eda25960 100644 --- a/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java +++ b/spring-zuul/spring-zuul-ui/src/main/java/org/baeldung/config/UiApplication.java @@ -2,11 +2,12 @@ package org.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @EnableZuulProxy @SpringBootApplication -public class UiApplication { +public class UiApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(UiApplication.class, args); diff --git a/vavr/pom.xml b/vavr/pom.xml index d35a408389..426155263c 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -71,4 +71,26 @@ 4.12 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + true + + + + + \ No newline at end of file diff --git a/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java index 1adff2e845..1c7d70a9a4 100644 --- a/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java @@ -1,18 +1,24 @@ package com.baeldung.vavr; +import io.vavr.MatchError; +import io.vavr.control.Option; +import org.junit.Test; + import static io.vavr.API.$; import static io.vavr.API.Case; import static io.vavr.API.Match; import static io.vavr.API.run; -import static io.vavr.Predicates.*; +import static io.vavr.Predicates.allOf; +import static io.vavr.Predicates.anyOf; +import static io.vavr.Predicates.instanceOf; +import static io.vavr.Predicates.is; +import static io.vavr.Predicates.isIn; +import static io.vavr.Predicates.isNotNull; +import static io.vavr.Predicates.isNull; +import static io.vavr.Predicates.noneOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import org.junit.Test; - -import io.vavr.MatchError; -import io.vavr.control.Option; - public class PatternMatchingUnitTest { @Test public void whenMatchesDefault_thenCorrect() { diff --git a/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java index 8409dbfa60..e93084f2c0 100644 --- a/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java @@ -9,7 +9,9 @@ import org.junit.Test; import java.util.function.Predicate; -import static io.vavr.API.*; +import static io.vavr.API.$; +import static io.vavr.API.Case; +import static io.vavr.API.Match; public class PropertyBasedLongRunningUnitTest { diff --git a/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java index 5ddd344c5c..08a5e20b40 100644 --- a/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java @@ -5,7 +5,9 @@ import io.vavr.Function1; import io.vavr.Function2; import io.vavr.Function5; import io.vavr.Lazy; -import io.vavr.*; +import io.vavr.Tuple; +import io.vavr.Tuple2; +import io.vavr.Tuple3; import io.vavr.collection.List; import io.vavr.collection.Seq; import io.vavr.control.Option; @@ -13,23 +15,25 @@ import io.vavr.control.Try; import io.vavr.control.Validation; import org.junit.Test; -import com.baeldung.vavr.Person; -import com.baeldung.vavr.PersonValidator; - import java.util.Arrays; import java.util.Collections; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.IntStream; -import static io.vavr.API.*; -import static org.junit.Assert.*; +import static io.vavr.API.$; +import static io.vavr.API.Case; +import static io.vavr.API.Match; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class VavrUnitTest { @Test public void givenList_whenSorts_thenCorrect() { List sortedList = List.of(3, 2, 1) - .sorted(); + .sorted(); } /* @@ -123,7 +127,7 @@ public class VavrUnitTest { @Test public void whenCreatesFunction_thenCorrect0() { Function0 getClazzName = () -> this.getClass() - .getName(); + .getName(); String clazzName = getClazzName.apply(); assertEquals("com.baeldung.vavr.VavrUnitTest", clazzName); } @@ -257,7 +261,7 @@ public class VavrUnitTest { public void whenSumsJava8List_thenCorrect() { // Arrays.asList(1, 2, 3).stream().reduce((i, j) -> i + j); int sum = IntStream.of(1, 2, 3) - .sum(); + .sum(); assertEquals(6, sum); } @@ -273,8 +277,8 @@ public class VavrUnitTest { @Test public void whenSumsVavrList_thenCorrect() { int sum = List.of(1, 2, 3) - .sum() - .intValue(); + .sum() + .intValue(); assertEquals(6, sum); } @@ -307,21 +311,21 @@ public class VavrUnitTest { int input = 2; String output; switch (input) { - case 0: - output = "zero"; - break; - case 1: - output = "one"; - break; - case 2: - output = "two"; - break; - case 3: - output = "three"; - break; - default: - output = "unknown"; - break; + case 0: + output = "zero"; + break; + case 1: + output = "one"; + break; + case 2: + output = "two"; + break; + case 3: + output = "three"; + break; + default: + output = "unknown"; + break; } assertEquals("two", output); } diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java index 9f0c48e3ee..4b4eb55fc5 100644 --- a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -1,17 +1,5 @@ package com.baeldung.vavr.collections; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.util.Comparator; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import org.junit.Test; - import io.vavr.Tuple; import io.vavr.Tuple2; import io.vavr.collection.Array; @@ -28,6 +16,17 @@ import io.vavr.collection.Stream; import io.vavr.collection.TreeMap; import io.vavr.collection.TreeSet; import io.vavr.collection.Vector; +import org.junit.Test; + +import java.util.Comparator; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; public class CollectionAPIUnitTest { @@ -234,7 +233,7 @@ public class CollectionAPIUnitTest { .toJavaMap(i -> Tuple.of(i, Integer.valueOf(i))); assertEquals(new Integer(2), map.get("2")); } - + @Test public void givenVavrList_whenCollected_thenCorrect() { java.util.Set javaSet = List.of(1, 2, 3) diff --git a/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java index 6b0a34f9e4..155932888d 100644 --- a/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java @@ -7,32 +7,32 @@ import static org.junit.Assert.assertEquals; public class EitherUnitTest { - @Test - public void givenMarks_whenPassNumber_thenExpectNumber() { - Either result = EitherDemo.computeWithEither(100); - int marks = result.right() - .getOrElseThrow(x -> new IllegalStateException()); + @Test + public void givenMarks_whenPassNumber_thenExpectNumber() { + Either result = EitherDemo.computeWithEither(100); + int marks = result.right() + .getOrElseThrow(x -> new IllegalStateException()); - assertEquals(100, marks); - } + assertEquals(100, marks); + } - @Test - public void givenMarks_whenFailNumber_thenExpectErrorMesssage() { - Either result = EitherDemo.computeWithEither(50); - String error = result.left() + @Test + public void givenMarks_whenFailNumber_thenExpectErrorMesssage() { + Either result = EitherDemo.computeWithEither(50); + String error = result.left() .getOrNull(); - assertEquals("Marks not acceptable", error); - } + assertEquals("Marks not acceptable", error); + } - @Test - public void givenPassMarks_whenModified_thenExpectNumber() { - Either result = EitherDemo.computeWithEither(90); - int marks = result.right() + @Test + public void givenPassMarks_whenModified_thenExpectNumber() { + Either result = EitherDemo.computeWithEither(90); + int marks = result.right() .map(x -> x * 2) .get(); - assertEquals(180, marks); - } + assertEquals(180, marks); + } } diff --git a/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java index 9c3e5a9cae..c7f17c2afc 100644 --- a/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java @@ -3,16 +3,18 @@ package com.baeldung.vavr.exception.handling; import com.baeldung.vavr.exception.handling.client.ClientException; import com.baeldung.vavr.exception.handling.client.HttpClient; import com.baeldung.vavr.exception.handling.client.Response; -import com.baeldung.vavr.exception.handling.VavrTry; - import io.vavr.collection.Stream; import io.vavr.control.Option; import io.vavr.control.Try; import org.junit.Test; -import static io.vavr.API.*; +import static io.vavr.API.$; +import static io.vavr.API.Case; +import static io.vavr.API.Match; import static io.vavr.Predicates.instanceOf; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; public class VavrTryUnitTest { @@ -26,8 +28,8 @@ public class VavrTryUnitTest { //when Try response = new VavrTry(httpClient).getResponse(); Integer chainedResult = response - .map(this::actionThatTakesResponse) - .getOrElse(defaultChainedResult); + .map(this::actionThatTakesResponse) + .getOrElse(defaultChainedResult); Stream stream = response.toStream().map(it -> it.id); //then @@ -49,8 +51,8 @@ public class VavrTryUnitTest { //when Try response = new VavrTry(httpClient).getResponse(); Integer chainedResult = response - .map(this::actionThatTakesResponse) - .getOrElse(defaultChainedResult); + .map(this::actionThatTakesResponse) + .getOrElse(defaultChainedResult); Option optionalResponse = response.toOption(); //then @@ -70,9 +72,9 @@ public class VavrTryUnitTest { //when Try recovered = new VavrTry(httpClient).getResponse() - .recover(r -> Match(r).of( - Case($(instanceOf(ClientException.class)), defaultResponse) - )); + .recover(r -> Match(r).of( + Case($(instanceOf(ClientException.class)), defaultResponse) + )); //then assertTrue(recovered.isFailure()); @@ -92,10 +94,10 @@ public class VavrTryUnitTest { //when Try recovered = new VavrTry(httpClient).getResponse() - .recover(r -> Match(r).of( - Case($(instanceOf(ClientException.class)), defaultResponse), - Case($(instanceOf(IllegalArgumentException.class)), defaultResponse) - )); + .recover(r -> Match(r).of( + Case($(instanceOf(ClientException.class)), defaultResponse), + Case($(instanceOf(IllegalArgumentException.class)), defaultResponse) + )); //then assertTrue(recovered.isSuccess()); @@ -106,7 +108,7 @@ public class VavrTryUnitTest { return response.id.hashCode(); } - public int actionThatTakesTryResponse(Try response, int defaultTransformation){ + public int actionThatTakesTryResponse(Try response, int defaultTransformation) { return response.transform(responses -> response.map(it -> it.id.hashCode()).getOrElse(defaultTransformation)); } diff --git a/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java b/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java index c2e9f377dd..63338afc24 100644 --- a/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java @@ -3,18 +3,18 @@ package com.baeldung.vavr.repositories; import com.baeldung.Application; import com.baeldung.repositories.VavrUserRepository; import com.baeldung.vavr.User; - import io.vavr.collection.Seq; import io.vavr.control.Option; - -import org.junit.Test; import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class)