diff --git a/apache-thrift/src/main/java/com/baeldung/thrift/Application.java b/apache-thrift/src/main/java/com/baeldung/thrift/Application.java index 09d5cc74f3..3321a0927a 100644 --- a/apache-thrift/src/main/java/com/baeldung/thrift/Application.java +++ b/apache-thrift/src/main/java/com/baeldung/thrift/Application.java @@ -1,8 +1,10 @@ package com.baeldung.thrift; +import org.apache.thrift.transport.TTransportException; + public class Application { - public static void main(String[] args) { + public static void main(String[] args) throws TTransportException { CrossPlatformServiceServer server = new CrossPlatformServiceServer(); server.start(); } diff --git a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java index 9a21512b52..32c7891ef2 100644 --- a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java +++ b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java @@ -6,25 +6,22 @@ import org.apache.thrift.server.TServer; import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TServerTransport; +import org.apache.thrift.transport.TTransportException; public class CrossPlatformServiceServer { private TServer server; - public void start() { - try { - TServerTransport serverTransport = new TServerSocket(9090); - server = new TSimpleServer(new TServer.Args(serverTransport) - .processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl()))); + public void start() throws TTransportException { + TServerTransport serverTransport = new TServerSocket(9090); + server = new TSimpleServer(new TServer.Args(serverTransport) + .processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl()))); - System.out.print("Starting the server... "); + System.out.print("Starting the server... "); - server.serve(); + server.serve(); - System.out.println("done."); - } catch (Exception e) { - e.printStackTrace(); - } + System.out.println("done."); } public void stop() { diff --git a/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java b/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java index 8a7022a281..4ba9ef2914 100644 --- a/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java +++ b/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java @@ -1,5 +1,6 @@ package com.baeldung.thrift; +import org.apache.thrift.transport.TTransportException; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -11,7 +12,13 @@ public class CrossPlatformServiceTest { @Before public void setUp() { - new Thread(() -> server.start()).start(); + new Thread(() -> { + try { + server.start(); + } catch (TTransportException e) { + e.printStackTrace(); + } + }).start(); try { // wait for the server start up Thread.sleep(1000); 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/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java new file mode 100644 index 0000000000..5e6855e18a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.concurrent.priorityblockingqueue; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.util.Lists.newArrayList; + +public class PriorityBlockingQueueUnitTest { + + @Test + public void givenUnorderedValues_whenPolling_thenShouldOrderQueue() throws InterruptedException { + PriorityBlockingQueue queue = new PriorityBlockingQueue<>(); + ArrayList polledElements = new ArrayList<>(); + + queue.add(1); + queue.add(5); + queue.add(2); + queue.add(3); + queue.add(4); + + queue.drainTo(polledElements); + + assertThat(polledElements).containsExactly(1, 2, 3, 4, 5); + } + + @Test + public void whenPollingEmptyQueue_thenShouldBlockThread() throws InterruptedException { + 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) {} + } + }); + thread.start(); + + Thread.sleep(TimeUnit.SECONDS.toMillis(5)); + System.out.println("Adding to queue"); + + queue.addAll(newArrayList(1, 5, 6, 1, 2, 6, 7)); + Thread.sleep(TimeUnit.SECONDS.toMillis(1)); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStream.java b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java similarity index 93% rename from core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStream.java rename to core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java index b8c0991b8d..5fd3fa4cb0 100644 --- a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStream.java +++ b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java @@ -13,7 +13,7 @@ import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class ThreadPoolInParallelStream { +public class ThreadPoolInParallelStreamTest { @Test public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() diff --git a/pom.xml b/pom.xml index 06feb5e4f5..41235dcc26 100644 --- a/pom.xml +++ b/pom.xml @@ -94,6 +94,7 @@ rest-assured rest-testing resteasy + rxjava selenium-junit-testng solr-fulltext-search diff --git a/rxjava/pom.xml b/rxjava/pom.xml new file mode 100644 index 0000000000..63aa1f127e --- /dev/null +++ b/rxjava/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + com.baeldung + rxjava + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + io.reactivex + rxjava + ${rx.java.version} + + + + + 1.2.5 + + + \ No newline at end of file diff --git a/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java b/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java new file mode 100644 index 0000000000..9855123a3b --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java @@ -0,0 +1,38 @@ +package com.baelding.rxjava; + +import rx.Observable; +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); + + Thread.sleep(10_000); + + // Observable.range(1, 1_000_000) //implementation of reactive pull backpressure on cold observable + // .subscribe(new Subscriber() { + // @Override + // public void onStart() { + // request(1); + // } + // + // public void onNext(Integer v) { + // compute(v); + // + // request(1); + // } + // + // @Override + // public void onError(Throwable ex) { + // ex.printStackTrace(); + // } + // + // @Override + // public void onCompleted() { + // System.out.println("Done!"); + // } + // }); + + } + +} diff --git a/rxjava/src/main/java/com/baelding/rxjava/ComputeFunction.java b/rxjava/src/main/java/com/baelding/rxjava/ComputeFunction.java new file mode 100644 index 0000000000..924862ab37 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/ComputeFunction.java @@ -0,0 +1,43 @@ +package com.baelding.rxjava; + +import rx.Observable; + +import java.util.List; + +public class ComputeFunction { + public static void compute(Integer v) { + try { + System.out.println("compute integer v: " + v); + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public static void compute(List v) { + try { + System.out.println("compute integer v: " + v); + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public static void compute(Observable v) { + try { + v.forEach(System.out::println); + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public static void compute(Long v) { + try { + System.out.println("compute integer v: " + v); + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java new file mode 100644 index 0000000000..6acda7eaad --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java @@ -0,0 +1,18 @@ +package com.baelding.rxjava; + +import rx.schedulers.Schedulers; +import rx.subjects.PublishSubject; + +public class HotObservableBackpressureBatching { + public static void main(String[] args) throws InterruptedException { + PublishSubject source = PublishSubject.create(); + + source.window(500).observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace); + + for (int i = 0; i < 1_000_000; i++) { + source.onNext(i); + } + Thread.sleep(10_000); + } + +} diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java new file mode 100644 index 0000000000..50638f4c8a --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java @@ -0,0 +1,17 @@ +package com.baelding.rxjava; + +import rx.schedulers.Schedulers; +import rx.subjects.PublishSubject; + +public class HotObservableBackpressureBuffering { + public static void main(String[] args) throws InterruptedException { + PublishSubject source = PublishSubject.create(); + + source.buffer(1024).observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace); + + for (int i = 0; i < 1_000_000; i++) { + source.onNext(i); + } + Thread.sleep(10_000); + } +} diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java new file mode 100644 index 0000000000..f6f8b9f563 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java @@ -0,0 +1,21 @@ +package com.baelding.rxjava; + +import rx.schedulers.Schedulers; +import rx.subjects.PublishSubject; + +import java.util.concurrent.TimeUnit; + +public class HotObservableBackpressureSkipping { + public static void main(String[] args) throws InterruptedException { + PublishSubject source = PublishSubject.create(); + + source.sample(100, TimeUnit.MILLISECONDS) + // .throttleFirst(100, TimeUnit.MILLISECONDS) + .observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace); + + for (int i = 0; i < 1_000_000; i++) { + source.onNext(i); + } + Thread.sleep(10_000); + } +} diff --git a/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackpressure.java b/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackpressure.java new file mode 100644 index 0000000000..afef8027bf --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackpressure.java @@ -0,0 +1,18 @@ +package com.baelding.rxjava; + +import rx.BackpressureOverflow; +import rx.Observable; +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).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 new file mode 100644 index 0000000000..7745dbe5c4 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java @@ -0,0 +1,20 @@ +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); + + + for (int i = 0; i < 1_000_000; i++) { + source.onNext(i); + } + Thread.sleep(10_000); + } +} 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 diff --git a/spring-core/src/main/java/com/baeldung/lombok/Apologizer.java b/spring-core/src/main/java/com/baeldung/lombok/ApologizeService.java similarity index 83% rename from spring-core/src/main/java/com/baeldung/lombok/Apologizer.java rename to spring-core/src/main/java/com/baeldung/lombok/ApologizeService.java index ddce9cdc52..25ef65cad2 100644 --- a/spring-core/src/main/java/com/baeldung/lombok/Apologizer.java +++ b/spring-core/src/main/java/com/baeldung/lombok/ApologizeService.java @@ -6,13 +6,13 @@ import org.springframework.stereotype.Component; @Component @AllArgsConstructor -public class Apologizer { +public class ApologizeService { private final Translator translator; private final String message; @Autowired - public Apologizer(Translator translator) { + public ApologizeService(Translator translator) { this(translator, "sorry"); } diff --git a/spring-core/src/main/java/com/baeldung/lombok/Fareweller.java b/spring-core/src/main/java/com/baeldung/lombok/FarewellService.java similarity index 79% rename from spring-core/src/main/java/com/baeldung/lombok/Fareweller.java rename to spring-core/src/main/java/com/baeldung/lombok/FarewellService.java index b10ebb72b9..4e8c4993cb 100644 --- a/spring-core/src/main/java/com/baeldung/lombok/Fareweller.java +++ b/spring-core/src/main/java/com/baeldung/lombok/FarewellService.java @@ -4,11 +4,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class Fareweller { +public class FarewellService { private final Translator translator; - public Fareweller(Translator translator) { + public FarewellService(Translator translator) { this.translator = translator; } diff --git a/spring-core/src/main/java/com/baeldung/lombok/Greeter.java b/spring-core/src/main/java/com/baeldung/lombok/GreetingService.java similarity index 90% rename from spring-core/src/main/java/com/baeldung/lombok/Greeter.java rename to spring-core/src/main/java/com/baeldung/lombok/GreetingService.java index ddbc024ce7..0e03e177e1 100644 --- a/spring-core/src/main/java/com/baeldung/lombok/Greeter.java +++ b/spring-core/src/main/java/com/baeldung/lombok/GreetingService.java @@ -4,7 +4,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class Greeter { +public class GreetingService { @Autowired private Translator translator; diff --git a/spring-core/src/main/java/com/baeldung/lombok/Thanker.java b/spring-core/src/main/java/com/baeldung/lombok/ThankingService.java similarity index 76% rename from spring-core/src/main/java/com/baeldung/lombok/Thanker.java rename to spring-core/src/main/java/com/baeldung/lombok/ThankingService.java index 784100c258..f3bdf8bb7f 100644 --- a/spring-core/src/main/java/com/baeldung/lombok/Thanker.java +++ b/spring-core/src/main/java/com/baeldung/lombok/ThankingService.java @@ -1,12 +1,11 @@ package com.baeldung.lombok; import lombok.AllArgsConstructor; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @AllArgsConstructor -public class Thanker { +public class ThankingService { private final Translator translator; diff --git a/spring-core/src/test/java/com/baeldung/lombok/ApologizerAutowiringTest.java b/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringTest.java similarity index 84% rename from spring-core/src/test/java/com/baeldung/lombok/ApologizerAutowiringTest.java rename to spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringTest.java index 3e7c775f91..755fc5868b 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/ApologizerAutowiringTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringTest.java @@ -14,12 +14,12 @@ import static org.mockito.Mockito.when; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = TestConfig.class) -public class ApologizerAutowiringTest { +public class ApologizeServiceAutowiringTest { private final static String TRANSLATED = "TRANSLATED"; @Autowired - private Apologizer apologizer; + private ApologizeService apologizeService; @Autowired private Translator translator; @@ -27,7 +27,7 @@ public class ApologizerAutowiringTest { @Test public void apologizeWithTranslatedMessage() { when(translator.translate("sorry")).thenReturn(TRANSLATED); - assertEquals(TRANSLATED, apologizer.apologize()); + assertEquals(TRANSLATED, apologizeService.apologize()); } } \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/lombok/ApologizerTest.java b/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceTest.java similarity index 72% rename from spring-core/src/test/java/com/baeldung/lombok/ApologizerTest.java rename to spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceTest.java index 28bd08c89f..ab545e7adf 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/ApologizerTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceTest.java @@ -6,7 +6,7 @@ import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ApologizerTest { +public class ApologizeServiceTest { private final static String MESSAGE = "MESSAGE"; private final static String TRANSLATED = "TRANSLATED"; @@ -14,8 +14,8 @@ public class ApologizerTest { @Test public void apologizeWithCustomTranslatedMessage() { Translator translator = mock(Translator.class); - Apologizer apologizer = new Apologizer(translator, MESSAGE); + ApologizeService apologizeService = new ApologizeService(translator, MESSAGE); when(translator.translate(MESSAGE)).thenReturn(TRANSLATED); - assertEquals(TRANSLATED, apologizer.apologize()); + assertEquals(TRANSLATED, apologizeService.apologize()); } } diff --git a/spring-core/src/test/java/com/baeldung/lombok/FarewellAutowiringTest.java b/spring-core/src/test/java/com/baeldung/lombok/FarewellAutowiringTest.java index d55d44fb3e..592e309236 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/FarewellAutowiringTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/FarewellAutowiringTest.java @@ -17,7 +17,7 @@ import static org.mockito.Mockito.when; public class FarewellAutowiringTest { @Autowired - private Fareweller fareweller; + private FarewellService farewellService; @Autowired private Translator translator; @@ -26,6 +26,6 @@ public class FarewellAutowiringTest { public void sayByeWithTranslatedMessage() { String translated = "translated"; when(translator.translate("bye")).thenReturn(translated); - assertEquals(translated, fareweller.farewell()); + assertEquals(translated, farewellService.farewell()); } } diff --git a/spring-core/src/test/java/com/baeldung/lombok/FarewellerTest.java b/spring-core/src/test/java/com/baeldung/lombok/FarewellServiceTest.java similarity index 70% rename from spring-core/src/test/java/com/baeldung/lombok/FarewellerTest.java rename to spring-core/src/test/java/com/baeldung/lombok/FarewellServiceTest.java index a02ad1d8ac..9ad593a489 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/FarewellerTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/FarewellServiceTest.java @@ -6,7 +6,7 @@ import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class FarewellerTest { +public class FarewellServiceTest { private final static String TRANSLATED = "TRANSLATED"; @@ -14,7 +14,7 @@ public class FarewellerTest { public void sayByeWithTranslatedMessage() { Translator translator = mock(Translator.class); when(translator.translate("bye")).thenReturn(TRANSLATED); - Fareweller fareweller = new Fareweller(translator); - assertEquals(TRANSLATED, fareweller.farewell()); + FarewellService farewellService = new FarewellService(translator); + assertEquals(TRANSLATED, farewellService.farewell()); } } \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/lombok/GreeterTest.java b/spring-core/src/test/java/com/baeldung/lombok/GreetingServiceTest.java similarity index 79% rename from spring-core/src/test/java/com/baeldung/lombok/GreeterTest.java rename to spring-core/src/test/java/com/baeldung/lombok/GreetingServiceTest.java index 0f66eaf301..d0207d681b 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/GreeterTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/GreetingServiceTest.java @@ -14,10 +14,10 @@ import static org.mockito.Mockito.when; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = TestConfig.class) -public class GreeterTest { +public class GreetingServiceTest { @Autowired - private Greeter greeter; + private GreetingService greetingService; @Autowired private Translator translator; @@ -26,12 +26,12 @@ public class GreeterTest { public void greetWithTranslatedMessage() { String translated = "translated"; when(translator.translate("hello")).thenReturn(translated); - assertEquals(translated, greeter.greet()); + assertEquals(translated, greetingService.greet()); } @Test(expected = NullPointerException.class) public void throwWhenInstantiated() { - Greeter greeter = new Greeter(); - greeter.greet(); + GreetingService greetingService = new GreetingService(); + greetingService.greet(); } } \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/lombok/ThankerAutowiringTest.java b/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringTest.java similarity index 84% rename from spring-core/src/test/java/com/baeldung/lombok/ThankerAutowiringTest.java rename to spring-core/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringTest.java index 59aded5831..b2a338b18f 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/ThankerAutowiringTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringTest.java @@ -14,10 +14,10 @@ import static org.mockito.Mockito.when; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = TestConfig.class) -public class ThankerAutowiringTest { +public class ThankingServiceAutowiringTest { @Autowired - private Thanker thanker; + private ThankingService thankingService; @Autowired private Translator translator; @@ -26,6 +26,6 @@ public class ThankerAutowiringTest { public void thankWithTranslatedMessage() { String translated = "translated"; when(translator.translate("thank you")).thenReturn(translated); - assertEquals(translated, thanker.thank()); + assertEquals(translated, thankingService.thank()); } } \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/lombok/ThankerTest.java b/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceTest.java similarity index 71% rename from spring-core/src/test/java/com/baeldung/lombok/ThankerTest.java rename to spring-core/src/test/java/com/baeldung/lombok/ThankingServiceTest.java index 466762fa50..7dc663622b 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/ThankerTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceTest.java @@ -6,7 +6,7 @@ import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ThankerTest { +public class ThankingServiceTest { private final static String TRANSLATED = "TRANSLATED"; @@ -14,7 +14,7 @@ public class ThankerTest { public void thankWithTranslatedMessage() { Translator translator = mock(Translator.class); when(translator.translate("thank you")).thenReturn(TRANSLATED); - Thanker thanker = new Thanker(translator); - assertEquals(TRANSLATED, thanker.thank()); + ThankingService thankingService = new ThankingService(translator); + assertEquals(TRANSLATED, thankingService.thank()); } } \ No newline at end of file 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/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java index ba54985853..e522dab48d 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java @@ -7,32 +7,31 @@ import org.hibernate.service.ServiceRegistry; public class HibernateAnnotationUtil { - private static SessionFactory sessionFactory; - - private static SessionFactory buildSessionFactory() { + private static SessionFactory sessionFactory; + + private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate-annotation.cfg.xml - Configuration configuration = new Configuration(); - configuration.configure("hibernate-annotation.cfg.xml"); - System.out.println("Hibernate Annotation Configuration loaded"); - - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); - System.out.println("Hibernate Annotation serviceRegistry created"); - - SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); - - + Configuration configuration = new Configuration(); + configuration.configure("hibernate-annotation.cfg.xml"); + System.out.println("Hibernate Annotation Configuration loaded"); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); + System.out.println("Hibernate Annotation serviceRegistry created"); + + SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); + return sessionFactory; - } - catch (Throwable ex) { + } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } } - - public static SessionFactory getSessionFactory() { - if(sessionFactory == null) sessionFactory = buildSessionFactory(); + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) + sessionFactory = buildSessionFactory(); return sessionFactory; } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java index d5c41bcfab..63b6450bf4 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java @@ -13,48 +13,49 @@ import com.baeldung.hibernate.oneToMany.model.Items; public class HibernateOneToManyAnnotationMain { - public static void main(String[] args) { + public static void main(String[] args) { - Cart cart = new Cart(); - cart.setName("MyCart"); - - Items item1 = new Items("I10", 10, 1, cart); - Items item2 = new Items("I20", 20, 2, cart); - Set itemsSet = new HashSet(); - itemsSet.add(item1); itemsSet.add(item2); - - cart.setItems(itemsSet); - cart.setTotal(10*1 + 20*2); - - SessionFactory sessionFactory = null; - Session session = null; - Transaction tx = null; - try{ - //Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - System.out.println("Session created"); - //start transaction - tx = session.beginTransaction(); - //Save the Model object - session.save(cart); - session.save(item1); - session.save(item2); - //Commit transaction - tx.commit(); - System.out.println("Cart ID="+cart.getId()); - System.out.println("item1 ID="+item1.getId()+", Foreign Key Cart ID="+item1.getCart().getId()); - System.out.println("item2 ID="+item2.getId()+", Foreign Key Cart ID="+item1.getCart().getId()); - - }catch(Exception e){ - System.out.println("Exception occured. "+e.getMessage()); - e.printStackTrace(); - }finally{ - if(!sessionFactory.isClosed()){ - System.out.println("Closing SessionFactory"); - sessionFactory.close(); - } - } - } + Cart cart = new Cart(); + cart.setName("MyCart"); + + Items item1 = new Items("I10", 10, 1, cart); + Items item2 = new Items("I20", 20, 2, cart); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + itemsSet.add(item2); + + cart.setItems(itemsSet); + cart.setTotal(10 * 1 + 20 * 2); + + SessionFactory sessionFactory = null; + Session session = null; + Transaction tx = null; + try { + // Get Session + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + session = sessionFactory.getCurrentSession(); + System.out.println("Session created"); + // start transaction + tx = session.beginTransaction(); + // Save the Model object + session.save(cart); + session.save(item1); + session.save(item2); + // Commit transaction + tx.commit(); + System.out.println("Cart ID=" + cart.getId()); + System.out.println("item1 ID=" + item1.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); + System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); + + } catch (Exception e) { + System.out.println("Exception occured. " + e.getMessage()); + e.printStackTrace(); + } finally { + if (!sessionFactory.isClosed()) { + System.out.println("Closing SessionFactory"); + sessionFactory.close(); + } + } + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java index fdbfda2279..61a32ba43f 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java @@ -11,46 +11,53 @@ import javax.persistence.OneToMany; import javax.persistence.Table; @Entity -@Table(name="CART") +@Table(name = "CART") public class Cart { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="cart_id") - private long id; - - @Column(name="total") - private double total; - - @Column(name="name") - private String name; - - @OneToMany(mappedBy="cart") - private Set items; - - public long getId() { - return id; - } - public void setId(long id) { - this.id = id; - } - public double getTotal() { - return total; - } - public void setTotal(double total) { - this.total = total; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public Set getItems() { - return items; - } - public void setItems(Set items) { - this.items = items; - } - + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "cart_id") + private long id; + + @Column(name = "total") + private double total; + + @Column(name = "name") + private String name; + + @OneToMany(mappedBy = "cart") + private Set items; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getTotal() { + return total; + } + + public void setTotal(double total) { + this.total = total; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Set getItems() { + return items; + } + + public void setItems(Set items) { + this.items = items; + } + } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java index 630bf0a12e..40ee6fdea1 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java @@ -10,65 +10,76 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity -@Table(name="ITEMS") +@Table(name = "ITEMS") public class Items { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="item_id") - private String itemId; - - @Column(name="item_total") - private double itemTotal; - - @Column(name="quantity") - private int quantity; - - @ManyToOne - @JoinColumn(name="cart_id", nullable=false) - private Cart cart; - - //Hibernate requires no-args constructor - public Items(){} - - public Items(String itemId, double total, int qty, Cart c){ - this.itemId=itemId; - this.itemTotal=total; - this.quantity=qty; - this.cart=c; - } - public String getItemId() { - return itemId; - } - public void setItemId(String itemId) { - this.itemId = itemId; - } - public double getItemTotal() { - return itemTotal; - } - public void setItemTotal(double itemTotal) { - this.itemTotal = itemTotal; - } - public int getQuantity() { - return quantity; - } - public void setQuantity(int quantity) { - this.quantity = quantity; - } - public Cart getCart() { - return cart; - } - public void setCart(Cart cart) { - this.cart = cart; - } - public long getId() { - return id; - } - public void setId(long id) { - this.id = id; - } - + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "item_id") + private String itemId; + + @Column(name = "item_total") + private double itemTotal; + + @Column(name = "quantity") + private int quantity; + + @ManyToOne + @JoinColumn(name = "cart_id", nullable = false) + private Cart cart; + + // Hibernate requires no-args constructor + public Items() { + } + + public Items(String itemId, double total, int qty, Cart c) { + this.itemId = itemId; + this.itemTotal = total; + this.quantity = qty; + this.cart = c; + } + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public double getItemTotal() { + return itemTotal; + } + + public void setItemTotal(double itemTotal) { + this.itemTotal = itemTotal; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public Cart getCart() { + return cart; + } + + public void setCart(Cart cart) { + this.cart = cart; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + } 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 539298ae1e..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,89 +1,97 @@ - package com.baeldung.hibernate.oneToMany.main; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; -import com.baeldung.hibernate.oneToMany.model.Cart; -import com.baeldung.hibernate.oneToMany.model.Items; import java.util.HashSet; import java.util.Set; -import static org.hamcrest.Matchers.hasSize; + import org.hibernate.Session; import org.hibernate.SessionFactory; 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 static org.junit.Assert.*; - +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Items; public class HibernateOneToManyAnnotationMainTest { - - private static SessionFactory sessionFactory; - private Session session; - - 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); - } - - @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); - - } - - + private static SessionFactory sessionFactory; + + private Session session; + + 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); + } + + @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_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(); + + 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(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.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"); - - } - - @Test - public void testSaveCart(){ - 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(); - - } - - } diff --git a/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java b/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java index eb65987e8b..d0e33bf471 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java +++ b/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java @@ -1,22 +1,24 @@ package com.baeldung.excel; -import jxl.*; -import java.util.Map; -import java.util.HashMap; -import java.util.ArrayList; +import jxl.Sheet; +import jxl.Workbook; +import jxl.format.Colour; import jxl.read.biff.BiffException; -import java.io.File; -import java.io.IOException; -import org.springframework.stereotype.Service; import jxl.write.*; import jxl.write.Number; -import jxl.format.Colour; +import org.springframework.stereotype.Service; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; @Service public class JExcelHelper { public Map> readJExcel(String fileLocation) throws IOException, BiffException { - Map> data = new HashMap>(); + Map> data = new HashMap<>(); Workbook workbook = Workbook.getWorkbook(new File(fileLocation)); Sheet sheet = workbook.getSheet(0); @@ -24,7 +26,7 @@ public class JExcelHelper { int columns = sheet.getColumns(); for (int i = 0; i < rows; i++) { - data.put(i, new ArrayList()); + data.put(i, new ArrayList<>()); for (int j = 0; j < columns; j++) { data.get(i).add(sheet.getCell(j, i).getContents()); }