diff --git a/animal-sniffer-mvn-plugin/README.md b/animal-sniffer-mvn-plugin/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/animal-sniffer-mvn-plugin/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/apache-cayenne/README.md b/apache-cayenne/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/apache-cayenne/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/asm/README.md b/asm/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/asm/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/asm/src/main/java/com/baeldung/examples/asm/instrumentation/Premain.java b/asm/src/main/java/com/baeldung/examples/asm/instrumentation/Premain.java index 105d7227d5..a3e69b6785 100644 --- a/asm/src/main/java/com/baeldung/examples/asm/instrumentation/Premain.java +++ b/asm/src/main/java/com/baeldung/examples/asm/instrumentation/Premain.java @@ -1,19 +1,32 @@ package com.baeldung.examples.asm.instrumentation; import com.baeldung.examples.asm.CustomClassWriter; - +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; +import java.security.ProtectionDomain; +/** + * + * @author baeldung + */ public class Premain { public static void premain(String agentArgs, Instrumentation inst) { - inst.addTransformer((l, name, c, d, b) -> { + inst.addTransformer(new ClassFileTransformer() { - if (name.equals("java/lang/Integer")) { - CustomClassWriter cr = new CustomClassWriter(b); - return cr.addField(); + @Override + public byte[] transform(ClassLoader l, String name, Class c, + ProtectionDomain d, byte[] b) + throws IllegalClassFormatException { + + if (name.equals("java/lang/Integer")) { + CustomClassWriter cr = new CustomClassWriter(b); + return cr.addField(); + } + return b; } - return b; }); } + } diff --git a/atomix/README.md b/atomix/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/atomix/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/cas-secured-app/README.md b/cas-secured-app/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/cas-secured-app/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/core-java/src/main/java/com/baeldung/staticdemo/Car.java b/core-java/src/main/java/com/baeldung/staticdemo/Car.java new file mode 100644 index 0000000000..cdb3806c35 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/staticdemo/Car.java @@ -0,0 +1,48 @@ +package com.baeldung.staticdemo; + +/** + * This class demonstrates the use of static fields and static methods + * the instance variables engine and displacement are distinct for + * each and every object whereas static/class variable numberOfCars + * is unique and is shared across all objects of this class. + * + * @author baeldung + * + */ +public class Car { + private String name; + private String engine; + + public static int numberOfCars; + + public Car(String name, String engine) { + this.name = name; + this.engine = engine; + numberOfCars++; + } + + //getters and setters + public static int getNumberOfCars() { + return numberOfCars; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEngine() { + return engine; + } + + public void setEngine(String engine) { + this.engine = engine; + } + + public static void setNumberOfCars(int numberOfCars) { + Car.numberOfCars = numberOfCars; + } +} diff --git a/core-java/src/main/java/com/baeldung/staticdemo/Singleton.java b/core-java/src/main/java/com/baeldung/staticdemo/Singleton.java new file mode 100644 index 0000000000..de75af9d9d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/staticdemo/Singleton.java @@ -0,0 +1,13 @@ +package com.baeldung.staticdemo; + +public class Singleton { + private Singleton() {} + + private static class SingletonHolder { + public static final Singleton instance = new Singleton(); + } + + public static Singleton getInstance() { + return SingletonHolder.instance; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/staticdemo/StaticBlock.java b/core-java/src/main/java/com/baeldung/staticdemo/StaticBlock.java new file mode 100644 index 0000000000..fde7afb090 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/staticdemo/StaticBlock.java @@ -0,0 +1,28 @@ +package com.baeldung.staticdemo; + +import java.util.LinkedList; +import java.util.List; + +public class StaticBlock { + private static List ranks = new LinkedList<>(); + + static { + ranks.add("Lieutenant"); + ranks.add("Captain"); + ranks.add("Major"); + } + + static { + ranks.add("Colonel"); + ranks.add("General"); + } + + //getters and setters + public static List getRanks() { + return ranks; + } + + public static void setRanks(List ranks) { + StaticBlock.ranks = ranks; + } +} diff --git a/core-java/src/test/java/com/baeldung/staticdemo/CarIntegrationTest.java b/core-java/src/test/java/com/baeldung/staticdemo/CarIntegrationTest.java new file mode 100644 index 0000000000..3150627269 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/staticdemo/CarIntegrationTest.java @@ -0,0 +1,14 @@ +package com.baeldung.staticdemo; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class CarIntegrationTest { + @Test + public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() { + new Car("Jaguar", "V8"); + new Car("Bugatti", "W16"); + assertEquals(2, Car.numberOfCars); + } +} diff --git a/core-java/src/test/java/com/baeldung/staticdemo/SingletonIntegrationTest.java b/core-java/src/test/java/com/baeldung/staticdemo/SingletonIntegrationTest.java new file mode 100644 index 0000000000..28d864073a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/staticdemo/SingletonIntegrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung.staticdemo; + +import org.junit.Assert; +import org.junit.Test; + +public class SingletonIntegrationTest { + + @Test + public void givenStaticInnerClass_whenMultipleTimesInstanceCalled_thenOnlyOneTimeInitialized() { + Singleton object1 = Singleton.getInstance(); + Singleton object2 = Singleton.getInstance(); + + Assert.assertSame(object1, object2); + } +} diff --git a/core-java/src/test/java/com/baeldung/staticdemo/StaticBlockIntegrationTest.java b/core-java/src/test/java/com/baeldung/staticdemo/StaticBlockIntegrationTest.java new file mode 100644 index 0000000000..f98e3e14db --- /dev/null +++ b/core-java/src/test/java/com/baeldung/staticdemo/StaticBlockIntegrationTest.java @@ -0,0 +1,17 @@ +package com.baeldung.staticdemo; + +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.junit.Test; + +public class StaticBlockIntegrationTest { + + @Test + public void whenAddedListElementsThroughStaticBlock_thenEnsureCorrectOrder() { + List actualList = StaticBlock.getRanks(); + assertThat(actualList, contains("Lieutenant", "Captain", "Major", "Colonel", "General")); + } +} diff --git a/deltaspike/README.md b/deltaspike/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/deltaspike/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/drools/backward-chaining/pom.xml b/drools/backward-chaining/pom.xml new file mode 100644 index 0000000000..bda0cf2abc --- /dev/null +++ b/drools/backward-chaining/pom.xml @@ -0,0 +1,38 @@ + + + + 4.0.0 + + drools-backward-chaining + 1.0 + drools-backward-chaining + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + 6.4.0.Final + + + + + org.kie + kie-api + ${runtime.version} + + + org.drools + drools-core + ${runtime.version} + + + org.drools + drools-decisiontables + ${runtime.version} + + + diff --git a/drools/backward-chaining/src/main/java/com/baeldung/BackwardChainingBeatles.java b/drools/backward-chaining/src/main/java/com/baeldung/BackwardChainingBeatles.java new file mode 100644 index 0000000000..7fc5bd3685 --- /dev/null +++ b/drools/backward-chaining/src/main/java/com/baeldung/BackwardChainingBeatles.java @@ -0,0 +1,28 @@ +package com.baeldung; + +import org.kie.api.KieServices; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.KieSession; + +import com.baeldung.model.Beatle; + +public class BackwardChainingBeatles { + public static void main(String[] args) { + + KieServices ks = KieServices.Factory.get(); + KieContainer kContainer = ks.getKieClasspathContainer(); + KieSession kSession = kContainer.newKieSession("ksession-backward-chaining"); + // drools session base on the xml configuration (kmodule.xml) + + // graph population + kSession.insert(new Beatle("Starr", "drums")); + kSession.insert(new Beatle("McCartney", "bass")); + kSession.insert(new Beatle("Lennon", "guitar")); + kSession.insert(new Beatle("Harrison", "guitar")); + + kSession.insert("Ringo"); // invoke the rule that calls the query implentation of backward chaining + kSession.fireAllRules(); // invoke all the rules + + } + +} \ No newline at end of file diff --git a/drools/backward-chaining/src/main/java/com/baeldung/model/Beatle.java b/drools/backward-chaining/src/main/java/com/baeldung/model/Beatle.java new file mode 100644 index 0000000000..4b219b3a69 --- /dev/null +++ b/drools/backward-chaining/src/main/java/com/baeldung/model/Beatle.java @@ -0,0 +1,33 @@ +package com.baeldung.model; + +import org.kie.api.definition.type.Position; + +public class Beatle { + + @Position(0) + private String lastName; + @Position(1) + private String instrument; + + public Beatle(String lastName, String instrument) { + this.lastName = lastName; + this.instrument = instrument; + } + + public String getInstrument() { + return instrument; + } + + public void setInstrument(String instrument) { + this.instrument = instrument; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + +} \ No newline at end of file diff --git a/drools/backward-chaining/src/main/resources/META-INF/kmodule.xml b/drools/backward-chaining/src/main/resources/META-INF/kmodule.xml new file mode 100644 index 0000000000..6498e26343 --- /dev/null +++ b/drools/backward-chaining/src/main/resources/META-INF/kmodule.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/drools/backward-chaining/src/main/resources/backward_chaining/Beatles.drl b/drools/backward-chaining/src/main/resources/backward_chaining/Beatles.drl new file mode 100644 index 0000000000..8d0d06a79e --- /dev/null +++ b/drools/backward-chaining/src/main/resources/backward_chaining/Beatles.drl @@ -0,0 +1,44 @@ +package com.baeldung + +import com.baeldung.model.Beatle; + + +query whichBeatle(String lastName, String instrument) + Beatle(lastName, instrument;) + or + (Beatle(lastName, null;) + and + whichBeatle(null, instrument;)) //recursive call to the function that allows to search in a derivation tree structure +end + +rule "Ringo" + when + String(this == "Ringo") + whichBeatle("Starr", "drums";) + then + System.out.println("The beatle is Ringo Starr"); +end + +rule "Paul" + when + String(this == "Paul") + whichBeatle("McCartney", "bass";) + then + System.out.println("The beatle is Paul McCartney"); +end + +rule "John" + when + String(this == "John") + whichBeatle("Lennon", "guitar";) + then + System.out.println("The beatle is John Lennon"); +end + +rule "George" + when + String(this == "George") + whichBeatle("Harrison", "guitar";) + then + System.out.println("The beatle is George Harrison"); +end diff --git a/eclipse/README.md b/eclipse/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/eclipse/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/enterprise-patterns/README.md b/enterprise-patterns/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/enterprise-patterns/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/events/README.md b/events/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/events/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/gradle/README.md b/gradle/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/gradle/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/graphql/graphql-java/README.md b/graphql/graphql-java/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/graphql/graphql-java/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/guest/README.md b/guest/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/guest/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/guest/spring-mvc/pom.xml b/guest/spring-mvc/pom.xml new file mode 100644 index 0000000000..9974a76e8a --- /dev/null +++ b/guest/spring-mvc/pom.xml @@ -0,0 +1,59 @@ + + + 4.0.0 + + com.forketyfork.guest + spring-mvc + 0.0.1-SNAPSHOT + jar + + spring-mvc + Spring MVC sample project + + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.M5 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + + + UTF-8 + UTF-8 + 1.8 + + + diff --git a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/Spring5Application.java b/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/Spring5Application.java new file mode 100644 index 0000000000..d9af7c8ac9 --- /dev/null +++ b/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/Spring5Application.java @@ -0,0 +1,15 @@ +package com.forketyfork.guest.springmvc; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.boot.SpringApplication; + +@SpringBootApplication +@ComponentScan(basePackages = {"com.forketyfork.guest.springmvc"}) +public class Spring5Application { + + public static void main(String[] args) { + SpringApplication.run(Spring5Application.class, args); + } + +} diff --git a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/model/LoginData.java b/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/model/LoginData.java new file mode 100644 index 0000000000..a9140da4f9 --- /dev/null +++ b/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/model/LoginData.java @@ -0,0 +1,27 @@ +package com.forketyfork.guest.springmvc.model; + +public class LoginData { + + private String login; + + private String password; + + public LoginData() { + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/InternalsController.java b/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/InternalsController.java new file mode 100644 index 0000000000..c39da4e3e5 --- /dev/null +++ b/guest/spring-mvc/src/main/java/com/forketyfork/guest/springmvc/web/InternalsController.java @@ -0,0 +1,31 @@ +package com.forketyfork.guest.springmvc.web; + +import com.forketyfork.guest.springmvc.model.LoginData; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.servlet.ModelAndView; + +import java.util.Collections; + +@Controller +public class InternalsController { + + private static final String LOGIN = "jack"; + private static final String PASSWORD = "halloween"; + + @GetMapping("/") + public String hello() { + return "login"; + } + + @PostMapping("/login") + public ModelAndView login(LoginData loginData) { + if (LOGIN.equals(loginData.getLogin()) && PASSWORD.equals(loginData.getPassword())) { + return new ModelAndView("success", Collections.singletonMap("login", loginData.getLogin())); + } else { + return new ModelAndView("failure", Collections.singletonMap("login", loginData.getLogin())); + } + } + +} diff --git a/guest/spring-mvc/src/main/resources/templates/failure.html b/guest/spring-mvc/src/main/resources/templates/failure.html new file mode 100644 index 0000000000..f319652ede --- /dev/null +++ b/guest/spring-mvc/src/main/resources/templates/failure.html @@ -0,0 +1,10 @@ + + + + Login Failure + +

+ User with login not found, please try again. +

+ \ No newline at end of file diff --git a/guest/spring-mvc/src/main/resources/templates/login.html b/guest/spring-mvc/src/main/resources/templates/login.html new file mode 100644 index 0000000000..d031ac8825 --- /dev/null +++ b/guest/spring-mvc/src/main/resources/templates/login.html @@ -0,0 +1,13 @@ + + +Login Form + + +
+ + + +
+ + + \ No newline at end of file diff --git a/guest/spring-mvc/src/main/resources/templates/success.html b/guest/spring-mvc/src/main/resources/templates/success.html new file mode 100644 index 0000000000..6966385f2e --- /dev/null +++ b/guest/spring-mvc/src/main/resources/templates/success.html @@ -0,0 +1,10 @@ + + + + Login Success + +

+ Hello, ! +

+ \ No newline at end of file diff --git a/hibernate5/README.md b/hibernate5/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/hibernate5/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 7e9a217dba..58e09816ea 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -2,7 +2,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - com.baeldung hystrix 1.0 hystrix diff --git a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutIntegrationTest.java b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutManualTest.java similarity index 72% rename from hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutIntegrationTest.java rename to hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutManualTest.java index bf0c542980..ed89104c05 100644 --- a/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutIntegrationTest.java +++ b/hystrix/src/test/java/com/baeldung/hystrix/HystrixTimeoutManualTest.java @@ -10,53 +10,53 @@ import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -public class HystrixTimeoutIntegrationTest { +public class HystrixTimeoutManualTest { @Test - public void givenInputBobAndDefaultSettings_whenCommandExecuted_thenReturnHelloBob(){ + public void givenInputBobAndDefaultSettings_whenCommandExecuted_thenReturnHelloBob() { assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!")); } @Test public void givenSvcTimeoutOf100AndDefaultSettings_whenRemoteSvcExecuted_thenReturnSuccess() - throws InterruptedException { + throws InterruptedException { HystrixCommand.Setter config = HystrixCommand - .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup2")); + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup2")); assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(), - equalTo("Success")); + equalTo("Success")); } @Test(expected = HystrixRuntimeException.class) public void givenSvcTimeoutOf10000AndDefaultSettings__whenRemoteSvcExecuted_thenExpectHRE() throws InterruptedException { HystrixCommand.Setter config = HystrixCommand - .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest3")); + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest3")); new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute(); } @Test public void givenSvcTimeoutOf5000AndExecTimeoutOf10000_whenRemoteSvcExecuted_thenReturnSuccess() - throws InterruptedException { + throws InterruptedException { HystrixCommand.Setter config = HystrixCommand - .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest4")); + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest4")); HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); commandProperties.withExecutionTimeoutInMilliseconds(10_000); config.andCommandPropertiesDefaults(commandProperties); assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), - equalTo("Success")); + equalTo("Success")); } @Test(expected = HystrixRuntimeException.class) public void givenSvcTimeoutOf15000AndExecTimeoutOf5000__whenExecuted_thenExpectHRE() - throws InterruptedException { + throws InterruptedException { HystrixCommand.Setter config = HystrixCommand - .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest5")); + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest5")); HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); commandProperties.withExecutionTimeoutInMilliseconds(5_000); config.andCommandPropertiesDefaults(commandProperties); @@ -65,45 +65,45 @@ public class HystrixTimeoutIntegrationTest { @Test public void givenSvcTimeoutOf500AndExecTimeoutOf10000AndThreadPool__whenExecuted_thenReturnSuccess() - throws InterruptedException { + throws InterruptedException { HystrixCommand.Setter config = HystrixCommand - .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupThreadPool")); + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupThreadPool")); HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter(); commandProperties.withExecutionTimeoutInMilliseconds(10_000); config.andCommandPropertiesDefaults(commandProperties); config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() - .withMaxQueueSize(10) - .withCoreSize(3) - .withQueueSizeRejectionThreshold(10)); + .withMaxQueueSize(10) + .withCoreSize(3) + .withQueueSizeRejectionThreshold(10)); assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), - equalTo("Success")); + equalTo("Success")); } @Test public void givenCircuitBreakerSetup__whenRemoteSvcCmdExecuted_thenReturnSuccess() - throws InterruptedException { + throws InterruptedException { HystrixCommand.Setter config = HystrixCommand - .Setter - .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupCircuitBreaker")); + .Setter + .withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupCircuitBreaker")); HystrixCommandProperties.Setter properties = HystrixCommandProperties.Setter(); properties.withExecutionTimeoutInMilliseconds(1000); properties.withCircuitBreakerSleepWindowInMilliseconds(4000); properties.withExecutionIsolationStrategy( - HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); + HystrixCommandProperties.ExecutionIsolationStrategy.THREAD); properties.withCircuitBreakerEnabled(true); properties.withCircuitBreakerRequestVolumeThreshold(1); config.andCommandPropertiesDefaults(properties); config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() - .withMaxQueueSize(1) - .withCoreSize(1) - .withQueueSizeRejectionThreshold(1)); + .withMaxQueueSize(1) + .withCoreSize(1) + .withQueueSizeRejectionThreshold(1)); assertThat(this.invokeRemoteService(config, 10_000), equalTo(null)); assertThat(this.invokeRemoteService(config, 10_000), equalTo(null)); @@ -111,19 +111,19 @@ public class HystrixTimeoutIntegrationTest { Thread.sleep(5000); assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), - equalTo("Success")); + equalTo("Success")); assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), - equalTo("Success")); + equalTo("Success")); assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(), - equalTo("Success")); + equalTo("Success")); } public String invokeRemoteService(HystrixCommand.Setter config, int timeout) - throws InterruptedException { + throws InterruptedException { String response = null; try { response = new RemoteServiceTestCommand(config, - new RemoteServiceTestSimulator(timeout)).execute(); + new RemoteServiceTestSimulator(timeout)).execute(); } catch (HystrixRuntimeException ex) { System.out.println("ex = " + ex); } diff --git a/intelliJ/README.md b/intelliJ/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/intelliJ/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/jhipster/README.md b/jhipster/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/jhipster/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/jmh/README.md b/jmh/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/jmh/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/jooby/README.md b/jooby/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/jooby/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/json-path/README.md b/json-path/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/json-path/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/linkrest/README.md b/linkrest/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/linkrest/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/metrics/pom.xml b/metrics/pom.xml index 926b6a95c5..25ce452d7a 100644 --- a/metrics/pom.xml +++ b/metrics/pom.xml @@ -16,7 +16,7 @@ 3.1.2 3.1.0 0.12.17 - 1.0.0-rc.2 + 0.12.0.RELEASE 2.0.0.M5 diff --git a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java index b2eb0ee7dc..826e06d598 100644 --- a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java @@ -16,6 +16,7 @@ import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import static io.micrometer.core.instrument.Meter.Type; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.hamcrest.core.IsCollectionContaining.hasItems; @@ -27,7 +28,7 @@ import static org.junit.Assert.assertTrue; */ public class MicrometerAtlasTest { - AtlasConfig atlasConfig; + private AtlasConfig atlasConfig; @Before public void init() { @@ -208,32 +209,27 @@ public class MicrometerAtlasTest { timer.record(8, TimeUnit.SECONDS); timer.record(13, TimeUnit.SECONDS); - List quantileGauges = registry + Map quantileMap = extractTagValueMap(registry, Type.Gauge, 1e9); + assertThat(quantileMap, allOf(hasEntry("quantile=0.3", 2), hasEntry("quantile=0.5", 3), hasEntry("quantile=0.95", 8))); + } + + private Map extractTagValueMap(MeterRegistry registry, Type meterType, double valueDivisor) { + return registry .getMeters() .stream() - .filter(meter -> meter - .getType() - .name() - .equals("Gauge")) - .map(meter -> (Gauge) meter) - .collect(Collectors.toList()); - assert (3 == quantileGauges.size()); - - Map quantileMap = quantileGauges - .stream() - .collect(Collectors.toMap(gauge -> { - Tag tag = gauge + .filter(meter -> meter.getType() == meterType) + .collect(Collectors.toMap(meter -> { + Tag tag = meter .getId() .getTags() .iterator() .next(); return tag.getKey() + "=" + tag.getValue(); - }, gauge -> (int) (gauge.value() / 1e9))); - - assertThat(quantileMap.keySet(), hasItems("quantile=0.3", "quantile=0.5", "quantile=0.95")); - assertThat(quantileMap.get("quantile=0.3"), is(2)); - assertThat(quantileMap.get("quantile=0.5"), is(3)); - assertThat(quantileMap.get("quantile=0.95"), is(8)); + }, meter -> (int) (meter + .measure() + .iterator() + .next() + .getValue() / valueDivisor))); } @Test @@ -243,6 +239,7 @@ public class MicrometerAtlasTest { .builder("summary") .histogram(Histogram.linear(0, 10, 5)) .register(registry); + hist.record(3); hist.record(8); hist.record(20); @@ -250,22 +247,7 @@ public class MicrometerAtlasTest { hist.record(13); hist.record(26); - Map histograms = registry - .getMeters() - .stream() - .filter(meter -> meter.getType() == Meter.Type.Counter) - .collect(Collectors.toMap(counter -> { - Tag tag = counter - .getId() - .getTags() - .iterator() - .next(); - return tag.getKey() + "=" + tag.getValue(); - }, counter -> (int) counter - .measure() - .iterator() - .next() - .getValue())); + Map histograms = extractTagValueMap(registry, Type.Counter, 1.0); assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=10.0", 2), hasEntry("bucket=20.0", 2), hasEntry("bucket=30.0", 1), hasEntry("bucket=40.0", 1), hasEntry("bucket=Infinity", 0))); } @@ -284,22 +266,7 @@ public class MicrometerAtlasTest { timer.record(341, TimeUnit.MILLISECONDS); timer.record(500, TimeUnit.MILLISECONDS); - Map histograms = registry - .getMeters() - .stream() - .filter(meter -> meter.getType() == Meter.Type.Counter) - .collect(Collectors.toMap(counter -> { - Tag tag = counter - .getId() - .getTags() - .iterator() - .next(); - return tag.getKey() + "=" + tag.getValue(); - }, counter -> (int) counter - .measure() - .iterator() - .next() - .getValue())); + Map histograms = extractTagValueMap(registry, Type.Counter, 1.0); assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=2.0E8", 1), hasEntry("bucket=4.0E8", 1), hasEntry("bucket=Infinity", 3))); diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java b/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java new file mode 100644 index 0000000000..cfe406c112 --- /dev/null +++ b/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGenerator.java @@ -0,0 +1,28 @@ +package com.baeldung.powermockito.introduction; + +class LuckyNumberGenerator { + + public int getLuckyNumber(String name) { + + saveIntoDatabase(name); + + if (name == null) { + return getDefaultLuckyNumber(); + } + + return getComputedLuckyNumber(name.length()); + } + + private void saveIntoDatabase(String name) { + // Save the name into the database + } + + private int getDefaultLuckyNumber() { + return 100; + } + + private int getComputedLuckyNumber(int length) { + return length < 5 ? 5 : 10000; + } + +} diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java b/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java new file mode 100644 index 0000000000..2836bcd317 --- /dev/null +++ b/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java @@ -0,0 +1,51 @@ +package com.baeldung.powermockito.introduction; + +import static org.junit.Assert.assertEquals; +import static org.powermock.api.mockito.PowerMockito.doReturn; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.verifyPrivate; +import static org.powermock.api.mockito.PowerMockito.when; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.LuckyNumberGenerator") +public class LuckyNumberGeneratorTest { + + @Test + public final void givenPrivateMethodWithReturn_whenUsingPowerMockito_thenCorrect() throws Exception { + LuckyNumberGenerator mock = spy(new LuckyNumberGenerator()); + + when(mock, "getDefaultLuckyNumber").thenReturn(300); + + int result = mock.getLuckyNumber(null); + + assertEquals(300, result); + } + + @Test + public final void givenPrivateMethodWithArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception { + LuckyNumberGenerator mock = spy(new LuckyNumberGenerator()); + + doReturn(1).when(mock, "getComputedLuckyNumber", ArgumentMatchers.anyInt()); + + int result = mock.getLuckyNumber("Jack"); + + assertEquals(1, result); + } + + @Test + public final void givenPrivateMethodWithNoArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception { + LuckyNumberGenerator mock = spy(new LuckyNumberGenerator()); + + int result = mock.getLuckyNumber("Tyranosorous"); + + verifyPrivate(mock).invoke("saveIntoDatabase", ArgumentMatchers.anyString()); + assertEquals(10000, result); + } + +} diff --git a/mocks/README.md b/mocks/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/mocks/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/mockserver/README.md b/mockserver/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/mockserver/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/parent-boot-4/README.md b/parent-boot-4/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/parent-boot-4/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/parent-boot-5/README.md b/parent-boot-5/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/parent-boot-5/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java b/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java index 13ba3ccac9..1b691414db 100644 --- a/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java +++ b/rest-assured/src/test/java/com/baeldung/restassured/RestAssured2IntegrationTest.java @@ -1,55 +1,53 @@ package com.baeldung.restassured; +import com.github.tomakehurst.wiremock.WireMockServer; +import io.restassured.RestAssured; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static io.restassured.RestAssured.get; import static org.hamcrest.Matchers.hasItems; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import static io.restassured.RestAssured.get; - -import com.github.tomakehurst.wiremock.WireMockServer; - public class RestAssured2IntegrationTest { - private WireMockServer wireMockServer = new WireMockServer(); + private static final int PORT = 8084; + private static WireMockServer wireMockServer = new WireMockServer(PORT); - private static final String EVENTS_PATH = "/odds"; - private static final String APPLICATION_JSON = "application/json"; - private static final String ODDS = getJson(); + private static final String EVENTS_PATH = "/odds"; + private static final String APPLICATION_JSON = "application/json"; + private static final String ODDS = getJson(); - @Before - public void before() throws Exception { - System.out.println("Setting up!"); - wireMockServer.start(); - configureFor("localhost", 8080); - stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( - aResponse().withStatus(200) - .withHeader("Content-Type", APPLICATION_JSON) - .withBody(ODDS))); - } + @BeforeClass + public static void before() throws Exception { + System.out.println("Setting up!"); + wireMockServer.start(); + configureFor("localhost", PORT); + RestAssured.port = PORT; + stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( + aResponse().withStatus(200) + .withHeader("Content-Type", APPLICATION_JSON) + .withBody(ODDS))); + } - @Test - public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() { - get("/odds").then().body("odds.findAll { it.status > 0 }.price", - hasItems(5.25f, 1.2f)); - } + @Test + public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() { + get("/odds").then().body("odds.findAll { it.status > 0 }.price", + hasItems(5.25f, 1.2f)); + } - private static String getJson() { - - return Util.inputStreamToString(new RestAssured2IntegrationTest().getClass() - .getResourceAsStream("/odds.json")); - - } - - @After - public void after() throws Exception { - System.out.println("Running: tearDown"); - wireMockServer.stop(); - } + private static String getJson() { + return Util.inputStreamToString(RestAssured2IntegrationTest.class + .getResourceAsStream("/odds.json")); + } + @AfterClass + public static void after() throws Exception { + System.out.println("Running: tearDown"); + wireMockServer.stop(); + } } diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java index f14d9920b6..4ad3cea22c 100644 --- a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java +++ b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredIntegrationTest.java @@ -1,5 +1,14 @@ package com.baeldung.restassured; +import com.github.fge.jsonschema.SchemaVersion; +import com.github.fge.jsonschema.cfg.ValidationConfiguration; +import com.github.fge.jsonschema.main.JsonSchemaFactory; +import com.github.tomakehurst.wiremock.WireMockServer; +import io.restassured.RestAssured; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; import static com.github.tomakehurst.wiremock.client.WireMock.get; @@ -11,96 +20,86 @@ import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItems; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.github.fge.jsonschema.SchemaVersion; -import com.github.fge.jsonschema.cfg.ValidationConfiguration; -import com.github.fge.jsonschema.main.JsonSchemaFactory; -import com.github.tomakehurst.wiremock.WireMockServer; - public class RestAssuredIntegrationTest { + private static final int PORT = 8083; + private static WireMockServer wireMockServer = new WireMockServer(PORT); - private WireMockServer wireMockServer = new WireMockServer(); - private static final String EVENTS_PATH = "/events?id=390"; - private static final String APPLICATION_JSON = "application/json"; - private static final String GAME_ODDS = getEventJson(); + private static final String EVENTS_PATH = "/events?id=390"; + private static final String APPLICATION_JSON = "application/json"; + private static final String GAME_ODDS = getEventJson(); - @Before - public void before() throws Exception { - System.out.println("Setting up!"); - wireMockServer.start(); - configureFor("localhost", 8080); - stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( - aResponse().withStatus(200) - .withHeader("Content-Type", APPLICATION_JSON) - .withBody(GAME_ODDS))); - } + @BeforeClass + public static void before() throws Exception { + System.out.println("Setting up!"); + wireMockServer.start(); + RestAssured.port = PORT; + configureFor("localhost", PORT); + stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( + aResponse().withStatus(200) + .withHeader("Content-Type", APPLICATION_JSON) + .withBody(GAME_ODDS))); + } - @Test - public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() { - get("/events?id=390").then().assertThat() - .body("odd.ck", equalTo(12.2f)); - } + @Test + public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() { + get("/events?id=390").then().assertThat() + .body("odd.ck", equalTo(12.2f)); + } - @Test - public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() { + @Test + public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() { - get("/events?id=390").then().statusCode(200).assertThat() - .body("id", equalTo("390")); + get("/events?id=390").then().statusCode(200).assertThat() + .body("id", equalTo("390")); + } - } + @Test + public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() { + get("/events?id=390").then().assertThat() + .body("odds.price", hasItems("1.30", "5.25", "2.70", "1.20")); + } - @Test - public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() { - get("/events?id=390").then().assertThat() - .body("odds.price", hasItems("1.30", "5.25", "2.70", "1.20")); - } + @Test + public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() { - @Test - public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() { + get("/events?id=390").then().assertThat() + .body(matchesJsonSchemaInClasspath("event_0.json")); + } - get("/events?id=390").then().assertThat() - .body(matchesJsonSchemaInClasspath("event_0.json")); - } + @Test + public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() { + JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory + .newBuilder() + .setValidationConfiguration( + ValidationConfiguration.newBuilder() + .setDefaultVersion(SchemaVersion.DRAFTV4) + .freeze()).freeze(); - @Test - public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() { - JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory - .newBuilder() - .setValidationConfiguration( - ValidationConfiguration.newBuilder() - .setDefaultVersion(SchemaVersion.DRAFTV4) - .freeze()).freeze(); + get("/events?id=390") + .then() + .assertThat() + .body(matchesJsonSchemaInClasspath("event_0.json").using( + jsonSchemaFactory)); + } - get("/events?id=390") - .then() - .assertThat() - .body(matchesJsonSchemaInClasspath("event_0.json").using( - jsonSchemaFactory)); + @Test + public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() { - } + get("/events?id=390") + .then() + .assertThat() + .body(matchesJsonSchemaInClasspath("event_0.json").using( + settings().with().checkedValidation(false))); + } - @Test - public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() { - - get("/events?id=390") - .then() - .assertThat() - .body(matchesJsonSchemaInClasspath("event_0.json").using( - settings().with().checkedValidation(false))); - } - - @After - public void after() throws Exception { - System.out.println("Running: tearDown"); - wireMockServer.stop(); - } - - private static String getEventJson() { - return Util.inputStreamToString(RestAssuredIntegrationTest.class - .getResourceAsStream("/event_0.json")); - } + @AfterClass + public static void after() throws Exception { + System.out.println("Running: tearDown"); + wireMockServer.stop(); + } + private static String getEventJson() { + return Util.inputStreamToString(RestAssuredIntegrationTest.class + .getResourceAsStream("/event_0.json")); + } } diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java index b77f24b15f..4a29d8832f 100644 --- a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java +++ b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXML2IntegrationTest.java @@ -1,54 +1,55 @@ package com.baeldung.restassured; +import com.github.tomakehurst.wiremock.WireMockServer; +import io.restassured.RestAssured; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static io.restassured.RestAssured.get; import static org.hamcrest.Matchers.hasItems; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import static io.restassured.RestAssured.get; - -import com.github.tomakehurst.wiremock.WireMockServer; - public class RestAssuredXML2IntegrationTest { - private WireMockServer wireMockServer = new WireMockServer(); + private static final int PORT = 8082; + private static WireMockServer wireMockServer = new WireMockServer(PORT); - private static final String EVENTS_PATH = "/teachers"; - private static final String APPLICATION_XML = "application/xml"; - private static final String TEACHERS = getXml(); + private static final String EVENTS_PATH = "/teachers"; + private static final String APPLICATION_XML = "application/xml"; + private static final String TEACHERS = getXml(); - @Before - public void before() throws Exception { - System.out.println("Setting up!"); - wireMockServer.start(); - configureFor("localhost", 8080); - stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( - aResponse().withStatus(200) - .withHeader("Content-Type", APPLICATION_XML) - .withBody(TEACHERS))); - } - @Test - public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() { - get("/teachers") - .then() - .body("teachers.teacher.find { it.@department == 'science' }.subject", - hasItems("math", "physics")); - } - private static String getXml() { - - return Util - .inputStreamToString(new RestAssuredXML2IntegrationTest().getClass().getResourceAsStream("/teachers.xml")); - -} - @After -public void after() throws Exception { - System.out.println("Running: tearDown"); - wireMockServer.stop(); -} + @BeforeClass + public static void before() throws Exception { + System.out.println("Setting up!"); + wireMockServer.start(); + RestAssured.port = PORT; + configureFor("localhost", PORT); + stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn( + aResponse().withStatus(200) + .withHeader("Content-Type", APPLICATION_XML) + .withBody(TEACHERS))); + } + @Test + public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() { + get("/teachers") + .then() + .body("teachers.teacher.find { it.@department == 'science' }.subject", + hasItems("math", "physics")); + } + + private static String getXml() { + return Util.inputStreamToString(RestAssuredXML2IntegrationTest.class + .getResourceAsStream("/teachers.xml")); + } + + @AfterClass + public static void after() throws Exception { + System.out.println("Running: tearDown"); + wireMockServer.stop(); + } } diff --git a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java index 10aef63cdb..f1a22831f4 100644 --- a/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java +++ b/rest-assured/src/test/java/com/baeldung/restassured/RestAssuredXMLIntegrationTest.java @@ -1,99 +1,90 @@ package com.baeldung.restassured; +import com.github.tomakehurst.wiremock.WireMockServer; +import io.restassured.RestAssured; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; -import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static io.restassured.RestAssured.post; -import static io.restassured.RestAssured.get; -import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; -import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.xml.HasXPath.hasXPath; -import java.io.FileNotFoundException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.github.fge.jsonschema.SchemaVersion; -import com.github.fge.jsonschema.cfg.ValidationConfiguration; -import com.github.fge.jsonschema.main.JsonSchemaFactory; -import com.github.tomakehurst.wiremock.WireMockServer; public class RestAssuredXMLIntegrationTest { - private WireMockServer wireMockServer = new WireMockServer(); - private static final String EVENTS_PATH = "/employees"; - private static final String APPLICATION_XML = "application/xml"; - private static final String EMPLOYEES = getXml(); + private static final int PORT = 8081; + private static WireMockServer wireMockServer = new WireMockServer(PORT); - @Before - public void before() throws Exception { - System.out.println("Setting up!"); - wireMockServer.start(); - configureFor("localhost", 8080); - stubFor(post(urlEqualTo(EVENTS_PATH)).willReturn( - aResponse().withStatus(200) - .withHeader("Content-Type", APPLICATION_XML) - .withBody(EMPLOYEES))); - } - @Test - public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() { - post("/employees").then().assertThat() - .body("employees.employee.first-name", equalTo("Jane")); - } + private static final String EVENTS_PATH = "/employees"; + private static final String APPLICATION_XML = "application/xml"; + private static final String EMPLOYEES = getXml(); - @Test - public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() { - post("/employees").then().assertThat() - .body("employees.employee.first-name", equalTo("Jane")) - .body("employees.employee.last-name", equalTo("Daisy")) - .body("employees.employee.sex", equalTo("f")); - } + @BeforeClass + public static void before() throws Exception { + System.out.println("Setting up!"); + wireMockServer.start(); + configureFor("localhost", PORT); + RestAssured.port = PORT; + stubFor(post(urlEqualTo(EVENTS_PATH)).willReturn( + aResponse().withStatus(200) + .withHeader("Content-Type", APPLICATION_XML) + .withBody(EMPLOYEES))); + } - @Test - public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() { - post("/employees") - .then() - .assertThat() - .body("employees.employee.first-name", equalTo("Jane"), - "employees.employee.last-name", equalTo("Daisy"), - "employees.employee.sex", equalTo("f")); - } + @Test + public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() { + post("/employees").then().assertThat() + .body("employees.employee.first-name", equalTo("Jane")); + } - @Test - public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() { - post("/employees") - .then() - .assertThat() - .body(hasXPath("/employees/employee/first-name", - containsString("Ja"))); + @Test + public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() { + post("/employees").then().assertThat() + .body("employees.employee.first-name", equalTo("Jane")) + .body("employees.employee.last-name", equalTo("Daisy")) + .body("employees.employee.sex", equalTo("f")); + } - } + @Test + public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() { + post("/employees") + .then() + .assertThat() + .body("employees.employee.first-name", equalTo("Jane"), + "employees.employee.last-name", equalTo("Daisy"), + "employees.employee.sex", equalTo("f")); + } - @Test - public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() { - post("/employees") - .then() - .assertThat() - .body(hasXPath("/employees/employee/first-name[text()='Jane']")); + @Test + public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() { + post("/employees") + .then() + .assertThat() + .body(hasXPath("/employees/employee/first-name", + containsString("Ja"))); + } - } + @Test + public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() { + post("/employees") + .then() + .assertThat() + .body(hasXPath("/employees/employee/first-name[text()='Jane']")); + } + private static String getXml() { + return Util + .inputStreamToString(RestAssuredXMLIntegrationTest.class.getResourceAsStream("/employees.xml")); + } - private static String getXml() { - - return Util - .inputStreamToString(new RestAssuredXMLIntegrationTest().getClass().getResourceAsStream("/employees.xml")); - -} - @After -public void after() throws Exception { - System.out.println("Running: tearDown"); - wireMockServer.stop(); -} + @AfterClass + public static void after() throws Exception { + System.out.println("Running: tearDown"); + wireMockServer.stop(); + } } diff --git a/rest-assured/src/test/java/com/baeldung/restassured/Util.java b/rest-assured/src/test/java/com/baeldung/restassured/Util.java index c75c52eb34..02dec87927 100644 --- a/rest-assured/src/test/java/com/baeldung/restassured/Util.java +++ b/rest-assured/src/test/java/com/baeldung/restassured/Util.java @@ -1,36 +1,15 @@ package com.baeldung.restassured; -import java.io.BufferedReader; -import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; +import java.util.Scanner; -public class Util { - public static String inputStreamToString(InputStream is) { - BufferedReader br = null; - StringBuilder sb = new StringBuilder(); +final class Util { - String line; - try { + private Util() { + } - br = new BufferedReader(new InputStreamReader(is)); - while ((line = br.readLine()) != null) { - sb.append(line); - } - - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - return sb.toString(); - - } + static String inputStreamToString(InputStream is) { + Scanner s = new Scanner(is).useDelimiter("\\A"); + return s.hasNext() ? s.next() : ""; + } } diff --git a/rest-with-spark-java/README.md b/rest-with-spark-java/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/rest-with-spark-java/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/rmi/README.md b/rmi/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/rmi/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/rule-engines/README.md b/rule-engines/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/rule-engines/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/saas/README.md b/saas/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/saas/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/spring-cucumber/src/main/java/com/baeldung/BaeldungController.java b/spring-cucumber/src/main/java/com/baeldung/BaeldungController.java index 8e87ed3028..e74e773106 100644 --- a/spring-cucumber/src/main/java/com/baeldung/BaeldungController.java +++ b/spring-cucumber/src/main/java/com/baeldung/BaeldungController.java @@ -1,22 +1,21 @@ package com.baeldung; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; +import javax.servlet.http.HttpServletResponse; + @RestController public class BaeldungController { - @RequestMapping(method = { RequestMethod.GET }, value = { "/hello" }) + @GetMapping("/hello") public String sayHello(HttpServletResponse response) { return "hello"; } - @RequestMapping(method = { RequestMethod.POST }, value = { "/baeldung" }) + @PostMapping("/baeldung") public String sayHelloPost(HttpServletResponse response) { return "hello"; } - } diff --git a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java index 820e7e8004..ff9b12ad85 100644 --- a/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java +++ b/spring-cucumber/src/main/java/com/baeldung/SpringDemoApplication.java @@ -2,23 +2,16 @@ package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication -public class SpringDemoApplication extends SpringBootServletInitializer { +public class SpringDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringDemoApplication.class, args); } - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(SpringDemoApplication.class); - } - @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); diff --git a/spring-cucumber/src/main/resources/application.properties b/spring-cucumber/src/main/resources/application.properties index e69de29bb2..8d51d0c619 100644 --- a/spring-cucumber/src/main/resources/application.properties +++ b/spring-cucumber/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8082 \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/OtherDefsIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/OtherDefsIntegrationTest.java deleted file mode 100644 index 17f298c3fb..0000000000 --- a/spring-cucumber/src/test/java/com/baeldung/OtherDefsIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung; - -import cucumber.api.java.en.Given; -import cucumber.api.java.en.When; - -public class OtherDefsIntegrationTest extends SpringIntegrationTest { - @When("^the client calls /baeldung$") - public void the_client_issues_POST_hello() throws Throwable { - executePost("http://localhost:8080/baeldung"); - } - - @Given("^the client calls /hello$") - public void the_client_issues_GET_hello() throws Throwable { - executeGet("http://localhost:8080/hello"); - } -} \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/ResponseResults.java b/spring-cucumber/src/test/java/com/baeldung/ResponseResults.java index 4c0125e9b4..0f5bcbb824 100644 --- a/spring-cucumber/src/test/java/com/baeldung/ResponseResults.java +++ b/spring-cucumber/src/test/java/com/baeldung/ResponseResults.java @@ -11,23 +11,19 @@ public class ResponseResults { private final ClientHttpResponse theResponse; private final String body; - protected ResponseResults(final ClientHttpResponse response) throws IOException { + ResponseResults(final ClientHttpResponse response) throws IOException { this.theResponse = response; final InputStream bodyInputStream = response.getBody(); - if (null == bodyInputStream) { - this.body = "{}"; - } else { - final StringWriter stringWriter = new StringWriter(); - IOUtils.copy(bodyInputStream, stringWriter); - this.body = stringWriter.toString(); - } + final StringWriter stringWriter = new StringWriter(); + IOUtils.copy(bodyInputStream, stringWriter); + this.body = stringWriter.toString(); } - protected ClientHttpResponse getTheResponse() { + ClientHttpResponse getTheResponse() { return theResponse; } - protected String getBody() { + String getBody() { return body; } } \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java index 34efff63fb..9fbaeb348d 100644 --- a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java @@ -1,9 +1,5 @@ package com.baeldung; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationContextLoader; @@ -12,40 +8,39 @@ import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.ResponseErrorHandler; -import org.springframework.web.client.ResponseExtractor; import org.springframework.web.client.RestTemplate; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + //@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpringDemoApplication.class, loader = SpringApplicationContextLoader.class) @WebAppConfiguration @IntegrationTest public class SpringIntegrationTest { - protected static ResponseResults latestResponse = null; + static ResponseResults latestResponse = null; @Autowired protected RestTemplate restTemplate; - protected void executeGet(String url) throws IOException { + void executeGet(String url) throws IOException { final Map headers = new HashMap<>(); headers.put("Accept", "application/json"); final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers); final ResponseResultErrorHandler errorHandler = new ResponseResultErrorHandler(); restTemplate.setErrorHandler(errorHandler); - latestResponse = restTemplate.execute(url, HttpMethod.GET, requestCallback, new ResponseExtractor() { - @Override - public ResponseResults extractData(ClientHttpResponse response) throws IOException { - if (errorHandler.hadError) { - return (errorHandler.getResults()); - } else { - return (new ResponseResults(response)); - } + latestResponse = restTemplate.execute(url, HttpMethod.GET, requestCallback, response -> { + if (errorHandler.hadError) { + return (errorHandler.getResults()); + } else { + return (new ResponseResults(response)); } }); - } - protected void executePost(String url) throws IOException { + void executePost() throws IOException { final Map headers = new HashMap<>(); headers.put("Accept", "application/json"); final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers); @@ -56,17 +51,14 @@ public class SpringIntegrationTest { } restTemplate.setErrorHandler(errorHandler); - latestResponse = restTemplate.execute(url, HttpMethod.POST, requestCallback, new ResponseExtractor() { - @Override - public ResponseResults extractData(ClientHttpResponse response) throws IOException { - if (errorHandler.hadError) { - return (errorHandler.getResults()); - } else { - return (new ResponseResults(response)); - } - } - }); - + latestResponse = restTemplate + .execute("http://localhost:8082/baeldung", HttpMethod.POST, requestCallback, response -> { + if (errorHandler.hadError) { + return (errorHandler.getResults()); + } else { + return (new ResponseResults(response)); + } + }); } private class ResponseResultErrorHandler implements ResponseErrorHandler { diff --git a/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java index 8220d5e861..e1b6e370c7 100644 --- a/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java @@ -3,6 +3,7 @@ package com.baeldung; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; +import cucumber.api.java.en.Given; import org.springframework.http.HttpStatus; import cucumber.api.java.en.And; @@ -11,9 +12,19 @@ import cucumber.api.java.en.When; public class StepDefsIntegrationTest extends SpringIntegrationTest { + @When("^the client calls /baeldung$") + public void the_client_issues_POST_hello() throws Throwable { + executePost(); + } + + @Given("^the client calls /hello$") + public void the_client_issues_GET_hello() throws Throwable { + executeGet("http://localhost:8082/hello"); + } + @When("^the client calls /version$") public void the_client_issues_GET_version() throws Throwable { - executeGet("http://localhost:8080/version"); + executeGet("http://localhost:8082/version"); } @Then("^the client receives status code of (\\d+)$") diff --git a/spring-drools/README.md b/spring-drools/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/spring-drools/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/spring-groovy/README.md b/spring-groovy/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/spring-groovy/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/spring-hibernate5/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java b/spring-hibernate5/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java index b8cc3dc1a6..d6ecdb29d6 100644 --- a/spring-hibernate5/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java +++ b/spring-hibernate5/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java @@ -23,11 +23,8 @@ public class HibernateImmutableIntegrationTest { @Before public void before() { - session = HibernateUtil.getSessionFactory().getCurrentSession(); + session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); - createEvent(); - createEventGenerated(); - session.setCacheMode(CacheMode.REFRESH); } @BeforeClass @@ -40,8 +37,6 @@ public class HibernateImmutableIntegrationTest { HibernateUtil.getSessionFactory().close(); } - // - @Test public void addEvent() { Event event = new Event(); @@ -49,15 +44,18 @@ public class HibernateImmutableIntegrationTest { event.setTitle("Public Event"); session.save(event); session.getTransaction().commit(); + session.close(); } @Test public void updateEvent() { + createEvent(); Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0); event.setTitle("Private Event"); session.update(event); session.flush(); session.refresh(event); + session.close(); assertThat(event.getTitle(), equalTo("New Event")); assertThat(event.getId(), equalTo(5L)); @@ -65,13 +63,16 @@ public class HibernateImmutableIntegrationTest { @Test public void deleteEvent() { + createEvent(); Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0); session.delete(event); session.getTransaction().commit(); + session.close(); } @Test public void addGuest() { + createEvent(); Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0); String newGuest = "Sara"; event.getGuestList().add(newGuest); @@ -79,6 +80,7 @@ public class HibernateImmutableIntegrationTest { exception.expect(PersistenceException.class); session.save(event); session.getTransaction().commit(); + session.close(); } @Test @@ -94,18 +96,18 @@ public class HibernateImmutableIntegrationTest { @Test public void updateEventGenerated() { + createEventGenerated(); EventGeneratedId eventGeneratedId = (EventGeneratedId) session.createQuery("FROM EventGeneratedId WHERE name LIKE '%John%'").list().get(0); eventGeneratedId.setName("Mike"); session.update(eventGeneratedId); session.flush(); session.refresh(eventGeneratedId); + session.close(); assertThat(eventGeneratedId.getName(), equalTo("John")); assertThat(eventGeneratedId.getId(), equalTo(1L)); } - // - private static void createEvent() { Event event = new Event(5L, "New Event", Sets.newHashSet("guest")); session.save(event); diff --git a/spring-mustache/README.md b/spring-mustache/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/spring-mustache/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/spring-mybatis/README.md b/spring-mybatis/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/spring-mybatis/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/spring-rest-simple/README.md b/spring-rest-simple/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/spring-rest-simple/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/vaadin/README.md b/vaadin/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/vaadin/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/video-tutorials/README.md b/video-tutorials/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/video-tutorials/README.md @@ -0,0 +1 @@ +## Relevant articles: