Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Kevin Gilmore 2017-02-04 13:24:15 -06:00
commit b4a5880394
38 changed files with 860 additions and 339 deletions

View File

@ -1,8 +1,10 @@
package com.baeldung.thrift; package com.baeldung.thrift;
import org.apache.thrift.transport.TTransportException;
public class Application { public class Application {
public static void main(String[] args) { public static void main(String[] args) throws TTransportException {
CrossPlatformServiceServer server = new CrossPlatformServiceServer(); CrossPlatformServiceServer server = new CrossPlatformServiceServer();
server.start(); server.start();
} }

View File

@ -6,13 +6,13 @@ import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport; import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
public class CrossPlatformServiceServer { public class CrossPlatformServiceServer {
private TServer server; private TServer server;
public void start() { public void start() throws TTransportException {
try {
TServerTransport serverTransport = new TServerSocket(9090); TServerTransport serverTransport = new TServerSocket(9090);
server = new TSimpleServer(new TServer.Args(serverTransport) server = new TSimpleServer(new TServer.Args(serverTransport)
.processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl()))); .processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl())));
@ -22,9 +22,6 @@ public class CrossPlatformServiceServer {
server.serve(); server.serve();
System.out.println("done."); System.out.println("done.");
} catch (Exception e) {
e.printStackTrace();
}
} }
public void stop() { public void stop() {

View File

@ -1,5 +1,6 @@
package com.baeldung.thrift; package com.baeldung.thrift;
import org.apache.thrift.transport.TTransportException;
import org.junit.After; import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
@ -11,7 +12,13 @@ public class CrossPlatformServiceTest {
@Before @Before
public void setUp() { public void setUp() {
new Thread(() -> server.start()).start(); new Thread(() -> {
try {
server.start();
} catch (TTransportException e) {
e.printStackTrace();
}
}).start();
try { try {
// wait for the server start up // wait for the server start up
Thread.sleep(1000); Thread.sleep(1000);

View File

@ -3,6 +3,7 @@ package com.baeldung.algorithms;
import java.util.Scanner; import java.util.Scanner;
import com.baeldung.algorithms.annealing.SimulatedAnnealing; import com.baeldung.algorithms.annealing.SimulatedAnnealing;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
import com.baeldung.algorithms.slope_one.SlopeOne; import com.baeldung.algorithms.slope_one.SlopeOne;
public class RunAlgorithm { public class RunAlgorithm {
@ -12,14 +13,19 @@ public class RunAlgorithm {
System.out.println("Run algorithm:"); System.out.println("Run algorithm:");
System.out.println("1 - Simulated Annealing"); System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One"); System.out.println("2 - Slope One");
System.out.println("3 - Simple Genetic Algorithm");
int decision = in.nextInt(); int decision = in.nextInt();
switch (decision) { switch (decision) {
case 1: case 1:
System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); System.out.println(
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
break; break;
case 2: case 2:
SlopeOne.slopeOne(3); SlopeOne.slopeOne(3);
break; break;
case 3:
SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
break;
default: default:
System.out.println("Unknown option"); System.out.println("Unknown option");
break; break;

View File

@ -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;
}
}

View File

@ -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<Individual> 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);
}
}
}

View File

@ -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;
}
}
}
}

View File

@ -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"));
}
}

View File

@ -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<Integer> queue = new PriorityBlockingQueue<>();
ArrayList<Integer> 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<Integer> 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));
}
}

View File

@ -13,7 +13,7 @@ import java.util.stream.Stream;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class ThreadPoolInParallelStream { public class ThreadPoolInParallelStreamTest {
@Test @Test
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal()

View File

@ -94,6 +94,7 @@
<module>rest-assured</module> <module>rest-assured</module>
<module>rest-testing</module> <module>rest-testing</module>
<module>resteasy</module> <module>resteasy</module>
<module>rxjava</module>
<module>selenium-junit-testng</module> <module>selenium-junit-testng</module>
<module>solr-fulltext-search</module> <module>solr-fulltext-search</module>

35
rxjava/pom.xml Normal file
View File

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>rxjava</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava</artifactId>
<version>${rx.java.version}</version>
</dependency>
</dependencies>
<properties>
<rx.java.version>1.2.5</rx.java.version>
</properties>
</project>

View File

@ -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<Integer>() {
// @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!");
// }
// });
}
}

View File

@ -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<Integer> v) {
try {
System.out.println("compute integer v: " + v);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void compute(Observable<Integer> 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();
}
}
}

