Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Kevin Gilmore 2017-02-08 21:44:46 -06:00
commit 429d60e63d
147 changed files with 3572 additions and 701 deletions

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

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

@ -8,29 +8,28 @@ import com.baeldung.algorithms.slope_one.SlopeOne;
public class RunAlgorithm {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Run algorithm:");
System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One");
System.out.println("3 - Simple Genetic Algorithm");
int decision = in.nextInt();
switch (decision) {
case 1:
System.out.println(
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
break;
case 2:
SlopeOne.slopeOne(3);
break;
case 3:
SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
break;
default:
System.out.println("Unknown option");
break;
}
in.close();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Run algorithm:");
System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One");
System.out.println("3 - Simple Genetic Algorithm");
int decision = in.nextInt();
switch (decision) {
case 1:
System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
break;
case 2:
SlopeOne.slopeOne(3);
break;
case 3:
SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
break;
default:
System.out.println("Unknown option");
break;
}
in.close();
}
}

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

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,23 @@
package com.baeldung.streamApi;
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 List<String> split ( String str ) {
return Stream.of(str.split(","))
.map (elem -> new String(elem))
.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,15 @@
package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
public class BinaryGeneticAlgorithmUnitTest {
@Test
public void testGA() {
Assert.assertTrue(SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"));
}
}

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,38 @@
package com.baeldung.stream;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.baeldung.streamApi.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_list_convert_to_stream_and_convert_to_list() {
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);
}
}

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

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

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

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

View File

