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

View File

@ -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() {

View File

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

View File

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

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.assertTrue;
public class ThreadPoolInParallelStream {
public class ThreadPoolInParallelStreamTest {
@Test
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal()

View File

@ -94,6 +94,7 @@
<module>rest-assured</module>
<module>rest-testing</module>
<module>resteasy</module>
<module>rxjava</module>
<module>selenium-junit-testng</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,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")));
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -10,4 +10,5 @@
# Packaged files #
*.jar
*.war
*.ear
*.ear
/target/

View File

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

View File

@ -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<Items> itemsSet = new HashSet<Items>();
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<Items> itemsSet = new HashSet<Items>();
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();
}
}
}
}

View File

@ -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> 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<Items> getItems() {
return items;
}
public void setItems(Set<Items> 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> 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<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
}
}

View File

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

View File

@ -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<Items> 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<Items> itemsSet = new HashSet<Items>();
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 <Items> cartItems = new HashSet<>();
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
public void testSaveCart(){
Cart cart = new Cart();
Set <Items> 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<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1);
assertNotNull(itemsSet);
cart.setItems(itemsSet);
assertNotNull(cart);
session.persist(cart);
session.getTransaction().commit();
session.close();
}
}

View File

@ -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<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));
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<String>());
data.put(i, new ArrayList<>());
for (int j = 0; j < columns; j++) {
data.get(i).add(sheet.getCell(j, i).getContents());
}