From 4771252f6bb4f6064b27e6b1b5862088f61f1b5b Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sat, 4 Feb 2017 17:22:28 +0100 Subject: [PATCH 01/21] AppTest -> AppLiveTest --- .../intro/{AppTest.java => AppLiveTest.java} | 76 +++++++++---------- 1 file changed, 38 insertions(+), 38 deletions(-) rename spring-boot/src/test/java/com/baeldung/intro/{AppTest.java => AppLiveTest.java} (95%) diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java similarity index 95% rename from spring-boot/src/test/java/com/baeldung/intro/AppTest.java rename to spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java index 749fe68838..772709dc30 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -1,39 +1,39 @@ -package com.baeldung.intro; - -import static org.hamcrest.Matchers.equalTo; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -public class AppTest { - - @Autowired - private MockMvc mvc; - - @Test - public void getIndex() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) - .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"))); - } - +package com.baeldung.intro; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import static org.hamcrest.Matchers.equalTo; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class AppLiveTest { + + @Autowired + private MockMvc mvc; + + @Test + public void getIndex() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) + .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"))); + } + } \ No newline at end of file From 93c704cbf7ede95fc7e9b6b582217e315d5837a6 Mon Sep 17 00:00:00 2001 From: Andrew Morgan Date: Sat, 4 Feb 2017 16:18:17 +0000 Subject: [PATCH 02/21] mesos marathon demo --- mesos-marathon/Dockerfile | 4 ++ mesos-marathon/dockerise.sh | 5 ++ mesos-marathon/marathon.json | 14 ++++++ mesos-marathon/pom.xml | 46 +++++++++++++++++++ .../java/com/mogronalol/DemoApplication.java | 14 ++++++ .../java/com/mogronalol/HelloController.java | 17 +++++++ .../src/main/resources/application.properties | 1 + .../com/mogronalol/DemoApplicationTests.java | 34 ++++++++++++++ pom.xml | 1 + 9 files changed, 136 insertions(+) create mode 100644 mesos-marathon/Dockerfile create mode 100644 mesos-marathon/dockerise.sh create mode 100644 mesos-marathon/marathon.json create mode 100644 mesos-marathon/pom.xml create mode 100644 mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java create mode 100644 mesos-marathon/src/main/java/com/mogronalol/HelloController.java create mode 100644 mesos-marathon/src/main/resources/application.properties create mode 100644 mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java diff --git a/mesos-marathon/Dockerfile b/mesos-marathon/Dockerfile new file mode 100644 index 0000000000..9f92f7fa6a --- /dev/null +++ b/mesos-marathon/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:8-jre-alpine +ADD build/libs/demo-0.0.1-SNAPSHOT.jar app.jar +EXPOSE 8082 +ENTRYPOINT ["java","-jar","/app.jar"] \ No newline at end of file diff --git a/mesos-marathon/dockerise.sh b/mesos-marathon/dockerise.sh new file mode 100644 index 0000000000..85b8554b52 --- /dev/null +++ b/mesos-marathon/dockerise.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -e +docker login -u mogronalol -p $DOCKER_PASSWORD +docker build -t mogronalol/mesos-marathon-demo:$BUILD_NUMBER . +docker push mogronalol/mesos-marathon-demo:$BUILD_NUMBER diff --git a/mesos-marathon/marathon.json b/mesos-marathon/marathon.json new file mode 100644 index 0000000000..6471259e92 --- /dev/null +++ b/mesos-marathon/marathon.json @@ -0,0 +1,14 @@ +{ + "id": "mesos-marathon-demo", + "container": { + "type": "DOCKER", + "docker": { + "image": "", + "network": "BRIDGE", + "portMappings": [ + { "containerPort": 8082, "hostPort": 0 } + ] + }, + "volumes": [] + } +} \ No newline at end of file diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml new file mode 100644 index 0000000000..ca17a5c4c4 --- /dev/null +++ b/mesos-marathon/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + com.baeldung + mesos-marathon + 0.0.1-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.5.1.RELEASE + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 1.5.1.RELEASE + + + + repackage + + + + + + + + \ No newline at end of file diff --git a/mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java b/mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java new file mode 100644 index 0000000000..f757178026 --- /dev/null +++ b/mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java @@ -0,0 +1,14 @@ +package com.mogronalol; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } +} diff --git a/mesos-marathon/src/main/java/com/mogronalol/HelloController.java b/mesos-marathon/src/main/java/com/mogronalol/HelloController.java new file mode 100644 index 0000000000..2059280ba0 --- /dev/null +++ b/mesos-marathon/src/main/java/com/mogronalol/HelloController.java @@ -0,0 +1,17 @@ +package com.mogronalol; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController(value = "/") +public class HelloController { + + @GetMapping + @ResponseBody + public String getMapping() { + return "Hello world"; + } + +} diff --git a/mesos-marathon/src/main/resources/application.properties b/mesos-marathon/src/main/resources/application.properties new file mode 100644 index 0000000000..8d51d0c619 --- /dev/null +++ b/mesos-marathon/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8082 \ No newline at end of file diff --git a/mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java b/mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java new file mode 100644 index 0000000000..5e88f9a70f --- /dev/null +++ b/mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java @@ -0,0 +1,34 @@ +package com.mogronalol; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.client.RestTemplate; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = {DemoApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class DemoApplicationTests { + + private RestTemplate restTemplate; + + @LocalServerPort + private int port; + + @Before + public void setUp() { + restTemplate = new RestTemplate(); + } + + @Test + public void contextLoads() { + final String result = restTemplate.getForObject("http://localhost:" + port + "/", String.class); + assertThat(result).isEqualTo("Hello world"); + } + +} diff --git a/pom.xml b/pom.xml index 41235dcc26..a17b8fc9ce 100644 --- a/pom.xml +++ b/pom.xml @@ -79,6 +79,7 @@ mapstruct metrics + mesos-marathon mockito mocks From ad104bfe8cf5c9790b78deda2984d278addf659f Mon Sep 17 00:00:00 2001 From: Andrew Morgan Date: Sat, 4 Feb 2017 17:21:41 +0000 Subject: [PATCH 03/21] Revert "mesos marathon demo" This reverts commit 93c704cbf7ede95fc7e9b6b582217e315d5837a6. --- mesos-marathon/Dockerfile | 4 -- mesos-marathon/dockerise.sh | 5 -- mesos-marathon/marathon.json | 14 ------ mesos-marathon/pom.xml | 46 ------------------- .../java/com/mogronalol/DemoApplication.java | 14 ------ .../java/com/mogronalol/HelloController.java | 17 ------- .../src/main/resources/application.properties | 1 - .../com/mogronalol/DemoApplicationTests.java | 34 -------------- pom.xml | 1 - 9 files changed, 136 deletions(-) delete mode 100644 mesos-marathon/Dockerfile delete mode 100644 mesos-marathon/dockerise.sh delete mode 100644 mesos-marathon/marathon.json delete mode 100644 mesos-marathon/pom.xml delete mode 100644 mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java delete mode 100644 mesos-marathon/src/main/java/com/mogronalol/HelloController.java delete mode 100644 mesos-marathon/src/main/resources/application.properties delete mode 100644 mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java diff --git a/mesos-marathon/Dockerfile b/mesos-marathon/Dockerfile deleted file mode 100644 index 9f92f7fa6a..0000000000 --- a/mesos-marathon/Dockerfile +++ /dev/null @@ -1,4 +0,0 @@ -FROM openjdk:8-jre-alpine -ADD build/libs/demo-0.0.1-SNAPSHOT.jar app.jar -EXPOSE 8082 -ENTRYPOINT ["java","-jar","/app.jar"] \ No newline at end of file diff --git a/mesos-marathon/dockerise.sh b/mesos-marathon/dockerise.sh deleted file mode 100644 index 85b8554b52..0000000000 --- a/mesos-marathon/dockerise.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash -set -e -docker login -u mogronalol -p $DOCKER_PASSWORD -docker build -t mogronalol/mesos-marathon-demo:$BUILD_NUMBER . -docker push mogronalol/mesos-marathon-demo:$BUILD_NUMBER diff --git a/mesos-marathon/marathon.json b/mesos-marathon/marathon.json deleted file mode 100644 index 6471259e92..0000000000 --- a/mesos-marathon/marathon.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "id": "mesos-marathon-demo", - "container": { - "type": "DOCKER", - "docker": { - "image": "", - "network": "BRIDGE", - "portMappings": [ - { "containerPort": 8082, "hostPort": 0 } - ] - }, - "volumes": [] - } -} \ No newline at end of file diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml deleted file mode 100644 index ca17a5c4c4..0000000000 --- a/mesos-marathon/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - 4.0.0 - - com.baeldung - mesos-marathon - 0.0.1-SNAPSHOT - - - org.springframework.boot - spring-boot-starter-parent - 1.5.1.RELEASE - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - 1.5.1.RELEASE - - - - repackage - - - - - - - - \ No newline at end of file diff --git a/mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java b/mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java deleted file mode 100644 index f757178026..0000000000 --- a/mesos-marathon/src/main/java/com/mogronalol/DemoApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.mogronalol; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -import javax.annotation.PostConstruct; - -@SpringBootApplication -public class DemoApplication { - - public static void main(String[] args) { - SpringApplication.run(DemoApplication.class, args); - } -} diff --git a/mesos-marathon/src/main/java/com/mogronalol/HelloController.java b/mesos-marathon/src/main/java/com/mogronalol/HelloController.java deleted file mode 100644 index 2059280ba0..0000000000 --- a/mesos-marathon/src/main/java/com/mogronalol/HelloController.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.mogronalol; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -@RestController(value = "/") -public class HelloController { - - @GetMapping - @ResponseBody - public String getMapping() { - return "Hello world"; - } - -} diff --git a/mesos-marathon/src/main/resources/application.properties b/mesos-marathon/src/main/resources/application.properties deleted file mode 100644 index 8d51d0c619..0000000000 --- a/mesos-marathon/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -server.port=8082 \ No newline at end of file diff --git a/mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java b/mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java deleted file mode 100644 index 5e88f9a70f..0000000000 --- a/mesos-marathon/src/test/java/com/mogronalol/DemoApplicationTests.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.mogronalol; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.context.embedded.LocalServerPort; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.client.RestTemplate; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = {DemoApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class DemoApplicationTests { - - private RestTemplate restTemplate; - - @LocalServerPort - private int port; - - @Before - public void setUp() { - restTemplate = new RestTemplate(); - } - - @Test - public void contextLoads() { - final String result = restTemplate.getForObject("http://localhost:" + port + "/", String.class); - assertThat(result).isEqualTo("Hello world"); - } - -} diff --git a/pom.xml b/pom.xml index a17b8fc9ce..41235dcc26 100644 --- a/pom.xml +++ b/pom.xml @@ -79,7 +79,6 @@ mapstruct metrics - mesos-marathon mockito mocks From ffd17c1b21071a912624792a6de2ccca2bbdf2d0 Mon Sep 17 00:00:00 2001 From: maibin Date: Sat, 4 Feb 2017 18:47:30 +0100 Subject: [PATCH 04/21] Fix the Hibernate4 issues (#1106) * Binary genetic algorithm * Fix the junit tests conflict --- .../com/baeldung/algorithms/RunAlgorithm.java | 44 ++++--- .../algorithms/ga/binary/Individual.java | 44 +++++++ .../algorithms/ga/binary/Population.java | 40 ++++++ .../ga/binary/SimpleGeneticAlgorithm.java | 119 +++++++++++++++++ .../BinaryGeneticAlgorithmTest.java | 16 +++ spring-hibernate4/.gitignore | 3 +- .../HibernateOneToManyAnnotationMainTest.java | 124 +++++++++--------- 7 files changed, 308 insertions(+), 82 deletions(-) create mode 100644 core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java create mode 100644 core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java create mode 100644 core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java create mode 100644 core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmTest.java diff --git a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java index 113ac1cc53..6d696dd272 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java +++ b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java @@ -3,28 +3,34 @@ package com.baeldung.algorithms; import java.util.Scanner; import com.baeldung.algorithms.annealing.SimulatedAnnealing; +import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; import com.baeldung.algorithms.slope_one.SlopeOne; public class RunAlgorithm { - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - System.out.println("Run algorithm:"); - System.out.println("1 - Simulated Annealing"); - System.out.println("2 - Slope One"); - int decision = in.nextInt(); - switch (decision) { - case 1: - System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); - break; - case 2: - SlopeOne.slopeOne(3); - break; - default: - System.out.println("Unknown option"); - break; - } - in.close(); - } + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + System.out.println("Run algorithm:"); + System.out.println("1 - Simulated Annealing"); + System.out.println("2 - Slope One"); + System.out.println("3 - Simple Genetic Algorithm"); + int decision = in.nextInt(); + switch (decision) { + case 1: + System.out.println( + "Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); + break; + case 2: + SlopeOne.slopeOne(3); + break; + case 3: + SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"); + break; + default: + System.out.println("Unknown option"); + break; + } + in.close(); + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java new file mode 100644 index 0000000000..e9b6c8f66a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java @@ -0,0 +1,44 @@ +package com.baeldung.algorithms.ga.binary; + +import lombok.Data; + +@Data +public class Individual { + + protected int defaultGeneLength = 64; + private byte[] genes = new byte[defaultGeneLength]; + private int fitness = 0; + + public Individual() { + for (int i = 0; i < genes.length; i++) { + byte gene = (byte) Math.round(Math.random()); + genes[i] = gene; + } + } + + protected byte getSingleGene(int index) { + return genes[index]; + } + + protected void setSingleGene(int index, byte value) { + genes[index] = value; + fitness = 0; + } + + public int getFitness() { + if (fitness == 0) { + fitness = SimpleGeneticAlgorithm.getFitness(this); + } + return fitness; + } + + @Override + public String toString() { + String geneString = ""; + for (int i = 0; i < genes.length; i++) { + geneString += getSingleGene(i); + } + return geneString; + } + +} diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java new file mode 100644 index 0000000000..dbd1e04e0f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java @@ -0,0 +1,40 @@ +package com.baeldung.algorithms.ga.binary; + +import java.util.ArrayList; +import java.util.List; + +import lombok.Data; + +@Data +public class Population { + + private List individuals; + + public Population(int size, boolean createNew) { + individuals = new ArrayList<>(); + if (createNew) { + createNewPopulation(size); + } + } + + protected Individual getIndividual(int index) { + return individuals.get(index); + } + + protected Individual getFittest() { + Individual fittest = individuals.get(0); + for (int i = 0; i < individuals.size(); i++) { + if (fittest.getFitness() <= getIndividual(i).getFitness()) { + fittest = getIndividual(i); + } + } + return fittest; + } + + private void createNewPopulation(int size) { + for (int i = 0; i < size; i++) { + Individual newIndividual = new Individual(); + individuals.add(i, newIndividual); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java new file mode 100644 index 0000000000..0f640e676a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java @@ -0,0 +1,119 @@ +package com.baeldung.algorithms.ga.binary; + +import lombok.Data; + +@Data +public class SimpleGeneticAlgorithm { + + private static final double uniformRate = 0.5; + private static final double mutationRate = 0.025; + private static final int tournamentSize = 5; + private static final boolean elitism = true; + private static byte[] solution = new byte[64]; + + public static boolean runAlgorithm(int populationSize, String solution) { + if (solution.length() != SimpleGeneticAlgorithm.solution.length) { + throw new RuntimeException( + "The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes"); + } + SimpleGeneticAlgorithm.setSolution(solution); + Population myPop = new Population(populationSize, true); + + int generationCount = 1; + while (myPop.getFittest().getFitness() < SimpleGeneticAlgorithm.getMaxFitness()) { + System.out.println( + "Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness()); + myPop = SimpleGeneticAlgorithm.evolvePopulation(myPop); + generationCount++; + } + System.out.println("Solution found!"); + System.out.println("Generation: " + generationCount); + System.out.println("Genes: "); + System.out.println(myPop.getFittest()); + return true; + } + + public static Population evolvePopulation(Population pop) { + int elitismOffset; + Population newPopulation = new Population(pop.getIndividuals().size(), false); + + if (elitism) { + newPopulation.getIndividuals().add(0, pop.getFittest()); + elitismOffset = 1; + } else { + elitismOffset = 0; + } + + for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) { + Individual indiv1 = tournamentSelection(pop); + Individual indiv2 = tournamentSelection(pop); + Individual newIndiv = crossover(indiv1, indiv2); + newPopulation.getIndividuals().add(i, newIndiv); + } + + for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) { + mutate(newPopulation.getIndividual(i)); + } + + return newPopulation; + } + + private static Individual crossover(Individual indiv1, Individual indiv2) { + Individual newSol = new Individual(); + for (int i = 0; i < newSol.getDefaultGeneLength(); i++) { + if (Math.random() <= uniformRate) { + newSol.setSingleGene(i, indiv1.getSingleGene(i)); + } else { + newSol.setSingleGene(i, indiv2.getSingleGene(i)); + } + } + return newSol; + } + + private static void mutate(Individual indiv) { + for (int i = 0; i < indiv.getDefaultGeneLength(); i++) { + if (Math.random() <= mutationRate) { + byte gene = (byte) Math.round(Math.random()); + indiv.setSingleGene(i, gene); + } + } + } + + private static Individual tournamentSelection(Population pop) { + Population tournament = new Population(tournamentSize, false); + for (int i = 0; i < tournamentSize; i++) { + int randomId = (int) (Math.random() * pop.getIndividuals().size()); + tournament.getIndividuals().add(i, pop.getIndividual(randomId)); + } + Individual fittest = tournament.getFittest(); + return fittest; + } + + protected static int getFitness(Individual individual) { + int fitness = 0; + for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) { + if (individual.getSingleGene(i) == solution[i]) { + fitness++; + } + } + return fitness; + } + + protected static int getMaxFitness() { + int maxFitness = solution.length; + return maxFitness; + } + + protected static void setSolution(String newSolution) { + solution = new byte[newSolution.length()]; + for (int i = 0; i < newSolution.length(); i++) { + String character = newSolution.substring(i, i + 1); + if (character.contains("0") || character.contains("1")) { + solution[i] = Byte.parseByte(character); + } else { + solution[i] = 0; + } + } + } + +} diff --git a/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmTest.java b/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmTest.java new file mode 100644 index 0000000000..8a16311dfb --- /dev/null +++ b/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmTest.java @@ -0,0 +1,16 @@ +package com.baeldung.algorithms; + +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; + +public class BinaryGeneticAlgorithmTest { + + @Test + public void testGA() { + Assert.assertTrue(SimpleGeneticAlgorithm.runAlgorithm(50, + "1011000100000100010000100000100111001000000100000100000000001111")); + } + +} diff --git a/spring-hibernate4/.gitignore b/spring-hibernate4/.gitignore index 83c05e60c8..478cca6dac 100644 --- a/spring-hibernate4/.gitignore +++ b/spring-hibernate4/.gitignore @@ -10,4 +10,5 @@ # Packaged files # *.jar *.war -*.ear \ No newline at end of file +*.ear +/target/ diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainTest.java index 10a89cdf14..688329e329 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainTest.java @@ -1,4 +1,3 @@ - package com.baeldung.hibernate.oneToMany.main; import static org.junit.Assert.assertNotNull; @@ -13,85 +12,86 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.dialect.HSQLDialect; import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; - import com.baeldung.hibernate.oneToMany.model.Cart; import com.baeldung.hibernate.oneToMany.model.Items; -//@RunWith(SpringJUnit4ClassRunner.class) public class HibernateOneToManyAnnotationMainTest { - private static SessionFactory sessionFactory; + private static SessionFactory sessionFactory; - private Session session; + private Session session; - public HibernateOneToManyAnnotationMainTest() { - } + public HibernateOneToManyAnnotationMainTest() { + } - @BeforeClass - public static void beforeTests() { - Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()).setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa") - .setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update"); - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); - sessionFactory = configuration.buildSessionFactory(serviceRegistry); - } + @BeforeClass + public static void beforeTests() { + Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class) + .setProperty("hibernate.dialect", HSQLDialect.class.getName()) + .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test") + .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "") + .setProperty("hibernate.hbm2ddl.auto", "update"); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(configuration.getProperties()).build(); + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + } - @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } - } + @Test + public void givenSession_checkIfDatabaseIsEmpty() { + Cart cart = (Cart) session.get(Cart.class, new Long(1)); + assertNull(cart); - @Test - public void givenSession_checkIfDatabaseIsEmpty() { - Cart cart = (Cart) session.get(Cart.class, new Long(1)); - assertNull(cart); + } - } + @Test + public void givenSession_checkIfDatabaseIsPopulated_afterCommit() { + Cart cart = new Cart(); + Set cartItems = new HashSet<>(); + cartItems = cart.getItems(); + Assert.assertNull(cartItems); + Items item1 = new Items(); + item1.setItemId("I10"); + item1.setItemTotal(10); + item1.setQuantity(1); + item1.setCart(cart); + assertNotNull(item1); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + assertNotNull(itemsSet); + cart.setItems(itemsSet); + assertNotNull(cart); + session.persist(cart); + session.getTransaction().commit(); + session.close(); - @Test - public void testAddItemsToCart() { - Cart cart = new Cart(); - Set cartItems = new HashSet<>(); - cartItems = cart.getItems(); - Assert.assertNull(cartItems); - Items item1 = new Items("I10", 10, 1, cart); - assertNotNull(item1); - Set itemsSet = new HashSet(); - cart.setItems(itemsSet); - assertNotNull(cart); - System.out.println("Items added to cart"); + session = sessionFactory.openSession(); + session.beginTransaction(); + cart = (Cart) session.get(Cart.class, new Long(1)); + assertNotNull(cart); + } - } + @After + public void tearDown() { + session.getTransaction().commit(); + session.close(); + } - @Test - public void givenSession_checkIfDatabaseIsPopulated_afterCommit() { - Cart cart = new Cart(); - Set cartItems = new HashSet<>(); - cartItems = cart.getItems(); - Assert.assertNull(cartItems); - Items item1 = new Items(); - item1.setItemId("I10"); - item1.setItemTotal(10); - item1.setQuantity(1); - item1.setCart(cart); - assertNotNull(item1); - Set itemsSet = new HashSet(); - itemsSet.add(item1); - assertNotNull(itemsSet); - cart.setItems(itemsSet); - assertNotNull(cart); - session.persist(cart); - session.getTransaction().commit(); - cart = (Cart) session.get(Cart.class, new Long(1)); - assertNotNull(cart); - session.close(); - - } + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } } From 791142c67e2f38b4eade3f82a6442253365f6625 Mon Sep 17 00:00:00 2001 From: eugenp Date: Sat, 4 Feb 2017 21:56:11 +0200 Subject: [PATCH 05/21] cleanup and testing work --- .../com/baeldung/algorithms/RunAlgorithm.java | 47 +++-- .../algorithms/ga/binary/Individual.java | 60 +++--- .../algorithms/ga/binary/Population.java | 50 ++--- .../ga/binary/SimpleGeneticAlgorithm.java | 192 +++++++++--------- .../concurrent/future/SquareCalculator.java | 2 +- .../baeldung/CharArrayToStringUnitTest.java | 44 ++-- .../baeldung/StringToCharArrayUnitTest.java | 14 +- .../BinaryGeneticAlgorithmTest.java | 16 -- .../BinaryGeneticAlgorithmUnitTest.java | 15 ++ .../PriorityBlockingQueueUnitTest.java | 15 +- .../ConcurrentNavigableMapTests.java | 4 +- .../ThreadPoolInParallelStreamTest.java | 23 +-- log-mdc/pom.xml | 4 +- ... ExternalPropertiesWithXmlManualTest.java} | 2 +- ...t.java => SpringRetryIntegrationTest.java} | 2 +- ...readPoolTaskSchedulerIntegrationTest.java} | 3 +- .../baeldung/test/IntegrationTestSuite.java | 4 +- ...BeanNameMappingConfigIntegrationTest.java} | 2 +- ...assNameHandlerMappingIntegrationTest.java} | 2 +- ...rMappingDefaultConfigIntegrationTest.java} | 14 +- ...MappingPriorityConfigIntegrationTest.java} | 2 +- ...impleUrlMappingConfigIntegrationTest.java} | 2 +- 22 files changed, 256 insertions(+), 263 deletions(-) delete mode 100644 core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmTest.java create mode 100644 core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java rename spring-all/src/test/java/org/baeldung/properties/external/{ExternalPropertiesWithXmlIntegrationTest.java => ExternalPropertiesWithXmlManualTest.java} (95%) rename spring-all/src/test/java/org/baeldung/springretry/{SpringRetryTest.java => SpringRetryIntegrationTest.java} (96%) rename spring-all/src/test/java/org/baeldung/taskscheduler/{ThreadPoolTaskSchedulerTest.java => ThreadPoolTaskSchedulerIntegrationTest.java} (90%) rename spring-mvc-java/src/test/java/com/baeldung/handlermappings/{BeanNameMappingConfigTest.java => BeanNameMappingConfigIntegrationTest.java} (96%) rename spring-mvc-java/src/test/java/com/baeldung/handlermappings/{ControllerClassNameHandlerMappingTest.java => ControllerClassNameHandlerMappingIntegrationTest.java} (96%) rename spring-mvc-java/src/test/java/com/baeldung/handlermappings/{HandlerMappingDefaultConfigTest.java => HandlerMappingDefaultConfigIntegrationTest.java} (93%) rename spring-mvc-java/src/test/java/com/baeldung/handlermappings/{HandlerMappingPriorityConfigTest.java => HandlerMappingPriorityConfigIntegrationTest.java} (96%) rename spring-mvc-java/src/test/java/com/baeldung/handlermappings/{SimpleUrlMappingConfigTest.java => SimpleUrlMappingConfigIntegrationTest.java} (96%) diff --git a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java index 6d696dd272..476e873f90 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java +++ b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java @@ -8,29 +8,28 @@ import com.baeldung.algorithms.slope_one.SlopeOne; public class RunAlgorithm { - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - System.out.println("Run algorithm:"); - System.out.println("1 - Simulated Annealing"); - System.out.println("2 - Slope One"); - System.out.println("3 - Simple Genetic Algorithm"); - int decision = in.nextInt(); - switch (decision) { - case 1: - System.out.println( - "Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); - break; - case 2: - SlopeOne.slopeOne(3); - break; - case 3: - SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"); - break; - default: - System.out.println("Unknown option"); - break; - } - in.close(); - } + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + System.out.println("Run algorithm:"); + System.out.println("1 - Simulated Annealing"); + System.out.println("2 - Slope One"); + System.out.println("3 - Simple Genetic Algorithm"); + int decision = in.nextInt(); + switch (decision) { + case 1: + System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); + break; + case 2: + SlopeOne.slopeOne(3); + break; + case 3: + SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"); + break; + default: + System.out.println("Unknown option"); + break; + } + in.close(); + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java index e9b6c8f66a..2a740777f3 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java @@ -5,40 +5,40 @@ import lombok.Data; @Data public class Individual { - protected int defaultGeneLength = 64; - private byte[] genes = new byte[defaultGeneLength]; - private int fitness = 0; + protected int defaultGeneLength = 64; + private byte[] genes = new byte[defaultGeneLength]; + private int fitness = 0; - public Individual() { - for (int i = 0; i < genes.length; i++) { - byte gene = (byte) Math.round(Math.random()); - genes[i] = gene; - } - } + public Individual() { + for (int i = 0; i < genes.length; i++) { + byte gene = (byte) Math.round(Math.random()); + genes[i] = gene; + } + } - protected byte getSingleGene(int index) { - return genes[index]; - } + protected byte getSingleGene(int index) { + return genes[index]; + } - protected void setSingleGene(int index, byte value) { - genes[index] = value; - fitness = 0; - } + protected void setSingleGene(int index, byte value) { + genes[index] = value; + fitness = 0; + } - public int getFitness() { - if (fitness == 0) { - fitness = SimpleGeneticAlgorithm.getFitness(this); - } - return fitness; - } + public int getFitness() { + if (fitness == 0) { + fitness = SimpleGeneticAlgorithm.getFitness(this); + } + return fitness; + } - @Override - public String toString() { - String geneString = ""; - for (int i = 0; i < genes.length; i++) { - geneString += getSingleGene(i); - } - return geneString; - } + @Override + public String toString() { + String geneString = ""; + for (int i = 0; i < genes.length; i++) { + geneString += getSingleGene(i); + } + return geneString; + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java index dbd1e04e0f..47677d7d88 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java @@ -8,33 +8,33 @@ import lombok.Data; @Data public class Population { - private List individuals; + private List individuals; - public Population(int size, boolean createNew) { - individuals = new ArrayList<>(); - if (createNew) { - createNewPopulation(size); - } - } + public Population(int size, boolean createNew) { + individuals = new ArrayList<>(); + if (createNew) { + createNewPopulation(size); + } + } - protected Individual getIndividual(int index) { - return individuals.get(index); - } + protected Individual getIndividual(int index) { + return individuals.get(index); + } - protected Individual getFittest() { - Individual fittest = individuals.get(0); - for (int i = 0; i < individuals.size(); i++) { - if (fittest.getFitness() <= getIndividual(i).getFitness()) { - fittest = getIndividual(i); - } - } - return fittest; - } + protected Individual getFittest() { + Individual fittest = individuals.get(0); + for (int i = 0; i < individuals.size(); i++) { + if (fittest.getFitness() <= getIndividual(i).getFitness()) { + fittest = getIndividual(i); + } + } + return fittest; + } - private void createNewPopulation(int size) { - for (int i = 0; i < size; i++) { - Individual newIndividual = new Individual(); - individuals.add(i, newIndividual); - } - } + private void createNewPopulation(int size) { + for (int i = 0; i < size; i++) { + Individual newIndividual = new Individual(); + individuals.add(i, newIndividual); + } + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java index 0f640e676a..c7e2a6b381 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java @@ -5,115 +5,113 @@ import lombok.Data; @Data public class SimpleGeneticAlgorithm { - private static final double uniformRate = 0.5; - private static final double mutationRate = 0.025; - private static final int tournamentSize = 5; - private static final boolean elitism = true; - private static byte[] solution = new byte[64]; + private static final double uniformRate = 0.5; + private static final double mutationRate = 0.025; + private static final int tournamentSize = 5; + private static final boolean elitism = true; + private static byte[] solution = new byte[64]; - public static boolean runAlgorithm(int populationSize, String solution) { - if (solution.length() != SimpleGeneticAlgorithm.solution.length) { - throw new RuntimeException( - "The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes"); - } - SimpleGeneticAlgorithm.setSolution(solution); - Population myPop = new Population(populationSize, true); + public static boolean runAlgorithm(int populationSize, String solution) { + if (solution.length() != SimpleGeneticAlgorithm.solution.length) { + throw new RuntimeException("The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes"); + } + SimpleGeneticAlgorithm.setSolution(solution); + Population myPop = new Population(populationSize, true); - int generationCount = 1; - while (myPop.getFittest().getFitness() < SimpleGeneticAlgorithm.getMaxFitness()) { - System.out.println( - "Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness()); - myPop = SimpleGeneticAlgorithm.evolvePopulation(myPop); - generationCount++; - } - System.out.println("Solution found!"); - System.out.println("Generation: " + generationCount); - System.out.println("Genes: "); - System.out.println(myPop.getFittest()); - return true; - } + int generationCount = 1; + while (myPop.getFittest().getFitness() < SimpleGeneticAlgorithm.getMaxFitness()) { + System.out.println("Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness()); + myPop = SimpleGeneticAlgorithm.evolvePopulation(myPop); + generationCount++; + } + System.out.println("Solution found!"); + System.out.println("Generation: " + generationCount); + System.out.println("Genes: "); + System.out.println(myPop.getFittest()); + return true; + } - public static Population evolvePopulation(Population pop) { - int elitismOffset; - Population newPopulation = new Population(pop.getIndividuals().size(), false); + public static Population evolvePopulation(Population pop) { + int elitismOffset; + Population newPopulation = new Population(pop.getIndividuals().size(), false); - if (elitism) { - newPopulation.getIndividuals().add(0, pop.getFittest()); - elitismOffset = 1; - } else { - elitismOffset = 0; - } + if (elitism) { + newPopulation.getIndividuals().add(0, pop.getFittest()); + elitismOffset = 1; + } else { + elitismOffset = 0; + } - for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) { - Individual indiv1 = tournamentSelection(pop); - Individual indiv2 = tournamentSelection(pop); - Individual newIndiv = crossover(indiv1, indiv2); - newPopulation.getIndividuals().add(i, newIndiv); - } + for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) { + Individual indiv1 = tournamentSelection(pop); + Individual indiv2 = tournamentSelection(pop); + Individual newIndiv = crossover(indiv1, indiv2); + newPopulation.getIndividuals().add(i, newIndiv); + } - for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) { - mutate(newPopulation.getIndividual(i)); - } + for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) { + mutate(newPopulation.getIndividual(i)); + } - return newPopulation; - } + return newPopulation; + } - private static Individual crossover(Individual indiv1, Individual indiv2) { - Individual newSol = new Individual(); - for (int i = 0; i < newSol.getDefaultGeneLength(); i++) { - if (Math.random() <= uniformRate) { - newSol.setSingleGene(i, indiv1.getSingleGene(i)); - } else { - newSol.setSingleGene(i, indiv2.getSingleGene(i)); - } - } - return newSol; - } + private static Individual crossover(Individual indiv1, Individual indiv2) { + Individual newSol = new Individual(); + for (int i = 0; i < newSol.getDefaultGeneLength(); i++) { + if (Math.random() <= uniformRate) { + newSol.setSingleGene(i, indiv1.getSingleGene(i)); + } else { + newSol.setSingleGene(i, indiv2.getSingleGene(i)); + } + } + return newSol; + } - private static void mutate(Individual indiv) { - for (int i = 0; i < indiv.getDefaultGeneLength(); i++) { - if (Math.random() <= mutationRate) { - byte gene = (byte) Math.round(Math.random()); - indiv.setSingleGene(i, gene); - } - } - } + private static void mutate(Individual indiv) { + for (int i = 0; i < indiv.getDefaultGeneLength(); i++) { + if (Math.random() <= mutationRate) { + byte gene = (byte) Math.round(Math.random()); + indiv.setSingleGene(i, gene); + } + } + } - private static Individual tournamentSelection(Population pop) { - Population tournament = new Population(tournamentSize, false); - for (int i = 0; i < tournamentSize; i++) { - int randomId = (int) (Math.random() * pop.getIndividuals().size()); - tournament.getIndividuals().add(i, pop.getIndividual(randomId)); - } - Individual fittest = tournament.getFittest(); - return fittest; - } + private static Individual tournamentSelection(Population pop) { + Population tournament = new Population(tournamentSize, false); + for (int i = 0; i < tournamentSize; i++) { + int randomId = (int) (Math.random() * pop.getIndividuals().size()); + tournament.getIndividuals().add(i, pop.getIndividual(randomId)); + } + Individual fittest = tournament.getFittest(); + return fittest; + } - protected static int getFitness(Individual individual) { - int fitness = 0; - for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) { - if (individual.getSingleGene(i) == solution[i]) { - fitness++; - } - } - return fitness; - } + protected static int getFitness(Individual individual) { + int fitness = 0; + for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) { + if (individual.getSingleGene(i) == solution[i]) { + fitness++; + } + } + return fitness; + } - protected static int getMaxFitness() { - int maxFitness = solution.length; - return maxFitness; - } + protected static int getMaxFitness() { + int maxFitness = solution.length; + return maxFitness; + } - protected static void setSolution(String newSolution) { - solution = new byte[newSolution.length()]; - for (int i = 0; i < newSolution.length(); i++) { - String character = newSolution.substring(i, i + 1); - if (character.contains("0") || character.contains("1")) { - solution[i] = Byte.parseByte(character); - } else { - solution[i] = 0; - } - } - } + protected static void setSolution(String newSolution) { + solution = new byte[newSolution.length()]; + for (int i = 0; i < newSolution.length(); i++) { + String character = newSolution.substring(i, i + 1); + if (character.contains("0") || character.contains("1")) { + solution[i] = Byte.parseByte(character); + } else { + solution[i] = 0; + } + } + } } diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java index e53a2413d1..bcd559dd3b 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java +++ b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java @@ -15,6 +15,6 @@ public class SquareCalculator { return executor.submit(() -> { Thread.sleep(1000); return input * input; - }); + }); } } diff --git a/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java b/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java index 2f7830bbf4..3488f8b390 100644 --- a/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java +++ b/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java @@ -8,55 +8,55 @@ public class CharArrayToStringUnitTest { @Test public void givenCharArray_whenCallingStringConstructor_shouldConvertToString() { - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = new String(charArray); String expectedValue = "character"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = new String(charArray, 4, 3); String expectedValue = "act"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = String.copyValueOf(charArray); String expectedValue = "character"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = String.copyValueOf(charArray, 0, 4); String expectedValue = "char"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringValueOf_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringValueOf_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = String.valueOf(charArray); String expectedValue = "character"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = String.valueOf(charArray, 3, 4); String expectedValue = "ract"; - + assertEquals(expectedValue, result); } } diff --git a/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java b/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java index 2e7dc24a17..cd996e58e2 100644 --- a/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java +++ b/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java @@ -6,15 +6,15 @@ import org.junit.Test; public class StringToCharArrayUnitTest { -@Test -public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() { - String givenString = "characters"; + @Test + public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() { + String givenString = "characters"; - char[] result = givenString.toCharArray(); + char[] result = givenString.toCharArray(); - char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' }; + char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' }; - assertArrayEquals(expectedCharArray, result); -} + assertArrayEquals(expectedCharArray, result); + } } diff --git a/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmTest.java b/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmTest.java deleted file mode 100644 index 8a16311dfb..0000000000 --- a/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.algorithms; - -import org.junit.Assert; -import org.junit.Test; - -import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; - -public class BinaryGeneticAlgorithmTest { - - @Test - public void testGA() { - Assert.assertTrue(SimpleGeneticAlgorithm.runAlgorithm(50, - "1011000100000100010000100000100111001000000100000100000000001111")); - } - -} diff --git a/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java b/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java new file mode 100644 index 0000000000..6b720898eb --- /dev/null +++ b/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.algorithms; + +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; + +public class BinaryGeneticAlgorithmUnitTest { + + @Test + public void testGA() { + Assert.assertTrue(SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111")); + } + +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java index 5e6855e18a..0272726465 100644 --- a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java +++ b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java @@ -32,13 +32,14 @@ public class PriorityBlockingQueueUnitTest { PriorityBlockingQueue queue = new PriorityBlockingQueue<>(); final Thread thread = new Thread(() -> { - System.out.println("Polling..."); - while (true) { - try { - Integer poll = queue.take(); - System.out.println("Polled: " + poll); - } catch (InterruptedException e) {} - } + System.out.println("Polling..."); + while (true) { + try { + Integer poll = queue.take(); + System.out.println("Polled: " + poll); + } catch (InterruptedException e) { + } + } }); thread.start(); diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java index 93087626a4..96a8a6bac3 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java @@ -18,9 +18,7 @@ public class ConcurrentNavigableMapTests { updateMapConcurrently(skipListMap, 4); - Iterator skipListIter = skipListMap - .keySet() - .iterator(); + Iterator skipListIter = skipListMap.keySet().iterator(); int previous = skipListIter.next(); while (skipListIter.hasNext()) { int current = skipListIter.next(); diff --git a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java index 5fd3fa4cb0..c2eb1cff5d 100644 --- a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java +++ b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java @@ -1,5 +1,5 @@ package org.baeldung.java.streams; - + import org.junit.Test; import java.util.ArrayList; @@ -14,28 +14,25 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ThreadPoolInParallelStreamTest { - + @Test - public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() - throws InterruptedException, ExecutionException { + public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException { long firstNum = 1; long lastNum = 1_000_000; - List aList = LongStream.rangeClosed(firstNum, lastNum).boxed() - .collect(Collectors.toList()); + List aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList()); ForkJoinPool customThreadPool = new ForkJoinPool(4); - long actualTotal = customThreadPool.submit(() -> aList.parallelStream() - .reduce(0L, Long::sum)).get(); - - assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); + long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get(); + + assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); } - + @Test - public void givenList_whenCallingParallelStream_shouldBeParallelStream(){ + public void givenList_whenCallingParallelStream_shouldBeParallelStream() { List aList = new ArrayList<>(); Stream parallelStream = aList.parallelStream(); - + assertTrue(parallelStream.isParallel()); } } diff --git a/log-mdc/pom.xml b/log-mdc/pom.xml index 28c8bb820e..931e68a178 100644 --- a/log-mdc/pom.xml +++ b/log-mdc/pom.xml @@ -2,9 +2,9 @@ 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 - logmdc + log-mdc 0.0.1-SNAPSHOT - logmdc + log-mdc war tutorial on logging with MDC and NDC diff --git a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java similarity index 95% rename from spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java rename to spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java index 2ea2822b9a..a8a7bda91c 100644 --- a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { ExternalPropertiesWithXmlConfig.class }, loader = AnnotationConfigContextLoader.class) @Ignore("manual only") -public class ExternalPropertiesWithXmlIntegrationTest { +public class ExternalPropertiesWithXmlManualTest { @Autowired private Environment env; diff --git a/spring-all/src/test/java/org/baeldung/springretry/SpringRetryTest.java b/spring-all/src/test/java/org/baeldung/springretry/SpringRetryIntegrationTest.java similarity index 96% rename from spring-all/src/test/java/org/baeldung/springretry/SpringRetryTest.java rename to spring-all/src/test/java/org/baeldung/springretry/SpringRetryIntegrationTest.java index 2f3411957e..d7d0943e6b 100644 --- a/spring-all/src/test/java/org/baeldung/springretry/SpringRetryTest.java +++ b/spring-all/src/test/java/org/baeldung/springretry/SpringRetryIntegrationTest.java @@ -12,7 +12,7 @@ import java.sql.SQLException; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class) -public class SpringRetryTest { +public class SpringRetryIntegrationTest { @Autowired private MyService myService; diff --git a/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerTest.java b/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerIntegrationTest.java similarity index 90% rename from spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerTest.java rename to spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerIntegrationTest.java index cc247cb384..d95857d384 100644 --- a/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerTest.java +++ b/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerIntegrationTest.java @@ -8,7 +8,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { ThreadPoolTaskSchedulerConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ThreadPoolTaskSchedulerTest { +public class ThreadPoolTaskSchedulerIntegrationTest { + @Test public void testThreadPoolTaskSchedulerAnnotation() throws InterruptedException { Thread.sleep(2550); diff --git a/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java b/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java index f9845f42a7..470ae9e538 100644 --- a/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java +++ b/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java @@ -5,7 +5,7 @@ import org.baeldung.properties.basic.PropertiesWithMultipleXmlsIntegrationTest; import org.baeldung.properties.basic.PropertiesWithXmlIntegrationTest; import org.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest; import org.baeldung.properties.external.ExternalPropertiesWithMultipleXmlsIntegrationTest; -import org.baeldung.properties.external.ExternalPropertiesWithXmlIntegrationTest; +import org.baeldung.properties.external.ExternalPropertiesWithXmlManualTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -15,7 +15,7 @@ import org.junit.runners.Suite.SuiteClasses; PropertiesWithXmlIntegrationTest.class, ExternalPropertiesWithJavaIntegrationTest.class, ExternalPropertiesWithMultipleXmlsIntegrationTest.class, - ExternalPropertiesWithXmlIntegrationTest.class, + ExternalPropertiesWithXmlManualTest.class, ExtendedPropertiesWithJavaIntegrationTest.class, PropertiesWithMultipleXmlsIntegrationTest.class, })// @formatter:on diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java similarity index 96% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java index f58e5cb0a1..f2c2c05f29 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java @@ -22,7 +22,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = BeanNameUrlHandlerMappingConfig.class) -public class BeanNameMappingConfigTest { +public class BeanNameMappingConfigIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java similarity index 96% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java index 6fdd168d0b..b84998470d 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java @@ -22,7 +22,7 @@ import com.baeldung.config.ControllerClassNameHandlerMappingConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = ControllerClassNameHandlerMappingConfig.class) -public class ControllerClassNameHandlerMappingTest { +public class ControllerClassNameHandlerMappingIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java similarity index 93% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java index 01be65b829..cb89c01fed 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java @@ -1,7 +1,10 @@ package com.baeldung.handlermappings; -import com.baeldung.config.HandlerMappingDefaultConfig; -import com.baeldung.config.HandlerMappingPrioritiesConfig; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,15 +17,12 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; +import com.baeldung.config.HandlerMappingDefaultConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = HandlerMappingDefaultConfig.class) -public class HandlerMappingDefaultConfigTest { +public class HandlerMappingDefaultConfigIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java similarity index 96% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java index d6329ca6c1..55007aec28 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java @@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = HandlerMappingPrioritiesConfig.class) -public class HandlerMappingPriorityConfigTest { +public class HandlerMappingPriorityConfigIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java similarity index 96% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java index 636339f152..ad35307330 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java @@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = SimpleUrlHandlerMappingConfig.class) -public class SimpleUrlMappingConfigTest { +public class SimpleUrlMappingConfigIntegrationTest { @Autowired private WebApplicationContext webAppContext; From b57cf0cf56b256f8fd27f009c50ace23082c0beb Mon Sep 17 00:00:00 2001 From: Abhinab Kanrar Date: Sun, 5 Feb 2017 02:46:35 +0530 Subject: [PATCH 06/21] spring requestmapping shortcuts (#1096) * rest with spark java * 4 * Update Application.java * indentation changes * spring @requestmapping shortcuts * removing spring requestmapping and pushing spring-mvc-java --- .../main/java/com/baeldung/Application.java | 7 +- .../RequestMappingShortcutsController.java | 47 ++++++++++ .../RequestMapingShortcutsUnitTest.java | 92 +++++++++++++++++++ 3 files changed, 143 insertions(+), 3 deletions(-) create mode 100644 spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java create mode 100644 spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsUnitTest.java diff --git a/spring-mobile/src/main/java/com/baeldung/Application.java b/spring-mobile/src/main/java/com/baeldung/Application.java index d384ab09b3..7275477b8d 100644 --- a/spring-mobile/src/main/java/com/baeldung/Application.java +++ b/spring-mobile/src/main/java/com/baeldung/Application.java @@ -6,9 +6,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java new file mode 100644 index 0000000000..5d4cbe9d78 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java @@ -0,0 +1,47 @@ +package com.baeldung.web.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RequestMappingShortcutsController { + + @GetMapping("/get") + public @ResponseBody ResponseEntity get() { + return new ResponseEntity("GET Response", HttpStatus.OK); + } + + @GetMapping("/get/{id}") + public @ResponseBody ResponseEntity getById(@PathVariable String id) { + return new ResponseEntity("GET Response : " + id, HttpStatus.OK); + } + + @PostMapping("/post") + public @ResponseBody ResponseEntity post() { + return new ResponseEntity("POST Response", HttpStatus.OK); + } + + @PutMapping("/put") + public @ResponseBody ResponseEntity put() { + return new ResponseEntity("PUT Response", HttpStatus.OK); + } + + @DeleteMapping("/delete") + public @ResponseBody ResponseEntity delete() { + return new ResponseEntity("DELETE Response", HttpStatus.OK); + } + + @PatchMapping("/patch") + public @ResponseBody ResponseEntity patch() { + return new ResponseEntity("PATCH Response", HttpStatus.OK); + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsUnitTest.java new file mode 100644 index 0000000000..d02a7140b5 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.web.controller; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +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.ResultMatcher; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.spring.web.config.WebConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = WebConfig.class) +public class RequestMapingShortcutsUnitTest { + + @Autowired + private WebApplicationContext ctx; + + private MockMvc mockMvc; + + @Before + public void setup () { + DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.ctx); + this.mockMvc = builder.build(); + } + + @Test + public void giventUrl_whenGetRequest_thenFindGetResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/get"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("GET Response"); + + this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); + + } + + @Test + public void giventUrl_whenPostRequest_thenFindPostResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/post"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("POST Response"); + + this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); + + } + + @Test + public void giventUrl_whenPutRequest_thenFindPutResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put("/put"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PUT Response"); + + this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); + + } + + @Test + public void giventUrl_whenDeleteRequest_thenFindDeleteResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete("/delete"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("DELETE Response"); + + this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); + + } + + @Test + public void giventUrl_whenPatchRequest_thenFindPatchResponse() throws Exception { + + MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch("/patch"); + + ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PATCH Response"); + + this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk()); + + } + +} From c7203bd564f840f528d5146035f2877b613e742a Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Wed, 25 Jan 2017 23:06:22 +0100 Subject: [PATCH 07/21] BAEL-614 base module for cache-control --- spring-security-cache-control/pom.xml | 49 +++++++++++++++++++ .../cachecontrol/ResourceEndpoint.java | 35 +++++++++++++ .../baeldung/cachecontrol/app/AppRunner.java | 12 +++++ .../config/SpringSecurityConfig.java | 22 +++++++++ .../cachecontrol/config/WebConfiguration.java | 21 ++++++++ .../cachecontrol/model/TimestampDto.java | 10 ++++ .../baeldung/cachecontrol/model/UserDto.java | 11 +++++ 7 files changed, 160 insertions(+) create mode 100644 spring-security-cache-control/pom.xml create mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java create mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java create mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java create mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java create mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/TimestampDto.java create mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/UserDto.java diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml new file mode 100644 index 0000000000..787804e3fe --- /dev/null +++ b/spring-security-cache-control/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + com.baeldung + spring-security-cache-control + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.security + spring-security-core + + + org.springframework.security + spring-security-config + + + org.springframework.security + spring-security-web + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + + + 3.1.0 + + + \ No newline at end of file diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java new file mode 100644 index 0000000000..7a9860922c --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -0,0 +1,35 @@ +package com.baeldung.cachecontrol; + + +import com.baeldung.cachecontrol.model.TimestampDto; +import com.baeldung.cachecontrol.model.UserDto; +import org.springframework.http.CacheControl; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.concurrent.TimeUnit; + +@RestController +public class ResourceEndpoint { + + @RequestMapping(value = "/users/{name}", method = RequestMethod.GET) + public ResponseEntity getUser(@PathVariable(value = "name") String name) { + return ResponseEntity.ok() + .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)) + .body(new UserDto(name)); + } + + + @RequestMapping(value = "/timestamp", method = RequestMethod.GET) + public ResponseEntity getServerTimestamp() { + return ResponseEntity.ok() + .cacheControl(CacheControl.noStore()) + .cacheControl(CacheControl.noCache()) + .body(new TimestampDto(LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli())); + } +} diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java new file mode 100644 index 0000000000..1da69f40ec --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java @@ -0,0 +1,12 @@ +package com.baeldung.cachecontrol.app; + + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AppRunner { + public static void main(String[] args) { + SpringApplication.run(AppRunner.class, args); + } +} \ No newline at end of file diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java new file mode 100644 index 0000000000..789d2132f3 --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java @@ -0,0 +1,22 @@ +package com.baeldung.cachecontrol.config; + + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .anyRequest().permitAll() + .and().headers() + .defaultsDisabled() + .cacheControl(); + } +} diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java new file mode 100644 index 0000000000..decc57ec8b --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java @@ -0,0 +1,21 @@ +package com.baeldung.cachecontrol.config; + +import org.springframework.http.CacheControl; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import java.util.concurrent.TimeUnit; + +@EnableWebMvc +public class WebConfiguration extends WebMvcConfigurerAdapter { + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry + .addResourceHandler("/resources/**") + .addResourceLocations("/resources/") + .setCacheControl(CacheControl.maxAge(24, TimeUnit.HOURS)); + + } +} + diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/TimestampDto.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/TimestampDto.java new file mode 100644 index 0000000000..cb3befacac --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/TimestampDto.java @@ -0,0 +1,10 @@ +package com.baeldung.cachecontrol.model; + + +public class TimestampDto { + public final Long timestamp; + + public TimestampDto(Long timestamp) { + this.timestamp = timestamp; + } +} diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/UserDto.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/UserDto.java new file mode 100644 index 0000000000..a41cb31d80 --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/UserDto.java @@ -0,0 +1,11 @@ +package com.baeldung.cachecontrol.model; + + +public class UserDto { + public final String name; + + public UserDto(String name) { + this.name = name; + } + +} From 3fa1b93f87ebf1fe0222aeb388e122ded13aad25 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Thu, 26 Jan 2017 18:56:42 +0100 Subject: [PATCH 08/21] BAEL-614 appRunner in proper place --- .../java/com/baeldung/cachecontrol/{app => }/AppRunner.java | 2 +- .../main/java/com/baeldung/cachecontrol/ResourceEndpoint.java | 4 ++-- .../baeldung/cachecontrol/config/SpringSecurityConfig.java | 2 ++ 3 files changed, 5 insertions(+), 3 deletions(-) rename spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/{app => }/AppRunner.java (87%) diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/AppRunner.java similarity index 87% rename from spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java rename to spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/AppRunner.java index 1da69f40ec..28ff90a570 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/app/AppRunner.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/AppRunner.java @@ -1,4 +1,4 @@ -package com.baeldung.cachecontrol.app; +package com.baeldung.cachecontrol; import org.springframework.boot.SpringApplication; diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java index 7a9860922c..34128e64fa 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -5,16 +5,16 @@ import com.baeldung.cachecontrol.model.TimestampDto; import com.baeldung.cachecontrol.model.UserDto; import org.springframework.http.CacheControl; import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.concurrent.TimeUnit; -@RestController +@Controller public class ResourceEndpoint { @RequestMapping(value = "/users/{name}", method = RequestMethod.GET) diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java index 789d2132f3..bd6d1a4aa1 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java @@ -2,12 +2,14 @@ package com.baeldung.cachecontrol.config; import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override From 4bac6e057165e891f2e9aad057d86f6e1aa72ca8 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Thu, 26 Jan 2017 20:16:31 +0100 Subject: [PATCH 09/21] BAEL-614 endpoint that has default cache-control headers --- .../cachecontrol/ResourceEndpoint.java | 6 ++++++ .../cachecontrol/config/WebConfiguration.java | 21 ------------------- 2 files changed, 6 insertions(+), 21 deletions(-) delete mode 100644 spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java index 34128e64fa..86f9747e1c 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -32,4 +32,10 @@ public class ResourceEndpoint { .cacheControl(CacheControl.noCache()) .body(new TimestampDto(LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli())); } + + @RequestMapping(value = "/private/users/{name}", method = RequestMethod.GET) + public ResponseEntity getUserNotCached(@PathVariable("name") String name) { + return ResponseEntity.ok() + .body(new UserDto(name)); + } } diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java deleted file mode 100644 index decc57ec8b..0000000000 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/WebConfiguration.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.cachecontrol.config; - -import org.springframework.http.CacheControl; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -import java.util.concurrent.TimeUnit; - -@EnableWebMvc -public class WebConfiguration extends WebMvcConfigurerAdapter { - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry - .addResourceHandler("/resources/**") - .addResourceLocations("/resources/") - .setCacheControl(CacheControl.maxAge(24, TimeUnit.HOURS)); - - } -} - From 25111c5b893090f65306af5797883c23ab206cef Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Thu, 26 Jan 2017 20:18:23 +0100 Subject: [PATCH 10/21] BAEL-542 use defaults --- .../baeldung/cachecontrol/config/SpringSecurityConfig.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java index bd6d1a4aa1..fbb6399c22 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java @@ -14,10 +14,7 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .anyRequest().permitAll() - .and().headers() + http.headers() .defaultsDisabled() .cacheControl(); } From c3cc42f458e92afcad3a906513a1358f5ca8fb32 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Thu, 26 Jan 2017 20:34:40 +0100 Subject: [PATCH 11/21] BAEL-542 wrote live tests --- spring-security-cache-control/pom.xml | 35 ++++++++++++++ .../cachecontrol/ResourceEndpointTest.java | 47 +++++++++++++++++++ .../com/baeldung/cachecontrol/TestConfig.java | 11 +++++ 3 files changed, 93 insertions(+) create mode 100644 spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java create mode 100644 spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml index 787804e3fe..1d154f333d 100644 --- a/spring-security-cache-control/pom.xml +++ b/spring-security-cache-control/pom.xml @@ -40,10 +40,45 @@ javax.servlet-api ${javax.servlet-api.version} + + + junit + junit + test + + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + + org.mockito + mockito-core + test + + + + org.springframework + spring-test + + + + com.jayway.restassured + rest-assured + ${rest-assured.version} + 3.1.0 + 2.9.0 \ No newline at end of file diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java new file mode 100644 index 0000000000..d0a15efb2b --- /dev/null +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java @@ -0,0 +1,47 @@ +package com.baeldung.cachecontrol; + +import com.jayway.restassured.http.ContentType; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import static com.jayway.restassured.RestAssured.given; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +public class ResourceEndpointTest { + private static final String URL_PREFIX = "http://localhost:8080"; + + @Test + public void givenServiceEndpoint_whenGetRequestForUser_shouldResponseWithCacheControlMaxAge() { + given() + .when() + .get(URL_PREFIX + "/users/Michael") + .then() + .contentType(ContentType.JSON).and().statusCode(200).and() + .header("Cache-Control", "max-age=60"); + } + + @Test + public void givenServiceEndpoint_whenGetRequestForNotCacheableContent_shouldResponseWithCacheControlNoCache() { + given() + .when() + .get(URL_PREFIX + "/timestamp") + .then() + .contentType(ContentType.JSON).and().statusCode(200).and() + .header("Cache-Control", "no-cache"); + } + + @Test + public void givenServiceEndpoint_whenGetRequestForPrivateUser_shouldResponseWithSecurityDefaultCacheControl() { + given() + .when() + .get(URL_PREFIX + "/private/users/Michael") + .then() + .contentType(ContentType.JSON).and().statusCode(200).and() + .header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); + } + +} \ No newline at end of file diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java new file mode 100644 index 0000000000..af393f4b98 --- /dev/null +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java @@ -0,0 +1,11 @@ +package com.baeldung.cachecontrol; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + + +@Configuration +@ComponentScan({ "com.baeldung" }) +public class TestConfig { + +} From cc70eae896402d889040758824230e37e88bf5cb Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Thu, 26 Jan 2017 21:47:52 +0100 Subject: [PATCH 12/21] BAEL-542 test fix --- .../cachecontrol/ResourceEndpoint.java | 1 - .../cachecontrol/ResourceEndpointTest.java | 20 +++++++++---------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java index 86f9747e1c..f1c9786c68 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -29,7 +29,6 @@ public class ResourceEndpoint { public ResponseEntity getServerTimestamp() { return ResponseEntity.ok() .cacheControl(CacheControl.noStore()) - .cacheControl(CacheControl.noCache()) .body(new TimestampDto(LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli())); } diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java index d0a15efb2b..e85dd11667 100644 --- a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java @@ -14,15 +14,15 @@ import static com.jayway.restassured.RestAssured.given; public class ResourceEndpointTest { private static final String URL_PREFIX = "http://localhost:8080"; - @Test - public void givenServiceEndpoint_whenGetRequestForUser_shouldResponseWithCacheControlMaxAge() { - given() - .when() - .get(URL_PREFIX + "/users/Michael") - .then() - .contentType(ContentType.JSON).and().statusCode(200).and() - .header("Cache-Control", "max-age=60"); - } + @Test + public void givenServiceEndpoint_whenGetRequestForUser_shouldResponseWithCacheControlMaxAge() { + given() + .when() + .get(URL_PREFIX + "/users/Michael") + .then() + .contentType(ContentType.JSON).and().statusCode(200).and() + .header("Cache-Control", "max-age=60"); + } @Test public void givenServiceEndpoint_whenGetRequestForNotCacheableContent_shouldResponseWithCacheControlNoCache() { @@ -31,7 +31,7 @@ public class ResourceEndpointTest { .get(URL_PREFIX + "/timestamp") .then() .contentType(ContentType.JSON).and().statusCode(200).and() - .header("Cache-Control", "no-cache"); + .header("Cache-Control", "no-store"); } @Test From c8f6bed73d1eb778298f70bfb4e898e86056cc38 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sat, 4 Feb 2017 18:02:28 +0100 Subject: [PATCH 13/21] BAEL-542 rename test to LiveTest suffix --- ...{ResourceEndpointTest.java => ResourceEndpointLiveTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/{ResourceEndpointTest.java => ResourceEndpointLiveTest.java} (97%) diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java similarity index 97% rename from spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java rename to spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java index e85dd11667..f6e95779cb 100644 --- a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java @@ -11,7 +11,7 @@ import static com.jayway.restassured.RestAssured.given; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) -public class ResourceEndpointTest { +public class ResourceEndpointLiveTest { private static final String URL_PREFIX = "http://localhost:8080"; @Test From 652def889a147bbfe59d757fb13817d15d953ac0 Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sat, 4 Feb 2017 20:44:16 +0100 Subject: [PATCH 14/21] BAEL-542 start application properly when integation test started --- pom.xml | 1 + spring-security-cache-control/pom.xml | 4 ++++ .../baeldung/cachecontrol/ResourceEndpointLiveTest.java | 9 ++++----- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index 41235dcc26..a24e3d4667 100644 --- a/pom.xml +++ b/pom.xml @@ -147,6 +147,7 @@ spring-rest-docs spring-rest spring-security-basic-auth + spring-security-cache-control spring-security-client/spring-security-jsp-authentication spring-security-client/spring-security-jsp-authorize spring-security-client/spring-security-jsp-config diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml index 1d154f333d..c30b0cd1aa 100644 --- a/spring-security-cache-control/pom.xml +++ b/spring-security-cache-control/pom.xml @@ -35,6 +35,10 @@ org.springframework.security spring-security-web + + org.springframework.boot + spring-boot-starter-test + javax.servlet javax.servlet-api diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java index f6e95779cb..0c23b1969d 100644 --- a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java @@ -3,14 +3,13 @@ package com.baeldung.cachecontrol; import com.jayway.restassured.http.ContentType; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import static com.jayway.restassured.RestAssured.given; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = AppRunner.class) public class ResourceEndpointLiveTest { private static final String URL_PREFIX = "http://localhost:8080"; From c9394b216ae01d23917735a140c11226f43bcace Mon Sep 17 00:00:00 2001 From: Tomasz Lelek Date: Sat, 4 Feb 2017 20:45:53 +0100 Subject: [PATCH 15/21] BAEL-542 do not need TestConfig class --- .../java/com/baeldung/cachecontrol/TestConfig.java | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java deleted file mode 100644 index af393f4b98..0000000000 --- a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/TestConfig.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.cachecontrol; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - - -@Configuration -@ComponentScan({ "com.baeldung" }) -public class TestConfig { - -} From 3f81460e90f0ec4408ca1e9beb4a9b54aea6d8e9 Mon Sep 17 00:00:00 2001 From: Andrew Morgan Date: Sat, 4 Feb 2017 23:46:53 +0000 Subject: [PATCH 16/21] Added extra endpoint for default caching --- .../cachecontrol/ResourceEndpoint.java | 6 +++- .../config/SpringSecurityConfig.java | 6 +--- .../ResourceEndpointLiveTest.java | 36 ++++++++++++++++--- 3 files changed, 37 insertions(+), 11 deletions(-) diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java index f1c9786c68..9f756b5ab4 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -17,6 +17,11 @@ import java.util.concurrent.TimeUnit; @Controller public class ResourceEndpoint { + @RequestMapping(value = "/default/users/{name}", method = RequestMethod.GET) + public ResponseEntity getUserWithDefaultCaching(@PathVariable(value = "name") String name) { + return ResponseEntity.ok(new UserDto(name)); + } + @RequestMapping(value = "/users/{name}", method = RequestMethod.GET) public ResponseEntity getUser(@PathVariable(value = "name") String name) { return ResponseEntity.ok() @@ -24,7 +29,6 @@ public class ResourceEndpoint { .body(new UserDto(name)); } - @RequestMapping(value = "/timestamp", method = RequestMethod.GET) public ResponseEntity getServerTimestamp() { return ResponseEntity.ok() diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java index fbb6399c22..b4127e9b71 100644 --- a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java @@ -13,9 +13,5 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override - protected void configure(HttpSecurity http) throws Exception { - http.headers() - .defaultsDisabled() - .cacheControl(); - } + protected void configure(HttpSecurity http) throws Exception {} } diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java index 0c23b1969d..94b6052ba4 100644 --- a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java @@ -3,21 +3,43 @@ package com.baeldung.cachecontrol; import com.jayway.restassured.http.ContentType; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static com.jayway.restassured.RestAssured.given; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = AppRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AppRunner.class) public class ResourceEndpointLiveTest { - private static final String URL_PREFIX = "http://localhost:8080"; + + @LocalServerPort + private int serverPort; + + @Test + public void whenGetRequestForUser_shouldRespondWithDefaultCacheHeaders() { + given() + .when() + .get(getBaseUrl() + "/default/users/Michael") + .then() + .headers("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate") + .header("Pragma", "no-cache"); + } + + @Test + public void whenGetRequestForUser_shouldRespondMaxAgeCacheControl() { + given() + .when() + .get(getBaseUrl() + "/users/Michael") + .then() + .header("Cache-Control", "max-age=60"); + } @Test public void givenServiceEndpoint_whenGetRequestForUser_shouldResponseWithCacheControlMaxAge() { given() .when() - .get(URL_PREFIX + "/users/Michael") + .get(getBaseUrl() + "/users/Michael") .then() .contentType(ContentType.JSON).and().statusCode(200).and() .header("Cache-Control", "max-age=60"); @@ -27,7 +49,7 @@ public class ResourceEndpointLiveTest { public void givenServiceEndpoint_whenGetRequestForNotCacheableContent_shouldResponseWithCacheControlNoCache() { given() .when() - .get(URL_PREFIX + "/timestamp") + .get(getBaseUrl() + "/timestamp") .then() .contentType(ContentType.JSON).and().statusCode(200).and() .header("Cache-Control", "no-store"); @@ -37,10 +59,14 @@ public class ResourceEndpointLiveTest { public void givenServiceEndpoint_whenGetRequestForPrivateUser_shouldResponseWithSecurityDefaultCacheControl() { given() .when() - .get(URL_PREFIX + "/private/users/Michael") + .get(getBaseUrl() + "/private/users/Michael") .then() .contentType(ContentType.JSON).and().statusCode(200).and() .header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); } + private String getBaseUrl() { + return "http://localhost:" + serverPort; + } + } \ No newline at end of file From 10eb6bfcc0ebaceae2b803bd6cbfc7ef77250fa1 Mon Sep 17 00:00:00 2001 From: lor6 Date: Sun, 5 Feb 2017 03:03:00 +0200 Subject: [PATCH 17/21] helper classes for excel processing, tests (#1093) * helper classes for excel processing, tests * fix imports * list declaration --- apache-poi/pom.xml | 16 ++ .../com/baeldung/jexcel/JExcelHelper.java | 79 ++++++++++ .../baeldung/poi/excel/ExcelPOIHelper.java | 137 ++++++++++++++++++ .../java/com/baeldung/jexcel/JExcelTest.java | 62 ++++++++ .../com/baeldung/poi/excel/ExcelTest.java | 59 ++++++++ 5 files changed, 353 insertions(+) create mode 100644 apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java create mode 100644 apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java create mode 100644 apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java create mode 100644 apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml index d94b2e2ad1..1b97248ab2 100644 --- a/apache-poi/pom.xml +++ b/apache-poi/pom.xml @@ -9,6 +9,7 @@ 3.6.0 4.12 3.15 + 1.0.6 @@ -37,5 +38,20 @@ poi-ooxml ${poi.version} + + org.apache.poi + poi + ${poi.version} + + + org.apache.poi + poi-ooxml-schemas + ${poi.version} + + + org.jxls + jxls-jexcel + ${jexcel.version} + diff --git a/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java b/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java new file mode 100644 index 0000000000..39076fd709 --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java @@ -0,0 +1,79 @@ +package com.baeldung.jexcel; + +import jxl.*; +import java.util.Map; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.List; +import jxl.read.biff.BiffException; +import java.io.File; +import java.io.IOException; +import jxl.write.*; +import jxl.write.Number; +import jxl.format.Colour; + +public class JExcelHelper { + + public Map> readJExcel(String fileLocation) throws IOException, BiffException { + Map> data = new HashMap<>(); + + Workbook workbook = Workbook.getWorkbook(new File(fileLocation)); + Sheet sheet = workbook.getSheet(0); + int rows = sheet.getRows(); + int columns = sheet.getColumns(); + + for (int i = 0; i < rows; i++) { + data.put(i, new ArrayList()); + for (int j = 0; j < columns; j++) { + data.get(i).add(sheet.getCell(j, i).getContents()); + } + } + return data; + } + + public void writeJExcel() throws IOException, WriteException { + WritableWorkbook workbook = null; + try { + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + String fileLocation = path.substring(0, path.length() - 1) + "temp.xls"; + + workbook = Workbook.createWorkbook(new File(fileLocation)); + + WritableSheet sheet = workbook.createSheet("Sheet 1", 0); + + WritableCellFormat headerFormat = new WritableCellFormat(); + WritableFont font = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD); + headerFormat.setFont(font); + headerFormat.setBackground(Colour.LIGHT_BLUE); + headerFormat.setWrap(true); + Label headerLabel = new Label(0, 0, "Name", headerFormat); + sheet.setColumnView(0, 60); + sheet.addCell(headerLabel); + + headerLabel = new Label(1, 0, "Age", headerFormat); + sheet.setColumnView(0, 40); + sheet.addCell(headerLabel); + + WritableCellFormat cellFormat = new WritableCellFormat(); + cellFormat.setWrap(true); + + Label cellLabel = new Label(0, 2, "John Smith", cellFormat); + sheet.addCell(cellLabel); + Number cellNumber = new Number(1, 2, 20, cellFormat); + sheet.addCell(cellNumber); + + cellLabel = new Label(0, 3, "Ana Johnson", cellFormat); + sheet.addCell(cellLabel); + cellNumber = new Number(1, 3, 30, cellFormat); + sheet.addCell(cellNumber); + + workbook.write(); + } finally { + if (workbook != null) { + workbook.close(); + } + } + + } +} \ No newline at end of file diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java new file mode 100644 index 0000000000..841be22d62 --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java @@ -0,0 +1,137 @@ +package com.baeldung.poi.excel; + +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.ss.usermodel.FillPatternType; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.List; + +public class ExcelPOIHelper { + + public Map> readExcel(String fileLocation) throws IOException { + + Map> data = new HashMap<>(); + FileInputStream file = new FileInputStream(new File(fileLocation)); + Workbook workbook = new XSSFWorkbook(file); + Sheet sheet = workbook.getSheetAt(0); + int i = 0; + for (Row row : sheet) { + data.put(i, new ArrayList()); + for (Cell cell : row) { + switch (cell.getCellTypeEnum()) { + case STRING: + data.get(i) + .add(cell.getRichStringCellValue() + .getString()); + break; + case NUMERIC: + if (DateUtil.isCellDateFormatted(cell)) { + data.get(i) + .add(cell.getDateCellValue() + ""); + } else { + data.get(i) + .add((int)cell.getNumericCellValue() + ""); + } + break; + case BOOLEAN: + data.get(i) + .add(cell.getBooleanCellValue() + ""); + break; + case FORMULA: + data.get(i) + .add(cell.getCellFormula() + ""); + break; + default: + data.get(i) + .add(" "); + } + } + i++; + } + if (workbook != null){ + workbook.close(); + } + return data; + } + + public void writeExcel() throws IOException { + Workbook workbook = new XSSFWorkbook(); + + try { + Sheet sheet = workbook.createSheet("Persons"); + sheet.setColumnWidth(0, 6000); + sheet.setColumnWidth(1, 4000); + + Row header = sheet.createRow(0); + + CellStyle headerStyle = workbook.createCellStyle(); + + headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex()); + headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); + + XSSFFont font = ((XSSFWorkbook) workbook).createFont(); + font.setFontName("Arial"); + font.setFontHeightInPoints((short) 16); + font.setBold(true); + headerStyle.setFont(font); + + Cell headerCell = header.createCell(0); + headerCell.setCellValue("Name"); + headerCell.setCellStyle(headerStyle); + + headerCell = header.createCell(1); + headerCell.setCellValue("Age"); + headerCell.setCellStyle(headerStyle); + + CellStyle style = workbook.createCellStyle(); + style.setWrapText(true); + + Row row = sheet.createRow(2); + Cell cell = row.createCell(0); + cell.setCellValue("John Smith"); + cell.setCellStyle(style); + + cell = row.createCell(1); + cell.setCellValue(20); + cell.setCellStyle(style); + + row = sheet.createRow(3); + cell = row.createCell(0); + cell.setCellValue("Ana Johnson"); + cell.setCellStyle(style); + + cell = row.createCell(1); + cell.setCellValue(30); + cell.setCellStyle(style); + + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx"; + + FileOutputStream outputStream = new FileOutputStream(fileLocation); + workbook.write(outputStream); + } finally { + if (workbook != null) { + + workbook.close(); + + } + } + } + +} \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java new file mode 100644 index 0000000000..f0c129eb22 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java @@ -0,0 +1,62 @@ +package com.baeldung.jexcel; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import jxl.read.biff.BiffException; +import java.util.Map; +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.jexcel.JExcelHelper; + +import jxl.write.WriteException; +import jxl.read.biff.BiffException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.Before; + +public class JExcelTest { + + private JExcelHelper jExcelHelper; + private static String FILE_NAME = "temp.xls"; + private String fileLocation; + + @Before + public void generateExcelFile() throws IOException, WriteException { + + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; + + jExcelHelper = new JExcelHelper(); + jExcelHelper.writeJExcel(); + + } + + @Test + public void whenParsingJExcelFile_thenCorrect() throws IOException, BiffException { + Map> data = jExcelHelper.readJExcel(fileLocation); + + assertEquals("Name", data.get(0) + .get(0)); + assertEquals("Age", data.get(0) + .get(1)); + + assertEquals("John Smith", data.get(2) + .get(0)); + assertEquals("20", data.get(2) + .get(1)); + + assertEquals("Ana Johnson", data.get(3) + .get(0)); + assertEquals("30", data.get(3) + .get(1)); + + } + +} \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java new file mode 100644 index 0000000000..f58db241b2 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java @@ -0,0 +1,59 @@ +package com.baeldung.poi.excel; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import jxl.read.biff.BiffException; +import java.util.Map; +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.poi.excel.ExcelPOIHelper; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.Before; + +public class ExcelTest { + + private ExcelPOIHelper excelPOIHelper; + private static String FILE_NAME = "temp.xlsx"; + private String fileLocation; + + @Before + public void generateExcelFile() throws IOException { + + File currDir = new File("."); + String path = currDir.getAbsolutePath(); + fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; + + excelPOIHelper = new ExcelPOIHelper(); + excelPOIHelper.writeExcel(); + + } + + @Test + public void whenParsingPOIExcelFile_thenCorrect() throws IOException { + Map> data = excelPOIHelper.readExcel(fileLocation); + + assertEquals("Name", data.get(0) + .get(0)); + assertEquals("Age", data.get(0) + .get(1)); + + assertEquals("John Smith", data.get(1) + .get(0)); + assertEquals("20", data.get(1) + .get(1)); + + assertEquals("Ana Johnson", data.get(2) + .get(0)); + assertEquals("30", data.get(2) + .get(1)); + + } + +} \ No newline at end of file From 6d0dcd52fad370d25ea43f96efed043e5cb4be35 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sun, 5 Feb 2017 08:30:32 +0100 Subject: [PATCH 18/21] Reformat Rxjava examples --- .../rxjava/ColdObservableBackpressure.java | 5 ++++- .../HotObservableBackpressureBatching.java | 7 +++++-- .../HotObservableBackpressureBuffering.java | 7 +++++-- .../HotObservableBackpressureSkipping.java | 7 ++++--- .../rxjava/HotObservableOnBackpressure.java | 19 ++++++++++++++----- .../HotObservableWithoutBackpressure.java | 9 ++++----- 6 files changed, 36 insertions(+), 18 deletions(-) diff --git a/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java b/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java index 9855123a3b..4d3d09da7e 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java +++ b/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java @@ -5,7 +5,10 @@ import rx.schedulers.Schedulers; public class ColdObservableBackpressure { public static void main(String[] args) throws InterruptedException { - Observable.range(1, 1_000_000).observeOn(Schedulers.computation()).subscribe(v -> ComputeFunction.compute(v), Throwable::printStackTrace); + Observable + .range(1, 1_000_000) + .observeOn(Schedulers.computation()) + .subscribe(ComputeFunction::compute, Throwable::printStackTrace); Thread.sleep(10_000); diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java index 6acda7eaad..9f7b8c107a 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java @@ -5,9 +5,12 @@ import rx.subjects.PublishSubject; public class HotObservableBackpressureBatching { public static void main(String[] args) throws InterruptedException { - PublishSubject source = PublishSubject.create(); + PublishSubject source = PublishSubject. create(); - source.window(500).observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace); + source + .window(500) + .observeOn(Schedulers.computation()) + .subscribe(ComputeFunction::compute, Throwable::printStackTrace); for (int i = 0; i < 1_000_000; i++) { source.onNext(i); diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java index 50638f4c8a..720918878f 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java @@ -5,9 +5,12 @@ import rx.subjects.PublishSubject; public class HotObservableBackpressureBuffering { public static void main(String[] args) throws InterruptedException { - PublishSubject source = PublishSubject.create(); + PublishSubject source = PublishSubject. create(); - source.buffer(1024).observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace); + source + .buffer(1024) + .observeOn(Schedulers.computation()) + .subscribe(ComputeFunction::compute, Throwable::printStackTrace); for (int i = 0; i < 1_000_000; i++) { source.onNext(i); diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java index f6f8b9f563..5b0a7f3a68 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java @@ -7,11 +7,12 @@ import java.util.concurrent.TimeUnit; public class HotObservableBackpressureSkipping { public static void main(String[] args) throws InterruptedException { - PublishSubject source = PublishSubject.create(); + PublishSubject source = PublishSubject. create(); source.sample(100, TimeUnit.MILLISECONDS) - // .throttleFirst(100, TimeUnit.MILLISECONDS) - .observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace); + //.throttleFirst(100, TimeUnit.MILLISECONDS) + .observeOn(Schedulers.computation()) + .subscribe(ComputeFunction::compute, Throwable::printStackTrace); for (int i = 0; i < 1_000_000; i++) { source.onNext(i); diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackpressure.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackpressure.java index afef8027bf..8ccd38beb6 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackpressure.java +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackpressure.java @@ -6,12 +6,21 @@ import rx.schedulers.Schedulers; public class HotObservableOnBackpressure { public static void main(String[] args) throws InterruptedException { - Observable.range(1, 1_000_000).onBackpressureBuffer(16, () -> { - }, BackpressureOverflow.ON_OVERFLOW_DROP_OLDEST).observeOn(Schedulers.computation()).subscribe(e -> { - }, Throwable::printStackTrace); + Observable + .range(1, 1_000_000) + .onBackpressureBuffer(16, () -> { + }, BackpressureOverflow.ON_OVERFLOW_DROP_OLDEST) + .observeOn(Schedulers.computation()) + .subscribe(e -> { + }, Throwable::printStackTrace); - Observable.range(1, 1_000_000).onBackpressureDrop().observeOn(Schedulers.io()).doOnNext(ComputeFunction::compute).subscribe(v -> { - }, Throwable::printStackTrace); + Observable + .range(1, 1_000_000) + .onBackpressureDrop() + .observeOn(Schedulers.io()) + .doOnNext(ComputeFunction::compute) + .subscribe(v -> { + }, Throwable::printStackTrace); Thread.sleep(10_000); } diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java index 7745dbe5c4..439db51695 100644 --- a/rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java @@ -1,16 +1,15 @@ package com.baelding.rxjava; - import rx.schedulers.Schedulers; import rx.subjects.PublishSubject; public class HotObservableWithoutBackpressure { public static void main(String[] args) throws InterruptedException { - PublishSubject source = PublishSubject.create(); - - source.observeOn(Schedulers.computation()) - .subscribe(ComputeFunction::compute, Throwable::printStackTrace); + PublishSubject source = PublishSubject. create(); + source + .observeOn(Schedulers.computation()) + .subscribe(ComputeFunction::compute, Throwable::printStackTrace); for (int i = 0; i < 1_000_000; i++) { source.onNext(i); From 14bee159bdfa977e35e264268867d615cabdd081 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sun, 5 Feb 2017 08:55:35 +0100 Subject: [PATCH 19/21] Fix JavaRandomUnitTest --- .../test/java/org/baeldung/java/JavaRandomUnitTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java index 4febe7c9fc..08f98025c3 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java @@ -1,12 +1,12 @@ package org.baeldung.java; -import java.nio.charset.Charset; -import java.util.Random; - import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.math3.random.RandomDataGenerator; import org.junit.Test; +import java.nio.charset.Charset; +import java.util.Random; + public class JavaRandomUnitTest { // tests - random long @@ -164,7 +164,7 @@ public class JavaRandomUnitTest { final int targetStringLength = 10; final StringBuilder buffer = new StringBuilder(targetStringLength); for (int i = 0; i < targetStringLength; i++) { - final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit)); + final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit + 1)); buffer.append((char) randomLimitedInt); } final String generatedString = buffer.toString(); From d4cb92250d036680bafa5a4ee322b7388d0c85b1 Mon Sep 17 00:00:00 2001 From: pivovarit Date: Sun, 5 Feb 2017 10:20:12 +0100 Subject: [PATCH 20/21] LiveTest -> Test --- ...esourceEndpointLiveTest.java => ResourceEndpointTest.java} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/{ResourceEndpointLiveTest.java => ResourceEndpointTest.java} (95%) diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java similarity index 95% rename from spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java rename to spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java index 94b6052ba4..6d532f98fc 100644 --- a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointLiveTest.java +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java @@ -11,7 +11,7 @@ import static com.jayway.restassured.RestAssured.given; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AppRunner.class) -public class ResourceEndpointLiveTest { +public class ResourceEndpointTest { @LocalServerPort private int serverPort; @@ -66,7 +66,7 @@ public class ResourceEndpointLiveTest { } private String getBaseUrl() { - return "http://localhost:" + serverPort; + return String.format("http://localhost:%d", serverPort); } } \ No newline at end of file From 4b0249410c4334427e1bc6ba2a580b2dde9a05f3 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 5 Feb 2017 10:27:13 +0100 Subject: [PATCH 21/21] Update README.md --- spring-core/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-core/README.md b/spring-core/README.md index f6aaaf44a0..a32d30939f 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -3,4 +3,4 @@ - [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory) - [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) - [Constructor Dependency Injection in Spring](http://www.baeldung.com/constructor-injection-in-spring) -- [Constructor Injection in Spring with Lombok](http://inprogress.baeldung.com/constructor-injection-in-spring-with-lombok) +- [Constructor Injection in Spring with Lombok](http://www.baeldung.com/spring-injection-lombok)