@ -147,6 +147,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>

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,171 @@
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,113 @@
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

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

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>spring-boot</artifactId>
@ -12,8 +12,8 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
<version>1.5.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
@ -24,6 +24,26 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-osgi-locator</artifactId>
<version>1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.geronimo.components</groupId>
<artifactId>geronimo-jaspi</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
@ -87,6 +107,20 @@
<artifactId>jquery</artifactId>
<version>${jquery.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomee</groupId>
<artifactId>arquillian-tomee-embedded</artifactId>
<version>${arquillian-tomee-embedded.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomee</groupId>
<artifactId>javaee-api</artifactId>
<version>${tomee-javaee-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
@ -166,7 +200,7 @@
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
@ -186,6 +220,8 @@
<jquery.version>3.1.1</jquery.version>
<bootstrap.version>3.3.7-1</bootstrap.version>
<subethasmtp.version>3.1.7</subethasmtp.version>
<arquillian-tomee-embedded.version>7.0.2</arquillian-tomee-embedded.version>
<tomee-javaee-api.version>7.0-1</tomee-javaee-api.version>
</properties>
</project>

View File

@ -0,0 +1,28 @@
package com.baeldung.annotation.servletcomponentscan;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Initialized;
import javax.enterprise.event.Observes;
import javax.servlet.ServletContext;
@ApplicationScoped
public class JavaEEApp {
private ServletContext context;
/**
* act as a servletContext provider
*/
private void setContext(@Observes @Initialized(ApplicationScoped.class) final ServletContext context) {
if (this.context != null) {
throw new IllegalStateException("app context started twice");
}
this.context = context;
}
public ServletContext getContext() {
return context;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.annotation.servletcomponentscan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* using the following annotations are equivalent:
* <ul><li>
* <code>@ServletComponentScan</code>
* </li><li>
* <code>@ServletComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.javaee")</code>
* </li><li>
* <code>@ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class})</code>
* </li></ul>
*/
@SpringBootApplication
@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.javaee")
public class SpringBootAnnotatedApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootAnnotatedApp.class, args);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.annotation.servletcomponentscan;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.javaee")
public class SpringBootPlainApp {
public static void main(String[] args) {
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.annotation.servletcomponentscan.javaee;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AttrListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
servletContextEvent
.getServletContext()
.setAttribute("servlet-context-attr", "test");
System.out.println("context init");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("context destroy");
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.annotation.servletcomponentscan.javaee;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
@WebServlet(name = "echo servlet", urlPatterns = "/echo")
public class EchoServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
Path path = File
.createTempFile("echo", "tmp")
.toPath();
Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
Files.copy(path, response.getOutputStream());
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.annotation.servletcomponentscan.javaee;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;
@WebFilter(urlPatterns = "/hello", description = "a filter for hello servlet", initParams = { @WebInitParam(name = "msg", value = "filtering ") }, filterName = "hello filter", servletNames = { "echo servlet" })
public class HelloFilter implements Filter {
private FilterConfig filterConfig;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("filter init");
this.filterConfig = filterConfig;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletResponse
.getOutputStream()
.print(filterConfig.getInitParameter("msg"));
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("filter destroy");
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.annotation.servletcomponentscan.javaee;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello")})
public class HelloServlet extends HttpServlet {
private ServletConfig servletConfig;
@Override
public void init(ServletConfig servletConfig){
this.servletConfig = servletConfig;
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
response
.getOutputStream()
.write(servletConfig.getInitParameter("msg").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.webjar;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

View File

@ -1,7 +1,8 @@
package com.baeldung;
package com.baeldung.webjar;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
public class WebjarsdemoApplication {

View File

@ -1,8 +1,8 @@
package org.baeldung.common.error;
import javax.servlet.Servlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import javax.servlet.Servlet;
public class SpringHelloServletRegistrationBean extends ServletRegistrationBean {

View File

@ -2,7 +2,7 @@ package org.baeldung.common.properties;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

View File

@ -0,0 +1,88 @@
package com.baeldung.annotation.servletcomponentscan;
import com.baeldung.annotation.servletcomponentscan.javaee.AttrListener;
import com.baeldung.annotation.servletcomponentscan.javaee.EchoServlet;
import com.baeldung.annotation.servletcomponentscan.javaee.HelloFilter;
import com.baeldung.annotation.servletcomponentscan.javaee.HelloServlet;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import static org.junit.Assert.*;
@RunWith(Arquillian.class)
public class JavaEEAppTest {
@Deployment
public static WebArchive createDeployment() {
return ShrinkWrap
.create(WebArchive.class)
.addClass(JavaEEApp.class)
.addClasses(AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class);
}
@Inject private ServletContext servletContext;
@Test
public void givenServletContextListener_whenAccessSpecialAttrs_thenFound() throws MalformedURLException {
assertNotNull(servletContext);
assertNotNull(servletContext.getAttribute("servlet-context-attr"));
assertEquals("test", servletContext.getAttribute("servlet-context-attr"));
}
@Test
public void givenServletContext_whenCheckHelloFilterMappings_thenCorrect() throws MalformedURLException {
assertNotNull(servletContext);
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
assertNotNull(filterRegistration);
assertTrue(filterRegistration
.getServletNameMappings()
.contains("echo servlet"));
}
@ArquillianResource private URL base;
@Test
@RunAsClient
public void givenFilterAndServlet_whenGetHello_thenRespondFilteringHello() throws MalformedURLException {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(URI.create(new URL(base, "hello").toExternalForm()));
Response response = target
.request()
.get();
assertEquals("filtering hello", response.readEntity(String.class));
}
@Test
@RunAsClient
public void givenFilterAndServlet_whenPostEcho_thenEchoFiltered() throws MalformedURLException {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(URI.create(new URL(base, "echo").toExternalForm()));
Response response = target
.request()
.post(Entity.entity("echo", MediaType.TEXT_PLAIN_TYPE));
assertEquals("filtering echo", response.readEntity(String.class));
}
}

View File

@ -0,0 +1,65 @@
package com.baeldung.annotation.servletcomponentscan;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class)
@AutoConfigureMockMvc
@TestPropertySource(properties = { "security.basic.enabled=false", "server.tomcat.additional-tld-skip-patterns=tomee-*.jar,tomcat-*.jar,openejb-*.jar,cxf-*.jar,activemq-*.jar" })
public class SpringBootWithServletComponentTest {
@Autowired private ServletContext servletContext;
@Test
public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() {
assertNotNull(servletContext);
assertNotNull(servletContext.getAttribute("servlet-context-attr"));
assertEquals("test", servletContext.getAttribute("servlet-context-attr"));
}
@Test
public void givenServletContext_whenCheckHelloFilterMappings_thenCorrect() {
assertNotNull(servletContext);
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
assertNotNull(filterRegistration);
assertTrue(filterRegistration
.getServletNameMappings()
.contains("echo servlet"));
}
@Autowired private TestRestTemplate restTemplate;
@Test
public void givenServletFilter_whenGetHello_thenRequestFiltered() {
ResponseEntity<String> responseEntity = this.restTemplate.getForEntity("/hello", String.class);
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertEquals("filtering hello", responseEntity.getBody());
}
@Test
public void givenFilterAndServlet_whenPostEcho_thenEchoFiltered() {
ResponseEntity<String> responseEntity = this.restTemplate.postForEntity("/echo", "echo", String.class);
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertEquals("filtering echo", responseEntity.getBody());
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.annotation.servletcomponentscan;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class)
@AutoConfigureMockMvc
@TestPropertySource(properties = { "security.basic.enabled=false", "server.tomcat.additional-tld-skip-patterns=tomee-*.jar,tomcat-*.jar,openejb-*.jar,cxf-*.jar,activemq-*.jar" })
public class SpringBootWithoutServletComponentTest {
@Autowired private ServletContext servletContext;
@Autowired private TestRestTemplate restTemplate;
@Test
public void givenServletContext_whenAccessAttrs_thenNotFound() {
assertNull(servletContext.getAttribute("servlet-context-attr"));
}
@Test
public void givenServletFilter_whenGetHello_thenEndpointNotFound() {
ResponseEntity<String> responseEntity = this.restTemplate.getForEntity("/hello", String.class);
assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
}
@Test
public void givenServletContext_whenCheckFilterMappings_thenEmpty() {
assertNotNull(servletContext);
FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter");
assertNull(filterRegistration);
}
}

View File

@ -6,6 +6,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@ -17,6 +18,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(properties = { "security.basic.enabled=false" })
public class AppLiveTest {
@Autowired

View File

@ -1,13 +1,13 @@
package com.baeldung;
package com.baeldung.webjar;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WebjarsdemoApplication.class)
@SpringBootTest(classes = WebjarsdemoApplication.class)
@WebAppConfiguration
public class WebjarsdemoApplicationIntegrationTest {

View File

@ -9,7 +9,7 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@ -22,7 +22,7 @@ import org.springframework.web.context.WebApplicationContext;
import java.nio.charset.Charset;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class SpringBootApplicationIntegrationTest {
@Autowired

View File

@ -5,14 +5,14 @@ import org.baeldung.repository.GenericEntityRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@SpringBootTest(classes = Application.class)
public class SpringBootJPAIntegrationTest {
@Autowired
private GenericEntityRepository genericEntityRepository;

View File

@ -5,7 +5,7 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -23,7 +23,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@SpringBootTest(classes = Application.class)
public class SpringBootMailIntegrationTest {
@Autowired
private JavaMailSender javaMailSender;

View File

@ -1,4 +1,4 @@
spring.application.name=resource
spring.application.name=book-service
server.port=8083
resource.returnString=hello cloud

View File

@ -6,9 +6,13 @@ eureka.client.registryFetchIntervalSeconds = 5
management.security.sessions=always
zuul.routes.resource.path=/resource/**
zuul.routes.resource.sensitive-headers=Set-Cookie,Authorization
hystrix.command.resource.execution.isolation.thread.timeoutInMilliseconds=600000
zuul.routes.book-service.path=/book-service/**
zuul.routes.book-service.sensitive-headers=Set-Cookie,Authorization
hystrix.command.book-service.execution.isolation.thread.timeoutInMilliseconds=600000
zuul.routes.rating-service.path=/rating-service/**
zuul.routes.rating-service.sensitive-headers=Set-Cookie,Authorization
hystrix.command.rating-service.execution.isolation.thread.timeoutInMilliseconds=600000
zuul.routes.discovery.path=/discovery/**
zuul.routes.discovery.sensitive-headers=Set-Cookie,Authorization

View File

@ -0,0 +1,17 @@
spring.application.name=rating-service
server.port=8084
resource.returnString=hello cloud
resource.user.returnString=hello cloud user
resource.admin.returnString=hello cloud admin
eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
management.security.sessions=never
logging.level.org.springframework.web.=debug
logging.level.org.springframework.security=debug
spring.redis.host=localhost
spring.redis.port=6379

View File

@ -22,14 +22,14 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resource/hello/cloud").permitAll()
.antMatchers("/book-service/books").permitAll()
.antMatchers("/eureka/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout().permitAll()
.logoutSuccessUrl("/resource/hello/cloud").permitAll()
.logoutSuccessUrl("/book-service/books").permitAll()
.and()
.csrf()
.disable();

View File

@ -14,12 +14,12 @@ public class GatewayApplicationLiveTest {
TestRestTemplate testRestTemplate = new TestRestTemplate();
String testUrl = "http://localhost:8080";
ResponseEntity<String> response = testRestTemplate.getForEntity(testUrl + "/resource/hello/cloud", String.class);
ResponseEntity<String> response = testRestTemplate.getForEntity(testUrl + "/book-service/books", String.class);
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
Assert.assertEquals("hello cloud", response.getBody());
Assert.assertNotNull(response.getBody());
//try the protected resource and confirm the redirect to login
response = testRestTemplate.getForEntity(testUrl + "/resource/hello/user", String.class);
response = testRestTemplate.getForEntity(testUrl + "/book-service/books/1", String.class);
Assert.assertEquals(HttpStatus.FOUND, response.getStatusCode());
Assert.assertEquals("http://localhost:8080/login", response.getHeaders().get("Location").get(0));
@ -36,12 +36,12 @@ public class GatewayApplicationLiveTest {
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
//request the protected resource
response = testRestTemplate.exchange(testUrl + "/resource/hello/user", HttpMethod.GET, httpEntity, String.class);
response = testRestTemplate.exchange(testUrl + "/book-service/books/1", HttpMethod.GET, httpEntity, String.class);
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
Assert.assertEquals("hello cloud user", response.getBody());
Assert.assertNotNull(response.getBody());
//request the admin protected resource to determine it is still protected
response = testRestTemplate.exchange(testUrl + "/resource/hello/admin", HttpMethod.GET, httpEntity, String.class);
response = testRestTemplate.exchange(testUrl + "/rating-service/ratings/all", HttpMethod.GET, httpEntity, String.class);
Assert.assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
//login as the admin
@ -57,9 +57,9 @@ public class GatewayApplicationLiveTest {
httpEntity = new HttpEntity<>(headers);
//request the protected resource
response = testRestTemplate.exchange(testUrl + "/resource/hello/admin", HttpMethod.GET, httpEntity, String.class);
response = testRestTemplate.exchange(testUrl + "/rating-service/ratings/all", HttpMethod.GET, httpEntity, String.class);
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
Assert.assertEquals("hello cloud admin", response.getBody());
Assert.assertNotNull(response.getBody());
//request the discovery resources as the admin
response = testRestTemplate.exchange(testUrl + "/discovery", HttpMethod.GET, httpEntity, String.class);

View File

@ -14,7 +14,8 @@
<module>config</module>
<module>discovery</module>
<module>gateway</module>
<module>resource</module>
<module>svc-book</module>
<module>svc-rating</module>
</modules>

View File

@ -1,41 +0,0 @@
package com.baeldung.spring.cloud.bootstrap.resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
@RestController
public class ResourceApplication {
public static void main(String[] args) {
SpringApplication.run(ResourceApplication.class, args);
}
@Value("${resource.returnString}")
private String returnString;
@Value("${resource.user.returnString}")
private String userReturnString;
@Value("${resource.admin.returnString}")
private String adminReturnString;
@RequestMapping("/hello/cloud")
public String getString() {
return returnString;
}
@RequestMapping("/hello/user")
public String getUserString() {
return userReturnString;
}
@RequestMapping("/hello/admin")
public String getAdminString() {
return adminReturnString;
}
}

View File

@ -4,7 +4,8 @@
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>
<artifactId>resource</artifactId>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>svc-book</artifactId>
<version>1.0.0-SNAPSHOT</version>
<parent>

View File

@ -0,0 +1,40 @@
package com.baeldung.spring.cloud.bootstrap.svcbook;
public class Book {
private Long id;
private String author;
private String title;
public Book(Long id, String title, String author) {
this.id = id;
this.author = author;
this.title = title;
}
public Book() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.spring.cloud.bootstrap.svcbook;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@SpringBootApplication
@EnableEurekaClient
@RestController
@RequestMapping("/books")
public class BookServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BookServiceApplication.class, args);
}
private List<Book> bookList = Arrays.asList(
new Book(1L, "Baeldung goes to the market", "Tim Schimandle"),
new Book(2L, "Baeldung goes to the park", "Slavisa")
);
@GetMapping("")
public List<Book> findAllBooks() {
return bookList;
}
@GetMapping("/{bookId}")
public Book findBook(@PathVariable Long bookId) {
return bookList.stream().filter(b -> b.getId().equals(bookId)).findFirst().orElse(null);
}
}

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