diff --git a/aws/src/main/java/com/baeldung/s3/S3Application.java b/aws/src/main/java/com/baeldung/s3/S3Application.java index fcbd7811b5..fdfb909f73 100644 --- a/aws/src/main/java/com/baeldung/s3/S3Application.java +++ b/aws/src/main/java/com/baeldung/s3/S3Application.java @@ -1,9 +1,10 @@ package com.baeldung.s3; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; +import org.apache.commons.io.FileUtils; + import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; @@ -28,7 +29,7 @@ public class S3Application { "", "" ); - } + } public static void main(String[] args) throws IOException { //set-up the client @@ -74,15 +75,7 @@ public class S3Application { //downloading an object S3Object s3object = awsService.getObject(bucketName, "Document/hello.txt"); S3ObjectInputStream inputStream = s3object.getObjectContent(); - FileOutputStream fos = new FileOutputStream(new File("/Users/user/Desktop/hello.txt")); - - int read = 0; - byte[] bytes = new byte[1024]; - while ((read = inputStream.read(bytes)) != -1) { - fos.write(bytes, 0, read); - } - inputStream.close(); - fos.close(); + FileUtils.copyInputStreamToFile(inputStream, new File("/Users/user/Desktop/hello.txt")); //copying an object awsService.copyObject( diff --git a/camel-api/src/main/java/com/baeldung/camel/Application.java b/camel-api/src/main/java/com/baeldung/camel/Application.java index f805385ff9..aadd37a3b4 100644 --- a/camel-api/src/main/java/com/baeldung/camel/Application.java +++ b/camel-api/src/main/java/com/baeldung/camel/Application.java @@ -13,14 +13,13 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; @SpringBootApplication @ComponentScan(basePackages="com.baeldung.camel") -public class Application extends SpringBootServletInitializer { +public class Application{ @Value("${server.port}") String serverPort; @@ -62,10 +61,12 @@ public class Application extends SpringBootServletInitializer { .bindingMode(RestBindingMode.json) .dataFormatProperty("prettyPrint", "true"); /** -The Rest DSL supports automatic binding json/xml contents to/from POJOs using Camels Data Format. -By default the binding mode is off, meaning there is no automatic binding happening for incoming and outgoing messages. -You may want to use binding if you develop POJOs that maps to your REST services request and response types. -This allows you, as a developer, to work with the POJOs in Java code. +The Rest DSL supports automatic binding json/xml contents to/from +POJOs using Camels Data Format. +By default the binding mode is off, meaning there is no automatic +binding happening for incoming and outgoing messages. +You may want to use binding if you develop POJOs that maps to +your REST services request and response types. */ rest("/api/").description("Teste REST Service") diff --git a/core-java/hashcode/pom.xml b/core-java/hashcode/pom.xml new file mode 100644 index 0000000000..393aa69153 --- /dev/null +++ b/core-java/hashcode/pom.xml @@ -0,0 +1,39 @@ + + + 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/main/java/com/baeldung/application/Application.java b/core-java/hashcode/src/main/java/com/baeldung/application/Application.java new file mode 100644 index 0000000000..08c670c82f --- /dev/null +++ b/core-java/hashcode/src/main/java/com/baeldung/application/Application.java @@ -0,0 +1,23 @@ +package com.baeldung.application; + +import com.baeldung.entities.User; +import java.util.HashMap; +import java.util.Map; + +public class Application { + + public static void main(String[] args) { + Map users = new HashMap<>(); + User user1 = new User(1L, "John", "john@domain.com"); + User user2 = new User(2L, "Jennifer", "jennifer@domain.com"); + User user3 = new User(3L, "Mary", "mary@domain.com"); + + users.put(user1, user1); + users.put(user2, user2); + users.put(user3, user3); + + if (users.containsKey(user1)) { + System.out.print("User found in the collection"); + } + } +} diff --git a/core-java/hashcode/src/main/java/com/baeldung/entities/User.java b/core-java/hashcode/src/main/java/com/baeldung/entities/User.java new file mode 100644 index 0000000000..a976233562 --- /dev/null +++ b/core-java/hashcode/src/main/java/com/baeldung/entities/User.java @@ -0,0 +1,38 @@ +package com.baeldung.entities; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class User { + + private final Logger logger = LoggerFactory.getLogger(User.class); + private long id; + private String name; + private String email; + + public User(long id, String name, String email) { + this.id = id; + this.name = name; + this.email = email; + } + + @Override + public boolean equals(Object o) { + 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; + hash = 31 * hash + (int) id; + hash = 31 * hash + (name == null ? 0 : name.hashCode()); + hash = 31 * hash + (email == null ? 0 : email.hashCode()); + logger.info("hashCode() method called - Computed hash: " + hash); + return hash; + } + // getters and setters here +} 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 new file mode 100644 index 0000000000..dcd853f451 --- /dev/null +++ b/core-java/hashcode/src/test/java/com/baeldung/application/ApplicationTest.java @@ -0,0 +1,30 @@ +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/hashcode/src/test/java/com/baeldung/entities/UserTest.java b/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java new file mode 100644 index 0000000000..01f6085d7e --- /dev/null +++ b/core-java/hashcode/src/test/java/com/baeldung/entities/UserTest.java @@ -0,0 +1,34 @@ +package com.baeldung.entities; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class UserTest { + + private User user; + private User comparisonUser; + + @Before + public void setUpUserInstances() { + this.user = new User(1L, "test", "test@domain.com"); + this.comparisonUser = this.user; + } + + @After + public void tearDownUserInstances() { + user = null; + comparisonUser = null; + } + + @Test + public void equals_EqualUserInstance_TrueAssertion(){ + Assert.assertTrue(user.equals(comparisonUser)); + } + + @Test + public void hashCode_UserHash_TrueAssertion() { + Assert.assertEquals(1792276941, user.hashCode()); + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java b/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java new file mode 100644 index 0000000000..b77019eea5 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java @@ -0,0 +1,34 @@ +package com.baeldung.concurrent.Scheduledexecutorservice; + +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +public class ScheduledExecutorServiceDemo { + + public void execute() { + ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + + ScheduledFuture scheduledFuture = executorService.schedule(() -> { + // Task + }, 1, TimeUnit.SECONDS); + + executorService.scheduleAtFixedRate(() -> { + // Task + }, 1, 10, TimeUnit.SECONDS); + + executorService.scheduleWithFixedDelay(() -> { + // Task + }, 1, 10, TimeUnit.SECONDS); + + Future future = executorService.schedule(() -> { + // Task + return "Hellow world"; + }, 1, TimeUnit.SECONDS); + + executorService.shutdown(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java new file mode 100644 index 0000000000..38633011bf --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.atomic; + +public class SafeCounterWithLock { + private volatile int counter; + + public int getValue() { + return counter; + } + + public synchronized void increment() { + counter++; + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java new file mode 100644 index 0000000000..41e10789a6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java @@ -0,0 +1,21 @@ +package com.baeldung.concurrent.atomic; + +import java.util.concurrent.atomic.AtomicInteger; + +public class SafeCounterWithoutLock { + private final AtomicInteger counter = new AtomicInteger(0); + + public int getValue() { + return counter.get(); + } + + public void increment() { + while(true) { + int existingValue = getValue(); + int newValue = existingValue + 1; + if(counter.compareAndSet(existingValue, newValue)) { + return; + } + } + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java b/core-java/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java new file mode 100644 index 0000000000..8a72788842 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.atomic; + +public class UnsafeCounter { + int counter; + + public int getValue() { + return counter; + } + + public void increment() { + counter++; + } +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java new file mode 100644 index 0000000000..85c0cf7680 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java @@ -0,0 +1,25 @@ +package com.baeldung.concurrent.cyclicbarrier; + +import java.util.concurrent.CyclicBarrier; + +public class CyclicBarrierExample { + + public void start() { + CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> { + // Task + System.out.println("All previous tasks are completed"); + }); + + Thread t1 = new Thread(new Task(cyclicBarrier), "T1"); + Thread t2 = new Thread(new Task(cyclicBarrier), "T2"); + Thread t3 = new Thread(new Task(cyclicBarrier), "T3"); + + if (!cyclicBarrier.isBroken()) { + t1.start(); + t2.start(); + t3.start(); + } + + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java new file mode 100644 index 0000000000..4f7801e8c5 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/Task.java @@ -0,0 +1,25 @@ +package com.baeldung.concurrent.cyclicbarrier; + +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +public class Task implements Runnable { + + private CyclicBarrier barrier; + + public Task(CyclicBarrier barrier) { + this.barrier = barrier; + } + + @Override + public void run() { + try { + System.out.println("Thread : "+ Thread.currentThread().getName() + " is waiting"); + barrier.await(); + System.out.println("Thread : "+ Thread.currentThread().getName() + " is released"); + } catch (InterruptedException | BrokenBarrierException e) { + e.printStackTrace(); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java b/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java new file mode 100644 index 0000000000..84998cb489 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/executor/ExecutorDemo.java @@ -0,0 +1,14 @@ +package com.baeldung.concurrent.executor; + +import java.util.concurrent.Executor; + +public class ExecutorDemo { + + public void execute() { + Executor executor = new Invoker(); + executor.execute(()->{ + // task to be performed + }); + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/executor/Invoker.java b/core-java/src/main/java/com/baeldung/concurrent/executor/Invoker.java new file mode 100644 index 0000000000..d9f11986d6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/executor/Invoker.java @@ -0,0 +1,12 @@ +package com.baeldung.concurrent.executor; + +import java.util.concurrent.Executor; + +public class Invoker implements Executor { + + @Override + public void execute(Runnable r) { + r.run(); + } + +} 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 new file mode 100644 index 0000000000..ae2b279d9a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/executorservice/ExecutorServiceDemo.java @@ -0,0 +1,27 @@ +package com.baeldung.concurrent.executorservice; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +public class ExecutorServiceDemo { + + ExecutorService executor = Executors.newFixedThreadPool(10); + + public void execute() { + + executor.submit(() -> { + new Task(); + }); + + 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/executorservice/Task.java b/core-java/src/main/java/com/baeldung/concurrent/executorservice/Task.java new file mode 100644 index 0000000000..9a21bca80c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/executorservice/Task.java @@ -0,0 +1,10 @@ +package com.baeldung.concurrent.executorservice; + +public class Task implements Runnable { + + @Override + public void run() { + // task details + } + +} 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 new file mode 100644 index 0000000000..7cb611be0f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/future/FutureDemo.java @@ -0,0 +1,44 @@ +package com.baeldung.concurrent.future; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class FutureDemo { + + public String invoke() { + + String str = null; + + ExecutorService executorService = Executors.newFixedThreadPool(10); + + Future future = executorService.submit(() -> { + // Task + Thread.sleep(10000l); + return "Hellow world"; + }); + + future.cancel(false); + + 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(); + } + } + + return str; + + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java b/core-java/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java new file mode 100644 index 0000000000..3a1d8555d3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/semaphore/SemaPhoreDemo.java @@ -0,0 +1,22 @@ +package com.baeldung.concurrent.semaphore; + +import java.util.concurrent.Semaphore; + +public class SemaPhoreDemo { + + static Semaphore semaphore = new Semaphore(10); + + public void execute() throws InterruptedException { + + System.out.println("Available permit : " + semaphore.availablePermits()); + System.out.println("Number of threads waiting to acquire: " + semaphore.getQueueLength()); + + if (semaphore.tryAcquire()) { + semaphore.acquire(); + // perform some critical operations + semaphore.release(); + } + + } + +} 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 new file mode 100644 index 0000000000..8744027e40 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/BaeldungThreadFactory.java @@ -0,0 +1,23 @@ +package com.baeldung.concurrent.threadfactory; + +import java.util.concurrent.ThreadFactory; + +public class BaeldungThreadFactory implements ThreadFactory { + + private int threadId; + private String 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; + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java new file mode 100644 index 0000000000..d2af97b761 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Demo.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.threadfactory; + +public class Demo { + + public void execute() { + BaeldungThreadFactory factory = new BaeldungThreadFactory("BaeldungThreadFactory"); + for (int i = 0; i < 10; i++) { + Thread t = factory.newThread(new Task()); + t.start(); + } + } + +} 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 new file mode 100644 index 0000000000..04ba62d457 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/threadfactory/Task.java @@ -0,0 +1,10 @@ +package com.baeldung.concurrent.threadfactory; + +public class Task implements Runnable { + + @Override + public void run() { + // task details + } + +} diff --git a/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java b/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java index d672b9a4f5..a10499b362 100644 --- a/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java +++ b/core-java/src/main/java/com/baeldung/deserialization/AppleProduct.java @@ -4,12 +4,12 @@ import java.io.Serializable; public class AppleProduct implements Serializable { - private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated) -// private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated) + private static final long serialVersionUID = 1234567L; // user-defined (i.e. not default or generated) + // private static final long serialVersionUID = 7654321L; // user-defined (i.e. not default or generated) public String headphonePort; public String thunderboltPort; - public String lighteningPort; + public String lightningPort; public String getHeadphonePort() { return headphonePort; @@ -23,4 +23,8 @@ public class AppleProduct implements Serializable { return serialVersionUID; } + public String getLightningPort() { + return lightningPort; + } + } \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java b/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java index 3ed2b8be1d..ad8e929898 100644 --- a/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java +++ b/core-java/src/main/java/com/baeldung/deserialization/DeserializationUtility.java @@ -9,11 +9,12 @@ public class DeserializationUtility { public static void main(String[] args) throws ClassNotFoundException, IOException { - String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA=="; + String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA=="; System.out.println("Deserializing AppleProduct..."); AppleProduct deserializedObj = (AppleProduct) deSerializeObjectFromString(serializedObj); System.out.println("Headphone port of AppleProduct:" + deserializedObj.getHeadphonePort()); System.out.println("Thunderbolt port of AppleProduct:" + deserializedObj.getThunderboltPort()); + System.out.println("LightningPort port of AppleProduct:" + deserializedObj.getLightningPort()); } public static Object deSerializeObjectFromString(String s) throws IOException, ClassNotFoundException { diff --git a/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java b/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java index 1dbcc40e6b..aa7f66659a 100644 --- a/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java +++ b/core-java/src/main/java/com/baeldung/deserialization/SerializationUtility.java @@ -13,6 +13,7 @@ public class SerializationUtility { AppleProduct macBook = new AppleProduct(); macBook.headphonePort = "headphonePort2020"; macBook.thunderboltPort = "thunderboltPort2020"; + macBook.lightningPort = "lightningPort2020"; String serializedObj = serializeObjectToString(macBook); System.out.println("Serialized AppleProduct object to string:"); 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 ab491bee66..bfb6681f7c 100644 --- a/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java +++ b/core-java/src/main/java/com/baeldung/temporaladjuster/CustomTemporalAdjuster.java @@ -10,14 +10,13 @@ public class CustomTemporalAdjuster implements TemporalAdjuster { @Override public Temporal adjustInto(Temporal temporal) { - DayOfWeek dayOfWeek = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK)); - int daysToAdd; - if (dayOfWeek == DayOfWeek.FRIDAY) - daysToAdd = 3; - else if (dayOfWeek == DayOfWeek.SATURDAY) - daysToAdd = 2; - else - daysToAdd = 1; - return temporal.plus(daysToAdd, ChronoUnit.DAYS); + 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); + } } } diff --git a/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java b/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java new file mode 100644 index 0000000000..e9b2e164ae --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java @@ -0,0 +1,38 @@ +package com.baeldung.concurrent.atomic; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import org.junit.Test; + +public class ThreadSafeCounterTest { + + @Test + public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + SafeCounterWithLock safeCounter = new SafeCounterWithLock(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(safeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, safeCounter.getValue()); + } + + @Test + public void givenMultiThread_whenSafeCounterWithoutLockIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(safeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, safeCounter.getValue()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java b/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java new file mode 100644 index 0000000000..cc7cc18bb5 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/atomic/ThreadUnsafeCounterManualTest.java @@ -0,0 +1,33 @@ +package com.baeldung.concurrent.atomic; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +import org.junit.Test; + +/** + * This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling + * the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will + * less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads + * called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this + * test from build by adding this in manual test + */ +public class ThreadUnsafeCounterManualTest { + + @Test + public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + UnsafeCounter unsafeCounter = new UnsafeCounter(); + + IntStream.range(0, 1000) + .forEach(count -> service.submit(unsafeCounter::increment)); + service.awaitTermination(100, TimeUnit.MILLISECONDS); + + assertEquals(1000, unsafeCounter.getValue()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java b/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java index 887e7e41da..d7c1ee17d4 100644 --- a/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java +++ b/core-java/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java @@ -12,7 +12,7 @@ import org.junit.Test; public class DeserializationUnitTest { - private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAEtaHAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADmxpZ2h0ZW5pbmdQb3J0cQB+AAFMAA90aHVuZGVyYm9sdFBvcnRxAH4AAXhwdAARaGVhZHBob25lUG9ydDIwMjBwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA=="; + private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAdMuxAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA"; private static long userDefinedSerialVersionUID = 1234567L; @@ -25,20 +25,22 @@ public class DeserializationUnitTest { public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException { assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID()); - + AppleProduct macBook = new AppleProduct(); macBook.headphonePort = "headphonePort2020"; macBook.thunderboltPort = "thunderboltPort2020"; - + macBook.lightningPort = "lightningPort2020"; + // serializes the "AppleProduct" object String serializedProduct = SerializationUtility.serializeObjectToString(macBook); // deserializes the "AppleProduct" object AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct); - + assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort)); assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort)); - + assertTrue(deserializedProduct.lightningPort.equalsIgnoreCase(macBook.lightningPort)); + } /** @@ -59,7 +61,6 @@ public class DeserializationUnitTest { public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException { assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID()); - // attempts to deserialize the "AppleProduct" object DeserializationUtility.deSerializeObjectFromString(serializedObj); } diff --git a/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java index a7acc9f743..ad8de82e1f 100644 --- a/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java +++ b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java @@ -1,34 +1,34 @@ package com.baeldung.temporaladjusters; -import java.time.DayOfWeek; -import java.time.LocalDate; -import java.time.Period; -import java.time.temporal.TemporalAdjuster; -import java.time.temporal.TemporalAdjusters; - +import com.baeldung.temporaladjuster.CustomTemporalAdjuster; import org.junit.Assert; import org.junit.Test; -import com.baeldung.temporaladjuster.CustomTemporalAdjuster; +import java.time.LocalDate; +import java.time.Period; +import java.time.temporal.TemporalAdjuster; + +import static org.junit.Assert.assertEquals; public class CustomTemporalAdjusterTest { + private static final TemporalAdjuster NEXT_WORKING_DAY = new CustomTemporalAdjuster(); + @Test public void whenAdjustAndImplementInterface_thenNextWorkingDay() { LocalDate localDate = LocalDate.of(2017, 07, 8); CustomTemporalAdjuster temporalAdjuster = new CustomTemporalAdjuster(); LocalDate nextWorkingDay = localDate.with(temporalAdjuster); - Assert.assertEquals("2017-07-10", nextWorkingDay.toString()); + assertEquals("2017-07-10", nextWorkingDay.toString()); } @Test public void whenAdjust_thenNextWorkingDay() { LocalDate localDate = LocalDate.of(2017, 07, 8); - TemporalAdjuster temporalAdjuster = NEXT_WORKING_DAY; - LocalDate date = localDate.with(temporalAdjuster); + LocalDate date = localDate.with(NEXT_WORKING_DAY); - Assert.assertEquals("2017-07-10", date.toString()); + assertEquals("2017-07-10", date.toString()); } @Test @@ -39,18 +39,6 @@ public class CustomTemporalAdjusterTest { String fourteenDaysAfterDate = "2017-07-22"; - Assert.assertEquals(fourteenDaysAfterDate, result.toString()); + assertEquals(fourteenDaysAfterDate, result.toString()); } - - static TemporalAdjuster NEXT_WORKING_DAY = TemporalAdjusters.ofDateAdjuster(date -> { - DayOfWeek dayOfWeek = date.getDayOfWeek(); - int daysToAdd; - if (dayOfWeek == DayOfWeek.FRIDAY) - daysToAdd = 3; - else if (dayOfWeek == DayOfWeek.SATURDAY) - daysToAdd = 2; - else - daysToAdd = 1; - return date.plusDays(daysToAdd); - }); } diff --git a/httpclient/pom.xml b/httpclient/pom.xml index 562b3e9bcd..b7567e0c4b 100644 --- a/httpclient/pom.xml +++ b/httpclient/pom.xml @@ -147,7 +147,7 @@ 2.5.1 4.4.5 - 4.5.2 + 4.5.3 1.6.1 diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java index f2086f2633..d39697c0a9 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpAsyncClientLiveTest.java @@ -101,12 +101,7 @@ public class HttpAsyncClientLiveTest { @Test public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception { - final TrustStrategy acceptingTrustStrategy = new TrustStrategy() { - @Override - public final boolean isTrusted(final X509Certificate[] certificate, final String authType) { - return true; - } - }; + final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslContext).build(); @@ -160,7 +155,7 @@ public class HttpAsyncClientLiveTest { private final HttpContext context; private final HttpGet request; - public GetThread(final CloseableHttpAsyncClient client, final HttpGet request) { + GetThread(final CloseableHttpAsyncClient client, final HttpGet request) { this.client = client; context = HttpClientContext.create(); this.request = request; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java index ebd67512e4..51c3817da5 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientHeadersLiveTest.java @@ -1,11 +1,7 @@ package org.baeldung.httpclient; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - +import com.google.common.collect.Lists; import org.apache.http.Header; -import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; @@ -20,7 +16,8 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.google.common.collect.Lists; +import java.io.IOException; +import java.util.List; public class HttpClientHeadersLiveTest { @@ -37,19 +34,7 @@ public class HttpClientHeadersLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests - headers - deprecated diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java index 954236a56f..9912e73c2b 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartLiveTest.java @@ -1,22 +1,7 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; @@ -30,6 +15,20 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + public class HttpClientMultipartLiveTest { // No longer available @@ -48,7 +47,7 @@ public class HttpClientMultipartLiveTest { @Before public final void before() { client = HttpClientBuilder.create() - .build(); + .build(); post = new HttpPost(SERVER); } @@ -67,15 +66,7 @@ public class HttpClientMultipartLiveTest { LOGGER.log(Level.SEVERE, e.getMessage(), e); throw e; } - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @@ -83,8 +74,8 @@ public class HttpClientMultipartLiveTest { @Test public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + TEXTFILENAME); + .getContextClassLoader() + .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); @@ -102,7 +93,7 @@ public class HttpClientMultipartLiveTest { response = client.execute(post); final int statusCode = response.getStatusLine() - .getStatusCode(); + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); @@ -113,10 +104,10 @@ public class HttpClientMultipartLiveTest { } @Test - public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws ClientProtocolException, IOException { + public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + TEXTFILENAME); + .getContextClassLoader() + .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final String message = "This is a multipart post"; final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); @@ -127,7 +118,7 @@ public class HttpClientMultipartLiveTest { post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() - .getStatusCode(); + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); @@ -138,13 +129,13 @@ public class HttpClientMultipartLiveTest { } @Test - public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException { + public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final URL url = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + ZIPFILENAME); + .getContextClassLoader() + .getResource("uploads/" + ZIPFILENAME); final URL url2 = Thread.currentThread() - .getContextClassLoader() - .getResource("uploads/" + IMAGEFILENAME); + .getContextClassLoader() + .getResource("uploads/" + IMAGEFILENAME); final InputStream inputStream = new FileInputStream(url.getPath()); final File file = new File(url2.getPath()); final String message = "This is a multipart post"; @@ -157,7 +148,7 @@ public class HttpClientMultipartLiveTest { post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() - .getStatusCode(); + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); @@ -169,7 +160,7 @@ public class HttpClientMultipartLiveTest { } @Test - public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException { + public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final String message = "This is a multipart post"; final byte[] bytes = "binary code".getBytes(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); @@ -180,7 +171,7 @@ public class HttpClientMultipartLiveTest { post.setEntity(entity); response = client.execute(post); final int statusCode = response.getStatusLine() - .getStatusCode(); + .getStatusCode(); final String responseString = getContent(); final String contentTypeInHeader = getContentTypeHeader(); assertThat(statusCode, equalTo(HttpStatus.SC_OK)); @@ -192,21 +183,21 @@ public class HttpClientMultipartLiveTest { // UTIL - final String getContent() throws IOException { + private String getContent() throws IOException { rd = new BufferedReader(new InputStreamReader(response.getEntity() - .getContent())); + .getContent())); String body = ""; - String content = ""; + StringBuilder content = new StringBuilder(); while ((body = rd.readLine()) != null) { - content += body + "\n"; + content.append(body).append("\n"); } - return content.trim(); + return content.toString().trim(); } - final String getContentTypeHeader() throws IOException { + private String getContentTypeHeader() throws IOException { return post.getEntity() - .getContentType() - .toString(); + .getContentType() + .toString(); } } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java index ada5667f0b..39ed8f09ef 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientPostingLiveTest.java @@ -1,20 +1,10 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.fluent.Form; import org.apache.http.client.fluent.Request; @@ -29,17 +19,26 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.junit.Test; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + /* * NOTE : Need module spring-rest to be running */ public class HttpClientPostingLiveTest { - private static final String SAMPLE_URL = "http://localhost:8080/spring-rest/users"; + private static final String SAMPLE_URL = "http://localhost:8082/spring-rest/users"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; private static final String DEFAULT_USER = "test"; private static final String DEFAULT_PASS = "test"; @Test - public void whenSendPostRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL); @@ -54,7 +53,7 @@ public class HttpClientPostingLiveTest { } @Test - public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException, AuthenticationException { + public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION); @@ -68,7 +67,7 @@ public class HttpClientPostingLiveTest { } @Test - public void whenPostJsonUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail"); @@ -84,14 +83,14 @@ public class HttpClientPostingLiveTest { } @Test - public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws ClientProtocolException, IOException { + public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException { final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse(); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } @Test - public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart"); @@ -109,7 +108,7 @@ public class HttpClientPostingLiveTest { } @Test - public void whenUploadFileUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload"); @@ -125,7 +124,7 @@ public class HttpClientPostingLiveTest { } @Test - public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException { final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload"); @@ -133,12 +132,7 @@ public class HttpClientPostingLiveTest { builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); final HttpEntity multipart = builder.build(); - final ProgressEntityWrapper.ProgressListener pListener = new ProgressEntityWrapper.ProgressListener() { - @Override - public void progress(final float percentage) { - assertFalse(Float.compare(percentage, 100) > 0); - } - }; + final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0); httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener)); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java index 3cb02dc767..a501367a6b 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientRedirectLiveTest.java @@ -1,13 +1,5 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; @@ -21,6 +13,12 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; +import java.util.Arrays; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + public class HttpClientRedirectLiveTest { private CloseableHttpClient instance; @@ -34,25 +32,13 @@ public class HttpClientRedirectLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @Test - public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectsAreDisabledViaNewApi_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException { instance = HttpClients.custom().disableRedirectHandling().build(); final HttpGet httpGet = new HttpGet("http://t.co/I5YYd9tddw"); @@ -62,7 +48,7 @@ public class HttpClientRedirectLiveTest { } @Test - public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException { instance = HttpClientBuilder.create().disableRedirectHandling().build(); response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); @@ -71,26 +57,22 @@ public class HttpClientRedirectLiveTest { // redirect with POST @Test - public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { + public final void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws IOException { instance = HttpClientBuilder.create().build(); response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); } @Test - public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException { final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() { /** Redirectable methods. */ - private final String[] REDIRECT_METHODS = new String[] { HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME }; + private final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME}; @Override protected boolean isRedirectable(final String method) { - for (final String m : REDIRECT_METHODS) { - if (m.equalsIgnoreCase(method)) { - return true; - } - } - return false; + return Arrays.stream(REDIRECT_METHODS) + .anyMatch(m -> m.equalsIgnoreCase(method)); } }).build(); @@ -99,7 +81,7 @@ public class HttpClientRedirectLiveTest { } @Test - public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectingPOSTVia4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException { final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build(); response = client.execute(new HttpPost("http://t.co/I5YYd9tddw")); @@ -107,7 +89,7 @@ public class HttpClientRedirectLiveTest { } @Test - public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { + public final void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException { instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java index 7e7dbe2146..74255e416c 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientTimeoutLiveTest.java @@ -1,13 +1,5 @@ package org.baeldung.httpclient; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -18,31 +10,24 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.junit.After; import org.junit.Test; +import java.io.IOException; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + public class HttpClientTimeoutLiveTest { private CloseableHttpResponse response; @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @Test - public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws ClientProtocolException, IOException { + public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws IOException { final int timeout = 2; final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); @@ -56,7 +41,7 @@ public class HttpClientTimeoutLiveTest { } @Test - public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws ClientProtocolException, IOException { + public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws IOException { final int timeout = 2; final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build(); @@ -70,7 +55,7 @@ public class HttpClientTimeoutLiveTest { } @Test - public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws ClientProtocolException, IOException { + public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws IOException { final int timeout = 5; final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); @@ -87,7 +72,7 @@ public class HttpClientTimeoutLiveTest { * This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP) */ @Test(expected = HttpHostConnectException.class) - public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws ClientProtocolException, IOException { + public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException { final int timeout = 3; final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java index 5dfecb85aa..4eadfe24d5 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpsClientSslLiveTest.java @@ -1,14 +1,5 @@ package org.baeldung.httpclient; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.security.GeneralSecurityException; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLHandshakeException; - import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ClientConnectionManager; @@ -28,6 +19,14 @@ import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.junit.Test; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import java.io.IOException; +import java.security.GeneralSecurityException; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + /** * This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build diff --git a/httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java b/httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java index f0b7e0e559..cd00d8711a 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/ProgressEntityWrapper.java @@ -10,7 +10,7 @@ import org.apache.http.entity.HttpEntityWrapper; public class ProgressEntityWrapper extends HttpEntityWrapper { private final ProgressListener listener; - public ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) { + ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) { super(entity); this.listener = listener; } @@ -20,7 +20,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper { super.writeTo(new CountingOutputStream(outstream, listener, getContentLength())); } - public static interface ProgressListener { + public interface ProgressListener { void progress(float percentage); } @@ -30,7 +30,7 @@ public class ProgressEntityWrapper extends HttpEntityWrapper { private long transferred; private long totalBytes; - public CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) { + CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) { super(out); this.listener = listener; transferred = 0; diff --git a/httpclient/src/test/java/org/baeldung/httpclient/ResponseUtil.java b/httpclient/src/test/java/org/baeldung/httpclient/ResponseUtil.java new file mode 100644 index 0000000000..fd38b95cbe --- /dev/null +++ b/httpclient/src/test/java/org/baeldung/httpclient/ResponseUtil.java @@ -0,0 +1,26 @@ +package org.baeldung.httpclient; + +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; + +import java.io.IOException; + +public final class ResponseUtil { + private ResponseUtil() { + } + + public static void closeResponse(CloseableHttpResponse response) throws IOException { + if (response == null) { + return; + } + + try { + final HttpEntity entity = response.getEntity(); + if (entity != null) { + entity.getContent().close(); + } + } finally { + response.close(); + } + } +} diff --git a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java index b5a76241d1..77d5a298c1 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/advancedconfig/HttpClientAdvancedConfigurationIntegrationTest.java @@ -24,7 +24,14 @@ import org.junit.Test; import java.io.IOException; -import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static org.junit.Assert.assertEquals; public class HttpClientAdvancedConfigurationIntegrationTest { @@ -40,9 +47,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest { //given String userAgent = "BaeldungAgent/1.0"; serviceMock.stubFor(get(urlEqualTo("/detail")) - .withHeader("User-Agent", equalTo(userAgent)) - .willReturn(aResponse() - .withStatus(200))); + .withHeader("User-Agent", equalTo(userAgent)) + .willReturn(aResponse() + .withStatus(200))); HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://localhost:8089/detail"); @@ -60,10 +67,10 @@ public class HttpClientAdvancedConfigurationIntegrationTest { //given String xmlBody = "1"; serviceMock.stubFor(post(urlEqualTo("/person")) - .withHeader("Content-Type", equalTo("application/xml")) - .withRequestBody(equalTo(xmlBody)) - .willReturn(aResponse() - .withStatus(200))); + .withHeader("Content-Type", equalTo("application/xml")) + .withRequestBody(equalTo(xmlBody)) + .willReturn(aResponse() + .withStatus(200))); HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:8089/person"); @@ -83,17 +90,17 @@ public class HttpClientAdvancedConfigurationIntegrationTest { public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException { //given proxyMock.stubFor(get(urlMatching(".*")) - .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); + .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); serviceMock.stubFor(get(urlEqualTo("/private")) - .willReturn(aResponse().withStatus(200))); + .willReturn(aResponse().withStatus(200))); HttpHost proxy = new HttpHost("localhost", 8090); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); HttpClient httpclient = HttpClients.custom() - .setRoutePlanner(routePlanner) - .build(); + .setRoutePlanner(routePlanner) + .build(); //when final HttpGet httpGet = new HttpGet("http://localhost:8089/private"); @@ -109,9 +116,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest { public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException { //given proxyMock.stubFor(get(urlMatching("/private")) - .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); + .willReturn(aResponse().proxiedFrom("http://localhost:8089/"))); serviceMock.stubFor(get(urlEqualTo("/private")) - .willReturn(aResponse().withStatus(200))); + .willReturn(aResponse().withStatus(200))); HttpHost proxy = new HttpHost("localhost", 8090); @@ -120,7 +127,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest { // Client credentials CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxy), - new UsernamePasswordCredentials("username_admin", "secret_password")); + new UsernamePasswordCredentials("username_admin", "secret_password")); // Create AuthCache instance @@ -135,9 +142,9 @@ public class HttpClientAdvancedConfigurationIntegrationTest { HttpClient httpclient = HttpClients.custom() - .setRoutePlanner(routePlanner) - .setDefaultCredentialsProvider(credentialsProvider) - .build(); + .setRoutePlanner(routePlanner) + .setDefaultCredentialsProvider(credentialsProvider) + .build(); //when diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java index 2a101ec816..fee9dc4343 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicLiveTest.java @@ -1,13 +1,5 @@ package org.baeldung.httpclient.base; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; @@ -16,10 +8,17 @@ import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertThat; + public class HttpClientBasicLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @@ -35,19 +34,7 @@ public class HttpClientBasicLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java index 7eb078b18b..fe275be082 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientBasicPostLiveTest.java @@ -1,22 +1,20 @@ package org.baeldung.httpclient.base; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + public class HttpClientBasicPostLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @@ -32,37 +30,25 @@ public class HttpClientBasicPostLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests - non-GET @Test - public final void whenExecutingPostRequest_thenNoExceptions() throws ClientProtocolException, IOException { + public final void whenExecutingPostRequest_thenNoExceptions() throws IOException { instance.execute(new HttpPost(SAMPLE_URL)); } @Test - public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException { + public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException { final HttpPost request = new HttpPost(SAMPLE_URL); request.setEntity(new StringEntity("in the body of the POST")); instance.execute(request); } @Test - public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException, AuthenticationException { + public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException { final HttpPost request = new HttpPost(SAMPLE_URL); request.setEntity(new StringEntity("in the body of the POST")); final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password"); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java index 878d220f67..78097227e7 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientLiveTest.java @@ -11,12 +11,12 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; -import java.io.InputStream; import static org.hamcrest.Matchers.emptyArray; import static org.hamcrest.Matchers.not; @@ -37,19 +37,7 @@ public class HttpClientLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests diff --git a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java index 40216a70a5..d945d075f2 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/base/HttpClientSandboxLiveTest.java @@ -1,9 +1,5 @@ package org.baeldung.httpclient.base; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; @@ -12,8 +8,11 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; +import org.baeldung.httpclient.ResponseUtil; import org.junit.Test; +import java.io.IOException; + /* * NOTE : Need module spring-security-rest-basic-auth to be running */ @@ -32,15 +31,6 @@ public class HttpClientSandboxLiveTest { System.out.println(response.getStatusLine()); - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - // EntityUtils.consume(entity); - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java index e04cd32d65..0f8ebefe6c 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/HttpClientConnectionManagementLiveTest.java @@ -1,11 +1,5 @@ package org.baeldung.httpclient.conn; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - import org.apache.http.HeaderElement; import org.apache.http.HeaderElementIterator; import org.apache.http.HttpClientConnection; @@ -36,6 +30,12 @@ import org.junit.Before; import org.junit.Ignore; import org.junit.Test; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertTrue; + public class HttpClientConnectionManagementLiveTest { private static final String SERVER1 = "http://www.petrikainulainen.net/"; private static final String SERVER7 = "http://www.baeldung.com/"; @@ -129,7 +129,7 @@ public class HttpClientConnectionManagementLiveTest { @Test // @Ignore // Example 3.2. TESTER VERSION - /*tester*/public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { + /*tester*/ public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException { poolingConnManager = new PoolingHttpClientConnectionManager(); final CloseableHttpClient client1 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final CloseableHttpClient client2 = HttpClients.custom().setConnectionManager(poolingConnManager).build(); @@ -173,7 +173,7 @@ public class HttpClientConnectionManagementLiveTest { @Test // @Ignore // 4.2 Tester Version - /*tester*/public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException { + /*tester*/ public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException, IOException { poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final TesterVersion_MultiHttpClientConnThread thread1 = new TesterVersion_MultiHttpClientConnThread(client, new HttpGet("http://www.google.com"), poolingConnManager); @@ -266,7 +266,7 @@ public class HttpClientConnectionManagementLiveTest { @Test // @Ignore // 6.2 TESTER VERSION - /*tester*/public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { + /*tester*/ public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException { poolingConnManager = new PoolingHttpClientConnectionManager(); poolingConnManager.setDefaultMaxPerRoute(5); poolingConnManager.setMaxTotal(5); @@ -333,7 +333,7 @@ public class HttpClientConnectionManagementLiveTest { @Test @Ignore("Very Long Running") // 8.2 TESTER VERSION - /*tester*/public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException { + /*tester*/ public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException, IOException { poolingConnManager = new PoolingHttpClientConnectionManager(); client = HttpClients.custom().setConnectionManager(poolingConnManager).build(); final IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(poolingConnManager); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java index 2a1c419e41..ffe4155a78 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/IdleConnectionMonitorThread.java @@ -9,7 +9,7 @@ public class IdleConnectionMonitorThread extends Thread { private final HttpClientConnectionManager connMgr; private volatile boolean shutdown; - public IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) { + IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) { super(); this.connMgr = connMgr; } @@ -31,7 +31,7 @@ public class IdleConnectionMonitorThread extends Thread { } } - public final void shutdown() { + private void shutdown() { shutdown = true; synchronized (this) { notifyAll(); diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java index 071b964710..3794943f02 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/MultiHttpClientConnThread.java @@ -18,23 +18,23 @@ public class MultiHttpClientConnThread extends Thread { private final HttpGet get; private PoolingHttpClientConnectionManager connManager; - public int leasedConn; + private int leasedConn; - public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { + MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { this.client = client; this.get = get; this.connManager = connManager; leasedConn = 0; } - public MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { + MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get) { this.client = client; this.get = get; } // API - public final int getLeasedConn() { + final int getLeasedConn() { return leasedConn; } @@ -61,8 +61,6 @@ public class MultiHttpClientConnThread extends Thread { } EntityUtils.consume(response.getEntity()); - } catch (final ClientProtocolException ex) { - logger.error("", ex); } catch (final IOException ex) { logger.error("", ex); } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java index 62cd466596..9cc6480e74 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/conn/TesterVersion_MultiHttpClientConnThread.java @@ -18,7 +18,7 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread { private final HttpGet get; private PoolingHttpClientConnectionManager connManager; - public TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { + TesterVersion_MultiHttpClientConnThread(final CloseableHttpClient client, final HttpGet get, final PoolingHttpClientConnectionManager connManager) { this.client = client; this.get = get; this.connManager = Preconditions.checkNotNull(connManager); @@ -38,8 +38,6 @@ public class TesterVersion_MultiHttpClientConnThread extends Thread { logger.info("After - Leased Connections = " + connManager.getTotalStats().getLeased()); logger.info("After - Available Connections = " + connManager.getTotalStats().getAvailable()); - } catch (final ClientProtocolException ex) { - logger.error("", ex); } catch (final IOException ex) { logger.error("", ex); } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java index a185e99639..8fc79baed9 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/rare/HttpClientUnshortenLiveTest.java @@ -1,12 +1,7 @@ package org.baeldung.httpclient.rare; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.http.Header; @@ -20,8 +15,12 @@ import org.apache.http.util.EntityUtils; import org.junit.Before; import org.junit.Test; -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; public class HttpClientUnshortenLiveTest { @@ -52,7 +51,7 @@ public class HttpClientUnshortenLiveTest { // API - final String expand(final String urlArg) throws IOException { + private String expand(final String urlArg) throws IOException { String originalUrl = urlArg; String newUrl = expandSingleLevel(originalUrl); while (!originalUrl.equals(newUrl)) { @@ -81,7 +80,7 @@ public class HttpClientUnshortenLiveTest { return newUrl; } - final Pair expandSingleLevelSafe(final String url) throws IOException { + private Pair expandSingleLevelSafe(final String url) throws IOException { HttpHead request = null; HttpEntity httpEntity = null; InputStream entityContentStream = null; @@ -95,15 +94,15 @@ public class HttpClientUnshortenLiveTest { final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != 301 && statusCode != 302) { - return new ImmutablePair(statusCode, url); + return new ImmutablePair<>(statusCode, url); } final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); Preconditions.checkState(headers.length == 1); final String newUrl = headers[0].getValue(); - return new ImmutablePair(statusCode, newUrl); + return new ImmutablePair<>(statusCode, newUrl); } catch (final IllegalArgumentException uriEx) { - return new ImmutablePair(500, url); + return new ImmutablePair<>(500, url); } finally { if (request != null) { request.releaseConnection(); @@ -117,7 +116,7 @@ public class HttpClientUnshortenLiveTest { } } - final String expandSingleLevel(final String url) throws IOException { + private String expandSingleLevel(final String url) throws IOException { HttpHead request = null; try { @@ -130,9 +129,8 @@ public class HttpClientUnshortenLiveTest { } final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); Preconditions.checkState(headers.length == 1); - final String newUrl = headers[0].getValue(); - return newUrl; + return headers[0].getValue(); } catch (final IllegalArgumentException uriEx) { return url; } finally { diff --git a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java index e98dd4d14f..7a75729ea5 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientAuthLiveTest.java @@ -1,21 +1,12 @@ package org.baeldung.httpclient.sec; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; - import org.apache.commons.codec.binary.Base64; -import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -26,10 +17,17 @@ import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpContext; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; +import java.nio.charset.Charset; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + /* * NOTE : Need module spring-security-rest-basic-auth to be running */ @@ -51,25 +49,13 @@ public class HttpClientAuthLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @Test - public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException { + public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException { client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build(); response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION)); @@ -79,7 +65,7 @@ public class HttpClientAuthLiveTest { } @Test - public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws ClientProtocolException, IOException { + public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException { client = HttpClientBuilder.create().build(); response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context()); @@ -88,7 +74,7 @@ public class HttpClientAuthLiveTest { } @Test - public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws ClientProtocolException, IOException { + public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws IOException { client = HttpClientBuilder.create().build(); final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); @@ -100,7 +86,7 @@ public class HttpClientAuthLiveTest { } @Test - public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws ClientProtocolException, IOException { + public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException { final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); final String auth = DEFAULT_USER + ":" + DEFAULT_PASS; final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); @@ -116,14 +102,14 @@ public class HttpClientAuthLiveTest { // UTILS - private final CredentialsProvider provider() { + private CredentialsProvider provider() { final CredentialsProvider provider = new BasicCredentialsProvider(); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); provider.setCredentials(AuthScope.ANY, credentials); return provider; } - private final HttpContext context() { + private HttpContext context() { final HttpHost targetHost = new HttpHost("localhost", 8080, "http"); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS)); @@ -141,12 +127,11 @@ public class HttpClientAuthLiveTest { return context; } - private final String authorizationHeader(final String username, final String password) { + private String authorizationHeader(final String username, final String password) { final String auth = username + ":" + password; final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); - final String authHeader = "Basic " + new String(encodedAuth); - return authHeader; + return "Basic " + new String(encodedAuth); } } diff --git a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java index 7da9ad04e4..ba27aca08d 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/sec/HttpClientCookieLiveTest.java @@ -1,13 +1,5 @@ package org.baeldung.httpclient.sec; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.http.HttpEntity; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -18,10 +10,16 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; +import org.baeldung.httpclient.ResponseUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + public class HttpClientCookieLiveTest { private CloseableHttpClient instance; @@ -35,25 +33,13 @@ public class HttpClientCookieLiveTest { @After public final void after() throws IllegalStateException, IOException { - if (response == null) { - return; - } - - try { - final HttpEntity entity = response.getEntity(); - if (entity != null) { - final InputStream instream = entity.getContent(); - instream.close(); - } - } finally { - response.close(); - } + ResponseUtil.closeResponse(response); } // tests @Test - public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtocolException, IOException { + public final void whenSettingCookiesOnARequest_thenCorrect() throws IOException { instance = HttpClientBuilder.create().build(); final HttpGet request = new HttpGet("http://www.github.com"); request.setHeader("Cookie", "JSESSIONID=1234"); @@ -64,7 +50,7 @@ public class HttpClientCookieLiveTest { } @Test - public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws ClientProtocolException, IOException { + public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); cookie.setDomain(".github.com"); @@ -80,7 +66,7 @@ public class HttpClientCookieLiveTest { } @Test - public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException { + public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); cookie.setDomain(".github.com"); @@ -96,7 +82,7 @@ public class HttpClientCookieLiveTest { } @Test - public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws ClientProtocolException, IOException { + public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); cookie.setDomain(".github.com"); diff --git a/jmh/pom.xml b/jmh/pom.xml index 8ecfaa9651..ef5c3f1bbf 100644 --- a/jmh/pom.xml +++ b/jmh/pom.xml @@ -1,52 +1,60 @@ - 4.0.0 - com.baeldung - jmh - jar - 1.0-SNAPSHOT - jmh - http://maven.apache.org + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + com.baeldung + jmh + jar + 1.0-SNAPSHOT + jmh + http://maven.apache.org - - UTF-8 - UTF-8 - 1.8 - + + UTF-8 + UTF-8 + 1.8 + 1.6 + 1.6 + - - - org.openjdk.jmh - jmh-core - 1.19 - - - org.openjdk.jmh - jmh-generator-annprocess - 1.19 - - - junit - junit - 3.8.1 - test - - + + + org.openjdk.jmh + jmh-core + 1.19 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.19 + + + junit + junit + 3.8.1 + test + - - - - org.apache.maven.plugins - maven-jar-plugin - - - - com.baeldung.Application - - - - - - + + com.google.guava + guava + 21.0 + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.baeldung.BenchmarkRunner + + + + + + \ No newline at end of file diff --git a/jmh/src/main/java/com/baeldung/Application.java b/jmh/src/main/java/com/baeldung/Application.java deleted file mode 100644 index 28e70740e0..0000000000 --- a/jmh/src/main/java/com/baeldung/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung; - -import java.io.IOException; - -import org.openjdk.jmh.Main; -import org.openjdk.jmh.runner.RunnerException; - -public class Application { - - public static void main(String[] args) throws RunnerException, IOException { - Main.main(args); - } - -} diff --git a/jmh/src/main/java/com/baeldung/BenchMark.java b/jmh/src/main/java/com/baeldung/BenchMark.java index f2b984d211..b0e1caf4dc 100644 --- a/jmh/src/main/java/com/baeldung/BenchMark.java +++ b/jmh/src/main/java/com/baeldung/BenchMark.java @@ -1,12 +1,48 @@ package com.baeldung; -import org.openjdk.jmh.annotations.Benchmark; +import com.google.common.hash.HashFunction; +import com.google.common.hash.Hasher; +import com.google.common.hash.Hashing; +import org.openjdk.jmh.annotations.*; + +import java.nio.charset.Charset; public class BenchMark { - @Benchmark - public void init() { - - } + @State(Scope.Benchmark) + public static class ExecutionPlan { + + @Param({ "100", "200", "300", "500", "1000" }) + public int iterations; + + public Hasher murmur3; + + public String password = "4v3rys3kur3p455w0rd"; + + @Setup(Level.Invocation) + public void setUp() { + murmur3 = Hashing.murmur3_128().newHasher(); + } + } + + @Fork(value = 1, warmups = 1) + @Benchmark + @BenchmarkMode(Mode.Throughput) + @Warmup(iterations = 5) + public void benchMurmur3_128(ExecutionPlan plan) { + + for (int i = plan.iterations; i > 0; i--) { + plan.murmur3.putString(plan.password, Charset.defaultCharset()); + } + + plan.murmur3.hash(); + } + + @Benchmark + @Fork(value = 1, warmups = 1) + @BenchmarkMode(Mode.Throughput) + public void init() { + // Do nothing + } } diff --git a/jmh/src/main/java/com/baeldung/BenchmarkRunner.java b/jmh/src/main/java/com/baeldung/BenchmarkRunner.java new file mode 100644 index 0000000000..ed6a5bb617 --- /dev/null +++ b/jmh/src/main/java/com/baeldung/BenchmarkRunner.java @@ -0,0 +1,9 @@ +package com.baeldung; + +public class BenchmarkRunner { + + public static void main(String[] args) throws Exception { + org.openjdk.jmh.Main.main(args); + } + +} diff --git a/jmh/src/test/java/com/baeldung/AppTest.java b/jmh/src/test/java/com/baeldung/AppTest.java deleted file mode 100644 index c9f61455bd..0000000000 --- a/jmh/src/test/java/com/baeldung/AppTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} diff --git a/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt new file mode 100644 index 0000000000..d3167ce033 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt @@ -0,0 +1,3 @@ +package com.baeldung.destructuringdeclarations + +data class Person(var id: Int, var name: String, var age: Int) \ No newline at end of file diff --git a/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt new file mode 100644 index 0000000000..e3da9b46a4 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt @@ -0,0 +1,3 @@ +package com.baeldung.destructuringdeclarations + +data class Result(val result: Int, val status: String) \ No newline at end of file diff --git a/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt new file mode 100644 index 0000000000..87775f9378 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt @@ -0,0 +1,55 @@ +package com.baeldung.destructuringdeclarations + +import com.baeldung.destructuringdeclarations.Person +import com.baeldung.destructuringdeclarations.Result + +fun main(args: Array) { + + //2.1. Objects + val person = Person(1, "Jon Snow", 20) + val(id, name, age) = person + + println(id) //1 + println(name) //Jon Snow + println(age) //20 + + //The equivalent of line 10 +/* val id = person.component1(); + val name = person.component2(); + val age = person.component3();*/ + + //2.2. Functions + fun getPersonInfo() = Person(2, "Ned Stark", 45) + val(idf, namef, agef) = getPersonInfo() + + fun twoValuesReturn(): Result { + + // needed code + + return Result(1, "success") + } + + // Now, to use this function: + val (result, status) = twoValuesReturn() + + //2.3. Collections and For-loops + var map: HashMap = HashMap() + map.put(1, person) + + for((key, value) in map){ + println("Key: $key, Value: $value") + } + + //2.4. Underscore and Destructuring in Lambdas + val (_, status2) = twoValuesReturn() + + map.mapValues { entry -> "${entry.value}!" } + map.mapValues { (key, value) -> "$value!" } + + //A pair of parameters vs. a destructuring pair +/* { a -> ... } // one parameter + { a, b -> ... } // two parameters + { (a, b) -> ... } // a destructured pair + { (a, b), c -> ... } // a destructured pair and another parameter*/ + +} \ No newline at end of file diff --git a/libraries/README.md b/libraries/README.md index c7e56db3b8..f0484ec710 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -24,7 +24,9 @@ - [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing) - [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) - [A Guide to Apache Commons DbUtils](http://www.baeldung.com/apache-commons-dbutils) - +- [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) +- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) +- [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph) 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 eebbdf3f0e..6ab312a535 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -7,7 +7,6 @@ 1.0.0-SNAPSHOT 4.0.0 - libraries libraries @@ -71,79 +70,51 @@ - + org.apache.maven.plugins - maven-war-plugin - 3.0.0 + maven-jar-plugin + 3.0.2 - false - WEB-INF/classes/VAADIN/widgetsets/WEB-INF/** + + **/log4j.properties + + + + com.baeldung.neuroph.NeurophXOR + + - com.vaadin - vaadin-maven-plugin - ${vaadin.plugin.version} + org.apache.maven.plugins + maven-surefire-plugin + 2.18.1 + test + test - update-theme - update-widgetset - compile - compile-theme + test + + + test/java/com/baeldung/neuroph/XORTest.java + + - - org.apache.maven.plugins - maven-clean-plugin - 3.0.0 - - - - src/main/webapp/VAADIN/themes - - **/styles.css - **/styles.scss.cache - - - - - - - org.eclipse.jetty - jetty-maven-plugin - ${jetty.version} - - 2 - true - - - + - - - - vaadin-addons - http://maven.vaadin.com/vaadin-addons - - - - - - com.vaadin - vaadin-bom - ${vaadin.version} - pom - import - - - - + + + org.beykery + neuroph + ${neuroph.version} + cglib @@ -227,11 +198,16 @@ commons-io ${commons.io.version} + + commons-chain + commons-chain + ${commons-chain.version} + commons-dbutils commons-dbutils ${commons.dbutils.version} - + org.apache.flink flink-core @@ -392,7 +368,6 @@ quartz 2.3.0 - one.util streamex @@ -458,68 +433,6 @@ ${org.hamcrest.java-hamcrest.version} test - - - com.vaadin - vaadin-server - - - com.vaadin - vaadin-client-compiled - - - com.vaadin - vaadin-themes - - - org.seleniumhq.selenium - selenium-java - test - 3.4.0 - - - org.seleniumhq.selenium - htmlunit-driver - 2.27 - - - org.eclipse.jetty.websocket - websocket-server - ${jetty.version} - - - org.eclipse.jetty.websocket - websocket-client - ${jetty.version} - - - org.eclipse.jetty.websocket - websocket-api - ${jetty.version} - - - org.eclipse.jetty.websocket - websocket-common - ${jetty.version} - - - org.eclipse.jetty - jetty-continuation - ${jetty.version} - - - org.eclipse.jetty - jetty-util - ${jetty.version} - - - org.seleniumhq.selenium - selenium-api - 3.4.0 - test - jar - - net.agkn hll @@ -535,6 +448,16 @@ byte-buddy-agent ${bytebuddy.version} + + net.bytebuddy + byte-buddy + ${bytebuddy.version} + + + net.bytebuddy + byte-buddy-agent + ${bytebuddy.version} + 0.7.0 @@ -542,6 +465,7 @@ 3.5 1.1 1.9.3 + 1.2 1.9.2 1.2 3.21.0-GA @@ -558,6 +482,7 @@ 2.5 1.2.0 2.8.5 + 2.92 1.4.0 1.24.0 1.1.3-rc.5 @@ -570,54 +495,7 @@ 3.5.0 3.0.0 2.0.0.0 - - 7.7.10 - 8.0.6 - mytheme - 1.6.0 1.7.1 - - - - vaadin-prerelease - - false - - - - vaadin-prereleases - http://maven.vaadin.com/vaadin-prereleases - - - vaadin-snapshots - https://oss.sonatype.org/content/repositories/vaadin-snapshots/ - - false - - - true - - - - - - vaadin-prereleases - http://maven.vaadin.com/vaadin-prereleases - - - vaadin-snapshots - https://oss.sonatype.org/content/repositories/vaadin-snapshots/ - - false - - - true - - - - - - diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java b/libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java new file mode 100644 index 0000000000..cbcf03c7d4 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AbstractDenominationDispenser.java @@ -0,0 +1,23 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.Command; +import org.apache.commons.chain.Context; + +import static com.baeldung.commons.chain.AtmConstants.AMOUNT_LEFT_TO_BE_WITHDRAWN; + +public abstract class AbstractDenominationDispenser implements Command { + + @Override + public boolean execute(Context context) throws Exception { + int amountLeftToBeWithdrawn = (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN); + if (amountLeftToBeWithdrawn >= getDenominationValue()) { + context.put(getDenominationString(), amountLeftToBeWithdrawn / getDenominationValue()); + context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, amountLeftToBeWithdrawn % getDenominationValue()); + } + return false; + } + + protected abstract String getDenominationString(); + + protected abstract int getDenominationValue(); +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java b/libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java new file mode 100644 index 0000000000..768517e19a --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AtmCatalog.java @@ -0,0 +1,13 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.impl.CatalogBase; + +import static com.baeldung.commons.chain.AtmConstants.ATM_WITHDRAWAL_CHAIN; + +public class AtmCatalog extends CatalogBase { + + public AtmCatalog() { + super(); + addCommand(ATM_WITHDRAWAL_CHAIN, new AtmWithdrawalChain()); + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java b/libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java new file mode 100644 index 0000000000..d9425fcfac --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AtmConstants.java @@ -0,0 +1,10 @@ +package com.baeldung.commons.chain; + +public class AtmConstants { + public static final String TOTAL_AMOUNT_TO_BE_WITHDRAWN = "totalAmountToBeWithdrawn"; + public static final String AMOUNT_LEFT_TO_BE_WITHDRAWN = "amountLeftToBeWithdrawn"; + public static final String NO_OF_HUNDREDS_DISPENSED = "noOfHundredsDispensed"; + public static final String NO_OF_FIFTIES_DISPENSED = "noOfFiftiesDispensed"; + public static final String NO_OF_TENS_DISPENSED = "noOfTensDispensed"; + public static final String ATM_WITHDRAWAL_CHAIN = "atmWithdrawalChain"; +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java b/libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java new file mode 100644 index 0000000000..ee089705ad --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AtmRequestContext.java @@ -0,0 +1,52 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.impl.ContextBase; + +public class AtmRequestContext extends ContextBase { + + int totalAmountToBeWithdrawn; + int noOfHundredsDispensed; + int noOfFiftiesDispensed; + int noOfTensDispensed; + int amountLeftToBeWithdrawn; + + public int getTotalAmountToBeWithdrawn() { + return totalAmountToBeWithdrawn; + } + + public void setTotalAmountToBeWithdrawn(int totalAmountToBeWithdrawn) { + this.totalAmountToBeWithdrawn = totalAmountToBeWithdrawn; + } + + public int getNoOfHundredsDispensed() { + return noOfHundredsDispensed; + } + + public void setNoOfHundredsDispensed(int noOfHundredsDispensed) { + this.noOfHundredsDispensed = noOfHundredsDispensed; + } + + public int getNoOfFiftiesDispensed() { + return noOfFiftiesDispensed; + } + + public void setNoOfFiftiesDispensed(int noOfFiftiesDispensed) { + this.noOfFiftiesDispensed = noOfFiftiesDispensed; + } + + public int getNoOfTensDispensed() { + return noOfTensDispensed; + } + + public void setNoOfTensDispensed(int noOfTensDispensed) { + this.noOfTensDispensed = noOfTensDispensed; + } + + public int getAmountLeftToBeWithdrawn() { + return amountLeftToBeWithdrawn; + } + + public void setAmountLeftToBeWithdrawn(int amountLeftToBeWithdrawn) { + this.amountLeftToBeWithdrawn = amountLeftToBeWithdrawn; + } +} diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java b/libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java new file mode 100644 index 0000000000..fdea5e5744 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AtmWithdrawalChain.java @@ -0,0 +1,14 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.impl.ChainBase; + +public class AtmWithdrawalChain extends ChainBase { + + public AtmWithdrawalChain() { + super(); + addCommand(new HundredDenominationDispenser()); + addCommand(new FiftyDenominationDispenser()); + addCommand(new TenDenominationDispenser()); + addCommand(new AuditFilter()); + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java b/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java new file mode 100644 index 0000000000..973e2d498e --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java @@ -0,0 +1,18 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.Context; +import org.apache.commons.chain.Filter; + +public class AuditFilter implements Filter { + + @Override + public boolean postprocess(Context context, Exception exception) { + // Send notification to customer & bank. + return false; + } + + @Override + public boolean execute(Context context) throws Exception { + return false; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java b/libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java new file mode 100644 index 0000000000..f0f5959764 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/FiftyDenominationDispenser.java @@ -0,0 +1,15 @@ +package com.baeldung.commons.chain; + +import static com.baeldung.commons.chain.AtmConstants.NO_OF_FIFTIES_DISPENSED; + +public class FiftyDenominationDispenser extends AbstractDenominationDispenser { + @Override + protected String getDenominationString() { + return NO_OF_FIFTIES_DISPENSED; + } + + @Override + protected int getDenominationValue() { + return 50; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java b/libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java new file mode 100644 index 0000000000..e65d0d34c9 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/HundredDenominationDispenser.java @@ -0,0 +1,15 @@ +package com.baeldung.commons.chain; + +import static com.baeldung.commons.chain.AtmConstants.NO_OF_HUNDREDS_DISPENSED; + +public class HundredDenominationDispenser extends AbstractDenominationDispenser { + @Override + protected String getDenominationString() { + return NO_OF_HUNDREDS_DISPENSED; + } + + @Override + protected int getDenominationValue() { + return 100; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java b/libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java new file mode 100644 index 0000000000..423440bc4d --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/chain/TenDenominationDispenser.java @@ -0,0 +1,15 @@ +package com.baeldung.commons.chain; + +import static com.baeldung.commons.chain.AtmConstants.NO_OF_TENS_DISPENSED; + +public class TenDenominationDispenser extends AbstractDenominationDispenser { + @Override + protected String getDenominationString() { + return NO_OF_TENS_DISPENSED; + } + + @Override + protected int getDenominationValue() { + return 10; + } +} \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java new file mode 100644 index 0000000000..fb6a01d4c1 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java @@ -0,0 +1,73 @@ +package com.baeldung.neuroph; + +import org.neuroph.core.Layer; +import org.neuroph.core.NeuralNetwork; +import org.neuroph.core.Neuron; +import org.neuroph.core.data.DataSet; +import org.neuroph.core.data.DataSetRow; +import org.neuroph.nnet.learning.BackPropagation; +import org.neuroph.util.ConnectionFactory; +import org.neuroph.util.NeuralNetworkType; + +public class NeurophXOR { + + public static NeuralNetwork assembleNeuralNetwork() { + + Layer inputLayer = new Layer(); + inputLayer.addNeuron(new Neuron()); + inputLayer.addNeuron(new Neuron()); + + Layer hiddenLayerOne = new Layer(); + hiddenLayerOne.addNeuron(new Neuron()); + hiddenLayerOne.addNeuron(new Neuron()); + hiddenLayerOne.addNeuron(new Neuron()); + hiddenLayerOne.addNeuron(new Neuron()); + + Layer hiddenLayerTwo = new Layer(); + hiddenLayerTwo.addNeuron(new Neuron()); + hiddenLayerTwo.addNeuron(new Neuron()); + hiddenLayerTwo.addNeuron(new Neuron()); + hiddenLayerTwo.addNeuron(new Neuron()); + + Layer outputLayer = new Layer(); + outputLayer.addNeuron(new Neuron()); + + NeuralNetwork ann = new NeuralNetwork(); + + ann.addLayer(0, inputLayer); + ann.addLayer(1, hiddenLayerOne); + ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(1)); + ann.addLayer(2, hiddenLayerTwo); + ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2)); + ann.addLayer(3, outputLayer); + ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3)); + ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount()-1), false); + + ann.setInputNeurons(inputLayer.getNeurons()); + ann.setOutputNeurons(outputLayer.getNeurons()); + + ann.setNetworkType(NeuralNetworkType.MULTI_LAYER_PERCEPTRON); + return ann; + } + + public static NeuralNetwork trainNeuralNetwork(NeuralNetwork ann) { + int inputSize = 2; + int outputSize = 1; + DataSet ds = new DataSet(inputSize, outputSize); + + DataSetRow rOne = new DataSetRow(new double[] {0, 1}, new double[] {1}); + ds.addRow(rOne); + DataSetRow rTwo = new DataSetRow(new double[] {1, 1}, new double[] {0}); + ds.addRow(rTwo); + DataSetRow rThree = new DataSetRow(new double[] {0, 0}, new double[] {0}); + ds.addRow(rThree); + DataSetRow rFour = new DataSetRow(new double[] {1, 0}, new double[] {1}); + ds.addRow(rFour); + + BackPropagation backPropagation = new BackPropagation(); + backPropagation.setMaxIterations(1000); + + ann.learn(ds, backPropagation); + return ann; + } +} diff --git a/libraries/src/main/webapp/VAADIN/themes/valo/addons.scss b/libraries/src/main/webapp/VAADIN/themes/valo/addons.scss deleted file mode 100644 index a5670b70c7..0000000000 --- a/libraries/src/main/webapp/VAADIN/themes/valo/addons.scss +++ /dev/null @@ -1,7 +0,0 @@ -/* This file is automatically managed and will be overwritten from time to time. */ -/* Do not manually edit this file. */ - -/* Import and include this mixin into your project theme to include the addon themes */ -@mixin addons { -} - diff --git a/libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java b/libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java new file mode 100644 index 0000000000..cd9a7baaf3 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/chain/AtmChainTest.java @@ -0,0 +1,37 @@ +package com.baeldung.commons.chain; + +import org.apache.commons.chain.Catalog; +import org.apache.commons.chain.Command; +import org.apache.commons.chain.Context; +import org.junit.Assert; +import org.junit.Test; + +import static com.baeldung.commons.chain.AtmConstants.*; + +public class AtmChainTest { + + public static final int EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN = 460; + public static final int EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN = 0; + public static final int EXPECTED_NO_OF_HUNDREDS_DISPENSED = 4; + public static final int EXPECTED_NO_OF_FIFTIES_DISPENSED = 1; + public static final int EXPECTED_NO_OF_TENS_DISPENSED = 1; + + @Test + public void givenInputsToContext_whenAppliedChain_thenExpectedContext() { + Context context = new AtmRequestContext(); + context.put(TOTAL_AMOUNT_TO_BE_WITHDRAWN, 460); + context.put(AMOUNT_LEFT_TO_BE_WITHDRAWN, 460); + Catalog catalog = new AtmCatalog(); + Command atmWithdrawalChain = catalog.getCommand(ATM_WITHDRAWAL_CHAIN); + try { + atmWithdrawalChain.execute(context); + } catch (Exception e) { + e.printStackTrace(); + } + Assert.assertEquals(EXPECTED_TOTAL_AMOUNT_TO_BE_WITHDRAWN, (int) context.get(TOTAL_AMOUNT_TO_BE_WITHDRAWN)); + Assert.assertEquals(EXPECTED_AMOUNT_LEFT_TO_BE_WITHDRAWN, (int) context.get(AMOUNT_LEFT_TO_BE_WITHDRAWN)); + Assert.assertEquals(EXPECTED_NO_OF_HUNDREDS_DISPENSED, (int) context.get(NO_OF_HUNDREDS_DISPENSED)); + Assert.assertEquals(EXPECTED_NO_OF_FIFTIES_DISPENSED, (int) context.get(NO_OF_FIFTIES_DISPENSED)); + Assert.assertEquals(EXPECTED_NO_OF_TENS_DISPENSED, (int) context.get(NO_OF_TENS_DISPENSED)); + } +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java index 470eb46cb0..4685d84781 100644 --- a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java +++ b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java @@ -4,14 +4,19 @@ import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.MapUtils; import org.apache.commons.collections4.PredicateUtils; import org.apache.commons.collections4.TransformerUtils; +import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import java.util.Collection; import java.util.HashMap; import java.util.Map; +import java.util.Set; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.collection.IsMapWithSize.aMapWithSize; @@ -63,19 +68,7 @@ public class MapUtilsTest { @Test public void whenVerbosePrintMap_thenMustPrintFormattedMap() { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - PrintStream outPrint = new PrintStream(out); - - outPrint.println("Optional Label = "); - outPrint.println("{"); - outPrint.println(" RED = #FF0000"); - outPrint.println(" BLUE = #0000FF"); - outPrint.println(" GREEN = #00FF00"); - outPrint.println("}"); - - out.reset(); - - MapUtils.verbosePrint(outPrint, "Optional Label", this.colorMap); + MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap); } @Test @@ -97,19 +90,12 @@ public class MapUtilsTest { @Test public void whenInvertMap_thenMustReturnInvertedMap() { Map invColorMap = MapUtils.invertMap(this.colorMap); - assertEquals(this.colorMap.size(), invColorMap.size()); - MapIterator itColorMap - = MapUtils.iterableMap(this.colorMap).mapIterator(); - - while (itColorMap.hasNext()) { - String colorMapKey = itColorMap.next(); - String colorMapValue = itColorMap.getValue(); - - String invColorMapValue = MapUtils.getString(invColorMap, colorMapValue); - - assertTrue(invColorMapValue.equals(colorMapKey)); - } + int size = invColorMap.size(); + Assertions.assertThat(invColorMap) + .hasSameSizeAs(colorMap) + .containsKeys(this.colorMap.values().toArray(new String[size])) + .containsValues(this.colorMap.keySet().toArray(new String[size])); } @Test(expected = IllegalArgumentException.class) diff --git a/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java b/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java index 2745e1e681..8d09c99f0f 100644 --- a/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java +++ b/libraries/src/test/java/com/baeldung/hll/HLLUnitTest.java @@ -4,6 +4,7 @@ package com.baeldung.hll; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import net.agkn.hll.HLL; +import org.assertj.core.data.Offset; import org.junit.Test; import java.util.stream.LongStream; @@ -15,8 +16,8 @@ public class HLLUnitTest { @Test public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() { //given - int numberOfElements = 100_000_000; - int toleratedDifference = 1_000_000; + long numberOfElements = 100_000_000; + long toleratedDifference = 1_000_000; HashFunction hashFunction = Hashing.murmur3_128(); HLL hll = new HLL(14, 5); @@ -29,14 +30,14 @@ public class HLLUnitTest { //then long cardinality = hll.cardinality(); - assertThat(isSimilarTo(cardinality, numberOfElements, toleratedDifference)).isTrue(); + assertThat(cardinality).isCloseTo(numberOfElements, Offset.offset(toleratedDifference)); } @Test public void givenTwoHLLs_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinalityForUnionOfHLLs() { //given - int numberOfElements = 100_000_000; - int toleratedDifference = 1_000_000; + long numberOfElements = 100_000_000; + long toleratedDifference = 1_000_000; HashFunction hashFunction = Hashing.murmur3_128(); HLL firstHll = new HLL(15, 5); HLL secondHLL = new HLL(15, 5); @@ -57,12 +58,6 @@ public class HLLUnitTest { //then firstHll.union(secondHLL); long cardinality = firstHll.cardinality(); - assertThat(isSimilarTo(cardinality, numberOfElements * 2, - toleratedDifference * 2)).isTrue(); - } - - private boolean isSimilarTo(long cardinality, int numberOfElements, int maxToleratedDifference) { - System.out.println(cardinality); - return Math.abs(cardinality - numberOfElements) <= maxToleratedDifference; + assertThat(cardinality).isCloseTo(numberOfElements * 2, Offset.offset(toleratedDifference * 2)); } } diff --git a/libraries/src/test/java/com/baeldung/neuroph/XORTest.java b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java new file mode 100644 index 0000000000..063c57195b --- /dev/null +++ b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java @@ -0,0 +1,50 @@ +package com.baeldung.neuroph; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.neuroph.core.NeuralNetwork; + +import static org.junit.Assert.*; + +public class XORTest { + private NeuralNetwork ann = null; + + @Before + public void annInit() { + ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork()); + } + + @Test + public void leftDisjunctTest() { + ann.setInput(0, 1); + ann.calculate(); + 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); + } + + @Test + public void bothFalseConjunctTest() { + ann.setInput(0, 0); + ann.calculate(); + 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); + } + + @After + public void annClose() { + ann = null; + } +} diff --git a/mockserver/pom.xml b/mockserver/pom.xml new file mode 100644 index 0000000000..8d3e97f129 --- /dev/null +++ b/mockserver/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + com.baeldung + mockserver + 1.0.0-SNAPSHOT + + 3.10.8 + 4.4.1 + + + + + org.mock-server + mockserver-netty + ${mock-sever-netty-version} + + + + org.mock-server + mockserver-client-java + ${mock-sever-netty-version} + + + + org.apache.httpcomponents + httpclient + ${apche-http-version} + + + org.apache.httpcomponents + httpcore + ${apche-http-version} + + + + + + + maven-surefire-plugin + 2.20 + + + **/**LiveTest.java + + + + + + + \ No newline at end of file diff --git a/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java b/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java new file mode 100644 index 0000000000..a74dca28da --- /dev/null +++ b/mockserver/src/main/java/com/baeldung/mock/server/ExpectationCallbackHandler.java @@ -0,0 +1,23 @@ +package com.baeldung.mock.server; + +import org.mockserver.mock.action.ExpectationCallback; +import org.mockserver.model.HttpRequest; +import org.mockserver.model.HttpResponse; + +import static org.mockserver.model.HttpResponse.notFoundResponse; +import static org.mockserver.model.HttpResponse.response; + + +public class ExpectationCallbackHandler implements ExpectationCallback { + + public HttpResponse handle(HttpRequest httpRequest) { + if (httpRequest.getPath().getValue().endsWith("/callback")) { + return httpResponse; + } else { + return notFoundResponse(); + } + } + + public static HttpResponse httpResponse = response() + .withStatusCode(200); +} diff --git a/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java b/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java new file mode 100644 index 0000000000..56d354be7f --- /dev/null +++ b/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java @@ -0,0 +1,176 @@ +package com.baeldung.mock.server; + +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.junit.*; +import org.mockserver.client.server.MockServerClient; +import org.mockserver.integration.ClientAndProxy; +import org.mockserver.integration.ClientAndServer; +import org.mockserver.model.Header; +import org.mockserver.model.HttpForward; +import org.mockserver.verify.VerificationTimes; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import static junit.framework.Assert.assertEquals; +import static org.mockserver.integration.ClientAndProxy.startClientAndProxy; +import static org.mockserver.integration.ClientAndServer.startClientAndServer; +import static org.mockserver.matchers.Times.exactly; +import static org.mockserver.model.HttpClassCallback.callback; +import static org.mockserver.model.HttpForward.forward; +import static org.mockserver.model.HttpRequest.request; +import static org.mockserver.model.HttpResponse.response; +import static org.mockserver.model.StringBody.exact; + +public class MockServerLiveTest { + + private static ClientAndProxy proxy; + private static ClientAndServer mockServer; + + @BeforeClass + public static void startProxy() { + mockServer = startClientAndServer(1080); + proxy = startClientAndProxy(1090); + } + + + @Test + public void whenPostRequestMockServer_thenServerReceived(){ + createExpectationForInvalidAuth(); + hitTheServerWithPostRequest(); + verifyPostRequest(); + } + + @Test + public void whenPostRequestForInvalidAuth_then401Received(){ + createExpectationForInvalidAuth(); + org.apache.http.HttpResponse response = hitTheServerWithPostRequest(); + assertEquals(401, response.getStatusLine().getStatusCode()); + } + + @Test + public void whenGetRequest_ThenForward(){ + createExpectationForForward(); + hitTheServerWithGetRequest("index.html"); + verifyGetRequest(); + + } + + @Test + public void whenCallbackRequest_ThenCallbackMethodCalled(){ + createExpectationForCallBack(); + org.apache.http.HttpResponse response= hitTheServerWithGetRequest("/callback"); + assertEquals(200,response.getStatusLine().getStatusCode()); + } + + private void verifyPostRequest() { + new MockServerClient("localhost", 1080).verify( + request() + .withMethod("POST") + .withPath("/validate") + .withBody(exact("{username: 'foo', password: 'bar'}")), + VerificationTimes.exactly(1) + ); + } + private void verifyGetRequest() { + new MockServerClient("localhost", 1080).verify( + request() + .withMethod("GET") + .withPath("/index.html"), + VerificationTimes.exactly(1) + ); + } + + private org.apache.http.HttpResponse hitTheServerWithPostRequest() { + String url = "http://127.0.0.1:1080/validate"; + HttpClient client = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(url); + post.setHeader("Content-type", "application/json"); + org.apache.http.HttpResponse response=null; + + try { + StringEntity stringEntity = new StringEntity("{username: 'foo', password: 'bar'}"); + post.getRequestLine(); + post.setEntity(stringEntity); + response=client.execute(post); + + } catch (Exception e) { + throw new RuntimeException(e); + } + return response; + } + + private org.apache.http.HttpResponse hitTheServerWithGetRequest(String page) { + String url = "http://127.0.0.1:1080/"+page; + HttpClient client = HttpClientBuilder.create().build(); + org.apache.http.HttpResponse response=null; + HttpGet get = new HttpGet(url); + try { + response=client.execute(get); + } catch (IOException e) { + throw new RuntimeException(e); + } + + return response; + } + + private void createExpectationForInvalidAuth() { + new MockServerClient("127.0.0.1", 1080) + .when( + request() + .withMethod("POST") + .withPath("/validate") + .withHeader("\"Content-type\", \"application/json\"") + .withBody(exact("{username: 'foo', password: 'bar'}")), + exactly(1) + ) + .respond( + response() + .withStatusCode(401) + .withHeaders( + new Header("Content-Type", "application/json; charset=utf-8"), + new Header("Cache-Control", "public, max-age=86400") + ) + .withBody("{ message: 'incorrect username and password combination' }") + .withDelay(TimeUnit.SECONDS,1) + ); + } + + private void createExpectationForForward(){ + new MockServerClient("127.0.0.1", 1080) + .when( + request() + .withMethod("GET") + .withPath("/index.html"), + exactly(1) + ) + .forward( + forward() + .withHost("www.mock-server.com") + .withPort(80) + .withScheme(HttpForward.Scheme.HTTP) + ); + } + + private void createExpectationForCallBack(){ + mockServer + .when( + request() + .withPath("/callback") + ) + .callback( + callback() + .withCallbackClass("com.baeldung.mock.server.ExpectationCallbackHandler") + ); + } + + @AfterClass + public static void stopProxy() { + proxy.stop(); + mockServer.stop(); + } +} diff --git a/pom.xml b/pom.xml index d01134fb30..b6813a8c18 100644 --- a/pom.xml +++ b/pom.xml @@ -210,6 +210,7 @@ spring-zuul spring-reactor spring-vertx + testing testng @@ -230,6 +231,7 @@ drools liquibase spring-boot-property-exp + mockserver diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 8d5eb56bf4..660b461ab6 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -14,15 +14,18 @@ import org.springframework.test.context.junit4.SpringRunner; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) @AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false" }) +@TestPropertySource(properties = {"security.basic.enabled=false"}) public class SpringBootWithServletComponentIntegrationTest { - @Autowired private ServletContext servletContext; + @Autowired + private ServletContext servletContext; @Test public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() { @@ -42,7 +45,8 @@ public class SpringBootWithServletComponentIntegrationTest { .contains("echo servlet")); } - @Autowired private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; @Test public void givenServletFilter_whenGetHello_thenRequestFiltered() { @@ -59,7 +63,6 @@ public class SpringBootWithServletComponentIntegrationTest { } - } diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java index 64507ad02c..31bb2ab195 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java @@ -14,17 +14,21 @@ import org.springframework.test.context.junit4.SpringRunner; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class) @AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false" }) +@TestPropertySource(properties = {"security.basic.enabled=false"}) public class SpringBootWithoutServletComponentIntegrationTest { - @Autowired private ServletContext servletContext; + @Autowired + private ServletContext servletContext; - @Autowired private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; @Test public void givenServletContext_whenAccessAttrs_thenNotFound() { diff --git a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java index dda9d69edd..e886042c8d 100644 --- a/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/autoconfiguration/AutoconfigurationIntegrationTest.java @@ -1,5 +1,8 @@ package com.baeldung.autoconfiguration; +import com.baeldung.autoconfiguration.example.AutoconfigurationApplication; +import com.baeldung.autoconfiguration.example.MyUser; +import com.baeldung.autoconfiguration.example.MyUserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -7,13 +10,9 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.baeldung.autoconfiguration.example.AutoconfigurationApplication; -import com.baeldung.autoconfiguration.example.MyUser; -import com.baeldung.autoconfiguration.example.MyUserRepository; - @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AutoconfigurationApplication.class) -@EnableJpaRepositories(basePackages = { "com.baeldung.autoconfiguration.example" }) +@EnableJpaRepositories(basePackages = {"com.baeldung.autoconfiguration.example"}) public class AutoconfigurationIntegrationTest { @Autowired diff --git a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java index 530b8e9cb3..413f6980ce 100644 --- a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java @@ -1,15 +1,5 @@ package com.baeldung.displayallbeans; -import static org.assertj.core.api.BDDAssertions.then; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -23,7 +13,15 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.displayallbeans.Application; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.assertj.core.api.BDDAssertions.then; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @@ -46,10 +44,10 @@ public class DisplayBeanIntegrationTest { public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception { ResponseEntity entity = this.testRestTemplate.getForEntity( "http://localhost:" + this.port + "/displayallbeans", String.class); - + then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } - + @Test public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception { @SuppressWarnings("rawtypes") @@ -68,14 +66,14 @@ public class DisplayBeanIntegrationTest { List> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans"); List beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList()); - assertThat( beanNamesList, hasItem("fooController")); - assertThat( beanNamesList, hasItem("fooService")); + assertThat(beanNamesList, hasItem("fooController")); + assertThat(beanNamesList, hasItem("fooService")); } - + @Test public void givenWebApplicationContext_whenAccessGetBeanDefinitionNames_thenReturnsBeanNames() throws Exception { String[] beanNames = context.getBeanDefinitionNames(); - + List beanNamesList = Arrays.asList(beanNames); assertTrue(beanNamesList.contains("fooController")); assertTrue(beanNamesList.contains("fooService")); diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java index af46fe0423..fa05dbab66 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -18,7 +18,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false" }) +@TestPropertySource(properties = {"security.basic.enabled=false"}) public class AppLiveTest { @Autowired @@ -27,15 +27,15 @@ public class AppLiveTest { @Test public void getIndex() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("Index Page"))); + .andExpect(status().isOk()) + .andExpect(content().string(equalTo("Index Page"))); } @Test public void getLocal() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("/local"))); + .andExpect(status().isOk()) + .andExpect(content().string(equalTo("/local"))); } } \ No newline at end of file diff --git a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java index e40678603b..ca6230e8f5 100644 --- a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java @@ -1,9 +1,5 @@ package com.baeldung.toggle; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,6 +12,10 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import static org.junit.Assert.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ToggleApplication.class) @AutoConfigureMockMvc diff --git a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java index 829c0a6ac4..edb40e9a1f 100644 --- a/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.utils; +import com.baeldung.utils.controller.UtilsController; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -10,32 +11,29 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import com.baeldung.utils.controller.UtilsController; - public class UtilsControllerIntegrationTest { - @InjectMocks + @InjectMocks private UtilsController utilsController; - + private MockMvc mockMvc; - + @Before public void setup() { MockitoAnnotations.initMocks(this); this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController) - .build(); + .build(); } - + @Test public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception { - String param = "testparam"; - this.mockMvc.perform( - post("/setParam") - .param("param", param) - .sessionAttr("parameter", param)) - .andExpect(status().isOk()); + String param = "testparam"; + this.mockMvc.perform( + post("/setParam") + .param("param", param) + .sessionAttr("parameter", param)) + .andExpect(status().isOk()); } - + } diff --git a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java index f30c8ee4e7..b52ab5b1d3 100644 --- a/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java @@ -6,11 +6,6 @@ import org.mockito.Mockito; import org.springframework.messaging.simp.stomp.StompHeaders; import org.springframework.messaging.simp.stomp.StompSession; -/** - * Test class for MyStompSessionHandler - * @author Kalyan - * - */ public class MyStompSessionHandlerIntegrationTest { @Test diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java index 2146fc09bc..6623a6396f 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeControllerIntegrationTest.java @@ -45,9 +45,9 @@ public class EmployeeControllerIntegrationTest { given(service.save(Mockito.anyObject())).willReturn(alex); mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON) - .content(JsonUtil.toJson(alex))) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.name", is("alex"))); + .content(JsonUtil.toJson(alex))) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name", is("alex"))); verify(service, VerificationModeFactory.times(1)).save(Mockito.anyObject()); reset(service); } @@ -63,11 +63,11 @@ public class EmployeeControllerIntegrationTest { given(service.getAllEmployees()).willReturn(allEmployees); mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$", hasSize(3))) - .andExpect(jsonPath("$[0].name", is(alex.getName()))) - .andExpect(jsonPath("$[1].name", is(john.getName()))) - .andExpect(jsonPath("$[2].name", is(bob.getName()))); + .andExpect(status().isOk()) + .andExpect(jsonPath("$", hasSize(3))) + .andExpect(jsonPath("$[0].name", is(alex.getName()))) + .andExpect(jsonPath("$[1].name", is(john.getName()))) + .andExpect(jsonPath("$[2].name", is(bob.getName()))); verify(service, VerificationModeFactory.times(1)).getAllEmployees(); reset(service); } diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java index ec599beedf..952ff19707 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRepositoryIntegrationTest.java @@ -1,9 +1,5 @@ package org.baeldung.boot.boottest; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.List; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -11,6 +7,10 @@ import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringRunner.class) @DataJpaTest public class EmployeeRepositoryIntegrationTest { @@ -65,7 +65,7 @@ public class EmployeeRepositoryIntegrationTest { List allEmployees = employeeRepository.findAll(); assertThat(allEmployees).hasSize(3) - .extracting(Employee::getName) - .containsOnly(alex.getName(), ron.getName(), bob.getName()); + .extracting(Employee::getName) + .containsOnly(alex.getName(), ron.getName(), bob.getName()); } } diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java index 4c3a50f933..c1d8c52eb9 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeRestControllerIntegrationTest.java @@ -1,19 +1,5 @@ package org.baeldung.boot.boottest; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.hasSize; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.io.IOException; -import java.util.List; - import org.baeldung.boot.DemoApplication; import org.junit.After; import org.junit.Test; @@ -27,6 +13,20 @@ import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.hasSize; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class) @AutoConfigureMockMvc @@ -49,11 +49,11 @@ public class EmployeeRestControllerIntegrationTest { public void whenValidInput_thenCreateEmployee() throws IOException, Exception { Employee bob = new Employee("bob"); mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON) - .content(JsonUtil.toJson(bob))); + .content(JsonUtil.toJson(bob))); List found = repository.findAll(); assertThat(found).extracting(Employee::getName) - .containsOnly("bob"); + .containsOnly("bob"); } @Test @@ -63,12 +63,12 @@ public class EmployeeRestControllerIntegrationTest { createTestEmployee("alex"); mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) - .andExpect(jsonPath("$[0].name", is("bob"))) - .andExpect(jsonPath("$[1].name", is("alex"))); + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) + .andExpect(jsonPath("$[0].name", is("bob"))) + .andExpect(jsonPath("$[1].name", is("alex"))); } private void createTestEmployee(String name) { diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java index 8038ae4373..5bd6b34c40 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/EmployeeServiceImplIntegrationTest.java @@ -1,10 +1,5 @@ package org.baeldung.boot.boottest; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.List; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,6 +11,11 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + @RunWith(SpringRunner.class) public class EmployeeServiceImplIntegrationTest { @@ -44,27 +44,27 @@ public class EmployeeServiceImplIntegrationTest { List allEmployees = Arrays.asList(john, bob, alex); Mockito.when(employeeRepository.findByName(john.getName())) - .thenReturn(john); + .thenReturn(john); Mockito.when(employeeRepository.findByName(alex.getName())) - .thenReturn(alex); + .thenReturn(alex); Mockito.when(employeeRepository.findByName("wrong_name")) - .thenReturn(null); + .thenReturn(null); Mockito.when(employeeRepository.findById(john.getId())) - .thenReturn(john); + .thenReturn(john); Mockito.when(employeeRepository.findAll()) - .thenReturn(allEmployees); + .thenReturn(allEmployees); Mockito.when(employeeRepository.findById(-99L)) - .thenReturn(null); + .thenReturn(null); } @Test public void whenValidName_thenEmployeeShouldBeFound() { String name = "alex"; Employee found = employeeService.getEmployeeByName(name); - - assertThat(found.getName()) + + assertThat(found.getName()) .isEqualTo(name); - } + } @Test public void whenInValidName_thenEmployeeShouldNotBeFound() { @@ -114,25 +114,25 @@ public class EmployeeServiceImplIntegrationTest { List allEmployees = employeeService.getAllEmployees(); verifyFindAllEmployeesIsCalledOnce(); assertThat(allEmployees).hasSize(3) - .extracting(Employee::getName) - .contains(alex.getName(), john.getName(), bob.getName()); + .extracting(Employee::getName) + .contains(alex.getName(), john.getName(), bob.getName()); } private void verifyFindByNameIsCalledOnce(String name) { Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findByName(name); + .findByName(name); Mockito.reset(employeeRepository); } private void verifyFindByIdIsCalledOnce() { Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findById(Mockito.anyLong()); + .findById(Mockito.anyLong()); Mockito.reset(employeeRepository); } private void verifyFindAllEmployeesIsCalledOnce() { Mockito.verify(employeeRepository, VerificationModeFactory.times(1)) - .findAll(); + .findAll(); Mockito.reset(employeeRepository); } } diff --git a/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java b/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java index 8c7e5576ce..36d07164b2 100644 --- a/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java +++ b/spring-boot/src/test/java/org/baeldung/boot/boottest/JsonUtil.java @@ -1,10 +1,10 @@ package org.baeldung.boot.boottest; -import java.io.IOException; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; + class JsonUtil { static byte[] toJson(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 84d49a3e35..7060ec5b36 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -115,7 +115,7 @@ 4.3.4.RELEASE - 1.9.6.RELEASE + 1.10.4.RELEASE 2.9.0 4.1.4 diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java index 79840fb570..acc377011d 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java @@ -3,6 +3,7 @@ package org.baeldung.event; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; +import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent; import org.springframework.util.ReflectionUtils; public class CascadeSaveMongoEventListener extends AbstractMongoEventListener { @@ -11,7 +12,8 @@ public class CascadeSaveMongoEventListener extends AbstractMongoEventListener event) { + final Object source = event.getSource(); ReflectionUtils.doWithFields(source.getClass(), new CascadeCallback(source, mongoOperations)); } } \ No newline at end of file diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java index 423df59b95..ade20bcc1d 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java @@ -4,14 +4,16 @@ import org.baeldung.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; +import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent; public class UserCascadeSaveMongoEventListener extends AbstractMongoEventListener { @Autowired private MongoOperations mongoOperations; @Override - public void onBeforeConvert(final Object source) { - if (source instanceof User && ((User) source).getEmailAddress() != null) { + public void onBeforeConvert(final BeforeConvertEvent event) { + final Object source = event.getSource(); + if ((source instanceof User) && (((User) source).getEmailAddress() != null)) { mongoOperations.save(((User) source).getEmailAddress()); } } diff --git a/spring-mustache/.gitignore b/spring-mustache/.gitignore new file mode 100644 index 0000000000..2af7cefb0a --- /dev/null +++ b/spring-mustache/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/spring-mustache/pom.xml b/spring-mustache/pom.xml new file mode 100644 index 0000000000..45fee6b10e --- /dev/null +++ b/spring-mustache/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + com.baeldung + spring-mustache + 0.0.1-SNAPSHOT + jar + + spring-mustache + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 1.5.4.RELEASE + + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-mustache + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.webjars + bootstrap + 3.3.7 + + + org.fluttercode.datafactory + datafactory + 0.8 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java b/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java new file mode 100644 index 0000000000..addd1fa088 --- /dev/null +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/SpringMustacheApplication.java @@ -0,0 +1,34 @@ +package com.baeldung.springmustache; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.mustache.MustacheEnvironmentCollector; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.core.env.Environment; + +import com.samskivert.mustache.Mustache; + +@SpringBootApplication +@ComponentScan(basePackages = {"com.baeldung"}) +public class SpringMustacheApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringMustacheApplication.class, args); + } + + @Bean + public Mustache.Compiler mustacheCompiler(Mustache.TemplateLoader templateLoader, Environment environment) { + + MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector(); + collector.setEnvironment(environment); + + Mustache.Compiler compiler = Mustache.compiler() + .defaultValue("Some Default Value") + .withLoader(templateLoader) + .withCollector(collector); + return compiler; + + } +} + diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java b/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java new file mode 100644 index 0000000000..b24625e7d5 --- /dev/null +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/controller/ArticleController.java @@ -0,0 +1,48 @@ +package com.baeldung.springmustache.controller; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.IntStream; + +import org.fluttercode.datafactory.impl.DataFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.baeldung.springmustache.model.Article; + +@Controller +public class ArticleController { + + @RequestMapping("/article") + public ModelAndView displayArticle(Map model) { + + List
articles = new LinkedList<>(); + IntStream.range(0, 10) + .forEach(count -> { + articles.add(generateArticle("Article Title " + count)); + }); + + Map modelMap = new HashMap<>(); + modelMap.put("articles", articles); + + return new ModelAndView("index", modelMap); + } + + private Article generateArticle(String title) { + Article article = new Article(); + DataFactory factory = new DataFactory(); + article.setTitle(title); + article.setBody( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur faucibus tempor diam. In molestie arcu eget ante facilisis sodales. Maecenas porta tellus sapien, eget rutrum nisi blandit in. Mauris tempor auctor ante, ut blandit velit venenatis id. Ut varius, augue aliquet feugiat congue, arcu ipsum finibus purus, dapibus semper velit sapien venenatis magna. Nunc quam ex, aliquet at rutrum sed, vestibulum quis libero. In laoreet libero cursus maximus vulputate. Nullam in fermentum sem. Duis aliquam ullamcorper dui, et dictum justo placerat id. Aliquam pretium orci quis sapien convallis, non blandit est tempus."); + article.setPublishDate(factory.getBirthDate().toString()); + article.setAuthor(factory.getName()); + return article; + } +} + + diff --git a/spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java b/spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java new file mode 100644 index 0000000000..78b08f877f --- /dev/null +++ b/spring-mustache/src/main/java/com/baeldung/springmustache/model/Article.java @@ -0,0 +1,41 @@ +package com.baeldung.springmustache.model; + +public class Article { + private String title; + private String body; + private String author; + private String publishDate; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getPublishDate() { + return publishDate; + } + + public void setPublishDate(String publishDate) { + this.publishDate = publishDate; + } + +} diff --git a/spring-mustache/src/main/resources/application.properties b/spring-mustache/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-mustache/src/main/resources/templates/error/error.html b/spring-mustache/src/main/resources/templates/error/error.html new file mode 100644 index 0000000000..fa29db41c4 --- /dev/null +++ b/spring-mustache/src/main/resources/templates/error/error.html @@ -0,0 +1,9 @@ + + + + + + Something went wrong: {{status}} {{error}} + + + \ No newline at end of file diff --git a/spring-mustache/src/main/resources/templates/index.html b/spring-mustache/src/main/resources/templates/index.html new file mode 100644 index 0000000000..bda60f9d8f --- /dev/null +++ b/spring-mustache/src/main/resources/templates/index.html @@ -0,0 +1,9 @@ +{{>layout/header}} + +
{{>layout/article}}
+ + + + +{{>layout/footer}} diff --git a/spring-mustache/src/main/resources/templates/layout/article.html b/spring-mustache/src/main/resources/templates/layout/article.html new file mode 100644 index 0000000000..9d573580d3 --- /dev/null +++ b/spring-mustache/src/main/resources/templates/layout/article.html @@ -0,0 +1,8 @@ +
+ {{#articles}} +

{{title}}

+

{{publishDate}}

+

{{author}}

+

{{body}}

+ {{/articles}} +
\ No newline at end of file diff --git a/spring-mustache/src/main/resources/templates/layout/footer.html b/spring-mustache/src/main/resources/templates/layout/footer.html new file mode 100644 index 0000000000..04f34cac54 --- /dev/null +++ b/spring-mustache/src/main/resources/templates/layout/footer.html @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/spring-mustache/src/main/resources/templates/layout/header.html b/spring-mustache/src/main/resources/templates/layout/header.html new file mode 100644 index 0000000000..d203ef800b --- /dev/null +++ b/spring-mustache/src/main/resources/templates/layout/header.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java new file mode 100644 index 0000000000..9138dfe92b --- /dev/null +++ b/spring-mustache/src/test/java/com/baeldung/springmustache/SpringMustacheApplicationTests.java @@ -0,0 +1,30 @@ +package com.baeldung.springmustache; + +import org.junit.Assert; +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.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class SpringMustacheApplicationTests { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + public void givenIndexPageWhenContainsArticleThenTrue() { + + ResponseEntity entity = this.restTemplate.getForEntity("/article", String.class); + + Assert.assertTrue(entity.getStatusCode().equals(HttpStatus.OK)); + Assert.assertTrue(entity.getBody().contains("Article Title 0")); + } + +} diff --git a/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java index 0912023fb7..f2ac9d0f82 100644 --- a/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java +++ b/spring-rest-docs/src/test/java/com/example/ApiDocumentationIntegrationTest.java @@ -28,9 +28,17 @@ import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.li import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; -import static org.springframework.restdocs.payload.PayloadDocumentation.*; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.patch; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; +import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; +import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; +import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.restdocs.snippet.Attributes.key; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.util.StringUtils.collectionToDelimitedString; diff --git a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java index 1af626d03b..c02c0c27f8 100644 --- a/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java +++ b/spring-rest-docs/src/test/java/com/example/GettingStartedDocumentationIntegrationTest.java @@ -1,8 +1,6 @@ package com.example; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.jayway.jsonpath.JsonPath; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -14,21 +12,19 @@ import org.springframework.restdocs.RestDocumentation; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import java.io.UnsupportedEncodingException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; -import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SpringRestDocsApplication.class) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index c12028149d..6065d7e529 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -1,321 +1,329 @@ - 4.0.0 - com.baeldung - spring-rest - 0.1-SNAPSHOT - spring-rest - war + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + spring-rest + 0.1-SNAPSHOT + spring-rest + war - - parent-boot-4 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-4 - + + parent-boot-4 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-4 + - + - + - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-devtools - - - org.springframework.boot - spring-boot-test - + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-devtools + + + org.springframework.boot + spring-boot-test + - + - - org.springframework - spring-web - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - - - org.springframework - spring-oxm - + + org.springframework + spring-web + + + commons-logging + commons-logging + + + + + org.springframework + spring-webmvc + + + org.springframework + spring-oxm + - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - - + + commons-fileupload + commons-fileupload + ${commons-fileupload.version} + + - - javax.servlet - javax.servlet-api - provided - + + javax.servlet + javax.servlet-api + provided + - - javax.servlet - jstl - runtime - + + javax.servlet + jstl + runtime + - + - - com.fasterxml.jackson.core - jackson-databind - + + com.fasterxml.jackson.core + jackson-databind + - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + - - com.thoughtworks.xstream - xstream - ${xstream.version} - + + com.thoughtworks.xstream + xstream + ${xstream.version} + - + - - com.google.guava - guava - ${guava.version} - + + com.google.guava + guava + ${guava.version} + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - + - - com.squareup.okhttp3 - okhttp - ${com.squareup.okhttp3.version} - + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + - + - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + - - org.mockito - mockito-core - test - + + org.mockito + mockito-core + test + - - org.springframework - spring-test - + + org.springframework + spring-test + - - - com.google.protobuf - protobuf-java - ${protobuf-java.version} - - - com.googlecode.protobuf-java-format - protobuf-java-format - ${protobuf-java-format.version} - + + + com.google.protobuf + protobuf-java + ${protobuf-java.version} + + + com.googlecode.protobuf-java-format + protobuf-java-format + ${protobuf-java-format.version} + - - com.esotericsoftware - kryo - ${kryo.version} - + + com.esotericsoftware + kryo + ${kryo.version} + - - com.jayway.jsonpath - json-path - + + com.jayway.jsonpath + json-path + - - - spring-rest - - - src/main/resources - true - - + + + commons-io + commons-io + 2.4 + - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - org.apache.maven.plugins - maven-war-plugin - + - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - tomcat8x - embedded - - - - - - - 8082 - - - - + + spring-rest + + + src/main/resources + true + + - + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + org.apache.maven.plugins + maven-war-plugin + - + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + tomcat8x + embedded + + + + + + + 8082 + + + + - + - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*IntegrationTest.java - - - - - + - - - + - - live - - - - org.codehaus.cargo - cargo-maven2-plugin - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*IntegrationTest.java + + + + + - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*LiveTest.java - - - cargo - - - - - + + + - - - + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + - + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + - - 1.3.2 - 4.0.0 - 1.4 - 3.1.0 - 3.5 - 1.4.9 + + + - - 20.0 + - - 1.6.0 - 3.0.4 + + 1.3.2 + 4.0.0 + 1.4 + 3.1.0 + 3.5 + 1.4.9 - - 3.4.1 + + 20.0 - 2.2.0 - + + 1.6.0 + 3.0.4 + + + 3.4.1 + + 2.2.0 + diff --git a/spring-rest/src/main/java/com/baeldung/web/log/app/Application.java b/spring-rest/src/main/java/com/baeldung/web/log/app/Application.java new file mode 100644 index 0000000000..9bdbbd0d9f --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/app/Application.java @@ -0,0 +1,18 @@ +package com.baeldung.web.log.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; + +@EnableAutoConfiguration +@ComponentScan("com.baeldung.web.log") +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + + public static void main(final String[] args) { + SpringApplication.run(Application.class, args); + } + +} \ No newline at end of file diff --git a/spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java b/spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java new file mode 100644 index 0000000000..831d236edd --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/app/TaxiFareRequestInterceptor.java @@ -0,0 +1,44 @@ +package com.baeldung.web.log.app; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; +import org.springframework.web.util.ContentCachingRequestWrapper; + +import com.baeldung.web.log.util.RequestLoggingUtil; + +@Component +public class TaxiFareRequestInterceptor extends HandlerInterceptorAdapter { + + Logger LOGGER = LoggerFactory.getLogger(TaxiFareRequestInterceptor.class); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String postData = null; + HttpServletRequest requestCacheWrapperObject = null; + try { + // Uncomment to produce the stream closed issue + // postData = RequestLoggingUtil.getStringFromInputStream(request.getInputStream()); + + // To overcome request stream closed issue + requestCacheWrapperObject = new ContentCachingRequestWrapper(request); + requestCacheWrapperObject.getParameterMap(); + } catch (Exception exception) { + exception.printStackTrace(); + } finally { + postData = RequestLoggingUtil.readPayload(requestCacheWrapperObject); + LOGGER.info("REQUEST DATA: " + postData); + } + return true; + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + LOGGER.info("RESPONSE: " + response.getStatus()); + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java b/spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java new file mode 100644 index 0000000000..bc9ad1cf84 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/config/RequestLoggingFilterConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.web.log.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.CommonsRequestLoggingFilter; + +@Configuration +public class RequestLoggingFilterConfig { + + @Bean + public CommonsRequestLoggingFilter logFilter() { + CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter(); + filter.setIncludeQueryString(true); + filter.setIncludePayload(true); + filter.setMaxPayloadLength(10000); + filter.setIncludeHeaders(false); + filter.setAfterMessagePrefix("REQUEST DATA : "); + return filter; + } +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java b/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java new file mode 100644 index 0000000000..fa26706ff0 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/config/TaxiFareMVCConfig.java @@ -0,0 +1,20 @@ +package com.baeldung.web.log.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import com.baeldung.web.log.app.TaxiFareRequestInterceptor; + +@Configuration +public class TaxiFareMVCConfig extends WebMvcConfigurerAdapter { + + @Autowired + private TaxiFareRequestInterceptor taxiFareRequestInterceptor; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(taxiFareRequestInterceptor).addPathPatterns("/**/taxifare/**/"); + } +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java b/spring-rest/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java new file mode 100644 index 0000000000..28bf07e8a6 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java @@ -0,0 +1,43 @@ +package com.baeldung.web.log.controller; + +import javax.validation.Valid; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.web.log.data.RateCard; +import com.baeldung.web.log.data.TaxiRide; +import com.baeldung.web.log.service.TaxiFareCalculatorService; + +@Controller +public class TaxiFareController { + + @Autowired + private TaxiFareCalculatorService taxiFareCalculatorService; + + private static final Logger LOGGER = LoggerFactory.getLogger(TaxiFareController.class); + + @RequestMapping(method = RequestMethod.GET, value = "/taxifare/get/") + @ResponseBody + public RateCard getTaxiFare() { + LOGGER.debug("getTaxiFare() - START"); + return new RateCard(); + } + + @RequestMapping(method = RequestMethod.POST, value = "/taxifare/calculate/") + @ResponseBody + public String calculateTaxiFare(@RequestBody @Valid TaxiRide taxiRide) { + LOGGER.debug("calculateTaxiFare() - START"); + String totalFare = taxiFareCalculatorService.calculateFare(taxiRide); + LOGGER.debug("calculateTaxiFare() - Total Fare : {}",totalFare); + LOGGER.debug("calculateTaxiFare() - END"); + return totalFare; + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java b/spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java new file mode 100644 index 0000000000..35ae38fd11 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/data/RateCard.java @@ -0,0 +1,28 @@ +package com.baeldung.web.log.data; + +public class RateCard { + + private String nightSurcharge; + private String ratePerMile; + + public RateCard(){ + nightSurcharge="Extra $ 100"; + ratePerMile="$ 10 Per Mile"; + } + + + public String getNightSurcharge() { + return nightSurcharge; + } + public void setNightSurcharge(String nightSurcharge) { + this.nightSurcharge = nightSurcharge; + } + public String getRatePerMile() { + return ratePerMile; + } + public void setRatePerMile(String ratePerMile) { + this.ratePerMile = ratePerMile; + } + + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java b/spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java new file mode 100644 index 0000000000..0877cdced4 --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/data/TaxiRide.java @@ -0,0 +1,32 @@ +package com.baeldung.web.log.data; + +public class TaxiRide { + + private Boolean isNightSurcharge; + private Long distanceInMile; + + public TaxiRide(){} + + public TaxiRide(Boolean isNightSurcharge, Long distanceInMile){ + this.isNightSurcharge = isNightSurcharge; + this.distanceInMile = distanceInMile; + } + + + public Boolean getIsNightSurcharge() { + return isNightSurcharge; + } + + public void setIsNightSurcharge(Boolean isNightSurcharge) { + this.isNightSurcharge = isNightSurcharge; + } + + public Long getDistanceInMile() { + return distanceInMile; + } + + public void setDistanceInMile(Long distanceInMile) { + this.distanceInMile = distanceInMile; + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java b/spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java new file mode 100644 index 0000000000..ec9c81187a --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/service/TaxiFareCalculatorService.java @@ -0,0 +1,20 @@ +package com.baeldung.web.log.service; + +import org.springframework.stereotype.Service; + +import com.baeldung.web.log.data.TaxiRide; + +@Service +public class TaxiFareCalculatorService { + + public String calculateFare(TaxiRide taxiRide) { + Long fare = 0l; + if (taxiRide.getIsNightSurcharge()) { + fare = taxiRide.getDistanceInMile() * 10 + 100; + } else { + fare = taxiRide.getDistanceInMile() * 10; + } + return String.valueOf(fare); + } + +} diff --git a/spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java b/spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java new file mode 100644 index 0000000000..c13d35b55c --- /dev/null +++ b/spring-rest/src/main/java/com/baeldung/web/log/util/RequestLoggingUtil.java @@ -0,0 +1,38 @@ +package com.baeldung.web.log.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.io.IOUtils; +import org.springframework.web.util.ContentCachingRequestWrapper; +import org.springframework.web.util.WebUtils; + +public class RequestLoggingUtil { + + public static String getStringFromInputStream(InputStream is) { + StringWriter writer = new StringWriter(); + String encoding = "UTF-8"; + try { + IOUtils.copy(is, writer, encoding); + } catch (IOException e) { + e.printStackTrace(); + } + return writer.toString(); + } + + public static String readPayload(final HttpServletRequest request) throws IOException { + String payloadData = null; + ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class); + if (null != contentCachingRequestWrapper) { + byte[] buf = contentCachingRequestWrapper.getContentAsByteArray(); + if (buf.length > 0) { + payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding()); + } + } + return payloadData; + } + +} diff --git a/spring-rest/src/main/resources/logback.xml b/spring-rest/src/main/resources/logback.xml index ec0dc2469a..3496a4a03c 100644 --- a/spring-rest/src/main/resources/logback.xml +++ b/spring-rest/src/main/resources/logback.xml @@ -6,6 +6,10 @@ + + + + diff --git a/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java b/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java new file mode 100644 index 0000000000..398e3c04e9 --- /dev/null +++ b/spring-rest/src/test/java/com/baeldung/web/log/test/TestTaxiFareController.java @@ -0,0 +1,33 @@ +package com.baeldung.web.log.test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.Test; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import com.baeldung.web.log.data.TaxiRide; + +public class TestTaxiFareController { + + private static final String URL = "http://localhost:" + 8082 + "/spring-rest/taxifare/"; + + @Test + public void givenRequest_whenFetchTaxiFareRateCard_thanOK() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + ResponseEntity response = testRestTemplate.getForEntity(URL + "get/", String.class); + + assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); + } + + @Test + public void givenTaxiRide_whenCalculatedFare_thanStatus200() { + TestRestTemplate testRestTemplate = new TestRestTemplate(); + TaxiRide taxiRide = new TaxiRide(true, 10l); + String fare = testRestTemplate.postForObject(URL + "calculate/", taxiRide, String.class); + + assertThat(fare, equalTo("200")); + } +} diff --git a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java index 2d3ad7b13f..e7456f1667 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/common/web/AbstractDiscoverabilityLiveTest.java @@ -37,7 +37,7 @@ public abstract class AbstractDiscoverabilityLiveTest ex // Then final String allowHeader = res.getHeader(HttpHeaders.ALLOW); - assertThat(allowHeader, AnyOf. anyOf(containsString("GET"), containsString("PUT"), containsString("DELETE"))); + assertThat(allowHeader, AnyOf.anyOf(containsString("GET"), containsString("PUT"), containsString("DELETE"))); } @Test diff --git a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java index be9b7cf27e..6e70f979c8 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/security/csrf/CsrfAbstractIntegrationTest.java @@ -31,7 +31,7 @@ public abstract class CsrfAbstractIntegrationTest { @Autowired private Filter springSecurityFilterChain; - protected MockMvc mvc; + MockMvc mvc; // @@ -40,15 +40,15 @@ public abstract class CsrfAbstractIntegrationTest { mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); } - protected RequestPostProcessor testUser() { + RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } - protected RequestPostProcessor testAdmin() { + RequestPostProcessor testAdmin() { return user("admin").password("adminPass").roles("USER", "ADMIN"); } - protected String createFoo() throws JsonProcessingException { + String createFoo() throws JsonProcessingException { return new ObjectMapper().writeValueAsString(new Foo(randomAlphabetic(6))); } } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java b/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java index 392e101193..a899d387ab 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java @@ -33,10 +33,6 @@ public final class JacksonMarshaller implements IMarshaller { String entityAsJSON = null; try { entityAsJSON = objectMapper.writeValueAsString(resource); - } catch (final JsonParseException parseEx) { - logger.error("", parseEx); - } catch (final JsonMappingException mappingEx) { - logger.error("", mappingEx); } catch (final IOException ioEx) { logger.error("", ioEx); } @@ -51,10 +47,6 @@ public final class JacksonMarshaller implements IMarshaller { T entity = null; try { entity = objectMapper.readValue(resourceAsString, clazz); - } catch (final JsonParseException parseEx) { - logger.error("", parseEx); - } catch (final JsonMappingException mappingEx) { - logger.error("", mappingEx); } catch (final IOException ioEx) { logger.error("", ioEx); } @@ -76,10 +68,6 @@ public final class JacksonMarshaller implements IMarshaller { } else { entities = objectMapper.readValue(resourcesAsString, List.class); } - } catch (final JsonParseException parseEx) { - logger.error("", parseEx); - } catch (final JsonMappingException mappingEx) { - logger.error("", mappingEx); } catch (final IOException ioEx) { logger.error("", ioEx); } diff --git a/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java b/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java index 84fb63a321..85ab623e5f 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/util/IDUtil.java @@ -10,21 +10,21 @@ public final class IDUtil { // API - public final static String randomPositiveLongAsString() { + public static String randomPositiveLongAsString() { return Long.toString(randomPositiveLong()); } - public final static String randomNegativeLongAsString() { + public static String randomNegativeLongAsString() { return Long.toString(randomNegativeLong()); } - public final static long randomPositiveLong() { + public static long randomPositiveLong() { long id = new Random().nextLong() * 10000; id = (id < 0) ? (-1 * id) : id; return id; } - public final static long randomNegativeLong() { + private static long randomNegativeLong() { long id = new Random().nextLong() * 10000; id = (id > 0) ? (-1 * id) : id; return id; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java index 7dcaec5a12..44dc860e62 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/interceptor/LoggerInterceptorIntegrationTest.java @@ -27,6 +27,7 @@ public class LoggerInterceptorIntegrationTest { @Autowired WebApplicationContext wac; + @Autowired MockHttpSession session; diff --git a/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java b/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java index bb3919eacc..29f1c91ca3 100644 --- a/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java +++ b/spring-security-rest-full/src/test/java/org/baeldung/web/util/HTTPLinkHeaderUtil.java @@ -1,10 +1,5 @@ package org.baeldung.web.util; -import java.util.List; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; - public final class HTTPLinkHeaderUtil { private HTTPLinkHeaderUtil() { @@ -13,23 +8,6 @@ public final class HTTPLinkHeaderUtil { // - /** - * ex.
- * https://api.github.com/users/steveklabnik/gists?page=2>; rel="next", ; rel="last" - */ - public static List extractAllURIs(final String linkHeader) { - Preconditions.checkNotNull(linkHeader); - - final List linkHeaders = Lists.newArrayList(); - final String[] links = linkHeader.split(", "); - for (final String link : links) { - final int positionOfSeparator = link.indexOf(';'); - linkHeaders.add(link.substring(1, positionOfSeparator - 1)); - } - - return linkHeaders; - } - public static String extractURIByRel(final String linkHeader, final String rel) { if (linkHeader == null) { return null; @@ -37,7 +15,7 @@ public final class HTTPLinkHeaderUtil { String uriWithSpecifiedRel = null; final String[] links = linkHeader.split(", "); - String linkRelation = null; + String linkRelation; for (final String link : links) { final int positionOfSeparator = link.indexOf(';'); linkRelation = link.substring(positionOfSeparator + 1, link.length()).trim(); @@ -50,20 +28,9 @@ public final class HTTPLinkHeaderUtil { return uriWithSpecifiedRel; } - static Object extractTypeOfRelation(final String linkRelation) { + private static Object extractTypeOfRelation(final String linkRelation) { final int positionOfEquals = linkRelation.indexOf('='); return linkRelation.substring(positionOfEquals + 2, linkRelation.length() - 1).trim(); } - /** - * ex.
- * https://api.github.com/users/steveklabnik/gists?page=2>; rel="next" - */ - public static String extractSingleURI(final String linkHeader) { - Preconditions.checkNotNull(linkHeader); - final int positionOfSeparator = linkHeader.indexOf(';'); - - return linkHeader.substring(1, positionOfSeparator - 1); - } - } diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index 64c0160e1f..13db431ae3 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -307,7 +307,7 @@ 2.9.0 - 2.6.1 + 2.7.0 4.4.5 4.5.2 diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java index 6c551b53b2..462e9e8c21 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerIntegrationTest.java @@ -41,7 +41,7 @@ public class ExpressionUtilityObjectsControllerIntegrationTest { @Autowired private Filter springSecurityFilterChain; - protected RequestPostProcessor testUser() { + private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java index 62c364f864..9c5efdbfc2 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/LayoutDialectControllerIntegrationTest.java @@ -41,7 +41,7 @@ public class LayoutDialectControllerIntegrationTest { @Autowired private Filter springSecurityFilterChain; - protected RequestPostProcessor testUser() { + private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } diff --git a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index 3d8ddfdd5c..4f6480e3b2 100644 --- a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -41,7 +41,7 @@ public class CsrfEnabledIntegrationTest { @Autowired private Filter springSecurityFilterChain; - protected RequestPostProcessor testUser() { + private RequestPostProcessor testUser() { return user("user1").password("user1Pass").roles("USER"); } diff --git a/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java b/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java new file mode 100644 index 0000000000..ed72602f99 --- /dev/null +++ b/static-analysis/src/test/java/com/baeldung/pmd/CntTest.java @@ -0,0 +1,17 @@ +package com.baeldung.pmd; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class CntTest { + + private Cnt service; + + @Test + public void whenSecondParamIsZeroShouldReturnIntMax(){ + service = new Cnt(); + int answer = service.d(100,0); + assertEquals(Integer.MAX_VALUE, answer); + } +} diff --git a/testing/pom.xml b/testing/pom.xml index aa10392aa8..bfd47dbc4a 100644 --- a/testing/pom.xml +++ b/testing/pom.xml @@ -45,6 +45,12 @@ test + + info.cukes + cucumber-java8 + ${cucumber.version} + test + org.pitest diff --git a/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java b/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java index 8ab49309cd..f1659437ec 100644 --- a/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java +++ b/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java @@ -1,20 +1,20 @@ package com.baeldung.junitparams; -import static org.junit.Assert.assertEquals; - import junitparams.FileParameters; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Test; import org.junit.runner.RunWith; +import static org.junit.Assert.assertEquals; + @RunWith(JUnitParamsRunner.class) public class SafeAdditionUtilTest { private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil(); @Test - @Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" }) + @Parameters({"1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15"}) public void whenWithAnnotationProvidedParams_thenSafeAdd(int a, int b, int expectedValue) { assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b)); } @@ -26,7 +26,7 @@ public class SafeAdditionUtilTest { } private Object[] parametersToTestAdd() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; } @Test @@ -36,7 +36,7 @@ public class SafeAdditionUtilTest { } private Object[] parametersForWhenWithnoParam_thenLoadByNameSafeAdd() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } }; + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}}; } @Test diff --git a/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java b/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java index d318345a56..08a472502e 100644 --- a/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java +++ b/testing/src/test/java/com/baeldung/junitparams/TestDataProvider.java @@ -3,11 +3,11 @@ package com.baeldung.junitparams; public class TestDataProvider { public static Object[] provideBasicData() { - return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { 15, -5, 10 }, new Object[] { -5, -10, -15 } }; + return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{15, -5, 10}, new Object[]{-5, -10, -15}}; } public static Object[] provideEdgeCaseData() { - return new Object[] { new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -2, Integer.MIN_VALUE }, }; + return new Object[]{new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -2, Integer.MIN_VALUE},}; } } diff --git a/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java b/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java index 1cdb92090a..20bd62396c 100644 --- a/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java +++ b/testing/src/test/java/com/baeldung/testing/calculator/CalculatorIntegrationTest.java @@ -1,15 +1,14 @@ package com.baeldung.testing.calculator; -import org.junit.runner.RunWith; - import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; +import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions( - features={"classpath:features/calculator.feature", "classpath:features/calculator-scenario-outline.feature"} - , plugin = { "pretty", "json:target/reports/json/calculator.json" } - , glue = {"com.baeldung.cucumber.calculator"} + features = {"classpath:features/calculator.feature", "classpath:features/calculator-scenario-outline.feature"} + , plugin = {"pretty", "json:target/reports/json/calculator.json"} + , glue = {"com.baeldung.cucumber.calculator"} ) public class CalculatorIntegrationTest { } diff --git a/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java b/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java new file mode 100644 index 0000000000..7bf8641ed6 --- /dev/null +++ b/testing/src/test/java/com/baeldung/testing/shopping/ShoppingIntegrationTest.java @@ -0,0 +1,12 @@ +package com.baeldung.testing.shopping; + +import org.junit.runner.RunWith; + +import cucumber.api.CucumberOptions; +import cucumber.api.junit.Cucumber; + +@RunWith(Cucumber.class) +@CucumberOptions(features = { "classpath:features/shopping.feature" }) +public class ShoppingIntegrationTest { + +} diff --git a/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java b/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java new file mode 100644 index 0000000000..2c4bf2eeae --- /dev/null +++ b/testing/src/test/java/com/baeldung/testing/shopping/ShoppingStepsDef.java @@ -0,0 +1,22 @@ +package com.baeldung.testing.shopping; + +import static org.junit.Assert.assertEquals; +import cucumber.api.java8.En; + +public class ShoppingStepsDef implements En { + + private int budget = 0; + + public ShoppingStepsDef() { + + Given("I have (\\d+) in my wallet", (Integer money) -> budget = money); + + When("I buy .* with (\\d+)", (Integer price) -> budget -= price); + + Then("I should have (\\d+) in my wallet", (Integer finalBudget) -> { + assertEquals(budget, finalBudget.intValue()); + }); + + } + +} \ No newline at end of file diff --git a/testing/src/test/resources/features/shopping.feature b/testing/src/test/resources/features/shopping.feature new file mode 100644 index 0000000000..d1ce43df75 --- /dev/null +++ b/testing/src/test/resources/features/shopping.feature @@ -0,0 +1,11 @@ +Feature: Shopping + + Scenario: Track my budget + Given I have 100 in my wallet + When I buy milk with 10 + Then I should have 90 in my wallet + + Scenario: Track my budget + Given I have 200 in my wallet + When I buy rice with 20 + Then I should have 180 in my wallet diff --git a/vaadin/pom.xml b/vaadin/pom.xml new file mode 100644 index 0000000000..6d3512ba2d --- /dev/null +++ b/vaadin/pom.xml @@ -0,0 +1,173 @@ + + + 4.0.0 + + org.test + vaadin-app + war + 1.0-SNAPSHOT + vaadin-app + + + 3 + + + + 7.7.10 + 8.0.6 + 9.3.9.v20160517 + UTF-8 + 1.8 + 1.8 + local + mytheme + + + + + vaadin-addons + http://maven.vaadin.com/vaadin-addons + + + + + + + com.vaadin + vaadin-bom + ${vaadin.version} + pom + import + + + + + + + javax.servlet + javax.servlet-api + 3.0.1 + provided + + + com.vaadin + vaadin-server + + + com.vaadin + vaadin-push + + + com.vaadin + vaadin-client-compiled + + + com.vaadin + vaadin-themes + + + + + + + org.apache.maven.plugins + maven-war-plugin + 3.0.0 + + false + + WEB-INF/classes/VAADIN/widgetsets/WEB-INF/** + + + + com.vaadin + vaadin-maven-plugin + ${vaadin.plugin.version} + + + + update-theme + update-widgetset + compile + + compile-theme + + + + + + org.apache.maven.plugins + maven-clean-plugin + 3.0.0 + + + + + src/main/webapp/VAADIN/themes + + **/styles.css + **/styles.scss.cache + + + + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.plugin.version} + + 2 + + + + + + + + + vaadin-prerelease + + false + + + + + vaadin-prereleases + http://maven.vaadin.com/vaadin-prereleases + + + vaadin-snapshots + https://oss.sonatype.org/content/repositories/vaadin-snapshots/ + + false + + + true + + + + + + vaadin-prereleases + http://maven.vaadin.com/vaadin-prereleases + + + vaadin-snapshots + https://oss.sonatype.org/content/repositories/vaadin-snapshots/ + + false + + + true + + + + + + + diff --git a/vaadin/src/main/java/com/baeldung/introduction/BindData.java b/vaadin/src/main/java/com/baeldung/introduction/BindData.java new file mode 100644 index 0000000000..299554c039 --- /dev/null +++ b/vaadin/src/main/java/com/baeldung/introduction/BindData.java @@ -0,0 +1,20 @@ +package com.baeldung.introduction; + +public class BindData { + + private String bindName; + + public BindData(String bindName){ + this.bindName = bindName; + } + + public String getBindName() { + return bindName; + } + + public void setBindName(String bindName) { + this.bindName = bindName; + } + + +} diff --git a/libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java similarity index 70% rename from libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java rename to vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java index e134b501c8..1b3733ad74 100644 --- a/libraries/src/main/java/com/baeldung/vaadin/VaadinUI.java +++ b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java @@ -1,7 +1,21 @@ -package com.baeldung.vaadin; +package com.baeldung.introduction; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.servlet.annotation.WebServlet; + +import com.vaadin.annotations.Push; import com.vaadin.annotations.Theme; import com.vaadin.annotations.VaadinServletConfiguration; +import com.vaadin.data.Validator.InvalidValueException; +import com.vaadin.data.fieldgroup.BeanFieldGroup; +import com.vaadin.data.validator.StringLengthValidator; import com.vaadin.server.ExternalResource; import com.vaadin.server.FontAwesome; import com.vaadin.server.VaadinRequest; @@ -29,14 +43,14 @@ import com.vaadin.ui.TwinColSelect; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; -import javax.servlet.annotation.WebServlet; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - +@SuppressWarnings("serial") +@Push @Theme("mytheme") public class VaadinUI extends UI { + private Label currentTime; + + @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected void init(VaadinRequest vaadinRequest) { final VerticalLayout verticalLayout = new VerticalLayout(); @@ -61,8 +75,7 @@ public class VaadinUI extends UI { label.setCaption("Label"); gridLayout.addComponent(label); - final Link link = new Link("Baeldung", - new ExternalResource("http://www.baeldung.com/")); + final Link link = new Link("Baeldung", new ExternalResource("http://www.baeldung.com/")); link.setId("Link"); link.setTargetName("_blank"); gridLayout.addComponent(link); @@ -118,28 +131,23 @@ public class VaadinUI extends UI { smallButton.addStyleName("small"); buttonLayout.addComponent(smallButton); - Button largeButton = new Button("Large Button"); largeButton.addStyleName("large"); buttonLayout.addComponent(largeButton); - Button hugeButton = new Button("Huge Button"); hugeButton.addStyleName("huge"); buttonLayout.addComponent(hugeButton); - Button disabledButton = new Button("Disabled Button"); disabledButton.setDescription("This button cannot be clicked"); disabledButton.setEnabled(false); buttonLayout.addComponent(disabledButton); - Button dangerButton = new Button("Danger Button"); dangerButton.addStyleName("danger"); buttonLayout.addComponent(dangerButton); - Button friendlyButton = new Button("Friendly Button"); friendlyButton.addStyleName("friendly"); buttonLayout.addComponent(friendlyButton); @@ -171,8 +179,7 @@ public class VaadinUI extends UI { final CheckBox checkbox = new CheckBox("CheckBox"); checkbox.setValue(true); - checkbox.addValueChangeListener(e -> - checkbox.setValue(!checkbox.getValue())); + checkbox.addValueChangeListener(e -> checkbox.setValue(!checkbox.getValue())); formLayout.addComponent(checkbox); List numbers = new ArrayList(); @@ -204,12 +211,66 @@ public class VaadinUI extends UI { panel.setContent(grid); panel.setSizeUndefined(); + Panel serverPushPanel = new Panel("Server Push"); + FormLayout timeLayout = new FormLayout(); + timeLayout.setSpacing(true); + timeLayout.setMargin(true); + currentTime = new Label("No TIME..."); + timeLayout.addComponent(currentTime); + serverPushPanel.setContent(timeLayout); + serverPushPanel.setSizeUndefined(); + ScheduledExecutorService scheduleExecutor = Executors.newScheduledThreadPool(1); + Runnable task = () -> { + currentTime.setValue("Current Time : " + Instant.now()); + }; + scheduleExecutor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS); + + FormLayout dataBindingLayout = new FormLayout(); + dataBindingLayout.setSpacing(true); + dataBindingLayout.setMargin(true); + + BindData bindData = new BindData("BindData"); + BeanFieldGroup beanFieldGroup = new BeanFieldGroup(BindData.class); + beanFieldGroup.setItemDataSource(bindData); + TextField bindedTextField = (TextField) beanFieldGroup.buildAndBind("BindName", "bindName"); + bindedTextField.setWidth("250px"); + dataBindingLayout.addComponent(bindedTextField); + + FormLayout validatorLayout = new FormLayout(); + validatorLayout.setSpacing(true); + validatorLayout.setMargin(true); + + HorizontalLayout textValidatorLayout = new HorizontalLayout(); + textValidatorLayout.setSpacing(true); + textValidatorLayout.setMargin(true); + + TextField stringValidator = new TextField(); + stringValidator.setNullSettingAllowed(true); + stringValidator.setNullRepresentation(""); + stringValidator.addValidator(new StringLengthValidator("String must have 2-5 characters lenght", 2, 5, true)); + stringValidator.setValidationVisible(false); + textValidatorLayout.addComponent(stringValidator); + Button buttonStringValidator = new Button("Validate String"); + buttonStringValidator.addClickListener(e -> { + try { + stringValidator.setValidationVisible(false); + stringValidator.validate(); + } catch (InvalidValueException err) { + stringValidator.setValidationVisible(true); + } + }); + textValidatorLayout.addComponent(buttonStringValidator); + + validatorLayout.addComponent(textValidatorLayout); verticalLayout.addComponent(gridLayout); verticalLayout.addComponent(richTextPanel); verticalLayout.addComponent(horizontalLayout); verticalLayout.addComponent(formLayout); verticalLayout.addComponent(twinColSelect); verticalLayout.addComponent(panel); + verticalLayout.addComponent(serverPushPanel); + verticalLayout.addComponent(dataBindingLayout); + verticalLayout.addComponent(validatorLayout); setContent(verticalLayout); } @@ -217,4 +278,4 @@ public class VaadinUI extends UI { @VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false) public static class MyUIServlet extends VaadinServlet { } -} \ No newline at end of file +} diff --git a/vaadin/src/main/resources/README b/vaadin/src/main/resources/README new file mode 100644 index 0000000000..faabc74ad5 --- /dev/null +++ b/vaadin/src/main/resources/README @@ -0,0 +1 @@ +Please add your static resources here diff --git a/libraries/src/main/webapp/VAADIN/themes/mytheme/addons.scss b/vaadin/src/main/webapp/VAADIN/themes/mytheme/addons.scss similarity index 100% rename from libraries/src/main/webapp/VAADIN/themes/mytheme/addons.scss rename to vaadin/src/main/webapp/VAADIN/themes/mytheme/addons.scss diff --git a/libraries/src/main/webapp/VAADIN/themes/mytheme/favicon.ico b/vaadin/src/main/webapp/VAADIN/themes/mytheme/favicon.ico similarity index 100% rename from libraries/src/main/webapp/VAADIN/themes/mytheme/favicon.ico rename to vaadin/src/main/webapp/VAADIN/themes/mytheme/favicon.ico diff --git a/libraries/src/main/webapp/VAADIN/themes/mytheme/mytheme.scss b/vaadin/src/main/webapp/VAADIN/themes/mytheme/mytheme.scss similarity index 100% rename from libraries/src/main/webapp/VAADIN/themes/mytheme/mytheme.scss rename to vaadin/src/main/webapp/VAADIN/themes/mytheme/mytheme.scss diff --git a/libraries/src/main/webapp/VAADIN/themes/mytheme/styles.css b/vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.css similarity index 100% rename from libraries/src/main/webapp/VAADIN/themes/mytheme/styles.css rename to vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.css diff --git a/libraries/src/main/webapp/VAADIN/themes/mytheme/styles.scss b/vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.scss similarity index 100% rename from libraries/src/main/webapp/VAADIN/themes/mytheme/styles.scss rename to vaadin/src/main/webapp/VAADIN/themes/mytheme/styles.scss diff --git a/vavr/README.md b/vavr/README.md index d95e026bde..c4155c2680 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -4,3 +4,4 @@ - [Guide to Pattern Matching in Vavr](http://www.baeldung.com/javaslang-pattern-matching) - [Property Testing Example With Vavr](http://www.baeldung.com/javaslang-property-testing) - [Exceptions in Lambda Expression Using Vavr](http://www.baeldung.com/exceptions-using-vavr) +- [Vavr (ex-Javaslang) Support in Spring Data](http://www.baeldung.com/spring-vavr) diff --git a/vavr/pom.xml b/vavr/pom.xml index cbf2a37ec9..d35a408389 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -51,8 +51,20 @@ true + + snapshots + libs-snapshot + https://repo.spring.io/libs-snapshot + - + + + + spring-snapshots + http://repo.spring.io/snapshot + + + 1.8 0.9.0 diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java new file mode 100644 index 0000000000..9f0c48e3ee --- /dev/null +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -0,0 +1,274 @@ +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; +import io.vavr.collection.CharSeq; +import io.vavr.collection.HashSet; +import io.vavr.collection.Iterator; +import io.vavr.collection.List; +import io.vavr.collection.Map; +import io.vavr.collection.Queue; +import io.vavr.collection.Set; +import io.vavr.collection.SortedMap; +import io.vavr.collection.SortedSet; +import io.vavr.collection.Stream; +import io.vavr.collection.TreeMap; +import io.vavr.collection.TreeSet; +import io.vavr.collection.Vector; + +public class CollectionAPIUnitTest { + + @Test + public void givenEmptyList_whenStacked_thenCorrect() { + List intList = List.empty(); + + List anotherList = intList.push(4) + .push(0); + Iterator iterator = anotherList.iterator(); + + assertEquals(new Integer(0), iterator.next()); + assertEquals(new Integer(4), iterator.next()); + } + + @Test + public void givenList_whenPrependTail_thenCorrect() { + List intList = List.of(1, 2, 3); + + List newList = intList.tail() + .prepend(0); + + assertEquals(new Integer(1), intList.get(0)); + assertEquals(new Integer(2), intList.get(1)); + assertEquals(new Integer(3), intList.get(2)); + + assertNotSame(intList.get(0), newList.get(0)); + assertEquals(new Integer(0), newList.get(0)); + assertSame(intList.get(1), newList.get(1)); + assertSame(intList.get(2), newList.get(2)); + } + + @Test + public void givenQueue_whenEnqueued_thenCorrect() { + Queue queue = Queue.of(1, 2, 3); + Queue secondQueue = queue.enqueue(4) + .enqueue(5); + + assertEquals(3, queue.size()); + assertEquals(5, secondQueue.size()); + + Tuple2> result = secondQueue.dequeue(); + Integer headValue = result.apply((head, tail) -> head); + assertEquals(new Integer(1), headValue); + + Iterator iterator = result.apply((head, tail) -> tail.iterator()); + + assertEquals(new Integer(2), iterator.next()); + assertEquals(new Integer(3), iterator.next()); + assertEquals(new Integer(4), iterator.next()); + assertEquals(new Integer(5), iterator.next()); + } + + @Test + public void givenStream_whenProcessed_thenCorrect() { + Stream intStream = Stream.iterate(0, i -> i + 1) + .take(10); + + assertEquals(10, intStream.size()); + + long evenSum = intStream.filter(i -> i % 2 == 0) + .sum() + .longValue(); + + assertEquals(20, evenSum); + assertEquals(new Integer(5), intStream.get(5)); + } + + @Test + public void givenArray_whenQueried_thenCorrect() { + Array intArray = Array.of(1, 2, 3); + Array newArray = intArray.removeAt(1); + + assertEquals(3, intArray.size()); + assertEquals(2, newArray.size()); + + assertEquals(new Integer(1), intArray.get(0)); + assertEquals(new Integer(2), intArray.get(1)); + assertEquals(new Integer(3), intArray.get(2)); + assertEquals(new Integer(3), newArray.get(1)); + } + + @Test + public void givenVector_whenQueried_thenCorrect() { + Vector intVector = Vector.range(1, 5); + Vector newVector = intVector.replace(2, 6); + + assertEquals(4, intVector.size()); + assertEquals(4, newVector.size()); + + assertEquals(new Integer(1), intVector.get(0)); + assertEquals(new Integer(2), intVector.get(1)); + assertEquals(new Integer(3), intVector.get(2)); + assertEquals(new Integer(6), newVector.get(1)); + } + + @Test + public void givenCharSeq_whenProcessed_thenCorrect() { + CharSeq chars = CharSeq.of("vavr"); + CharSeq newChars = chars.replace('v', 'V'); + + assertEquals(4, chars.size()); + assertEquals(4, newChars.size()); + + assertEquals('v', chars.charAt(0)); + assertEquals('V', newChars.charAt(0)); + assertEquals("Vavr", newChars.mkString()); + } + + @Test + public void givenHashSet_whenModified_thenCorrect() { + HashSet set = HashSet.of("Red", "Green", "Blue"); + HashSet newSet = set.add("Yellow"); + + assertEquals(3, set.size()); + assertEquals(4, newSet.size()); + assertFalse(set.contains("Yellow")); + assertTrue(newSet.contains("Yellow")); + } + + @Test + public void givenSortedSet_whenIterated_thenCorrect() { + SortedSet set = TreeSet.of("Red", "Green", "Blue"); + + Iterator iterator = set.iterator(); + assertEquals("Blue", iterator.next()); + assertEquals("Green", iterator.next()); + assertEquals("Red", iterator.next()); + } + + @Test + public void givenSortedSet_whenReversed_thenCorrect() { + SortedSet set = TreeSet.of(Comparator.reverseOrder(), "Green", "Red", "Blue"); + + Iterator iterator = set.iterator(); + assertEquals("Red", iterator.next()); + assertEquals("Green", iterator.next()); + assertEquals("Blue", iterator.next()); + } + + @Test + public void givenMap_whenIterated_thenCorrect() { + Map> map = List.rangeClosed(0, 10) + .groupBy(i -> i % 2); + + assertEquals(2, map.size()); + + Iterator>> iterator = map.iterator(); + assertEquals(6, iterator.next() + ._2() + .size()); + assertEquals(5, iterator.next() + ._2() + .size()); + } + + @Test + public void givenTreeMap_whenIterated_thenCorrect() { + SortedMap map = TreeMap.of(3, "Three", 2, "Two", 4, "Four", 1, "One"); + + Iterator> iterator = map.iterator(); + assertEquals(new Integer(1), iterator.next() + ._1()); + assertEquals(new Integer(2), iterator.next() + ._1()); + assertEquals(new Integer(3), iterator.next() + ._1()); + } + + @Test + public void givenJavaList_whenConverted_thenCorrect() { + java.util.List javaList = java.util.Arrays.asList(1, 2, 3, 4); + List vavrList = List.ofAll(javaList); + + assertEquals(4, vavrList.size()); + assertEquals(new Integer(1), vavrList.head()); + + java.util.stream.Stream javaStream = javaList.stream(); + Set vavrSet = HashSet.ofAll(javaStream); + + assertEquals(4, vavrSet.size()); + assertEquals(new Integer(2), vavrSet.tail() + .head()); + } + + @Test + public void givenJavaStream_whenCollected_thenCorrect() { + List vavrList = IntStream.range(1, 10) + .boxed() + .filter(i -> i % 2 == 0) + .collect(List.collector()); + + assertEquals(4, vavrList.size()); + assertEquals(new Integer(2), vavrList.head()); + } + + @Test + public void givenVavrList_whenConverted_thenCorrect() { + Integer[] array = List.of(1, 2, 3) + .toJavaArray(Integer.class); + assertEquals(3, array.length); + + java.util.Map map = List.of("1", "2", "3") + .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) + .collect(Collectors.toSet()); + + assertEquals(3, javaSet.size()); + assertEquals(new Integer(1), javaSet.iterator() + .next()); + } + + @Test + public void givenVavrList_whenConvertedView_thenCorrect() { + java.util.List javaList = List.of(1, 2, 3) + .asJavaMutable(); + javaList.add(4); + + assertEquals(new Integer(4), javaList.get(3)); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenVavrList_whenConvertedView_thenException() { + java.util.List javaList = List.of(1, 2, 3) + .asJava(); + + assertEquals(new Integer(3), javaList.get(2)); + javaList.add(4); + } + + @Test + public void givenList_whenSquared_thenCorrect() { + List vavrList = List.of(1, 2, 3); + Number sum = vavrList.map(i -> i * i) + .sum(); + + assertEquals(14L, sum); + } +} diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorUnitTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorUnitTest.java index 1b1986417d..33c96acf52 100644 --- a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorUnitTest.java +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/deserialization/jsoncreator/JsonCreatorUnitTest.java @@ -21,10 +21,10 @@ public class JsonCreatorUnitTest { // arrange String authorJson = - "{" + - " \"christianName\": \"Alex\"," + - " \"surname\": \"Theedom\"" + - "}"; + "{" + + " \"christianName\": \"Alex\"," + + " \"surname\": \"Theedom\"" + + "}"; // act final Author author = new ObjectMapper().readerFor(Author.class).readValue(authorJson); diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterUnitTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterUnitTest.java index 133f8b1f21..5491168f9b 100644 --- a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterUnitTest.java +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonfilter/JsonFilterUnitTest.java @@ -24,7 +24,7 @@ public class JsonFilterUnitTest { // arrange Author author = new Author("Alex", "Theedom"); FilterProvider filters = new SimpleFilterProvider() - .addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); + .addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName")); // act String result = new ObjectMapper().writer(filters).writeValueAsString(author); diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatUnitTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatUnitTest.java index 373e8d716a..6801516dfd 100644 --- a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatUnitTest.java +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonformat/JsonFormatUnitTest.java @@ -32,8 +32,8 @@ public class JsonFormatUnitTest { Date date = df.parse(toParse); Book book = new Book( - "Design Patterns: Elements of Reusable Object-oriented Software", - new Author("The", "GoF") + "Design Patterns: Elements of Reusable Object-oriented Software", + new Author("The", "GoF") ); book.setPublished(date); diff --git a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyUnitTest.java b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyUnitTest.java index 191330be86..62f9b498ac 100644 --- a/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyUnitTest.java +++ b/video-tutorials/jackson-annotations/src/test/java/com/baeldung/jacksonannotation/general/jsonproperty/JsonPropertyUnitTest.java @@ -22,8 +22,8 @@ public class JsonPropertyUnitTest { // arrange Book book = new Book( - "Design Patterns: Elements of Reusable Object-oriented Software", - new Author("The", "GoF") + "Design Patterns: Elements of Reusable Object-oriented Software", + new Author("The", "GoF") ); book.configureBinding("Hardback");