Merge branch 'master' into sla-pr/1108-junit

This commit is contained in:
slavisa-baeldung 2017-02-13 01:21:45 +01:00
commit 04a87a9df5
268 changed files with 4783 additions and 1020 deletions

17
.travis.yml Normal file
View File

@ -0,0 +1,17 @@
language: java
install: travis_wait 40 mvn -q clean install -Dgib.enabled=true
jdk:
- oraclejdk8
sudo: false
addons:
apt:
packages:
- oracle-java8-installer
cache:
directories:
- .autoconf
- $HOME/.m2

View File

@ -1,2 +1,3 @@
### Relevant Articles:
- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel)

View File

@ -9,6 +9,7 @@
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<junit.version>4.12</junit.version>
<poi.version>3.15</poi.version>
<jexcel.version>1.0.6</jexcel.version>
</properties>
<build>
@ -37,5 +38,10 @@
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-jexcel</artifactId>
<version>${jexcel.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,74 @@
package com.baeldung.jexcel;
import jxl.*;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import jxl.read.biff.BiffException;
import java.io.File;
import java.io.IOException;
import jxl.write.*;
import jxl.write.Number;
import jxl.format.Colour;
public class JExcelHelper {
public Map<Integer, List<String>> readJExcel(String fileLocation) throws IOException, BiffException {
Map<Integer, List<String>> data = new HashMap<>();
Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
Sheet sheet = workbook.getSheet(0);
int rows = sheet.getRows();
int columns = sheet.getColumns();
for (int i = 0; i < rows; i++) {
data.put(i, new ArrayList<String>());
for (int j = 0; j < columns; j++) {
data.get(i).add(sheet.getCell(j, i).getContents());
}
}
return data;
}
public void writeJExcel() throws IOException, WriteException {
WritableWorkbook workbook = null;
try {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
String fileLocation = path.substring(0, path.length() - 1) + "temp.xls";
workbook = Workbook.createWorkbook(new File(fileLocation));
WritableSheet sheet = workbook.createSheet("Sheet 1", 0);
WritableCellFormat headerFormat = new WritableCellFormat();
WritableFont font = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
headerFormat.setFont(font);
headerFormat.setBackground(Colour.LIGHT_BLUE);
headerFormat.setWrap(true);
Label headerLabel = new Label(0, 0, "Name", headerFormat);
sheet.setColumnView(0, 60);
sheet.addCell(headerLabel);
headerLabel = new Label(1, 0, "Age", headerFormat);
sheet.setColumnView(0, 40);
sheet.addCell(headerLabel);
WritableCellFormat cellFormat = new WritableCellFormat();
cellFormat.setWrap(true);
Label cellLabel = new Label(0, 2, "John Smith", cellFormat);
sheet.addCell(cellLabel);
Number cellNumber = new Number(1, 2, 20, cellFormat);
sheet.addCell(cellNumber);
workbook.write();
} finally {
if (workbook != null) {
workbook.close();
}
}
}
}

View File

@ -0,0 +1,128 @@
package com.baeldung.poi.excel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FillPatternType;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
public class ExcelPOIHelper {
public Map<Integer, List<String>> readExcel(String fileLocation) throws IOException {
Map<Integer, List<String>> data = new HashMap<>();
FileInputStream file = new FileInputStream(new File(fileLocation));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
int i = 0;
for (Row row : sheet) {
data.put(i, new ArrayList<String>());
for (Cell cell : row) {
switch (cell.getCellTypeEnum()) {
case STRING:
data.get(i)
.add(cell.getRichStringCellValue()
.getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
data.get(i)
.add(cell.getDateCellValue() + "");
} else {
data.get(i)
.add((int)cell.getNumericCellValue() + "");
}
break;
case BOOLEAN:
data.get(i)
.add(cell.getBooleanCellValue() + "");
break;
case FORMULA:
data.get(i)
.add(cell.getCellFormula() + "");
break;
default:
data.get(i)
.add(" ");
}
}
i++;
}
if (workbook != null){
workbook.close();
}
return data;
}
public void writeExcel() throws IOException {
Workbook workbook = new XSSFWorkbook();
try {
Sheet sheet = workbook.createSheet("Persons");
sheet.setColumnWidth(0, 6000);
sheet.setColumnWidth(1, 4000);
Row header = sheet.createRow(0);
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
XSSFFont font = ((XSSFWorkbook) workbook).createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 16);
font.setBold(true);
headerStyle.setFont(font);
Cell headerCell = header.createCell(0);
headerCell.setCellValue("Name");
headerCell.setCellStyle(headerStyle);
headerCell = header.createCell(1);
headerCell.setCellValue("Age");
headerCell.setCellStyle(headerStyle);
CellStyle style = workbook.createCellStyle();
style.setWrapText(true);
Row row = sheet.createRow(2);
Cell cell = row.createCell(0);
cell.setCellValue("John Smith");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue(20);
cell.setCellStyle(style);
File currDir = new File(".");
String path = currDir.getAbsolutePath();
String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx";
FileOutputStream outputStream = new FileOutputStream(fileLocation);
workbook.write(outputStream);
} finally {
if (workbook != null) {
workbook.close();
}
}
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.jexcel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import jxl.read.biff.BiffException;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.jexcel.JExcelHelper;
import jxl.write.WriteException;
import jxl.read.biff.BiffException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.Before;
public class JExcelTest {
private JExcelHelper jExcelHelper;
private static String FILE_NAME = "temp.xls";
private String fileLocation;
@Before
public void generateExcelFile() throws IOException, WriteException {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
jExcelHelper = new JExcelHelper();
jExcelHelper.writeJExcel();
}
@Test
public void whenParsingJExcelFile_thenCorrect() throws IOException, BiffException {
Map<Integer, List<String>> data = jExcelHelper.readJExcel(fileLocation);
assertEquals("Name", data.get(0)
.get(0));
assertEquals("Age", data.get(0)
.get(1));
assertEquals("John Smith", data.get(2)
.get(0));
assertEquals("20", data.get(2)
.get(1));
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.poi.excel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import jxl.read.biff.BiffException;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.poi.excel.ExcelPOIHelper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.Before;
public class ExcelTest {
private ExcelPOIHelper excelPOIHelper;
private static String FILE_NAME = "temp.xlsx";
private String fileLocation;
@Before
public void generateExcelFile() throws IOException {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
excelPOIHelper = new ExcelPOIHelper();
excelPOIHelper.writeExcel();
}
@Test
public void whenParsingPOIExcelFile_thenCorrect() throws IOException {
Map<Integer, List<String>> data = excelPOIHelper.readExcel(fileLocation);
assertEquals("Name", data.get(0)
.get(0));
assertEquals("Age", data.get(0)
.get(1));
assertEquals("John Smith", data.get(1)
.get(0));
assertEquals("20", data.get(1)
.get(1));
}
}

BIN
apache-poi/temp.xls Normal file

Binary file not shown.

BIN
apache-poi/temp.xlsx Normal file

Binary file not shown.

View File

View File

View File

View File

View File

View File

View File

View File

@ -57,3 +57,4 @@
- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future)
- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch)
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)

View File

@ -1,5 +1,5 @@
<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">
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>core-java</artifactId>
@ -10,6 +10,44 @@
<dependencies>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-jdbc-driver</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm-core</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm-embedded-driver</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.1.0</version>
<classifier>no_aop</classifier>
<scope>test</scope>
</dependency>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
@ -63,7 +101,6 @@
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
@ -154,6 +191,12 @@
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
@ -263,7 +306,8 @@
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
@ -371,6 +415,7 @@
<mockito.version>1.10.19</mockito.version>
<testng.version>6.10</testng.version>
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>

View File

@ -24,7 +24,8 @@ public class RunAlgorithm {
SlopeOne.slopeOne(3);
break;
case 3:
SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
break;
default:
System.out.println("Unknown option");

View File

@ -5,40 +5,40 @@ import lombok.Data;
@Data
public class Individual {
protected int defaultGeneLength = 64;
private byte[] genes = new byte[defaultGeneLength];
private int fitness = 0;
protected int defaultGeneLength = 64;
private byte[] genes = new byte[defaultGeneLength];
private int fitness = 0;
public Individual() {
for (int i = 0; i < genes.length; i++) {
byte gene = (byte) Math.round(Math.random());
genes[i] = gene;
}
}
public Individual() {
for (int i = 0; i < genes.length; i++) {
byte gene = (byte) Math.round(Math.random());
genes[i] = gene;
}
}
protected byte getSingleGene(int index) {
return genes[index];
}
protected byte getSingleGene(int index) {
return genes[index];
}
protected void setSingleGene(int index, byte value) {
genes[index] = value;
fitness = 0;
}
protected void setSingleGene(int index, byte value) {
genes[index] = value;
fitness = 0;
}
public int getFitness() {
if (fitness == 0) {
fitness = SimpleGeneticAlgorithm.getFitness(this);
}
return fitness;
}
public int getFitness() {
if (fitness == 0) {
fitness = SimpleGeneticAlgorithm.getFitness(this);
}
return fitness;
}
@Override
public String toString() {
String geneString = "";
for (int i = 0; i < genes.length; i++) {
geneString += getSingleGene(i);
}
return geneString;
}
@Override
public String toString() {
String geneString = "";
for (int i = 0; i < genes.length; i++) {
geneString += getSingleGene(i);
}
return geneString;
}
}

View File

@ -8,33 +8,33 @@ import lombok.Data;
@Data
public class Population {
private List<Individual> individuals;
private List<Individual> individuals;
public Population(int size, boolean createNew) {
individuals = new ArrayList<>();
if (createNew) {
createNewPopulation(size);
}
}
public Population(int size, boolean createNew) {
individuals = new ArrayList<>();
if (createNew) {
createNewPopulation(size);
}
}
protected Individual getIndividual(int index) {
return individuals.get(index);
}
protected Individual getIndividual(int index) {
return individuals.get(index);
}
protected Individual getFittest() {
Individual fittest = individuals.get(0);
for (int i = 0; i < individuals.size(); i++) {
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
fittest = getIndividual(i);
}
}
return fittest;
}
protected Individual getFittest() {
Individual fittest = individuals.get(0);
for (int i = 0; i < individuals.size(); i++) {
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
fittest = getIndividual(i);
}
}
return fittest;
}
private void createNewPopulation(int size) {
for (int i = 0; i < size; i++) {
Individual newIndividual = new Individual();
individuals.add(i, newIndividual);
}
}
private void createNewPopulation(int size) {
for (int i = 0; i < size; i++) {
Individual newIndividual = new Individual();
individuals.add(i, newIndividual);
}
}
}