View File

@ -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<Integer> source = PublishSubject.<Integer>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);
}
}

View File

@ -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<Integer> source = PublishSubject.<Integer>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);
}
}

View File

@ -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<Integer> source = PublishSubject.<Integer>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);
}
}

View File

@ -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);
}
}

View File

@ -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<Integer> source = PublishSubject.<Integer>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);
}
}

View File

@ -1,9 +1,5 @@
package com.baeldung.intro; 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.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -14,10 +10,14 @@ import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 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) @RunWith(SpringRunner.class)
@SpringBootTest @SpringBootTest
@AutoConfigureMockMvc @AutoConfigureMockMvc
public class AppTest { public class AppLiveTest {
@Autowired @Autowired
private MockMvc mvc; private MockMvc mvc;

View File

@ -6,13 +6,13 @@ import org.springframework.stereotype.Component;
@Component @Component
@AllArgsConstructor @AllArgsConstructor
public class Apologizer { public class ApologizeService {
private final Translator translator; private final Translator translator;
private final String message; private final String message;
@Autowired @Autowired
public Apologizer(Translator translator) { public ApologizeService(Translator translator) {
this(translator, "sorry"); this(translator, "sorry");
} }

View File

@ -4,11 +4,11 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
public class Fareweller { public class FarewellService {
private final Translator translator; private final Translator translator;
public Fareweller(Translator translator) { public FarewellService(Translator translator) {
this.translator = translator; this.translator = translator;
} }

View File

@ -4,7 +4,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
public class Greeter { public class GreetingService {
@Autowired @Autowired
private Translator translator; private Translator translator;

View File

@ -1,12 +1,11 @@
package com.baeldung.lombok; package com.baeldung.lombok;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
@AllArgsConstructor @AllArgsConstructor
public class Thanker { public class ThankingService {
private final Translator translator; private final Translator translator;

View File

@ -14,12 +14,12 @@ import static org.mockito.Mockito.when;
@ContextConfiguration( @ContextConfiguration(
loader = AnnotationConfigContextLoader.class, loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class) classes = TestConfig.class)
public class ApologizerAutowiringTest { public class ApologizeServiceAutowiringTest {
private final static String TRANSLATED = "TRANSLATED"; private final static String TRANSLATED = "TRANSLATED";
@Autowired @Autowired
private Apologizer apologizer; private ApologizeService apologizeService;
@Autowired @Autowired
private Translator translator; private Translator translator;
@ -27,7 +27,7 @@ public class ApologizerAutowiringTest {
@Test @Test
public void apologizeWithTranslatedMessage() { public void apologizeWithTranslatedMessage() {
when(translator.translate("sorry")).thenReturn(TRANSLATED); when(translator.translate("sorry")).thenReturn(TRANSLATED);
assertEquals(TRANSLATED, apologizer.apologize()); assertEquals(TRANSLATED, apologizeService.apologize());
} }
} }

View File

@ -6,7 +6,7 @@ import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class ApologizerTest { public class ApologizeServiceTest {
private final static String MESSAGE = "MESSAGE"; private final static String MESSAGE = "MESSAGE";
private final static String TRANSLATED = "TRANSLATED"; private final static String TRANSLATED = "TRANSLATED";
@ -14,8 +14,8 @@ public class ApologizerTest {
@Test @Test
public void apologizeWithCustomTranslatedMessage() { public void apologizeWithCustomTranslatedMessage() {
Translator translator = mock(Translator.class); Translator translator = mock(Translator.class);
Apologizer apologizer = new Apologizer(translator, MESSAGE); ApologizeService apologizeService = new ApologizeService(translator, MESSAGE);
when(translator.translate(MESSAGE)).thenReturn(TRANSLATED); when(translator.translate(MESSAGE)).thenReturn(TRANSLATED);
assertEquals(TRANSLATED, apologizer.apologize()); assertEquals(TRANSLATED, apologizeService.apologize());
} }
} }

View File

@ -17,7 +17,7 @@ import static org.mockito.Mockito.when;
public class FarewellAutowiringTest { public class FarewellAutowiringTest {
@Autowired @Autowired
private Fareweller fareweller; private FarewellService farewellService;
@Autowired @Autowired
private Translator translator; private Translator translator;
@ -26,6 +26,6 @@ public class FarewellAutowiringTest {
public void sayByeWithTranslatedMessage() { public void sayByeWithTranslatedMessage() {
String translated = "translated"; String translated = "translated";
when(translator.translate("bye")).thenReturn(translated); when(translator.translate("bye")).thenReturn(translated);
assertEquals(translated, fareweller.farewell()); assertEquals(translated, farewellService.farewell());
} }
} }

View File

@ -6,7 +6,7 @@ import static org.junit.Assert.*;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class FarewellerTest { public class FarewellServiceTest {
private final static String TRANSLATED = "TRANSLATED"; private final static String TRANSLATED = "TRANSLATED";
@ -14,7 +14,7 @@ public class FarewellerTest {
public void sayByeWithTranslatedMessage() { public void sayByeWithTranslatedMessage() {
Translator translator = mock(Translator.class); Translator translator = mock(Translator.class);
when(translator.translate("bye")).thenReturn(TRANSLATED); when(translator.translate("bye")).thenReturn(TRANSLATED);
Fareweller fareweller = new Fareweller(translator); FarewellService farewellService = new FarewellService(translator);
assertEquals(TRANSLATED, fareweller.farewell()); assertEquals(TRANSLATED, farewellService.farewell());
} }
} }

View File

@ -14,10 +14,10 @@ import static org.mockito.Mockito.when;
@ContextConfiguration( @ContextConfiguration(
loader = AnnotationConfigContextLoader.class, loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class) classes = TestConfig.class)
public class GreeterTest { public class GreetingServiceTest {
@Autowired @Autowired
private Greeter greeter; private GreetingService greetingService;
@Autowired @Autowired
private Translator translator; private Translator translator;
@ -26,12 +26,12 @@ public class GreeterTest {
public void greetWithTranslatedMessage() { public void greetWithTranslatedMessage() {
String translated = "translated"; String translated = "translated";
when(translator.translate("hello")).thenReturn(translated); when(translator.translate("hello")).thenReturn(translated);
assertEquals(translated, greeter.greet()); assertEquals(translated, greetingService.greet());
} }
@Test(expected = NullPointerException.class) @Test(expected = NullPointerException.class)
public void throwWhenInstantiated() { public void throwWhenInstantiated() {
Greeter greeter = new Greeter(); GreetingService greetingService = new GreetingService();
greeter.greet(); greetingService.greet();
} }
} }

View File

@ -14,10 +14,10 @@ import static org.mockito.Mockito.when;
@ContextConfiguration( @ContextConfiguration(
loader = AnnotationConfigContextLoader.class, loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class) classes = TestConfig.class)
public class ThankerAutowiringTest { public class ThankingServiceAutowiringTest {
@Autowired @Autowired
private Thanker thanker; private ThankingService thankingService;
@Autowired @Autowired
private Translator translator; private Translator translator;
@ -26,6 +26,6 @@ public class ThankerAutowiringTest {
public void thankWithTranslatedMessage() { public void thankWithTranslatedMessage() {
String translated = "translated"; String translated = "translated";
when(translator.translate("thank you")).thenReturn(translated); when(translator.translate("thank you")).thenReturn(translated);
assertEquals(translated, thanker.thank()); assertEquals(translated, thankingService.thank());
} }
} }

View File

@ -6,7 +6,7 @@ import static org.junit.Assert.*;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class ThankerTest { public class ThankingServiceTest {
private final static String TRANSLATED = "TRANSLATED"; private final static String TRANSLATED = "TRANSLATED";
@ -14,7 +14,7 @@ public class ThankerTest {
public void thankWithTranslatedMessage() { public void thankWithTranslatedMessage() {
Translator translator = mock(Translator.class); Translator translator = mock(Translator.class);
when(translator.translate("thank you")).thenReturn(TRANSLATED); when(translator.translate("thank you")).thenReturn(TRANSLATED);
Thanker thanker = new Thanker(translator); ThankingService thankingService = new ThankingService(translator);
assertEquals(TRANSLATED, thanker.thank()); assertEquals(TRANSLATED, thankingService.thank());
} }
} }

View File

@ -11,3 +11,4 @@
*.jar *.jar
*.war *.war
*.ear *.ear
/target/

View File

@ -21,10 +21,8 @@ public class HibernateAnnotationUtil {
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory; return sessionFactory;
} } catch (Throwable ex) {
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex); System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace(); ex.printStackTrace();
throw new ExceptionInInitializerError(ex); throw new ExceptionInInitializerError(ex);
@ -32,7 +30,8 @@ public class HibernateAnnotationUtil {
} }
public static SessionFactory getSessionFactory() { public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory(); if (sessionFactory == null)
sessionFactory = buildSessionFactory();
return sessionFactory; return sessionFactory;
} }
} }

View File

@ -21,7 +21,8 @@ public class HibernateOneToManyAnnotationMain {
Items item1 = new Items("I10", 10, 1, cart); Items item1 = new Items("I10", 10, 1, cart);
Items item2 = new Items("I20", 20, 2, cart); Items item2 = new Items("I20", 20, 2, cart);
Set<Items> itemsSet = new HashSet<Items>(); Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1); itemsSet.add(item2); itemsSet.add(item1);
itemsSet.add(item2);
cart.setItems(itemsSet); cart.setItems(itemsSet);
cart.setTotal(10 * 1 + 20 * 2); cart.setTotal(10 * 1 + 20 * 2);

View File

@ -31,24 +31,31 @@ public class Cart {
public long getId() { public long getId() {
return id; return id;
} }
public void setId(long id) { public void setId(long id) {
this.id = id; this.id = id;
} }
public double getTotal() { public double getTotal() {
return total; return total;
} }
public void setTotal(double total) { public void setTotal(double total) {
this.total = total; this.total = total;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public Set<Items> getItems() { public Set<Items> getItems() {
return items; return items;
} }
public void setItems(Set<Items> items) { public void setItems(Set<Items> items) {
this.items = items; this.items = items;
} }

View File

@ -32,7 +32,8 @@ public class Items {
private Cart cart; private Cart cart;
// Hibernate requires no-args constructor // Hibernate requires no-args constructor
public Items(){} public Items() {
}
public Items(String itemId, double total, int qty, Cart c) { public Items(String itemId, double total, int qty, Cart c) {
this.itemId = itemId; this.itemId = itemId;
@ -40,33 +41,43 @@ public class Items {
this.quantity = qty; this.quantity = qty;
this.cart = c; this.cart = c;
} }
public String getItemId() { public String getItemId() {
return itemId; return itemId;
} }
public void setItemId(String itemId) { public void setItemId(String itemId) {
this.itemId = itemId; this.itemId = itemId;
} }
public double getItemTotal() { public double getItemTotal() {
return itemTotal; return itemTotal;
} }
public void setItemTotal(double itemTotal) { public void setItemTotal(double itemTotal) {
this.itemTotal = itemTotal; this.itemTotal = itemTotal;
} }
public int getQuantity() { public int getQuantity() {
return quantity; return quantity;
} }
public void setQuantity(int quantity) { public void setQuantity(int quantity) {
this.quantity = quantity; this.quantity = quantity;
} }
public Cart getCart() { public Cart getCart() {
return cart; return cart;
} }
public void setCart(Cart cart) { public void setCart(Cart cart) {
this.cart = cart; this.cart = cart;
} }
public long getId() { public long getId() {
return id; return id;
} }
public void setId(long id) { public void setId(long id) {
this.id = id; this.id = id;
} }

View File

@ -1,24 +1,25 @@
package com.baeldung.hibernate.oneToMany.main; 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.HashSet;
import java.util.Set; import java.util.Set;
import static org.hamcrest.Matchers.hasSize;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.HSQLDialect; import org.hibernate.dialect.HSQLDialect;
import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; 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 { public class HibernateOneToManyAnnotationMainTest {
@ -29,12 +30,16 @@ public class HibernateOneToManyAnnotationMainTest {
public HibernateOneToManyAnnotationMainTest() { public HibernateOneToManyAnnotationMainTest() {
} }
@BeforeClass @BeforeClass
public static void beforeTests() { 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()) Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class)
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update"); .setProperty("hibernate.dialect", HSQLDialect.class.getName())
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); .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); sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} }
@ -42,28 +47,17 @@ public class HibernateOneToManyAnnotationMainTest {
public void setUp() { public void setUp() {
session = sessionFactory.openSession(); session = sessionFactory.openSession();
session.beginTransaction(); session.beginTransaction();
} }
@Test @Test
public void testAddItemsToCart() { public void givenSession_checkIfDatabaseIsEmpty() {
Cart cart = new Cart(); Cart cart = (Cart) session.get(Cart.class, new Long(1));
Set <Items> cartItems = new HashSet<>(); assertNull(cart);
cartItems = cart.getItems();
Assert.assertNull(cartItems);
Items item1 = new Items("I10", 10, 1, cart);
assertNotNull(item1);
Set<Items> itemsSet = new HashSet<Items>();
cart.setItems(itemsSet);
assertNotNull(cart);
System.out.println("Items added to cart");
} }
@Test @Test
public void testSaveCart(){ public void givenSession_checkIfDatabaseIsPopulated_afterCommit() {
Cart cart = new Cart(); Cart cart = new Cart();
Set<Items> cartItems = new HashSet<>(); Set<Items> cartItems = new HashSet<>();
cartItems = cart.getItems(); cartItems = cart.getItems();
@ -83,7 +77,21 @@ public class HibernateOneToManyAnnotationMainTest {
session.getTransaction().commit(); session.getTransaction().commit();
session.close(); 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();
}
} }

View File

@ -1,22 +1,24 @@
package com.baeldung.excel; package com.baeldung.excel;
import jxl.*; import jxl.Sheet;
import java.util.Map; import jxl.Workbook;
import java.util.HashMap; import jxl.format.Colour;
import java.util.ArrayList;
import jxl.read.biff.BiffException; import jxl.read.biff.BiffException;
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Service;
import jxl.write.*; import jxl.write.*;
import jxl.write.Number; 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 @Service
public class JExcelHelper { public class JExcelHelper {
public Map<Integer, ArrayList<String>> readJExcel(String fileLocation) throws IOException, BiffException { public Map<Integer, ArrayList<String>> readJExcel(String fileLocation) throws IOException, BiffException {
Map<Integer, ArrayList<String>> data = new HashMap<Integer, ArrayList<String>>(); Map<Integer, ArrayList<String>> data = new HashMap<>();
Workbook workbook = Workbook.getWorkbook(new File(fileLocation)); Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
Sheet sheet = workbook.getSheet(0); Sheet sheet = workbook.getSheet(0);
@ -24,7 +26,7 @@ public class JExcelHelper {
int columns = sheet.getColumns(); int columns = sheet.getColumns();
for (int i = 0; i < rows; i++) { for (int i = 0; i < rows; i++) {
data.put(i, new ArrayList<String>()); data.put(i, new ArrayList<>());
for (int j = 0; j < columns; j++) { for (int j = 0; j < columns; j++) {
data.get(i).add(sheet.getCell(j, i).getContents()); data.get(i).add(sheet.getCell(j, i).getContents());
} }