Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
429d60e63d
@ -1,2 +1,3 @@
|
|||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi)
|
- [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)
|
||||||
|
@ -9,6 +9,7 @@
|
|||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
<junit.version>4.12</junit.version>
|
<junit.version>4.12</junit.version>
|
||||||
<poi.version>3.15</poi.version>
|
<poi.version>3.15</poi.version>
|
||||||
|
<jexcel.version>1.0.6</jexcel.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -37,5 +38,10 @@
|
|||||||
<artifactId>poi-ooxml</artifactId>
|
<artifactId>poi-ooxml</artifactId>
|
||||||
<version>${poi.version}</version>
|
<version>${poi.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jxls</groupId>
|
||||||
|
<artifactId>jxls-jexcel</artifactId>
|
||||||
|
<version>${jexcel.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</project>
|
</project>
|
||||||
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -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();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
56
apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java
Normal file
56
apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java
Normal 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));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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
BIN
apache-poi/temp.xls
Normal file
Binary file not shown.
BIN
apache-poi/temp.xlsx
Normal file
BIN
apache-poi/temp.xlsx
Normal file
Binary file not shown.
0
core-java/0.004102810554955205
Normal file
0
core-java/0.004102810554955205
Normal file
0
core-java/0.04832801936270381
Normal file
0
core-java/0.04832801936270381
Normal file
0
core-java/0.5633433244738808
Normal file
0
core-java/0.5633433244738808
Normal file
0
core-java/0.6256429734439612
Normal file
0
core-java/0.6256429734439612
Normal file
0
core-java/0.9799201796740292
Normal file
0
core-java/0.9799201796740292
Normal file
@ -10,6 +10,44 @@
|
|||||||
|
|
||||||
<dependencies>
|
<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 -->
|
<!-- utils -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>net.sourceforge.collections</groupId>
|
<groupId>net.sourceforge.collections</groupId>
|
||||||
@ -63,7 +101,6 @@
|
|||||||
<artifactId>grep4j</artifactId>
|
<artifactId>grep4j</artifactId>
|
||||||
<version>${grep4j.version}</version>
|
<version>${grep4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- web -->
|
<!-- web -->
|
||||||
|
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
@ -154,6 +191,12 @@
|
|||||||
<version>${mockito.version}</version>
|
<version>${mockito.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.jayway.awaitility</groupId>
|
||||||
|
<artifactId>awaitility</artifactId>
|
||||||
|
<version>${avaitility.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-codec</groupId>
|
<groupId>commons-codec</groupId>
|
||||||
@ -263,7 +306,8 @@
|
|||||||
<configuration>
|
<configuration>
|
||||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||||
<transformers>
|
<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>
|
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||||
</transformer>
|
</transformer>
|
||||||
</transformers>
|
</transformers>
|
||||||
@ -371,6 +415,7 @@
|
|||||||
<mockito.version>1.10.19</mockito.version>
|
<mockito.version>1.10.19</mockito.version>
|
||||||
<testng.version>6.10</testng.version>
|
<testng.version>6.10</testng.version>
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
||||||
|
<avaitility.version>1.7.0</avaitility.version>
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
|
@ -17,8 +17,7 @@ public class RunAlgorithm {
|
|||||||
int decision = in.nextInt();
|
int decision = in.nextInt();
|
||||||
switch (decision) {
|
switch (decision) {
|
||||||
case 1:
|
case 1:
|
||||||
System.out.println(
|
System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||||
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
|
||||||
break;
|
break;
|
||||||
case 2:
|
case 2:
|
||||||
SlopeOne.slopeOne(3);
|
SlopeOne.slopeOne(3);
|
||||||
|
@ -13,16 +13,14 @@ public class SimpleGeneticAlgorithm {
|
|||||||
|
|
||||||
public static boolean runAlgorithm(int populationSize, String solution) {
|
public static boolean runAlgorithm(int populationSize, String solution) {
|
||||||
if (solution.length() != SimpleGeneticAlgorithm.solution.length) {
|
if (solution.length() != SimpleGeneticAlgorithm.solution.length) {
|
||||||
throw new RuntimeException(
|
throw new RuntimeException("The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes");
|
||||||
"The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes");
|
|
||||||
}
|
}
|
||||||
SimpleGeneticAlgorithm.setSolution(solution);
|
SimpleGeneticAlgorithm.setSolution(solution);
|
||||||
Population myPop = new Population(populationSize, true);
|
Population myPop = new Population(populationSize, true);
|
||||||
|
|
||||||
int generationCount = 1;
|
int generationCount = 1;
|
||||||
while (myPop.getFittest().getFitness() < SimpleGeneticAlgorithm.getMaxFitness()) {
|
while (myPop.getFittest().getFitness() < SimpleGeneticAlgorithm.getMaxFitness()) {
|
||||||
System.out.println(
|
System.out.println("Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness());
|
||||||
"Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness());
|
|
||||||
myPop = SimpleGeneticAlgorithm.evolvePopulation(myPop);
|
myPop = SimpleGeneticAlgorithm.evolvePopulation(myPop);
|
||||||
generationCount++;
|
generationCount++;
|
||||||
}
|
}
|
||||||
|
50
core-java/src/main/java/com/baeldung/graph/Car.java
Normal file
50
core-java/src/main/java/com/baeldung/graph/Car.java
Normal 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;
|
||||||
|
}
|
45
core-java/src/main/java/com/baeldung/graph/Company.java
Normal file
45
core-java/src/main/java/com/baeldung/graph/Company.java
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
@ -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 + '}';
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.java_8_features.groupingby;
|
||||||
|
|
||||||
|
public enum BlogPostType {
|
||||||
|
NEWS, REVIEW, GUIDE
|
||||||
|
}
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
@ -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());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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"));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -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"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -37,7 +37,8 @@ public class PriorityBlockingQueueUnitTest {
|
|||||||
try {
|
try {
|
||||||
Integer poll = queue.take();
|
Integer poll = queue.take();
|
||||||
System.out.println("Polled: " + poll);
|
System.out.println("Polled: " + poll);
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
thread.start();
|
thread.start();
|
||||||
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
46
core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java
Normal file
46
core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java
Normal 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());
|
||||||
|
}
|
||||||
|
}
|
167
core-java/src/test/java/com/baeldung/graph/Neo4jTest.java
Normal file
167
core-java/src/test/java/com/baeldung/graph/Neo4jTest.java
Normal 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");
|
||||||
|
}
|
||||||
|
}
|
@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit;
|
|||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertNotEquals;
|
import static org.junit.Assert.assertNotEquals;
|
||||||
|
|
||||||
public class ConcurrentMapAggregateStatusTest {
|
public class ConcurrentMapAggregateStatusManualTest {
|
||||||
|
|
||||||
private ExecutorService executorService;
|
private ExecutorService executorService;
|
||||||
private Map<String, Integer> concurrentMap;
|
private Map<String, Integer> concurrentMap;
|
@ -10,7 +10,7 @@ import java.util.concurrent.ConcurrentMap;
|
|||||||
|
|
||||||
import static org.junit.Assert.assertNull;
|
import static org.junit.Assert.assertNull;
|
||||||
|
|
||||||
public class ConcurrentMapNullKeyValueTest {
|
public class ConcurrentMapNullKeyValueManualTest {
|
||||||
|
|
||||||
ConcurrentMap<String, Object> concurrentMap;
|
ConcurrentMap<String, Object> concurrentMap;
|
||||||
|
|
@ -11,7 +11,7 @@ import java.util.concurrent.*;
|
|||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class ConcurrentMapPerformanceTest {
|
public class ConcurrentMapPerformanceManualTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenMaps_whenGetPut500KTimes_thenConcurrentMapFaster() throws Exception {
|
public void givenMaps_whenGetPut500KTimes_thenConcurrentMapFaster() throws Exception {
|
@ -10,7 +10,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
|||||||
|
|
||||||
import static org.testng.Assert.*;
|
import static org.testng.Assert.*;
|
||||||
|
|
||||||
public class ConcurrentNavigableMapTests {
|
public class ConcurrentNavigableMapManualTests {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throws InterruptedException {
|
public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throws InterruptedException {
|
||||||
@ -18,9 +18,7 @@ public class ConcurrentNavigableMapTests {
|
|||||||
|
|
||||||
updateMapConcurrently(skipListMap, 4);
|
updateMapConcurrently(skipListMap, 4);
|
||||||
|
|
||||||
Iterator<Integer> skipListIter = skipListMap
|
Iterator<Integer> skipListIter = skipListMap.keySet().iterator();
|
||||||
.keySet()
|
|
||||||
.iterator();
|
|
||||||
int previous = skipListIter.next();
|
int previous = skipListIter.next();
|
||||||
while (skipListIter.hasNext()) {
|
while (skipListIter.hasNext()) {
|
||||||
int current = skipListIter.next();
|
int current = skipListIter.next();
|
@ -10,7 +10,7 @@ import java.util.concurrent.TimeUnit;
|
|||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class ConcurretMapMemoryConsistencyTest {
|
public class ConcurretMapMemoryConsistencyManualTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
|
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
|
@ -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");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,12 +1,12 @@
|
|||||||
package org.baeldung.java;
|
package org.baeldung.java;
|
||||||
|
|
||||||
import java.nio.charset.Charset;
|
|
||||||
import java.util.Random;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.RandomStringUtils;
|
import org.apache.commons.lang3.RandomStringUtils;
|
||||||
import org.apache.commons.math3.random.RandomDataGenerator;
|
import org.apache.commons.math3.random.RandomDataGenerator;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
public class JavaRandomUnitTest {
|
public class JavaRandomUnitTest {
|
||||||
|
|
||||||
// tests - random long
|
// tests - random long
|
||||||
@ -164,7 +164,7 @@ public class JavaRandomUnitTest {
|
|||||||
final int targetStringLength = 10;
|
final int targetStringLength = 10;
|
||||||
final StringBuilder buffer = new StringBuilder(targetStringLength);
|
final StringBuilder buffer = new StringBuilder(targetStringLength);
|
||||||
for (int i = 0; i < targetStringLength; i++) {
|
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);
|
buffer.append((char) randomLimitedInt);
|
||||||
}
|
}
|
||||||
final String generatedString = buffer.toString();
|
final String generatedString = buffer.toString();
|
||||||
|
@ -16,17 +16,14 @@ import static org.junit.Assert.assertTrue;
|
|||||||
public class ThreadPoolInParallelStreamTest {
|
public class ThreadPoolInParallelStreamTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal()
|
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {
|
||||||
throws InterruptedException, ExecutionException {
|
|
||||||
long firstNum = 1;
|
long firstNum = 1;
|
||||||
long lastNum = 1_000_000;
|
long lastNum = 1_000_000;
|
||||||
|
|
||||||
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed()
|
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
ForkJoinPool customThreadPool = new ForkJoinPool(4);
|
ForkJoinPool customThreadPool = new ForkJoinPool(4);
|
||||||
long actualTotal = customThreadPool.submit(() -> aList.parallelStream()
|
long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
|
||||||
.reduce(0L, Long::sum)).get();
|
|
||||||
|
|
||||||
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
|
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
|
||||||
}
|
}
|
||||||
|
@ -57,6 +57,32 @@
|
|||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</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>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
<artifactId>assertj-core</artifactId>
|
<artifactId>assertj-core</artifactId>
|
||||||
@ -112,6 +138,9 @@
|
|||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-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>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -1,6 +1,5 @@
|
|||||||
package org.baeldung.guava;
|
package org.baeldung.guava;
|
||||||
|
|
||||||
|
|
||||||
public class CustomEvent {
|
public class CustomEvent {
|
||||||
private String action;
|
private String action;
|
||||||
|
|
@ -18,5 +18,4 @@ class EventBusWrapper {
|
|||||||
eventBus.post(object);
|
eventBus.post(object);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
31
guava/src/main/java/org/baeldung/guava/EventListener.java
Normal file
31
guava/src/main/java/org/baeldung/guava/EventListener.java
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
@ -11,18 +11,18 @@ public class GuavaEventBusTest {
|
|||||||
private EventListener listener;
|
private EventListener listener;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() throws Exception {
|
public void setUp() {
|
||||||
listener = new EventListener();
|
listener = new EventListener();
|
||||||
EventBusWrapper.register(listener);
|
EventBusWrapper.register(listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
public void tearDown() throws Exception {
|
public void tearDown() {
|
||||||
EventBusWrapper.unregister(listener);
|
EventBusWrapper.unregister(listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenStringEvent_whenEventHandled_thenSuccess() throws Exception {
|
public void givenStringEvent_whenEventHandled_thenSuccess() {
|
||||||
listener.resetEventsHandled();
|
listener.resetEventsHandled();
|
||||||
|
|
||||||
EventBusWrapper.post("String Event");
|
EventBusWrapper.post("String Event");
|
||||||
@ -31,7 +31,7 @@ public class GuavaEventBusTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenCustomEvent_whenEventHandled_thenSuccess() throws Exception {
|
public void givenCustomEvent_whenEventHandled_thenSuccess() {
|
||||||
listener.resetEventsHandled();
|
listener.resetEventsHandled();
|
||||||
|
|
||||||
CustomEvent customEvent = new CustomEvent("Custom Event");
|
CustomEvent customEvent = new CustomEvent("Custom Event");
|
||||||
|
@ -3,7 +3,7 @@ package org.baeldung.guava;
|
|||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import static com.google.common.base.Preconditions.*;
|
import com.google.common.base.*;
|
||||||
|
|
||||||
public class GuavaPreConditionsTest {
|
public class GuavaPreConditionsTest {
|
||||||
|
|
||||||
@ -11,10 +11,7 @@ public class GuavaPreConditionsTest {
|
|||||||
public void whenCheckArgumentEvaluatesFalse_throwsException() {
|
public void whenCheckArgumentEvaluatesFalse_throwsException() {
|
||||||
int age = -18;
|
int age = -18;
|
||||||
|
|
||||||
assertThatThrownBy(() -> checkArgument(age > 0))
|
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0)).isInstanceOf(IllegalArgumentException.class).hasMessage(null).hasNoCause();
|
||||||
.isInstanceOf(IllegalArgumentException.class)
|
|
||||||
.hasMessage(null)
|
|
||||||
.hasNoCause();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -22,10 +19,7 @@ public class GuavaPreConditionsTest {
|
|||||||
final int age = -18;
|
final int age = -18;
|
||||||
final String message = "Age can't be zero or less than zero";
|
final String message = "Age can't be zero or less than zero";
|
||||||
|
|
||||||
assertThatThrownBy(() -> checkArgument(age > 0, message))
|
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message)).isInstanceOf(IllegalArgumentException.class).hasMessage(message).hasNoCause();
|
||||||
.isInstanceOf(IllegalArgumentException.class)
|
|
||||||
.hasMessage(message)
|
|
||||||
.hasNoCause();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -33,19 +27,14 @@ public class GuavaPreConditionsTest {
|
|||||||
final int age = -18;
|
final int age = -18;
|
||||||
final String message = "Age can't be zero or less than zero, you supplied %s.";
|
final String message = "Age can't be zero or less than zero, you supplied %s.";
|
||||||
|
|
||||||
assertThatThrownBy(() -> checkArgument(age > 0, message, age))
|
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message, age)).isInstanceOf(IllegalArgumentException.class).hasMessage(message, age).hasNoCause();
|
||||||
.isInstanceOf(IllegalArgumentException.class)
|
|
||||||
.hasMessage(message, age)
|
|
||||||
.hasNoCause();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenArrayOfIntegers_whenCheckElementIndexEvaluatesFalse_throwsException() {
|
public void givenArrayOfIntegers_whenCheckElementIndexEvaluatesFalse_throwsException() {
|
||||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||||
|
|
||||||
assertThatThrownBy(() -> checkElementIndex(6, numbers.length - 1))
|
assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
|
||||||
.isInstanceOf(IndexOutOfBoundsException.class)
|
|
||||||
.hasNoCause();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -53,20 +42,7 @@ public class GuavaPreConditionsTest {
|
|||||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||||
final String message = "Please check the bound of an array and retry";
|
final String message = "Please check the bound of an array and retry";
|
||||||
|
|
||||||
assertThatThrownBy(() -> checkElementIndex(6, numbers.length - 1, message))
|
assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause();
|
||||||
.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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -74,10 +50,7 @@ public class GuavaPreConditionsTest {
|
|||||||
final String nullObject = null;
|
final String nullObject = null;
|
||||||
final String message = "Please check the Object supplied, its null!";
|
final String message = "Please check the Object supplied, its null!";
|
||||||
|
|
||||||
assertThatThrownBy(() -> checkNotNull(nullObject, message))
|
assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message)).isInstanceOf(NullPointerException.class).hasMessage(message).hasNoCause();
|
||||||
.isInstanceOf(NullPointerException.class)
|
|
||||||
.hasMessage(message)
|
|
||||||
.hasNoCause();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -85,19 +58,14 @@ public class GuavaPreConditionsTest {
|
|||||||
final String nullObject = null;
|
final String nullObject = null;
|
||||||
final String message = "Please check the Object supplied, its %s!";
|
final String message = "Please check the Object supplied, its %s!";
|
||||||
|
|
||||||
assertThatThrownBy(() -> checkNotNull(nullObject, message, nullObject))
|
assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message, new Object[] { null })).isInstanceOf(NullPointerException.class).hasMessage(message, nullObject).hasNoCause();
|
||||||
.isInstanceOf(NullPointerException.class)
|
|
||||||
.hasMessage(message, nullObject)
|
|
||||||
.hasNoCause();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenArrayOfIntegers_whenCheckPositionIndexEvaluatesFalse_throwsException() {
|
public void givenArrayOfIntegers_whenCheckPositionIndexEvaluatesFalse_throwsException() {
|
||||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||||
|
|
||||||
assertThatThrownBy(() -> checkPositionIndex(6, numbers.length - 1))
|
assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
|
||||||
.isInstanceOf(IndexOutOfBoundsException.class)
|
|
||||||
.hasNoCause();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -105,30 +73,14 @@ public class GuavaPreConditionsTest {
|
|||||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||||
final String message = "Please check the bound of an array and retry";
|
final String message = "Please check the bound of an array and retry";
|
||||||
|
|
||||||
assertThatThrownBy(() -> checkPositionIndex(6, numbers.length - 1, message))
|
assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause();
|
||||||
.isInstanceOf(IndexOutOfBoundsException.class)
|
|
||||||
.hasMessageStartingWith(message)
|
|
||||||
.hasNoCause();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenArrayOfIntegers_whenCheckPositionIndexesEvaluatesFalse_throwsException() {
|
public void givenArrayOfIntegers_whenCheckPositionIndexesEvaluatesFalse_throwsException() {
|
||||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||||
|
|
||||||
assertThatThrownBy(() -> checkPositionIndexes(6, 0, numbers.length - 1))
|
assertThatThrownBy(() -> Preconditions.checkPositionIndexes(6, 0, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
|
||||||
.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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -137,10 +89,7 @@ public class GuavaPreConditionsTest {
|
|||||||
final int givenState = 10;
|
final int givenState = 10;
|
||||||
final String message = "You have entered an invalid state";
|
final String message = "You have entered an invalid state";
|
||||||
|
|
||||||
assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0, message))
|
assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message)).isInstanceOf(IllegalStateException.class).hasMessageStartingWith(message).hasNoCause();
|
||||||
.isInstanceOf(IllegalStateException.class)
|
|
||||||
.hasMessageStartingWith(message)
|
|
||||||
.hasNoCause();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -149,9 +98,7 @@ public class GuavaPreConditionsTest {
|
|||||||
final int givenState = 10;
|
final int givenState = 10;
|
||||||
final String message = "State can't be %s, It can be one of %s.";
|
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)))
|
assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates))).isInstanceOf(IllegalStateException.class)
|
||||||
.isInstanceOf(IllegalStateException.class)
|
.hasMessage(message, givenState, Arrays.toString(validStates)).hasNoCause();
|
||||||
.hasMessage(message, givenState, Arrays.toString(validStates))
|
|
||||||
.hasNoCause();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -2,9 +2,9 @@
|
|||||||
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>logmdc</artifactId>
|
<artifactId>log-mdc</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<name>logmdc</name>
|
<name>log-mdc</name>
|
||||||
<packaging>war</packaging>
|
<packaging>war</packaging>
|
||||||
<description>tutorial on logging with MDC and NDC</description>
|
<description>tutorial on logging with MDC and NDC</description>
|
||||||
|
|
||||||
|
@ -138,15 +138,15 @@ public class MetricsTest {
|
|||||||
|
|
||||||
long elapsed1 = context1.stop();
|
long elapsed1 = context1.stop();
|
||||||
|
|
||||||
assertEquals(5000000000L, elapsed1, 10000000);
|
assertEquals(5000000000L, elapsed1, 1000000000);
|
||||||
assertThat(timer.getCount(), equalTo(1L));
|
assertThat(timer.getCount(), equalTo(1L));
|
||||||
assertEquals(0.2, timer.getMeanRate(), 0.1);
|
assertEquals(0.2, timer.getMeanRate(), 0.2);
|
||||||
|
|
||||||
Timer.Context context2 = timer.time();
|
Timer.Context context2 = timer.time();
|
||||||
TimeUnit.SECONDS.sleep(2);
|
TimeUnit.SECONDS.sleep(2);
|
||||||
context2.close();
|
context2.close();
|
||||||
|
|
||||||
assertThat(timer.getCount(), equalTo(2L));
|
assertThat(timer.getCount(), equalTo(2L));
|
||||||
assertEquals(0.3, timer.getMeanRate(), 0.1);
|
assertEquals(0.3, timer.getMeanRate(), 0.2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
1
pom.xml
1
pom.xml
@ -147,6 +147,7 @@
|
|||||||
<module>spring-rest-docs</module>
|
<module>spring-rest-docs</module>
|
||||||
<module>spring-rest</module>
|
<module>spring-rest</module>
|
||||||
<module>spring-security-basic-auth</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-authentication</module>
|
||||||
<module>spring-security-client/spring-security-jsp-authorize</module>
|
<module>spring-security-client/spring-security-jsp-authorize</module>
|
||||||
<module>spring-security-client/spring-security-jsp-config</module>
|
<module>spring-security-client/spring-security-jsp-config</module>
|
||||||
|
@ -26,10 +26,25 @@
|
|||||||
<artifactId>rxjava</artifactId>
|
<artifactId>rxjava</artifactId>
|
||||||
<version>${rx.java.version}</version>
|
<version>${rx.java.version}</version>
|
||||||
</dependency>
|
</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>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
<rx.java.version>1.2.5</rx.java.version>
|
<rx.java.version>1.2.5</rx.java.version>
|
||||||
|
<hamcrest.version>1.3</hamcrest.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -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!");
|
|
||||||
// }
|
|
||||||
// });
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -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);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
@ -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);
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
@ -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);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
113
rxjava/src/test/java/com/baeldung/rxjava/RxJavaTesting.java
Normal file
113
rxjava/src/test/java/com/baeldung/rxjava/RxJavaTesting.java
Normal 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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
|||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = { ExternalPropertiesWithXmlConfig.class }, loader = AnnotationConfigContextLoader.class)
|
@ContextConfiguration(classes = { ExternalPropertiesWithXmlConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||||
@Ignore("manual only")
|
@Ignore("manual only")
|
||||||
public class ExternalPropertiesWithXmlIntegrationTest {
|
public class ExternalPropertiesWithXmlManualTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private Environment env;
|
private Environment env;
|
@ -12,7 +12,7 @@ import java.sql.SQLException;
|
|||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
|
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
|
||||||
public class SpringRetryTest {
|
public class SpringRetryIntegrationTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private MyService myService;
|
private MyService myService;
|
@ -8,7 +8,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
|||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = { ThreadPoolTaskSchedulerConfig.class }, loader = AnnotationConfigContextLoader.class)
|
@ContextConfiguration(classes = { ThreadPoolTaskSchedulerConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||||
public class ThreadPoolTaskSchedulerTest {
|
public class ThreadPoolTaskSchedulerIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testThreadPoolTaskSchedulerAnnotation() throws InterruptedException {
|
public void testThreadPoolTaskSchedulerAnnotation() throws InterruptedException {
|
||||||
Thread.sleep(2550);
|
Thread.sleep(2550);
|
@ -5,7 +5,7 @@ import org.baeldung.properties.basic.PropertiesWithMultipleXmlsIntegrationTest;
|
|||||||
import org.baeldung.properties.basic.PropertiesWithXmlIntegrationTest;
|
import org.baeldung.properties.basic.PropertiesWithXmlIntegrationTest;
|
||||||
import org.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest;
|
import org.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest;
|
||||||
import org.baeldung.properties.external.ExternalPropertiesWithMultipleXmlsIntegrationTest;
|
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.runner.RunWith;
|
||||||
import org.junit.runners.Suite;
|
import org.junit.runners.Suite;
|
||||||
import org.junit.runners.Suite.SuiteClasses;
|
import org.junit.runners.Suite.SuiteClasses;
|
||||||
@ -15,7 +15,7 @@ import org.junit.runners.Suite.SuiteClasses;
|
|||||||
PropertiesWithXmlIntegrationTest.class,
|
PropertiesWithXmlIntegrationTest.class,
|
||||||
ExternalPropertiesWithJavaIntegrationTest.class,
|
ExternalPropertiesWithJavaIntegrationTest.class,
|
||||||
ExternalPropertiesWithMultipleXmlsIntegrationTest.class,
|
ExternalPropertiesWithMultipleXmlsIntegrationTest.class,
|
||||||
ExternalPropertiesWithXmlIntegrationTest.class,
|
ExternalPropertiesWithXmlManualTest.class,
|
||||||
ExtendedPropertiesWithJavaIntegrationTest.class,
|
ExtendedPropertiesWithJavaIntegrationTest.class,
|
||||||
PropertiesWithMultipleXmlsIntegrationTest.class,
|
PropertiesWithMultipleXmlsIntegrationTest.class,
|
||||||
})// @formatter:on
|
})// @formatter:on
|
||||||
|
@ -12,7 +12,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
<version>1.4.2.RELEASE</version>
|
<version>1.5.1.RELEASE</version>
|
||||||
<relativePath/> <!-- lookup parent from repository -->
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
@ -24,6 +24,26 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<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>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -87,6 +107,20 @@
|
|||||||
<artifactId>jquery</artifactId>
|
<artifactId>jquery</artifactId>
|
||||||
<version>${jquery.version}</version>
|
<version>${jquery.version}</version>
|
||||||
</dependency>
|
</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>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -186,6 +220,8 @@
|
|||||||
<jquery.version>3.1.1</jquery.version>
|
<jquery.version>3.1.1</jquery.version>
|
||||||
<bootstrap.version>3.3.7-1</bootstrap.version>
|
<bootstrap.version>3.3.7-1</bootstrap.version>
|
||||||
<subethasmtp.version>3.1.7</subethasmtp.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>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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) {
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung;
|
package com.baeldung.webjar;
|
||||||
|
|
||||||
import org.springframework.stereotype.Controller;
|
import org.springframework.stereotype.Controller;
|
||||||
import org.springframework.ui.Model;
|
import org.springframework.ui.Model;
|
@ -1,7 +1,8 @@
|
|||||||
package com.baeldung;
|
package com.baeldung.webjar;
|
||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class WebjarsdemoApplication {
|
public class WebjarsdemoApplication {
|
@ -1,8 +1,8 @@
|
|||||||
package org.baeldung.common.error;
|
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 {
|
public class SpringHelloServletRegistrationBean extends ServletRegistrationBean {
|
||||||
|
|
||||||
|
@ -2,7 +2,7 @@ package org.baeldung.common.properties;
|
|||||||
|
|
||||||
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
|
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
|
||||||
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
|
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.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@ -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));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -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.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.test.context.TestPropertySource;
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
import org.springframework.test.web.servlet.MockMvc;
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||||
@ -17,6 +18,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
|||||||
@RunWith(SpringRunner.class)
|
@RunWith(SpringRunner.class)
|
||||||
@SpringBootTest
|
@SpringBootTest
|
||||||
@AutoConfigureMockMvc
|
@AutoConfigureMockMvc
|
||||||
|
@TestPropertySource(properties = { "security.basic.enabled=false" })
|
||||||
public class AppLiveTest {
|
public class AppLiveTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
package com.baeldung;
|
package com.baeldung.webjar;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
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.junit4.SpringJUnit4ClassRunner;
|
||||||
import org.springframework.test.context.web.WebAppConfiguration;
|
import org.springframework.test.context.web.WebAppConfiguration;
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@SpringApplicationConfiguration(classes = WebjarsdemoApplication.class)
|
@SpringBootTest(classes = WebjarsdemoApplication.class)
|
||||||
@WebAppConfiguration
|
@WebAppConfiguration
|
||||||
public class WebjarsdemoApplicationIntegrationTest {
|
public class WebjarsdemoApplicationIntegrationTest {
|
||||||
|
|
@ -9,7 +9,7 @@ import org.junit.Before;
|
|||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.SpringApplicationConfiguration;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
import org.springframework.test.context.web.WebAppConfiguration;
|
import org.springframework.test.context.web.WebAppConfiguration;
|
||||||
@ -22,7 +22,7 @@ import org.springframework.web.context.WebApplicationContext;
|
|||||||
import java.nio.charset.Charset;
|
import java.nio.charset.Charset;
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@SpringApplicationConfiguration(classes = Application.class)
|
@SpringBootTest(classes = Application.class)
|
||||||
@WebAppConfiguration
|
@WebAppConfiguration
|
||||||
public class SpringBootApplicationIntegrationTest {
|
public class SpringBootApplicationIntegrationTest {
|
||||||
@Autowired
|
@Autowired
|
||||||
|
@ -5,14 +5,14 @@ import org.baeldung.repository.GenericEntityRepository;
|
|||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
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.junit4.SpringJUnit4ClassRunner;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertNotNull;
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@SpringApplicationConfiguration(classes = Application.class)
|
@SpringBootTest(classes = Application.class)
|
||||||
public class SpringBootJPAIntegrationTest {
|
public class SpringBootJPAIntegrationTest {
|
||||||
@Autowired
|
@Autowired
|
||||||
private GenericEntityRepository genericEntityRepository;
|
private GenericEntityRepository genericEntityRepository;
|
||||||
|
@ -5,7 +5,7 @@ import org.junit.Before;
|
|||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.SpringApplicationConfiguration;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.springframework.mail.SimpleMailMessage;
|
import org.springframework.mail.SimpleMailMessage;
|
||||||
import org.springframework.mail.javamail.JavaMailSender;
|
import org.springframework.mail.javamail.JavaMailSender;
|
||||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
@ -23,7 +23,7 @@ import static org.junit.Assert.assertEquals;
|
|||||||
import static org.junit.Assert.assertThat;
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@SpringApplicationConfiguration(classes = Application.class)
|
@SpringBootTest(classes = Application.class)
|
||||||
public class SpringBootMailIntegrationTest {
|
public class SpringBootMailIntegrationTest {
|
||||||
@Autowired
|
@Autowired
|
||||||
private JavaMailSender javaMailSender;
|
private JavaMailSender javaMailSender;
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
spring.application.name=resource
|
spring.application.name=book-service
|
||||||
server.port=8083
|
server.port=8083
|
||||||
|
|
||||||
resource.returnString=hello cloud
|
resource.returnString=hello cloud
|
@ -6,9 +6,13 @@ eureka.client.registryFetchIntervalSeconds = 5
|
|||||||
|
|
||||||
management.security.sessions=always
|
management.security.sessions=always
|
||||||
|
|
||||||
zuul.routes.resource.path=/resource/**
|
zuul.routes.book-service.path=/book-service/**
|
||||||
zuul.routes.resource.sensitive-headers=Set-Cookie,Authorization
|
zuul.routes.book-service.sensitive-headers=Set-Cookie,Authorization
|
||||||
hystrix.command.resource.execution.isolation.thread.timeoutInMilliseconds=600000
|
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.path=/discovery/**
|
||||||
zuul.routes.discovery.sensitive-headers=Set-Cookie,Authorization
|
zuul.routes.discovery.sensitive-headers=Set-Cookie,Authorization
|
||||||
|
@ -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
|
@ -22,14 +22,14 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
http.authorizeRequests()
|
http.authorizeRequests()
|
||||||
.antMatchers("/resource/hello/cloud").permitAll()
|
.antMatchers("/book-service/books").permitAll()
|
||||||
.antMatchers("/eureka/**").hasRole("ADMIN")
|
.antMatchers("/eureka/**").hasRole("ADMIN")
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
.and()
|
.and()
|
||||||
.formLogin()
|
.formLogin()
|
||||||
.and()
|
.and()
|
||||||
.logout().permitAll()
|
.logout().permitAll()
|
||||||
.logoutSuccessUrl("/resource/hello/cloud").permitAll()
|
.logoutSuccessUrl("/book-service/books").permitAll()
|
||||||
.and()
|
.and()
|
||||||
.csrf()
|
.csrf()
|
||||||
.disable();
|
.disable();
|
||||||
|
@ -14,12 +14,12 @@ public class GatewayApplicationLiveTest {
|
|||||||
TestRestTemplate testRestTemplate = new TestRestTemplate();
|
TestRestTemplate testRestTemplate = new TestRestTemplate();
|
||||||
String testUrl = "http://localhost:8080";
|
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(HttpStatus.OK, response.getStatusCode());
|
||||||
Assert.assertEquals("hello cloud", response.getBody());
|
Assert.assertNotNull(response.getBody());
|
||||||
|
|
||||||
//try the protected resource and confirm the redirect to login
|
//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(HttpStatus.FOUND, response.getStatusCode());
|
||||||
Assert.assertEquals("http://localhost:8080/login", response.getHeaders().get("Location").get(0));
|
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);
|
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
|
||||||
|
|
||||||
//request the protected resource
|
//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(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
|
//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());
|
Assert.assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
|
||||||
|
|
||||||
//login as the admin
|
//login as the admin
|
||||||
@ -57,9 +57,9 @@ public class GatewayApplicationLiveTest {
|
|||||||
httpEntity = new HttpEntity<>(headers);
|
httpEntity = new HttpEntity<>(headers);
|
||||||
|
|
||||||
//request the protected resource
|
//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(HttpStatus.OK, response.getStatusCode());
|
||||||
Assert.assertEquals("hello cloud admin", response.getBody());
|
Assert.assertNotNull(response.getBody());
|
||||||
|
|
||||||
//request the discovery resources as the admin
|
//request the discovery resources as the admin
|
||||||
response = testRestTemplate.exchange(testUrl + "/discovery", HttpMethod.GET, httpEntity, String.class);
|
response = testRestTemplate.exchange(testUrl + "/discovery", HttpMethod.GET, httpEntity, String.class);
|
||||||
|
@ -14,7 +14,8 @@
|
|||||||
<module>config</module>
|
<module>config</module>
|
||||||
<module>discovery</module>
|
<module>discovery</module>
|
||||||
<module>gateway</module>
|
<module>gateway</module>
|
||||||
<module>resource</module>
|
<module>svc-book</module>
|
||||||
|
<module>svc-rating</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
|
|
||||||
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
@ -4,7 +4,8 @@
|
|||||||
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<artifactId>resource</artifactId>
|
<groupId>com.baeldung.spring.cloud</groupId>
|
||||||
|
<artifactId>svc-book</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.spring.cloud.bootstrap.resource;
|
package com.baeldung.spring.cloud.bootstrap.svcbook;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
@ -22,9 +22,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|||||||
http.httpBasic()
|
http.httpBasic()
|
||||||
.disable()
|
.disable()
|
||||||
.authorizeRequests()
|
.authorizeRequests()
|
||||||
.antMatchers("/hello/cloud").permitAll()
|
.antMatchers("/books").permitAll()
|
||||||
.antMatchers("/hello/user").hasAnyRole("USER", "ADMIN")
|
.antMatchers("/books/*").hasAnyRole("USER", "ADMIN")
|
||||||
.antMatchers("/hello/admin").hasRole("ADMIN")
|
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
.and()
|
.and()
|
||||||
.csrf()
|
.csrf()
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.spring.cloud.bootstrap.resource;
|
package com.baeldung.spring.cloud.bootstrap.svcbook;
|
||||||
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
|
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
|
@ -1,4 +1,4 @@
|
|||||||
spring.cloud.config.name=resource
|
spring.cloud.config.name=book-service
|
||||||
spring.cloud.config.discovery.service-id=config
|
spring.cloud.config.discovery.service-id=config
|
||||||
spring.cloud.config.discovery.enabled=true
|
spring.cloud.config.discovery.enabled=true
|
||||||
spring.cloud.config.username=configUser
|
spring.cloud.config.username=configUser
|
85
spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml
Normal file
85
spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<groupId>com.baeldung.spring.cloud</groupId>
|
||||||
|
<artifactId>svc-rating</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
|
<version>1.4.2.RELEASE</version>
|
||||||
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-starter-config</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-starter-eureka</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.session</groupId>
|
||||||
|
<artifactId>spring-session</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<dependencyManagement>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-dependencies</artifactId>
|
||||||
|
<version>${spring-cloud-dependencies.version}</version>
|
||||||
|
<type>pom</type>
|
||||||
|
<scope>import</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</dependencyManagement>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
<properties>
|
||||||
|
<spring-cloud-dependencies.version>Brixton.SR7</spring-cloud-dependencies.version>
|
||||||
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
@ -0,0 +1,40 @@
|
|||||||
|
package com.baeldung.spring.cloud.bootstrap.svcrating;
|
||||||
|
|
||||||
|
public class Rating {
|
||||||
|
private Long id;
|
||||||
|
private Long bookId;
|
||||||
|
private int stars;
|
||||||
|
|
||||||
|
public Rating() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Rating(Long id, Long bookId, int stars) {
|
||||||
|
this.id = id;
|
||||||
|
this.bookId = bookId;
|
||||||
|
this.stars = stars;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(Long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getBookId() {
|
||||||
|
return bookId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBookId(Long bookId) {
|
||||||
|
this.bookId = bookId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getStars() {
|
||||||
|
return stars;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStars(int stars) {
|
||||||
|
this.stars = stars;
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user