View File

@ -5,115 +5,113 @@ import lombok.Data;
@Data
public class SimpleGeneticAlgorithm {
private static final double uniformRate = 0.5;
private static final double mutationRate = 0.025;
private static final int tournamentSize = 5;
private static final boolean elitism = true;
private static byte[] solution = new byte[64];
private static final double uniformRate = 0.5;
private static final double mutationRate = 0.025;
private static final int tournamentSize = 5;
private static final boolean elitism = true;
private static byte[] solution = new byte[64];
public static boolean runAlgorithm(int populationSize, String solution) {
if (solution.length() != SimpleGeneticAlgorithm.solution.length) {
throw new RuntimeException(
"The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes");
}
SimpleGeneticAlgorithm.setSolution(solution);
Population myPop = new Population(populationSize, true);
public boolean runAlgorithm(int populationSize, String solution) {
if (solution.length() != SimpleGeneticAlgorithm.solution.length) {
throw new RuntimeException("The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes");
}
setSolution(solution);
Population myPop = new Population(populationSize, true);
int generationCount = 1;
while (myPop.getFittest().getFitness() < SimpleGeneticAlgorithm.getMaxFitness()) {
System.out.println(
"Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness());
myPop = SimpleGeneticAlgorithm.evolvePopulation(myPop);
generationCount++;
}
System.out.println("Solution found!");
System.out.println("Generation: " + generationCount);
System.out.println("Genes: ");
System.out.println(myPop.getFittest());
return true;
}
int generationCount = 1;
while (myPop.getFittest().getFitness() < getMaxFitness()) {
System.out.println("Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness());
myPop = evolvePopulation(myPop);
generationCount++;
}
System.out.println("Solution found!");
System.out.println("Generation: " + generationCount);
System.out.println("Genes: ");
System.out.println(myPop.getFittest());
return true;
}
public static Population evolvePopulation(Population pop) {
int elitismOffset;
Population newPopulation = new Population(pop.getIndividuals().size(), false);
public Population evolvePopulation(Population pop) {
int elitismOffset;
Population newPopulation = new Population(pop.getIndividuals().size(), false);
if (elitism) {
newPopulation.getIndividuals().add(0, pop.getFittest());
elitismOffset = 1;
} else {
elitismOffset = 0;
}
if (elitism) {
newPopulation.getIndividuals().add(0, pop.getFittest());
elitismOffset = 1;
} else {
elitismOffset = 0;
}
for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) {
Individual indiv1 = tournamentSelection(pop);
Individual indiv2 = tournamentSelection(pop);
Individual newIndiv = crossover(indiv1, indiv2);
newPopulation.getIndividuals().add(i, newIndiv);
}
for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) {
Individual indiv1 = tournamentSelection(pop);
Individual indiv2 = tournamentSelection(pop);
Individual newIndiv = crossover(indiv1, indiv2);
newPopulation.getIndividuals().add(i, newIndiv);
}
for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) {
mutate(newPopulation.getIndividual(i));
}
for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) {
mutate(newPopulation.getIndividual(i));
}
return newPopulation;
}
return newPopulation;
}
private static Individual crossover(Individual indiv1, Individual indiv2) {
Individual newSol = new Individual();
for (int i = 0; i < newSol.getDefaultGeneLength(); i++) {
if (Math.random() <= uniformRate) {
newSol.setSingleGene(i, indiv1.getSingleGene(i));
} else {
newSol.setSingleGene(i, indiv2.getSingleGene(i));
}
}
return newSol;
}
private 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 void mutate(Individual indiv) {
for (int i = 0; i < indiv.getDefaultGeneLength(); i++) {
if (Math.random() <= mutationRate) {
byte gene = (byte) Math.round(Math.random());
indiv.setSingleGene(i, gene);
}
}
}
private static Individual tournamentSelection(Population pop) {
Population tournament = new Population(tournamentSize, false);
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.getIndividuals().size());
tournament.getIndividuals().add(i, pop.getIndividual(randomId));
}
Individual fittest = tournament.getFittest();
return fittest;
}
private Individual tournamentSelection(Population pop) {
Population tournament = new Population(tournamentSize, false);
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.getIndividuals().size());
tournament.getIndividuals().add(i, pop.getIndividual(randomId));
}
Individual fittest = tournament.getFittest();
return fittest;
}
protected static int getFitness(Individual individual) {
int fitness = 0;
for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) {
if (individual.getSingleGene(i) == solution[i]) {
fitness++;
}
}
return fitness;
}
protected static int getFitness(Individual individual) {
int fitness = 0;
for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) {
if (individual.getSingleGene(i) == solution[i]) {
fitness++;
}
}
return fitness;
}
protected static int getMaxFitness() {
int maxFitness = solution.length;
return maxFitness;
}
protected int getMaxFitness() {
int maxFitness = solution.length;
return maxFitness;
}
protected static void setSolution(String newSolution) {
solution = new byte[newSolution.length()];
for (int i = 0; i < newSolution.length(); i++) {
String character = newSolution.substring(i, i + 1);
if (character.contains("0") || character.contains("1")) {
solution[i] = Byte.parseByte(character);
} else {
solution[i] = 0;
}
}
}
protected 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

@ -15,6 +15,6 @@ public class SquareCalculator {
return executor.submit(() -> {
Thread.sleep(1000);
return input * input;
});
});
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.graph;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
/**
* @author Danil Kornishev (danil.kornishev@mastercard.com)
*/
@NodeEntity
public class Car {
@GraphId
private Long id;
private String make;
@Relationship(direction = "INCOMING")
private Company company;
public Car(String make, String model) {
this.make = make;
this.model = model;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
private String model;
}

View File

@ -0,0 +1,45 @@
package com.baeldung.graph;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
/**
* @author Danil Kornishev (danil.kornishev@mastercard.com)
*/
@NodeEntity
public class Company {
private Long id;
private String name;
@Relationship(type="owns")
private Car car;
public Company(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.java_8_features.groupingby;
public class BlogPost {
private String title;
private String author;
private BlogPostType type;
private int likes;
public BlogPost(String title, String author, BlogPostType type, int likes) {
this.title = title;
this.author = author;
this.type = type;
this.likes = likes;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public BlogPostType getType() {
return type;
}
public int getLikes() {
return likes;
}
@Override
public String toString() {
return "BlogPost{" + "title='" + title + '\'' + ", type=" + type + ", likes=" + likes + '}';
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.java_8_features.groupingby;
public enum BlogPostType {
NEWS, REVIEW, GUIDE
}

View File

@ -0,0 +1,11 @@
package com.baeldung.strategy;
import java.math.BigDecimal;
public class ChristmasDiscounter implements Discounter {
@Override
public BigDecimal apply(BigDecimal amount) {
return amount.multiply(BigDecimal.valueOf(0.9));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.strategy;
import java.math.BigDecimal;
import java.util.function.UnaryOperator;
public interface Discounter extends UnaryOperator<BigDecimal> {
default Discounter combine(Discounter after) {
return value -> after.apply(this.apply(value));
}
static Discounter christmas() {
return (amount) -> amount.multiply(BigDecimal.valueOf(0.9));
}
static Discounter newYear() {
return (amount) -> amount.multiply(BigDecimal.valueOf(0.8));
}
static Discounter easter() {
return (amount) -> amount.multiply(BigDecimal.valueOf(0.5));
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.strategy;
import java.math.BigDecimal;
public class EasterDiscounter implements Discounter {
@Override
public BigDecimal apply(BigDecimal amount) {
return amount.multiply(BigDecimal.valueOf(0.5));
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.stream;
import java.util.stream.Stream;
public class InfiniteStreams {
public static void main(String[] args) {
doWhileOldWay();
doWhileStreamWay();
}
private static void doWhileOldWay() {
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
}
private static void doWhileStreamWay() {
Stream<Integer> integers = Stream.iterate(0, i -> i + 1);
integers.limit(10).forEach(System.out::println);
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.string;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class JoinerSplitter {
public static String join ( String[] arrayOfString ) {
return Arrays.asList(arrayOfString)
.stream()
.map(x -> x)
.collect(Collectors.joining(","));
}
public static String joinWithPrefixPostFix ( String[] arrayOfString ) {
return Arrays.asList(arrayOfString)
.stream()
.map(x -> x)
.collect(Collectors.joining(",","[","]"));
}
public static List<String> split ( String str ) {
return Stream.of(str.split(","))
.map (elem -> new String(elem))
.collect(Collectors.toList());
}
public static List<Character> splitToListOfChar ( String str ) {
return str.chars()
.mapToObj(item -> (char) item)
.collect(Collectors.toList());
}
}

View File

@ -8,55 +8,55 @@ public class CharArrayToStringUnitTest {
@Test
public void givenCharArray_whenCallingStringConstructor_shouldConvertToString() {
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
String result = new String(charArray);
String expectedValue = "character";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString(){
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString() {
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
String result = new String(charArray, 4, 3);
String expectedValue = "act";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString(){
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString() {
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
String result = String.copyValueOf(charArray);
String expectedValue = "character";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString(){
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString() {
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
String result = String.copyValueOf(charArray, 0, 4);
String expectedValue = "char";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringValueOf_shouldConvertToString(){
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
public void givenCharArray_whenCallingStringValueOf_shouldConvertToString() {
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
String result = String.valueOf(charArray);
String expectedValue = "character";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString(){
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString() {
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
String result = String.valueOf(charArray, 3, 4);
String expectedValue = "ract";
assertEquals(expectedValue, result);
}
}

View File

@ -6,15 +6,15 @@ import org.junit.Test;
public class StringToCharArrayUnitTest {
@Test
public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() {
String givenString = "characters";
@Test
public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() {
String givenString = "characters";
char[] result = givenString.toCharArray();
char[] result = givenString.toCharArray();
char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' };
char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' };
assertArrayEquals(expectedCharArray, result);
}
assertArrayEquals(expectedCharArray, result);
}
}

View File

@ -1,16 +0,0 @@
package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
public class BinaryGeneticAlgorithmTest {
@Test
public void testGA() {
Assert.assertTrue(SimpleGeneticAlgorithm.runAlgorithm(50,
"1011000100000100010000100000100111001000000100000100000000001111"));
}
}

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 BinaryGeneticAlgorithmUnitTest {
@Test
public void testGA() {
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"));
}
}

View File

@ -32,13 +32,14 @@ public class PriorityBlockingQueueUnitTest {
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) {}
}
System.out.println("Polling...");
while (true) {
try {
Integer poll = queue.take();
System.out.println("Polled: " + poll);
} catch (InterruptedException e) {
}
}
});
thread.start();

View File

@ -0,0 +1,60 @@
package com.baeldung.graph;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Ignore;
import org.junit.Test;
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.testng.Assert;
@Ignore
public class Neo4JServerTest {
@Test
public void standAloneDriver() {
Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "12345"));
Session session = driver.session();
session.run("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
"-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
"RETURN baeldung, tesla");
StatementResult result = session.run("MATCH (company:Company)-[:owns]-> (car:Car)" +
"WHERE car.make='tesla' and car.model='modelX'" +
"RETURN company.name");
Assert.assertTrue(result.hasNext());
Assert.assertEquals(result.next().get("company.name").asString(), "Baeldung");
session.close();
driver.close();
}
@Test
public void standAloneJdbc() throws Exception {
Connection con = DriverManager.getConnection("jdbc:neo4j:bolt://localhost/?user=neo4j,password=12345,scheme=basic");
// Querying
try (Statement stmt = con.createStatement()) {
stmt.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
"-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
"RETURN baeldung, tesla");
ResultSet rs = stmt.executeQuery("MATCH (company:Company)-[:owns]-> (car:Car)" +
"WHERE car.make='tesla' and car.model='modelX'" +
"RETURN company.name");
while (rs.next()) {
Assert.assertEquals(rs.getString("company.name"), "Baeldung");
}
}
con.close();
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.graph;
import org.junit.Test;
import org.neo4j.ogm.config.Configuration;
import org.neo4j.ogm.model.Result;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
import org.testng.Assert;
import java.util.HashMap;
import java.util.Map;
/**
* @author Danil Kornishev (danil.kornishev@mastercard.com)
*/
public class Neo4jOgmTest {
@Test
public void testOgm() {
Configuration conf = new Configuration();
conf.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
SessionFactory factory = new SessionFactory(conf, "com.baeldung.graph");
Session session = factory.openSession();
Car tesla = new Car("tesla", "modelS");
Company baeldung = new Company("baeldung");
baeldung.setCar(tesla);
session.save(baeldung);
Map<String, String> params = new HashMap<>();
params.put("make", "tesla");
Result result = session.query("MATCH (car:Car) <-[:owns]- (company:Company)" +
" WHERE car.make=$make" +
" RETURN company", params);
Map<String, Object> firstResult = result.iterator().next();
Assert.assertEquals(firstResult.size(), 1);
Company actual = (Company) firstResult.get("company");
Assert.assertEquals(actual.getName(), baeldung.getName());
}
}

View File

@ -0,0 +1,167 @@
package com.baeldung.graph;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.NotFoundException;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.testng.Assert;
public class Neo4jTest {
private static GraphDatabaseService graphDb;
@Before
public void setUp() {
GraphDatabaseFactory graphDbFactory = new GraphDatabaseFactory();
graphDb = graphDbFactory.newEmbeddedDatabase(new File("data/cars"));
}
@After
public void tearDown() {
graphDb.shutdown();
}
@Test
public void testPersonCar() {
graphDb.beginTx();
Node car = graphDb.createNode(Label.label("Car"));
car.setProperty("make", "tesla");
car.setProperty("model", "model3");
Node owner = graphDb.createNode(Label.label("Person"));
owner.setProperty("firstName", "baeldung");
owner.setProperty("lastName", "baeldung");
owner.createRelationshipTo(car, RelationshipType.withName("owner"));
Result result = graphDb.execute("MATCH (c:Car) <-[owner]- (p:Person) " +
"WHERE c.make = 'tesla'" +
"RETURN p.firstName, p.lastName");
Map<String, Object> firstResult = result.next();
Assert.assertEquals("baeldung", firstResult.get("p.firstName"));
}
@Test
public void testCreateNode() {
graphDb.beginTx();
Result result = graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"})" +
"RETURN baeldung");
Map<String, Object> firstResult = result.next();
Node firstNode = (Node) firstResult.get("baeldung");
Assert.assertEquals(firstNode.getProperty("name"), "Baeldung");
}
@Test
public void testCreateNodeAndLink() {
graphDb.beginTx();
Result result = graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
"-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
"RETURN baeldung, tesla");
Map<String, Object> firstResult = result.next();
Assert.assertTrue(firstResult.containsKey("baeldung"));
Assert.assertTrue(firstResult.containsKey("tesla"));
}
@Test
public void testFindAndReturn() {
graphDb.beginTx();
graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
"-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
"RETURN baeldung, tesla");
Result result = graphDb.execute("MATCH (company:Company)-[:owns]-> (car:Car)" +
"WHERE car.make='tesla' and car.model='modelX'" +
"RETURN company.name");
Map<String, Object> firstResult = result.next();
Assert.assertEquals(firstResult.get("company.name"), "Baeldung");
}
@Test
public void testUpdate() {
graphDb.beginTx();
graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
"-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
"RETURN baeldung, tesla");
Result result = graphDb.execute("MATCH (car:Car)" +
"WHERE car.make='tesla'" +
" SET car.milage=120" +
" SET car :Car:Electro" +
" SET car.model=NULL" +
" RETURN car");
Map<String, Object> firstResult = result.next();
Node car = (Node) firstResult.get("car");
Assert.assertEquals(car.getProperty("milage"), 120L);
Assert.assertEquals(car.getLabels(), Arrays.asList(Label.label("Car"), Label.label("Electro")));
try {
car.getProperty("model");
Assert.fail();
} catch (NotFoundException e) {
// expected
}
}
@Test
public void testDelete() {
graphDb.beginTx();
graphDb.execute("CREATE (baeldung:Company {name:\"Baeldung\"}) " +
"-[:owns]-> (tesla:Car {make: 'tesla', model: 'modelX'})" +
"RETURN baeldung, tesla");
graphDb.execute("MATCH (company:Company)" +
" WHERE company.name='Baeldung'" +
" DELETE company");
Result result = graphDb.execute("MATCH (company:Company)" +
" WHERE company.name='Baeldung'" +
" RETURN company");
Assert.assertFalse(result.hasNext());
}
@Test
public void testBindings() {
graphDb.beginTx();
Map<String, Object> params = new HashMap<>();
params.put("name", "baeldung");
params.put("make", "tesla");
params.put("model", "modelS");
Result result = graphDb.execute("CREATE (baeldung:Company {name:$name}) " +
"-[:owns]-> (tesla:Car {make: $make, model: $model})" +
"RETURN baeldung, tesla", params);
Map<String, Object> firstResult = result.next();
Assert.assertTrue(firstResult.containsKey("baeldung"));
Assert.assertTrue(firstResult.containsKey("tesla"));
Node car = (Node) firstResult.get("tesla");
Assert.assertEquals(car.getProperty("model"), "modelS");
}
}

View File

@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class ConcurrentMapAggregateStatusTest {
public class ConcurrentMapAggregateStatusManualTest {
private ExecutorService executorService;
private Map<String, Integer> concurrentMap;

View File

@ -10,7 +10,7 @@ import java.util.concurrent.ConcurrentMap;
import static org.junit.Assert.assertNull;
public class ConcurrentMapNullKeyValueTest {
public class ConcurrentMapNullKeyValueManualTest {
ConcurrentMap<String, Object> concurrentMap;

View File

@ -11,7 +11,7 @@ import java.util.concurrent.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConcurrentMapPerformanceTest {
public class ConcurrentMapPerformanceManualTest {
@Test
public void givenMaps_whenGetPut500KTimes_thenConcurrentMapFaster() throws Exception {

View File

@ -10,7 +10,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import static org.testng.Assert.*;
public class ConcurrentNavigableMapTests {
public class ConcurrentNavigableMapManualTests {
@Test
public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throws InterruptedException {
@ -18,9 +18,7 @@ public class ConcurrentNavigableMapTests {
updateMapConcurrently(skipListMap, 4);
Iterator<Integer> skipListIter = skipListMap
.keySet()
.iterator();
Iterator<Integer> skipListIter = skipListMap.keySet().iterator();
int previous = skipListIter.next();
while (skipListIter.hasNext()) {
int current = skipListIter.next();

View File

@ -10,7 +10,7 @@ import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class ConcurretMapMemoryConsistencyTest {
public class ConcurretMapMemoryConsistencyManualTest {
@Test
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {

View File

@ -0,0 +1,80 @@
package com.baeldung.java.concurrentmodification;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.util.Lists.newArrayList;
public class ConcurrentModificationUnitTest {
@Test(expected = ConcurrentModificationException.class)
public void givenIterating_whenRemoving_thenThrowException() throws InterruptedException {
List<Integer> integers = newArrayList(1, 2, 3);
for (Integer integer : integers) {
integers.remove(1);
}
}
@Test
public void givenIterating_whenUsingIteratorRemove_thenNoError() throws InterruptedException {
List<Integer> integers = newArrayList(1, 2, 3);
for (Iterator<Integer> iterator = integers.iterator(); iterator.hasNext();) {
Integer integer = iterator.next();
if(integer == 2) {
iterator.remove();
}
}
assertThat(integers).containsExactly(1, 3);
}
@Test
public void givenIterating_whenUsingRemovalList_thenNoError() throws InterruptedException {
List<Integer> integers = newArrayList(1, 2, 3);
List<Integer> toRemove = newArrayList();
for (Integer integer : integers) {
if(integer == 2) {
toRemove.add(integer);
}
}
integers.removeAll(toRemove);
assertThat(integers).containsExactly(1, 3);
}
@Test
public void whenUsingRemoveIf_thenRemoveElements() throws InterruptedException {
Collection<Integer> integers = newArrayList(1, 2, 3);
integers.removeIf(i -> i == 2);
assertThat(integers).containsExactly(1, 3);
}
@Test
public void whenUsingStream_thenRemoveElements() {
Collection<Integer> integers = newArrayList(1, 2, 3);
List<String> collected = integers
.stream()
.filter(i -> i != 2)
.map(Object::toString)
.collect(toList());
assertThat(collected).containsExactly("1", "3");
}
}

View File

@ -0,0 +1,231 @@
package com.baeldung.java8;
import com.baeldung.java_8_features.groupingby.BlogPost;
import com.baeldung.java_8_features.groupingby.BlogPostType;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.*;
import static org.junit.Assert.*;
public class Java8GroupingByCollectorUnitTest {
private static final List<BlogPost> posts = Arrays.asList(
new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15),
new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20),
new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35),
new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
@Test
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
Map<BlogPostType, List<BlogPost>> postsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType));
assertEquals(2, postsPerType
.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType
.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
Map<BlogPostType, String> postsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
assertEquals("Post titles: [Tech review 1, Tech review 2]", postsPerType.get(BlogPostType.REVIEW));
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
Map<BlogPostType, Integer> likesPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
assertEquals(50, likesPerType
.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, likesPerType
.get(BlogPostType.REVIEW)
.intValue());
assertEquals(20, likesPerType
.get(BlogPostType.GUIDE)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
assertEquals(2, postsPerType
.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType
.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
Map<BlogPostType, Set<BlogPost>> postsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, toSet()));
assertEquals(2, postsPerType
.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType
.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts
.parallelStream()
.collect(groupingByConcurrent(BlogPost::getType));
assertEquals(2, postsPerType
.get(BlogPostType.NEWS)
.size());
assertEquals(1, postsPerType
.get(BlogPostType.GUIDE)
.size());
assertEquals(2, postsPerType
.get(BlogPostType.REVIEW)
.size());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
Map<BlogPostType, Double> averageLikesPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
assertEquals(25, averageLikesPerType
.get(BlogPostType.NEWS)
.intValue());
assertEquals(20, averageLikesPerType
.get(BlogPostType.GUIDE)
.intValue());
assertEquals(10, averageLikesPerType
.get(BlogPostType.REVIEW)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
Map<BlogPostType, Long> numberOfPostsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, counting()));
assertEquals(2, numberOfPostsPerType
.get(BlogPostType.NEWS)
.intValue());
assertEquals(1, numberOfPostsPerType
.get(BlogPostType.GUIDE)
.intValue());
assertEquals(2, numberOfPostsPerType
.get(BlogPostType.REVIEW)
.intValue());
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts
.stream()
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
assertTrue(maxLikesPerPostType
.get(BlogPostType.NEWS)
.isPresent());
assertEquals(35, maxLikesPerPostType
.get(BlogPostType.NEWS)
.get()
.getLikes());
assertTrue(maxLikesPerPostType
.get(BlogPostType.GUIDE)
.isPresent());
assertEquals(20, maxLikesPerPostType
.get(BlogPostType.GUIDE)
.get()
.getLikes());
assertTrue(maxLikesPerPostType
.get(BlogPostType.REVIEW)
.isPresent());
assertEquals(15, maxLikesPerPostType
.get(BlogPostType.REVIEW)
.get()
.getLikes());
}
@Test
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts
.stream()
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
assertEquals(1, map
.get("Author 1")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map
.get("Author 1")
.get(BlogPostType.GUIDE)
.size());
assertEquals(1, map
.get("Author 1")
.get(BlogPostType.REVIEW)
.size());
assertEquals(1, map
.get("Author 2")
.get(BlogPostType.NEWS)
.size());
assertEquals(1, map
.get("Author 2")
.get(BlogPostType.REVIEW)
.size());
assertNull(map
.get("Author 2")
.get(BlogPostType.GUIDE));
}
@Test
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts
.stream()
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);
assertEquals(2, newsLikeStatistics.getCount());
assertEquals(50, newsLikeStatistics.getSum());
assertEquals(25.0, newsLikeStatistics.getAverage(), 0.001);
assertEquals(35, newsLikeStatistics.getMax());
assertEquals(15, newsLikeStatistics.getMin());
}
}

View File

@ -0,0 +1,73 @@
package com.baeldung.strategy;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import static com.baeldung.strategy.Discounter.*;
import static org.assertj.core.api.Assertions.assertThat;
public class StrategyDesignPatternUnitTest {
@Test
public void shouldDivideByTwo_WhenApplyingStaffDiscounter() {
Discounter staffDiscounter = new EasterDiscounter();
final BigDecimal discountedValue = staffDiscounter
.apply(BigDecimal.valueOf(100));
assertThat(discountedValue)
.isEqualByComparingTo(BigDecimal.valueOf(50));
}
@Test
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithAnonyousTypes() {
Discounter staffDiscounter = new Discounter() {
@Override
public BigDecimal apply( BigDecimal amount) {
return amount.multiply(BigDecimal.valueOf(0.5));
}
};
final BigDecimal discountedValue = staffDiscounter
.apply(BigDecimal.valueOf(100));
assertThat(discountedValue)
.isEqualByComparingTo(BigDecimal.valueOf(50));
}
@Test
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithLamda() {
Discounter staffDiscounter = amount -> amount.multiply(BigDecimal.valueOf(0.5));
final BigDecimal discountedValue = staffDiscounter
.apply(BigDecimal.valueOf(100));
assertThat(discountedValue)
.isEqualByComparingTo(BigDecimal.valueOf(50));
}
@Test
public void shouldApplyAllDiscounts() {
List<Discounter> discounters = Arrays.asList(christmas(), newYear(), easter());
BigDecimal amount = BigDecimal.valueOf(100);
final Discounter combinedDiscounter = discounters
.stream()
.reduce(v -> v, Discounter::combine);
combinedDiscounter.apply(amount);
}
@Test
public void shouldChainDiscounters() {
final Function<BigDecimal, BigDecimal> combinedDiscounters = Discounter
.christmas()
.andThen(newYear());
combinedDiscounters.apply(BigDecimal.valueOf(100));
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.stream;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class InfiniteStreamTest {
@Test
public void givenInfiniteStream_whenUseIntermediateLimitMethod_thenShouldTerminateInFiniteTime() {
//given
Stream<Integer> infiniteStream = Stream.iterate(0, i -> i + 2);
//when
List<Integer> collect = infiniteStream
.limit(10)
.collect(Collectors.toList());
//then
assertEquals(collect, Arrays.asList(0, 2, 4, 6, 8, 10, 12, 14, 16, 18));
}
@Test
public void givenInfiniteStreamOfRandomInts_whenUseLimit_shouldTerminateInFiniteTime() {
//given
Supplier<UUID> randomUUIDSupplier = UUID::randomUUID;
Stream<UUID> infiniteStreamOfRandomUUID = Stream.generate(randomUUIDSupplier);
//when
List<UUID> randomInts = infiniteStreamOfRandomUUID
.skip(10)
.limit(10)
.collect(Collectors.toList());
//then
assertEquals(randomInts.size(), 10);
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.string;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.baeldung.string.JoinerSplitter;
public class JoinerSplitterTest {
@Test
public void provided_array_convert_to_stream_and_convert_to_string() {
String[] programming_languages = {"java", "python", "nodejs", "ruby"};
String expectation = "java,python,nodejs,ruby";
String result = JoinerSplitter.join(programming_languages);
assertEquals(result, expectation);
}
@Test
public void provided_array_convert_to_stream_and_convert_to_prefixPostfix() {
String[] programming_languages = {"java", "python",
"nodejs", "ruby"};
String expectation = "[java,python,nodejs,ruby]";
String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages);
assertEquals(result, expectation);
}
@Test
public void provided_string_convert_to_stream_and_convert_to_listOfString() {
String programming_languages = "java,python,nodejs,ruby";
List<String> expectation = new ArrayList<String>();
expectation.add("java");
expectation.add("python");
expectation.add("nodejs");
expectation.add("ruby");
List<String> result = JoinerSplitter.split(programming_languages);
assertEquals(result, expectation);
}
@Test
public void provided_string_convert_to_stream_and_convert_to_listOfChar() {
String programming_languages = "java,python,nodejs,ruby";
List<Character> expectation = new ArrayList<Character>();
char[] charArray = programming_languages.toCharArray();
for (char c : charArray) {
expectation.add(c);
}
List<Character> result = JoinerSplitter.splitToListOfChar(programming_languages);
assertEquals(result, expectation);
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.weakhashmap;
import org.junit.Test;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static org.junit.Assert.assertTrue;
public class WeakHashMapTest {
@Test
public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObject() {
//given
WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>();
BigImage bigImage = new BigImage("image_id");
UniqueImageName imageName = new UniqueImageName("name_of_big_image");
map.put(imageName, bigImage);
assertTrue(map.containsKey(imageName));
//when big image key is not reference anywhere
imageName = null;
System.gc();
//then GC will finally reclaim that object
await().atMost(10, TimeUnit.SECONDS).until(map::isEmpty);
}
@Test
public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObjectButLeaveReferencedObject() {
//given
WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>();
BigImage bigImageFirst = new BigImage("foo");
UniqueImageName imageNameFirst = new UniqueImageName("name_of_big_image");
BigImage bigImageSecond = new BigImage("foo_2");
UniqueImageName imageNameSecond = new UniqueImageName("name_of_big_image_2");
map.put(imageNameFirst, bigImageFirst);
map.put(imageNameSecond, bigImageSecond);
assertTrue(map.containsKey(imageNameFirst));
assertTrue(map.containsKey(imageNameSecond));
//when
imageNameFirst = null;
System.gc();
//then
await().atMost(10, TimeUnit.SECONDS).until(() -> map.size() == 1);
await().atMost(10, TimeUnit.SECONDS).until(() -> map.containsKey(imageNameSecond));
}
class BigImage {
public final String imageId;
BigImage(String imageId) {
this.imageId = imageId;
}
}
class UniqueImageName {
public final String imageName;
UniqueImageName(String imageName) {
this.imageName = imageName;
}
}
}

View File

@ -1,12 +1,12 @@
package org.baeldung.java;
import java.nio.charset.Charset;
import java.util.Random;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.math3.random.RandomDataGenerator;
import org.junit.Test;
import java.nio.charset.Charset;
import java.util.Random;
public class JavaRandomUnitTest {
// tests - random long
@ -164,7 +164,7 @@ public class JavaRandomUnitTest {
final int targetStringLength = 10;
final StringBuilder buffer = new StringBuilder(targetStringLength);
for (int i = 0; i < targetStringLength; i++) {
final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit));
final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit + 1));
buffer.append((char) randomLimitedInt);
}
final String generatedString = buffer.toString();

View File

@ -1,5 +1,5 @@
package org.baeldung.java.streams;
import org.junit.Test;
import java.util.ArrayList;
@ -14,28 +14,25 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ThreadPoolInParallelStreamTest {
@Test
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal()
throws InterruptedException, ExecutionException {
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {
long firstNum = 1;
long lastNum = 1_000_000;
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed()
.collect(Collectors.toList());
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
long actualTotal = customThreadPool.submit(() -> aList.parallelStream()
.reduce(0L, Long::sum)).get();
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
}
@Test
public void givenList_whenCallingParallelStream_shouldBeParallelStream(){
public void givenList_whenCallingParallelStream_shouldBeParallelStream() {
List<Long> aList = new ArrayList<>();
Stream<Long> parallelStream = aList.parallelStream();
assertTrue(parallelStream.isParallel());
}
}

View File

@ -102,10 +102,10 @@
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<couchbase.client.version>2.3.6</couchbase.client.version>
<spring-framework.version>4.3.4.RELEASE</spring-framework.version>
<logback.version>1.1.7</logback.version>
<org.slf4j.version>1.7.21</org.slf4j.version>
<couchbase.client.version>2.4.0</couchbase.client.version>
<spring-framework.version>4.3.5.RELEASE</spring-framework.version>
<logback.version>1.1.8</logback.version>
<org.slf4j.version>1.7.22</org.slf4j.version>
<junit.version>4.12</junit.version>
<commons-lang3.version>3.5</commons-lang3.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>

View File

@ -0,0 +1,6 @@
package com.baeldung.couchbase.mapreduce;
public interface CouchbaseKeyGenerator<T> {
String generateKey(T t);
}

View File

@ -0,0 +1,10 @@
package com.baeldung.couchbase.mapreduce;
@SuppressWarnings("serial")
public class DuplicateKeyException extends Exception {
public DuplicateKeyException(String s) {
super(s);
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.couchbase.mapreduce;
import java.util.UUID;
public class RandomUUIDGenerator<T> implements CouchbaseKeyGenerator<T> {
@Override
public String generateKey(T t) {
return UUID.randomUUID().toString();
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.couchbase.mapreduce;
public class StudentGrade {
private String name;
private String course;
private Integer grade;
private Integer hours;
public StudentGrade() { }
public StudentGrade(String name, String course, Integer grade, Integer hours) {
this.name = name;
this.course = course;
this.grade = grade;
this.hours = hours;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
public Integer getHours() {
return hours;
}
public void setHours(Integer hours) {
this.hours = hours;
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.couchbase.mapreduce;
public class StudentGradeKeyGenerator implements CouchbaseKeyGenerator<StudentGrade> {
@Override
public String generateKey(StudentGrade g) {
return g.getName() + ":" + g.getCourse();
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.couchbase.mapreduce;
import com.couchbase.client.deps.com.fasterxml.jackson.databind.ObjectMapper;
import com.couchbase.client.java.document.json.JsonArray;
import com.couchbase.client.java.view.ViewQuery;
public class StudentGradeQueryBuilder {
final ObjectMapper om = new ObjectMapper();
public ViewQuery findAll() {
return ViewQuery.from("studentGrades", "findByCourse");
}
public ViewQuery findByCourse(String course) {
return ViewQuery.from("studentGrades", "findByCourse")
.key(course);
}
public ViewQuery findByCourses(String... courses) {
return ViewQuery.from("studentGrades", "findByCourse")
.keys(JsonArray.from(courses));
}
public ViewQuery findByGradeInRange(int lower, int upper, boolean inclusiveEnd) {
return ViewQuery.from("studentGrades", "findByGrade")
.startKey(lower)
.endKey(upper)
.inclusiveEnd(inclusiveEnd);
}
public ViewQuery findByGradeLessThan(int upper) {
return ViewQuery.from("studentGrades", "findByGrade")
.endKey(upper)
.inclusiveEnd(false);
}
public ViewQuery findByGradeGreaterThan(int lower) {
return ViewQuery.from("studentGrades", "findByGrade")
.startKey(lower);
}
public ViewQuery findByCourseAndGradeInRange(String course, int minGrade, int maxGrade, boolean inclusiveEnd) {
return ViewQuery.from("studentGrades", "findByCourseAndGrade")
.startKey(JsonArray.from(course, minGrade))
.endKey(JsonArray.from(course, maxGrade))
.inclusiveEnd(inclusiveEnd);
}
public ViewQuery findTopGradesByCourse(String course, int limit) {
return ViewQuery.from("studentGrades", "findByCourseAndGrade")
.startKey(JsonArray.from(course, 100))
.endKey(JsonArray.from(course, 0))
.inclusiveEnd(true)
.descending()
.limit(limit);
}
public ViewQuery countStudentsByCourse() {
return ViewQuery.from("studentGrades", "countStudentsByCourse")
.reduce()
.groupLevel(1);
}
public ViewQuery sumCreditsByStudent() {
return ViewQuery.from("studentGrades", "sumCreditsByStudent")
.reduce()
.groupLevel(1);
}
}

View File

@ -0,0 +1,169 @@
package com.baeldung.couchbase.mapreduce;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.couchbase.client.deps.com.fasterxml.jackson.databind.ObjectMapper;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.document.json.JsonArray;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.view.ViewQuery;
import com.couchbase.client.java.view.ViewResult;
import com.couchbase.client.java.view.ViewRow;
public class StudentGradeService {
final CouchbaseKeyGenerator<StudentGrade> keyGenerator;
final CouchbaseCluster cluster;
final Bucket bucket;
final ObjectMapper om = new ObjectMapper();
final StudentGradeQueryBuilder queryBuilder;
public StudentGradeService(CouchbaseKeyGenerator<StudentGrade> keyGenerator) {
this.keyGenerator = keyGenerator;
this.queryBuilder = new StudentGradeQueryBuilder();
cluster = CouchbaseCluster.create("127.0.0.1");
bucket = cluster.openBucket("baeldung-tutorial");
}
public String insert(StudentGrade studentGrade) throws DuplicateKeyException {
String id = keyGenerator.generateKey(studentGrade);
if(bucket.exists(id)) {
throw new DuplicateKeyException("document already exists with key " + id);
}
JsonObject content = JsonObject.empty()
.put("type", "StudentGrade")
.put("name", studentGrade.getName())
.put("course", studentGrade.getCourse())
.put("grade", studentGrade.getGrade())
.put("hours", studentGrade.getHours());
JsonDocument doc = JsonDocument.create(id, content);
bucket.insert(doc);
return id;
}
public List<JsonDocument> findAll() {
ViewQuery query = queryBuilder.findAll();
ViewResult result = bucket.query(query);
return extractDocuments(result);
}
private List<JsonDocument> extractDocuments(ViewResult result) {
List<JsonDocument> docs = new ArrayList<>();
for(ViewRow row : result.allRows()) {
JsonDocument doc = row.document();
docs.add(doc);
}
return docs;
}
public List<JsonDocument> findByCourse(String course) {
ViewQuery query = queryBuilder.findByCourse(course);
ViewResult result = bucket.query(query);
return extractDocuments(result);
}
public List<JsonDocument> findByCourses(String... courses) {
ViewQuery query = queryBuilder.findByCourses(courses);
ViewResult result = bucket.query(query);
return extractDocuments(result);
}
public List<JsonDocument> findByGradeInRange(int lower, int upper, boolean inclusiveEnd) {
ViewQuery query = queryBuilder.findByGradeInRange(lower, upper, inclusiveEnd);
ViewResult result = bucket.query(query);
return extractDocuments(result);
}
public List<JsonDocument> findByGradeLessThan(int upper) {
ViewQuery query = queryBuilder.findByGradeLessThan(upper);
ViewResult result = bucket.query(query);
return extractDocuments(result);
}
public List<JsonDocument> findByGradeGreaterThan(int lower) {
ViewQuery query = queryBuilder.findByGradeGreaterThan(lower);
ViewResult result = bucket.query(query);
return extractDocuments(result);
}
public List<JsonDocument> findByCourseAndGradeInRange(String course, int minGrade, int maxGrade, boolean inclusiveEnd) {
ViewQuery query = queryBuilder.findByCourseAndGradeInRange(course, minGrade, maxGrade, inclusiveEnd);
ViewResult result = bucket.query(query);
return extractDocuments(result);
}
public List<JsonDocument> findTopGradesByCourse(String course, int limit) {
ViewQuery query = queryBuilder.findTopGradesByCourse(course, limit);
ViewResult result = bucket.query(query);
return extractDocuments(result);
}
public Map<String, Long> countStudentsByCourse() {
ViewQuery query = ViewQuery.from("studentGrades", "countStudentsByCourse")
.reduce()
.groupLevel(1);
ViewResult result = bucket.query(query);
Map<String, Long> numStudentsByCourse = new HashMap<>();
for(ViewRow row : result.allRows()) {
JsonArray keyArray = (JsonArray) row.key();
String course = keyArray.getString(0);
long count = Long.valueOf(row.value().toString());
numStudentsByCourse.put(course, count);
}
return numStudentsByCourse;
}
public Map<String, Long> sumCreditHoursByStudent() {
ViewQuery query = ViewQuery.from("studentGrades", "sumHoursByStudent")
.reduce()
.groupLevel(1);
ViewResult result = bucket.query(query);
Map<String, Long> creditHoursByStudent = new HashMap<>();
for(ViewRow row : result.allRows()) {
String course = (String) row.key();
long sum = Long.valueOf(row.value().toString());
creditHoursByStudent.put(course, sum);
}
return creditHoursByStudent;
}
public Map<String, Long> sumGradePointsByStudent() {
ViewQuery query = ViewQuery.from("studentGrades", "sumGradePointsByStudent")
.reduce()
.groupLevel(1);
ViewResult result = bucket.query(query);
Map<String, Long> gradePointsByStudent = new HashMap<>();
for(ViewRow row : result.allRows()) {
String course = (String) row.key();
long sum = Long.valueOf(row.value().toString());
gradePointsByStudent.put(course, sum);
}
return gradePointsByStudent;
}
public Map<String, Float> calculateGpaByStudent() {
Map<String, Long> creditHoursByStudent = sumCreditHoursByStudent();
Map<String, Long> gradePointsByStudent = sumGradePointsByStudent();
Map<String, Float> result = new HashMap<>();
for(Entry<String, Long> creditHoursEntry : creditHoursByStudent.entrySet()) {
String name = creditHoursEntry.getKey();
long totalHours = creditHoursEntry.getValue();
long totalGradePoints = gradePointsByStudent.get(name);
result.put(name, ((float) totalGradePoints / totalHours));
}
return result;
}
}

View File

@ -0,0 +1,150 @@
package com.baeldung.couchbase.mapreduce;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.view.ViewResult;
import com.couchbase.client.java.view.ViewRow;
public class StudentGradeServiceIntegrationTest {
private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceIntegrationTest.class);
static StudentGradeService studentGradeService;
static Set<String> gradeIds = new HashSet<>();
@BeforeClass
public static void setUpBeforeClass() throws Exception {
studentGradeService = new StudentGradeService(new StudentGradeKeyGenerator());
insertStudentGrade(new StudentGrade("John Doe", "History", 80, 3));
insertStudentGrade(new StudentGrade("Jane Doe", "History", 89, 3));
insertStudentGrade(new StudentGrade("Bob Smith", "History", 90, 3));
insertStudentGrade(new StudentGrade("Mary Jones", "History", 92, 3));
insertStudentGrade(new StudentGrade("Jane Doe", "Math", 59, 3));
insertStudentGrade(new StudentGrade("Bob Smith", "Math", 91, 3));
insertStudentGrade(new StudentGrade("Mary Jones", "Math", 86, 3));
insertStudentGrade(new StudentGrade("John Doe", "Science", 85, 4));
insertStudentGrade(new StudentGrade("Bob Smith", "Science", 97, 4));
insertStudentGrade(new StudentGrade("Mary Jones", "Science", 84, 4));
}
private static void insertStudentGrade(StudentGrade studentGrade) {
try {
String id = studentGradeService.insert(studentGrade);
gradeIds.add(id);
} catch (DuplicateKeyException e) {
}
}
@Test
public final void whenFindAll_thenSuccess() {
List<JsonDocument> docs = studentGradeService.findAll();
printDocuments(docs);
}
@Test
public final void whenFindByCourse_thenSuccess() {
List<JsonDocument> docs = studentGradeService.findByCourse("History");
printDocuments(docs);
}
@Test
public final void whenFindByCourses_thenSuccess() {
List<JsonDocument> docs = studentGradeService.findByCourses("History", "Science");
printDocuments(docs);
}
@Test
public final void whenFindByGradeInRange_thenSuccess() {
List<JsonDocument> docs = studentGradeService.findByGradeInRange(80, 89, true);
printDocuments(docs);
}
@Test
public final void whenFindByGradeLessThan_thenSuccess() {
List<JsonDocument> docs = studentGradeService.findByGradeLessThan(60);
printDocuments(docs);
}
@Test
public final void whenFindByGradeGreaterThan_thenSuccess() {
List<JsonDocument> docs = studentGradeService.findByGradeGreaterThan(90);
printDocuments(docs);
}
@Test
public final void whenFindByCourseAndGradeInRange_thenSuccess() {
List<JsonDocument> docs = studentGradeService.findByCourseAndGradeInRange("Math", 80, 89, true);
printDocuments(docs);
}
@Test
public final void whenFindTopGradesByCourse_thenSuccess() {
List<JsonDocument> docs = studentGradeService.findTopGradesByCourse("Science", 2);
printDocuments(docs);
}
@Test
public final void whenCountStudentsByCourse_thenSuccess() {
Map<String, Long> map = studentGradeService.countStudentsByCourse();
printMap(map);
}
@Test
public final void whenSumCreditHoursByStudent_thenSuccess() {
Map<String, Long> map = studentGradeService.sumCreditHoursByStudent();
printMap(map);
}
@Test
public final void whenSumGradePointsByStudent_thenSuccess() {
Map<String, Long> map = studentGradeService.sumGradePointsByStudent();
printMap(map);
}
@Test
public final void whenCalculateGpaByStudent_thenSuccess() {
Map<String, Float> map = studentGradeService.calculateGpaByStudent();
printGpaMap(map);
}
private void printMap(Map<String, Long> map) {
for(Map.Entry<String, Long> entry : map.entrySet()) {
logger.info(entry.getKey() + "=" + entry.getValue());
}
}
private void printGpaMap(Map<String, Float> map) {
for(Map.Entry<String, Float> entry : map.entrySet()) {
logger.info(entry.getKey() + "=" + entry.getValue());
}
}
private void printDocuments(List<JsonDocument> docs) {
for(JsonDocument doc : docs) {
String key = doc.id();
logger.info(key + " = " + doc.content().toString());
}
}
private void printViewResultDocuments(ViewResult result) {
for(ViewRow row : result.allRows()) {
JsonDocument doc = row.document();
String key = doc.id();
logger.info(key + "=" + doc.content().toString());
}
}
private void printViewResultRows(ViewResult result) {
for(ViewRow row : result.allRows()) {
logger.info(row.toString());
}
}
}

View File

@ -0,0 +1,17 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="com.baeldung" level="DEBUG" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -57,6 +57,32 @@
<scope>test</scope>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@ -112,6 +138,9 @@
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
</properties>
</project>

View File

@ -1,6 +1,5 @@
package org.baeldung.guava;
public class CustomEvent {
private String action;

View File

@ -6,17 +6,16 @@ class EventBusWrapper {
private static EventBus eventBus = new EventBus();
static void register(Object object){
static void register(Object object) {
eventBus.register(object);
}
static void unregister(Object object){
static void unregister(Object object) {
eventBus.unregister(object);
}
static void post(Object object){
static void post(Object object) {
eventBus.post(object);
}
}

View File

@ -0,0 +1,31 @@
package org.baeldung.guava;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EventListener {
private static int eventsHandled;
private static final Logger LOG = LoggerFactory.getLogger(EventListener.class);
@Subscribe
public void stringEvent(String event) {
LOG.info("do event [" + event + "]");
eventsHandled++;
}
@Subscribe
public void someCustomEvent(CustomEvent customEvent) {
LOG.info("do event [" + customEvent.getAction() + "]");
eventsHandled++;
}
public int getEventsHandled() {
return eventsHandled;
}
public void resetEventsHandled() {
eventsHandled = 0;
}
}

View File

@ -1,33 +0,0 @@
package org.baeldung.guava;
import com.google.common.eventbus.Subscribe;
public class EventListener {
private static int eventsHandled;
/**
* Handles events of type String *
*/
@Subscribe
public void stringEvent(String event){
System.out.println("do event ["+event+"]");
eventsHandled++;
}
/**
* Handles events of type CustomEvent
*/
@Subscribe
public void someEvent(CustomEvent customEvent){
System.out.println("do event ["+ customEvent.getAction()+"]");
eventsHandled++;
}
public int getEventsHandled() {
return eventsHandled;
}
public void resetEventsHandled(){
eventsHandled = 0;
}
}

View File

@ -11,18 +11,18 @@ public class GuavaEventBusTest {
private EventListener listener;
@Before
public void setUp() throws Exception {
public void setUp() {
listener = new EventListener();
EventBusWrapper.register(listener);
}
@After
public void tearDown() throws Exception {
public void tearDown() {
EventBusWrapper.unregister(listener);
}
@Test
public void givenStringEvent_whenEventHandled_thenSuccess() throws Exception {
public void givenStringEvent_whenEventHandled_thenSuccess() {
listener.resetEventsHandled();
EventBusWrapper.post("String Event");
@ -31,7 +31,7 @@ public class GuavaEventBusTest {
}
@Test
public void givenCustomEvent_whenEventHandled_thenSuccess() throws Exception {
public void givenCustomEvent_whenEventHandled_thenSuccess() {
listener.resetEventsHandled();
CustomEvent customEvent = new CustomEvent("Custom Event");

View File

@ -3,7 +3,7 @@ package org.baeldung.guava;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Arrays;
import org.junit.Test;
import static com.google.common.base.Preconditions.*;
import com.google.common.base.*;
public class GuavaPreConditionsTest {
@ -11,10 +11,7 @@ public class GuavaPreConditionsTest {
public void whenCheckArgumentEvaluatesFalse_throwsException() {
int age = -18;
assertThatThrownBy(() -> checkArgument(age > 0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(null)
.hasNoCause();
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0)).isInstanceOf(IllegalArgumentException.class).hasMessage(null).hasNoCause();
}
@Test
@ -22,10 +19,7 @@ public class GuavaPreConditionsTest {
final int age = -18;
final String message = "Age can't be zero or less than zero";
assertThatThrownBy(() -> checkArgument(age > 0, message))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(message)
.hasNoCause();
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message)).isInstanceOf(IllegalArgumentException.class).hasMessage(message).hasNoCause();
}
@Test
@ -33,19 +27,14 @@ public class GuavaPreConditionsTest {
final int age = -18;
final String message = "Age can't be zero or less than zero, you supplied %s.";
assertThatThrownBy(() -> checkArgument(age > 0, message, age))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(message, age)
.hasNoCause();
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message, age)).isInstanceOf(IllegalArgumentException.class).hasMessage(message, age).hasNoCause();
}
@Test
public void givenArrayOfIntegers_whenCheckElementIndexEvaluatesFalse_throwsException() {
final int[] numbers = { 1, 2, 3, 4, 5 };
assertThatThrownBy(() -> checkElementIndex(6, numbers.length - 1))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasNoCause();
assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
}
@Test
@ -53,20 +42,7 @@ public class GuavaPreConditionsTest {
final int[] numbers = { 1, 2, 3, 4, 5 };
final String message = "Please check the bound of an array and retry";
assertThatThrownBy(() -> checkElementIndex(6, numbers.length - 1, message))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith(message)
.hasNoCause();
}
@Test
public void givenNullString_whenCheckNotNullCalled_throwsException() {
final String nullObject = null;
assertThatThrownBy(() -> checkNotNull(nullObject))
.isInstanceOf(NullPointerException.class)
.hasMessage(null)
.hasNoCause();
assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause();
}
@Test
@ -74,10 +50,7 @@ public class GuavaPreConditionsTest {
final String nullObject = null;
final String message = "Please check the Object supplied, its null!";
assertThatThrownBy(() -> checkNotNull(nullObject, message))
.isInstanceOf(NullPointerException.class)
.hasMessage(message)
.hasNoCause();
assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message)).isInstanceOf(NullPointerException.class).hasMessage(message).hasNoCause();
}
@Test
@ -85,19 +58,14 @@ public class GuavaPreConditionsTest {
final String nullObject = null;
final String message = "Please check the Object supplied, its %s!";
assertThatThrownBy(() -> checkNotNull(nullObject, message, nullObject))
.isInstanceOf(NullPointerException.class)
.hasMessage(message, nullObject)
.hasNoCause();
assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message, new Object[] { null })).isInstanceOf(NullPointerException.class).hasMessage(message, nullObject).hasNoCause();
}
@Test
public void givenArrayOfIntegers_whenCheckPositionIndexEvaluatesFalse_throwsException() {
final int[] numbers = { 1, 2, 3, 4, 5 };
assertThatThrownBy(() -> checkPositionIndex(6, numbers.length - 1))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasNoCause();
assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
}
@Test
@ -105,30 +73,14 @@ public class GuavaPreConditionsTest {
final int[] numbers = { 1, 2, 3, 4, 5 };
final String message = "Please check the bound of an array and retry";
assertThatThrownBy(() -> checkPositionIndex(6, numbers.length - 1, message))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith(message)
.hasNoCause();
assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause();
}
@Test
public void givenArrayOfIntegers_whenCheckPositionIndexesEvaluatesFalse_throwsException() {
final int[] numbers = { 1, 2, 3, 4, 5 };
assertThatThrownBy(() -> checkPositionIndexes(6, 0, numbers.length - 1))
.isInstanceOf(IndexOutOfBoundsException.class)
.hasNoCause();
}
@Test
public void givenValidStates_whenCheckStateEvaluatesFalse_throwsException() {
final int[] validStates = { -1, 0, 1 };
final int givenState = 10;
assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0))
.isInstanceOf(IllegalStateException.class)
.hasMessage(null)
.hasNoCause();
assertThatThrownBy(() -> Preconditions.checkPositionIndexes(6, 0, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
}
@Test
@ -137,10 +89,7 @@ public class GuavaPreConditionsTest {
final int givenState = 10;
final String message = "You have entered an invalid state";
assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0, message))
.isInstanceOf(IllegalStateException.class)
.hasMessageStartingWith(message)
.hasNoCause();
assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message)).isInstanceOf(IllegalStateException.class).hasMessageStartingWith(message).hasNoCause();
}
@Test
@ -149,9 +98,7 @@ public class GuavaPreConditionsTest {
final int givenState = 10;
final String message = "State can't be %s, It can be one of %s.";
assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates)))
.isInstanceOf(IllegalStateException.class)
.hasMessage(message, givenState, Arrays.toString(validStates))
.hasNoCause();
assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates))).isInstanceOf(IllegalStateException.class)
.hasMessage(message, givenState, Arrays.toString(validStates)).hasNoCause();
}
}
}

View File

@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<version>1.4.4.RELEASE</version>
</parent>

View File

@ -67,6 +67,12 @@
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
@ -128,8 +134,8 @@
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<!-- logging -->
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
@ -152,7 +158,7 @@
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
</dependency>
</dependencies>
@ -189,7 +195,7 @@
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<jackson.version>2.8.6</jackson.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
@ -198,7 +204,7 @@
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-io.version>2.5</commons-io.version>
<commons-io.version>2.5</commons-io.version>
<joda-time.version>2.9.6</joda-time.version>
<gson.version>2.8.0</gson.version>
<commons-collections4.version>4.1</commons-collections4.version>

View File

@ -4,6 +4,7 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
public class ActorJackson {
@ -53,7 +54,7 @@ public class ActorJackson {
}
private String formatDateOfBirth() {
final DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy");
final DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy", Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
return formatter.format(dateOfBirth);
}

View File

@ -0,0 +1,25 @@
package com.baeldung.jackson.miscellaneous.mixin;
import java.util.Optional;
public class Book {
private String title;
private Optional<String> subTitle;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Optional<String> getSubTitle() {
return subTitle;
}
public void setSubTitle(Optional<String> subTitle) {
this.subTitle = subTitle;
}
}

View File

@ -3,12 +3,10 @@ package com.baeldung.jackson.deserialization;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import com.baeldung.jackson.entities.Movie;
import org.junit.Assert;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.junit.Assert.assertEquals;
public class JacksonDeserializeTest {
@ -20,7 +18,7 @@ public class JacksonDeserializeTest {
final Movie movie = mapper.readValue(jsonInput, Movie.class);
final String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]";
Assert.assertEquals(movie.toString(), expectedOutput);
assertEquals(expectedOutput, movie.toString());
}
@Test
@ -35,7 +33,7 @@ public class JacksonDeserializeTest {
final Movie movie = mapper.readValue(jsonInput, Movie.class);
final String expectedOutput = "Movie [imdbId=tt0472043, director=Mel Gibson, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]";
Assert.assertEquals(movie.toString(), expectedOutput);
assertEquals(expectedOutput, movie.toString());
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.jackson.miscellaneous.mixin;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import static io.restassured.path.json.JsonPath.from;
import java.io.IOException;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class OptionalTypeTest {
ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module());
@Test
public void givenPresentOptional_whenSerializing_thenValueInJson() throws JsonProcessingException {
String subTitle = "The Parish Boy's Progress";
Book book = new Book();
book.setTitle("Oliver Twist");
book.setSubTitle(Optional.of(subTitle));
String result = mapper.writeValueAsString(book);
assertThat(from(result).getString("subTitle")).isEqualTo(subTitle);
}
@Test
public void givenEmptyOptional_whenSerializing_thenNullValue() throws JsonProcessingException {
Book book = new Book();
book.setTitle("Oliver Twist");
book.setSubTitle(Optional.empty());
String result = mapper.writeValueAsString(book);
assertThat(from(result).getString("subTitle")).isNull();
}
@Test
public void givenField_whenDeserializingIntoOptional_thenIsPresentWithValue() throws IOException {
String subTitle = "The Parish Boy's Progress";
String book = "{ \"title\": \"Oliver Twist\", \"subTitle\": \"" + subTitle + "\" }";
Book result = mapper.readValue(book, Book.class);
assertThat(result.getSubTitle()).isEqualTo(Optional.of(subTitle));
}
@Test
public void givenNullField_whenDeserializingIntoOptional_thenIsEmpty() throws IOException {
String book = "{ \"title\": \"Oliver Twist\", \"subTitle\": null }";
Book result = mapper.readValue(book, Book.class);
assertThat(result.getSubTitle()).isEmpty();
}
}

View File

@ -14,7 +14,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<version>1.4.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

View File

@ -2,9 +2,9 @@
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>logmdc</artifactId>
<artifactId>log-mdc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>logmdc</name>
<name>log-mdc</name>
<packaging>war</packaging>
<description>tutorial on logging with MDC and NDC</description>

View File

@ -7,15 +7,15 @@ import java.util.UUID;
public class TransactionFactory {
private static final String[] NAMES = {"John", "Susan", "Marc", "Samantha"};
private static long nextId = 1;
public Transfer newInstance() {
String transactionId = String.valueOf( nextId++ );
String owner = NAMES[ (int) floor(random()*NAMES.length) ];
long amount = (long) (random()*1500 + 500);
Transfer tx = new Transfer(transactionId, owner, amount);
return tx;
}
private static final String[] NAMES = { "John", "Susan", "Marc", "Samantha" };
private static long nextId = 1;
public Transfer newInstance() {
String transactionId = String.valueOf(nextId++);
String owner = NAMES[(int) floor(random() * NAMES.length)];
long amount = (long) (random() * 1500 + 500);
Transfer tx = new Transfer(transactionId, owner, amount);
return tx;
}
}

View File

@ -18,11 +18,11 @@ public class TransferDemo {
for (int i = 0; i < 10; i++) {
Transfer tx = transactionFactory.newInstance();
//Runnable task = new Log4JRunnable(tx);
//Runnable task = new Log4J2Runnable(tx);
// Runnable task = new Log4JRunnable(tx);
// Runnable task = new Log4J2Runnable(tx);
Runnable task = new Slf4jRunnable(tx);
executor.submit(task);
}

View File

@ -13,7 +13,6 @@ import org.springframework.web.bind.annotation.RestController;
import com.baeldung.ndc.Investment;
import com.baeldung.ndc.service.InvestmentService;
@RestController
public class JBossLoggingController {
@Autowired

View File

@ -17,7 +17,7 @@ public class Demo {
TransactionFactory transactionFactory = new TransactionFactory();
for (int i = 0; i < 10; i++) {
Transfer tx = transactionFactory.newInstance();
Runnable task = new Log4JRunnable(tx);
Runnable task = new Log4JRunnable(tx);
executor.submit(task);
}
executor.shutdown();

View File

@ -21,7 +21,7 @@ public class Demo {
TransactionFactory transactionFactory = new TransactionFactory();
for (int i = 0; i < 10; i++) {
Transfer tx = transactionFactory.newInstance();
Runnable task = new Log4J2Runnable(tx);
Runnable task = new Log4J2Runnable(tx);
executor.submit(task);
}
executor.shutdown();

View File

@ -21,7 +21,7 @@ public class Demo {
TransactionFactory transactionFactory = new TransactionFactory();
for (int i = 0; i < 10; i++) {
Transfer tx = transactionFactory.newInstance();
Runnable task = new Slf4jRunnable(tx);
Runnable task = new Slf4jRunnable(tx);
executor.submit(task);
}
executor.shutdown();

View File

@ -138,15 +138,15 @@ public class MetricsTest {
long elapsed1 = context1.stop();
assertEquals(5000000000L, elapsed1, 10000000);
assertEquals(5000000000L, elapsed1, 1000000000);
assertThat(timer.getCount(), equalTo(1L));
assertEquals(0.2, timer.getMeanRate(), 0.1);
assertEquals(0.2, timer.getMeanRate(), 0.2);
Timer.Context context2 = timer.time();
TimeUnit.SECONDS.sleep(2);
context2.close();
assertThat(timer.getCount(), equalTo(2L));
assertEquals(0.3, timer.getMeanRate(), 0.1);
assertEquals(0.3, timer.getMeanRate(), 0.2);
}
}

16
pom.xml
View File

@ -11,6 +11,8 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<gib.referenceBranch>refs/heads/master</gib.referenceBranch>
<gib.enabled>false</gib.enabled>
</properties>
<modules>
@ -147,6 +149,7 @@
<module>spring-rest-docs</module>
<module>spring-rest</module>
<module>spring-security-basic-auth</module>
<module>spring-security-cache-control</module>
<module>spring-security-client/spring-security-jsp-authentication</module>
<module>spring-security-client/spring-security-jsp-authorize</module>
<module>spring-security-client/spring-security-jsp-config</module>
@ -155,7 +158,7 @@
<module>spring-security-client/spring-security-thymeleaf-authorize</module>
<module>spring-security-client/spring-security-thymeleaf-config</module>
<module>spring-security-core</module>
<module>spring-security-custom-permission</module>
<module>spring-security-mvc-boot</module>
<module>spring-security-mvc-custom</module>
<module>spring-security-mvc-digest-auth</module>
<module>spring-security-mvc-ldap</module>
@ -189,6 +192,15 @@
<module>struts2</module>
</modules>
</modules>
<build>
<extensions>
<extension>
<groupId>com.vackosar.gitflowincrementalbuilder</groupId>
<artifactId>gitflow-incremental-builder</artifactId>
<version>3.1</version>
</extension>
</extensions>
</build>
</project>

View File

@ -26,10 +26,25 @@
<artifactId>rxjava</artifactId>
<version>${rx.java.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<junit.version>4.12</junit.version>
<rx.java.version>1.2.5</rx.java.version>
<hamcrest.version>1.3</hamcrest.version>
</properties>
</project>

View File

@ -1,38 +0,0 @@
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

@ -1,18 +0,0 @@
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

@ -1,17 +0,0 @@
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

@ -1,21 +0,0 @@
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

@ -1,18 +0,0 @@
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

@ -1,20 +0,0 @@
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

@ -0,0 +1,130 @@
package com.baeldung.rxjava;
import org.junit.Test;
import rx.BackpressureOverflow;
import rx.Observable;
import rx.exceptions.MissingBackpressureException;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static org.junit.Assert.assertTrue;
public class RxJavaBackpressureTest {
@Test
public void givenColdObservable_shouldNotThrowException() {
// given
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>();
// when
Observable.range(1, 1_000_000).observeOn(Schedulers.computation()).subscribe(testSubscriber);
// then
testSubscriber.awaitTerminalEvent();
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
public void givenHotObservable_whenBackpressureNotDefined_shouldTrowException() {
// given
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>();
PublishSubject<Integer> source = PublishSubject.<Integer> create();
source.observeOn(Schedulers.computation()).subscribe(testSubscriber);
// when
IntStream.range(0, 1_000_000).forEach(source::onNext);
// then
testSubscriber.awaitTerminalEvent();
testSubscriber.assertError(MissingBackpressureException.class);
}
@Test
public void givenHotObservable_whenWindowIsDefined_shouldNotThrowException() {
// given
TestSubscriber<Observable<Integer>> testSubscriber = new TestSubscriber<>();
PublishSubject<Integer> source = PublishSubject.<Integer> create();
// when
source.window(500).observeOn(Schedulers.computation()).subscribe(testSubscriber);
IntStream.range(0, 1_000).forEach(source::onNext);
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
public void givenHotObservable_whenBufferIsDefined_shouldNotThrowException() {
// given
TestSubscriber<List<Integer>> testSubscriber = new TestSubscriber<>();
PublishSubject<Integer> source = PublishSubject.<Integer> create();
// when
source.buffer(1024).observeOn(Schedulers.computation()).subscribe(testSubscriber);
IntStream.range(0, 1_000).forEach(source::onNext);
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
public void givenHotObservable_whenSkippingOperationIsDefined_shouldNotThrowException() {
// given
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>();
PublishSubject<Integer> source = PublishSubject.<Integer> create();
// when
source.sample(100, TimeUnit.MILLISECONDS)
// .throttleFirst(100, TimeUnit.MILLISECONDS)
.observeOn(Schedulers.computation()).subscribe(testSubscriber);
IntStream.range(0, 1_000).forEach(source::onNext);
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
public void givenHotObservable_whenOnBackpressureBufferDefined_shouldNotThrowException() {
// given
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>();
// when
Observable.range(1, 1_000_000).onBackpressureBuffer(16, () -> {
}, BackpressureOverflow.ON_OVERFLOW_DROP_OLDEST).observeOn(Schedulers.computation()).subscribe(testSubscriber);
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
@Test
public void givenHotObservable_whenOnBackpressureDropDefined_shouldNotThrowException() {
// given
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>();
// when
Observable.range(1, 1_000_000).onBackpressureDrop().observeOn(Schedulers.computation()).subscribe(testSubscriber);
// then
testSubscriber.awaitTerminalEvent(2, TimeUnit.SECONDS);
assertTrue(testSubscriber.getOnErrorEvents().size() == 0);
}
}

View File

@ -0,0 +1,98 @@
package com.baeldung.rxjava;
import org.junit.Test;
import rx.Observable;
import rx.observers.TestSubscriber;
import rx.schedulers.TestScheduler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class RxJavaTesting {
@Test
public void givenObservable_whenZip_shouldAssertBlockingInASameThread() {
// given
List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
List<String> results = new ArrayList<>();
Observable<String> observable = Observable.from(letters).zipWith(Observable.range(1, Integer.MAX_VALUE), (string, index) -> index + "-" + string);
// when
observable.subscribe(results::add);
// then
assertThat(results, notNullValue());
assertThat(results, hasSize(5));
assertThat(results, hasItems("1-A", "2-B", "3-C", "4-D", "5-E"));
}
@Test
public void givenObservable_whenZip_shouldAssertOnTestSubscriber() {
// given
List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
TestSubscriber<String> subscriber = new TestSubscriber<>();
Observable<String> observable = Observable.from(letters).zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string));
// when
observable.subscribe(subscriber);
// then
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(5);
assertThat(subscriber.getOnNextEvents(), hasItems("1-A", "2-B", "3-C", "4-D", "5-E"));
}
@Test
public void givenTestObserver_whenExceptionWasThrowsOnObservable_observerShouldGetError() {
// given
List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
TestSubscriber<String> subscriber = new TestSubscriber<>();
Observable<String> observable = Observable.from(letters).zipWith(Observable.range(1, Integer.MAX_VALUE), ((string, index) -> index + "-" + string)).concatWith(Observable.error(new RuntimeException("error in Observable")));
// when
observable.subscribe(subscriber);
// then
subscriber.assertError(RuntimeException.class);
subscriber.assertNotCompleted();
}
@Test
public void givenObservableThatEmitsEventPerSecond_whenUseAdvanceByTime_shouldEmitEventPerSecond() {
// given
List<String> letters = Arrays.asList("A", "B", "C", "D", "E");
TestScheduler scheduler = new TestScheduler();
TestSubscriber<String> subscriber = new TestSubscriber<>();
Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS, scheduler);
Observable<String> observable = Observable.from(letters).zipWith(tick, (string, index) -> index + "-" + string);
observable.subscribeOn(scheduler).subscribe(subscriber);
// expect
subscriber.assertNoValues();
subscriber.assertNotCompleted();
// when
scheduler.advanceTimeBy(1, TimeUnit.SECONDS);
// then
subscriber.assertNoErrors();
subscriber.assertValueCount(1);
subscriber.assertValues("0-A");
// when
scheduler.advanceTimeTo(6, TimeUnit.SECONDS);
subscriber.assertCompleted();
subscriber.assertNoErrors();
subscriber.assertValueCount(5);
assertThat(subscriber.getOnNextEvents(), hasItems("0-A", "1-B", "2-C", "3-D", "4-E"));
}
}

View File

@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<version>1.4.4.RELEASE</version>
</parent>
<dependencies>

View File

@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ExternalPropertiesWithXmlConfig.class }, loader = AnnotationConfigContextLoader.class)
@Ignore("manual only")
public class ExternalPropertiesWithXmlIntegrationTest {
public class ExternalPropertiesWithXmlManualTest {
@Autowired
private Environment env;

View File

@ -12,7 +12,7 @@ import java.sql.SQLException;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class SpringRetryTest {
public class SpringRetryIntegrationTest {
@Autowired
private MyService myService;

View File

@ -8,7 +8,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ThreadPoolTaskSchedulerConfig.class }, loader = AnnotationConfigContextLoader.class)
public class ThreadPoolTaskSchedulerTest {
public class ThreadPoolTaskSchedulerIntegrationTest {
@Test
public void testThreadPoolTaskSchedulerAnnotation() throws InterruptedException {
Thread.sleep(2550);

View File

@ -5,7 +5,7 @@ import org.baeldung.properties.basic.PropertiesWithMultipleXmlsIntegrationTest;
import org.baeldung.properties.basic.PropertiesWithXmlIntegrationTest;
import org.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest;
import org.baeldung.properties.external.ExternalPropertiesWithMultipleXmlsIntegrationTest;
import org.baeldung.properties.external.ExternalPropertiesWithXmlIntegrationTest;
import org.baeldung.properties.external.ExternalPropertiesWithXmlManualTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@ -15,7 +15,7 @@ import org.junit.runners.Suite.SuiteClasses;
PropertiesWithXmlIntegrationTest.class,
ExternalPropertiesWithJavaIntegrationTest.class,
ExternalPropertiesWithMultipleXmlsIntegrationTest.class,
ExternalPropertiesWithXmlIntegrationTest.class,
ExternalPropertiesWithXmlManualTest.class,
ExtendedPropertiesWithJavaIntegrationTest.class,
PropertiesWithMultipleXmlsIntegrationTest.class,
})// @formatter:on

Some files were not shown because too many files have changed in this diff Show More