Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-572
Conflicts: rxjava/src/main/java/com/baelding/rxjava/ColdObservableBackpressure.java rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBatching.java rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureBuffering.java rxjava/src/main/java/com/baelding/rxjava/HotObservableBackpressureSkipping.java rxjava/src/main/java/com/baelding/rxjava/HotObservableOnBackpressure.java rxjava/src/main/java/com/baelding/rxjava/HotObservableWithoutBackpressure.java
This commit is contained in:
commit
976e6bce2f
|
@ -9,6 +9,7 @@
|
|||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<poi.version>3.15</poi.version>
|
||||
<jexcel.version>1.0.6</jexcel.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
|
@ -37,5 +38,20 @@
|
|||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml-schemas</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jxls</groupId>
|
||||
<artifactId>jxls-jexcel</artifactId>
|
||||
<version>${jexcel.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,79 @@
|
|||
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);
|
||||
|
||||
cellLabel = new Label(0, 3, "Ana Johnson", cellFormat);
|
||||
sheet.addCell(cellLabel);
|
||||
cellNumber = new Number(1, 3, 30, cellFormat);
|
||||
sheet.addCell(cellNumber);
|
||||
|
||||
workbook.write();
|
||||
} finally {
|
||||
if (workbook != null) {
|
||||
workbook.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,137 @@
|
|||
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);
|
||||
|
||||
row = sheet.createRow(3);
|
||||
cell = row.createCell(0);
|
||||
cell.setCellValue("Ana Johnson");
|
||||
cell.setCellStyle(style);
|
||||
|
||||
cell = row.createCell(1);
|
||||
cell.setCellValue(30);
|
||||
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();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
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));
|
||||
|
||||
assertEquals("Ana Johnson", data.get(3)
|
||||
.get(0));
|
||||
assertEquals("30", data.get(3)
|
||||
.get(1));
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
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));
|
||||
|
||||
assertEquals("Ana Johnson", data.get(2)
|
||||
.get(0));
|
||||
assertEquals("30", data.get(2)
|
||||
.get(1));
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -3,6 +3,7 @@ package com.baeldung.algorithms;
|
|||
import java.util.Scanner;
|
||||
|
||||
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
|
||||
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
|
||||
import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||
|
||||
public class RunAlgorithm {
|
||||
|
@ -12,6 +13,7 @@ public class RunAlgorithm {
|
|||
System.out.println("Run algorithm:");
|
||||
System.out.println("1 - Simulated Annealing");
|
||||
System.out.println("2 - Slope One");
|
||||
System.out.println("3 - Simple Genetic Algorithm");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
|
@ -20,6 +22,9 @@ public class RunAlgorithm {
|
|||
case 2:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
case 3:
|
||||
SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
|
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.algorithms.ga.binary;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class Individual {
|
||||
|
||||
protected int defaultGeneLength = 64;
|
||||
private byte[] genes = new byte[defaultGeneLength];
|
||||
private int fitness = 0;
|
||||
|
||||
public Individual() {
|
||||
for (int i = 0; i < genes.length; i++) {
|
||||
byte gene = (byte) Math.round(Math.random());
|
||||
genes[i] = gene;
|
||||
}
|
||||
}
|
||||
|
||||
protected byte getSingleGene(int index) {
|
||||
return genes[index];
|
||||
}
|
||||
|
||||
protected void setSingleGene(int index, byte value) {
|
||||
genes[index] = value;
|
||||
fitness = 0;
|
||||
}
|
||||
|
||||
public int getFitness() {
|
||||
if (fitness == 0) {
|
||||
fitness = SimpleGeneticAlgorithm.getFitness(this);
|
||||
}
|
||||
return fitness;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
String geneString = "";
|
||||
for (int i = 0; i < genes.length; i++) {
|
||||
geneString += getSingleGene(i);
|
||||
}
|
||||
return geneString;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.algorithms.ga.binary;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class Population {
|
||||
|
||||
private List<Individual> individuals;
|
||||
|
||||
public Population(int size, boolean createNew) {
|
||||
individuals = new ArrayList<>();
|
||||
if (createNew) {
|
||||
createNewPopulation(size);
|
||||
}
|
||||
}
|
||||
|
||||
protected Individual getIndividual(int index) {
|
||||
return individuals.get(index);
|
||||
}
|
||||
|
||||
protected Individual getFittest() {
|
||||
Individual fittest = individuals.get(0);
|
||||
for (int i = 0; i < individuals.size(); i++) {
|
||||
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
|
||||
fittest = getIndividual(i);
|
||||
}
|
||||
}
|
||||
return fittest;
|
||||
}
|
||||
|
||||
private void createNewPopulation(int size) {
|
||||
for (int i = 0; i < size; i++) {
|
||||
Individual newIndividual = new Individual();
|
||||
individuals.add(i, newIndividual);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,117 @@
|
|||
package com.baeldung.algorithms.ga.binary;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class SimpleGeneticAlgorithm {
|
||||
|
||||
private static final double uniformRate = 0.5;
|
||||
private static final double mutationRate = 0.025;
|
||||
private static final int tournamentSize = 5;
|
||||
private static final boolean elitism = true;
|
||||
private static byte[] solution = new byte[64];
|
||||
|
||||
public static boolean runAlgorithm(int populationSize, String solution) {
|
||||
if (solution.length() != SimpleGeneticAlgorithm.solution.length) {
|
||||
throw new RuntimeException("The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes");
|
||||
}
|
||||
SimpleGeneticAlgorithm.setSolution(solution);
|
||||
Population myPop = new Population(populationSize, true);
|
||||
|
||||
int generationCount = 1;
|
||||
while (myPop.getFittest().getFitness() < SimpleGeneticAlgorithm.getMaxFitness()) {
|
||||
System.out.println("Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness());
|
||||
myPop = SimpleGeneticAlgorithm.evolvePopulation(myPop);
|
||||
generationCount++;
|
||||
}
|
||||
System.out.println("Solution found!");
|
||||
System.out.println("Generation: " + generationCount);
|
||||
System.out.println("Genes: ");
|
||||
System.out.println(myPop.getFittest());
|
||||
return true;
|
||||
}
|
||||
|
||||
public static Population evolvePopulation(Population pop) {
|
||||
int elitismOffset;
|
||||
Population newPopulation = new Population(pop.getIndividuals().size(), false);
|
||||
|
||||
if (elitism) {
|
||||
newPopulation.getIndividuals().add(0, pop.getFittest());
|
||||
elitismOffset = 1;
|
||||
} else {
|
||||
elitismOffset = 0;
|
||||
}
|
||||
|
||||
for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) {
|
||||
Individual indiv1 = tournamentSelection(pop);
|
||||
Individual indiv2 = tournamentSelection(pop);
|
||||
Individual newIndiv = crossover(indiv1, indiv2);
|
||||
newPopulation.getIndividuals().add(i, newIndiv);
|
||||
}
|
||||
|
||||
for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) {
|
||||
mutate(newPopulation.getIndividual(i));
|
||||
}
|
||||
|
||||
return newPopulation;
|
||||
}
|
||||
|
||||
private static Individual crossover(Individual indiv1, Individual indiv2) {
|
||||
Individual newSol = new Individual();
|
||||
for (int i = 0; i < newSol.getDefaultGeneLength(); i++) {
|
||||
if (Math.random() <= uniformRate) {
|
||||
newSol.setSingleGene(i, indiv1.getSingleGene(i));
|
||||
} else {
|
||||
newSol.setSingleGene(i, indiv2.getSingleGene(i));
|
||||
}
|
||||
}
|
||||
return newSol;
|
||||
}
|
||||
|
||||
private static void mutate(Individual indiv) {
|
||||
for (int i = 0; i < indiv.getDefaultGeneLength(); i++) {
|
||||
if (Math.random() <= mutationRate) {
|
||||
byte gene = (byte) Math.round(Math.random());
|
||||
indiv.setSingleGene(i, gene);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Individual tournamentSelection(Population pop) {
|
||||
Population tournament = new Population(tournamentSize, false);
|
||||
for (int i = 0; i < tournamentSize; i++) {
|
||||
int randomId = (int) (Math.random() * pop.getIndividuals().size());
|
||||
tournament.getIndividuals().add(i, pop.getIndividual(randomId));
|
||||
}
|
||||
Individual fittest = tournament.getFittest();
|
||||
return fittest;
|
||||
}
|
||||
|
||||
protected static int getFitness(Individual individual) {
|
||||
int fitness = 0;
|
||||
for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) {
|
||||
if (individual.getSingleGene(i) == solution[i]) {
|
||||
fitness++;
|
||||
}
|
||||
}
|
||||
return fitness;
|
||||
}
|
||||
|
||||
protected static int getMaxFitness() {
|
||||
int maxFitness = solution.length;
|
||||
return maxFitness;
|
||||
}
|
||||
|
||||
protected static void setSolution(String newSolution) {
|
||||
solution = new byte[newSolution.length()];
|
||||
for (int i = 0; i < newSolution.length(); i++) {
|
||||
String character = newSolution.substring(i, i + 1);
|
||||
if (character.contains("0") || character.contains("1")) {
|
||||
solution[i] = Byte.parseByte(character);
|
||||
} else {
|
||||
solution[i] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -15,6 +15,6 @@ public class SquareCalculator {
|
|||
return executor.submit(() -> {
|
||||
Thread.sleep(1000);
|
||||
return input * input;
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,55 +8,55 @@ public class CharArrayToStringUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenCharArray_whenCallingStringConstructor_shouldConvertToString() {
|
||||
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
|
||||
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
|
||||
String result = new String(charArray);
|
||||
String expectedValue = "character";
|
||||
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString(){
|
||||
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
|
||||
public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString() {
|
||||
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
|
||||
String result = new String(charArray, 4, 3);
|
||||
String expectedValue = "act";
|
||||
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString(){
|
||||
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
|
||||
public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString() {
|
||||
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
|
||||
String result = String.copyValueOf(charArray);
|
||||
String expectedValue = "character";
|
||||
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString(){
|
||||
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
|
||||
public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString() {
|
||||
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
|
||||
String result = String.copyValueOf(charArray, 0, 4);
|
||||
String expectedValue = "char";
|
||||
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenCallingStringValueOf_shouldConvertToString(){
|
||||
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
|
||||
public void givenCharArray_whenCallingStringValueOf_shouldConvertToString() {
|
||||
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
|
||||
String result = String.valueOf(charArray);
|
||||
String expectedValue = "character";
|
||||
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString(){
|
||||
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
|
||||
public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString() {
|
||||
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
|
||||
String result = String.valueOf(charArray, 3, 4);
|
||||
String expectedValue = "ract";
|
||||
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,15 +6,15 @@ import org.junit.Test;
|
|||
|
||||
public class StringToCharArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() {
|
||||
String givenString = "characters";
|
||||
@Test
|
||||
public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() {
|
||||
String givenString = "characters";
|
||||
|
||||
char[] result = givenString.toCharArray();
|
||||
char[] result = givenString.toCharArray();
|
||||
|
||||
char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' };
|
||||
char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' };
|
||||
|
||||
assertArrayEquals(expectedCharArray, result);
|
||||
}
|
||||
assertArrayEquals(expectedCharArray, result);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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"));
|
||||
}
|
||||
|
||||
}
|
|
@ -32,13 +32,14 @@ public class PriorityBlockingQueueUnitTest {
|
|||
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
|
||||
|
||||
final Thread thread = new Thread(() -> {
|
||||
System.out.println("Polling...");
|
||||
while (true) {
|
||||
try {
|
||||
Integer poll = queue.take();
|
||||
System.out.println("Polled: " + poll);
|
||||
} catch (InterruptedException e) {}
|
||||
}
|
||||
System.out.println("Polling...");
|
||||
while (true) {
|
||||
try {
|
||||
Integer poll = queue.take();
|
||||
System.out.println("Polled: " + poll);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
|
||||
|
|
|
@ -18,9 +18,7 @@ public class ConcurrentNavigableMapTests {
|
|||
|
||||
updateMapConcurrently(skipListMap, 4);
|
||||
|
||||
Iterator<Integer> skipListIter = skipListMap
|
||||
.keySet()
|
||||
.iterator();
|
||||
Iterator<Integer> skipListIter = skipListMap.keySet().iterator();
|
||||
int previous = skipListIter.next();
|
||||
while (skipListIter.hasNext()) {
|
||||
int current = skipListIter.next();
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
package org.baeldung.java;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Random;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.apache.commons.math3.random.RandomDataGenerator;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Random;
|
||||
|
||||
public class JavaRandomUnitTest {
|
||||
|
||||
// tests - random long
|
||||
|
@ -164,7 +164,7 @@ public class JavaRandomUnitTest {
|
|||
final int targetStringLength = 10;
|
||||
final StringBuilder buffer = new StringBuilder(targetStringLength);
|
||||
for (int i = 0; i < targetStringLength; i++) {
|
||||
final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit));
|
||||
final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit + 1));
|
||||
buffer.append((char) randomLimitedInt);
|
||||
}
|
||||
final String generatedString = buffer.toString();
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
package org.baeldung.java.streams;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
@ -14,28 +14,25 @@ import static org.junit.Assert.assertEquals;
|
|||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ThreadPoolInParallelStreamTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal()
|
||||
throws InterruptedException, ExecutionException {
|
||||
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {
|
||||
long firstNum = 1;
|
||||
long lastNum = 1_000_000;
|
||||
|
||||
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed()
|
||||
.collect(Collectors.toList());
|
||||
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
|
||||
|
||||
ForkJoinPool customThreadPool = new ForkJoinPool(4);
|
||||
long actualTotal = customThreadPool.submit(() -> aList.parallelStream()
|
||||
.reduce(0L, Long::sum)).get();
|
||||
|
||||
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
|
||||
long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
|
||||
|
||||
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenList_whenCallingParallelStream_shouldBeParallelStream(){
|
||||
public void givenList_whenCallingParallelStream_shouldBeParallelStream() {
|
||||
List<Long> aList = new ArrayList<>();
|
||||
Stream<Long> parallelStream = aList.parallelStream();
|
||||
|
||||
|
||||
assertTrue(parallelStream.isParallel());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,9 +2,9 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>logmdc</artifactId>
|
||||
<artifactId>log-mdc</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>logmdc</name>
|
||||
<name>log-mdc</name>
|
||||
<packaging>war</packaging>
|
||||
<description>tutorial on logging with MDC and NDC</description>
|
||||
|
||||
|
|
1
pom.xml
1
pom.xml
|
@ -147,6 +147,7 @@
|
|||
<module>spring-rest-docs</module>
|
||||
<module>spring-rest</module>
|
||||
<module>spring-security-basic-auth</module>
|
||||
<module>spring-security-cache-control</module>
|
||||
<module>spring-security-client/spring-security-jsp-authentication</module>
|
||||
<module>spring-security-client/spring-security-jsp-authorize</module>
|
||||
<module>spring-security-client/spring-security-jsp-config</module>
|
||||
|
|
|
@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
|||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { ExternalPropertiesWithXmlConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
@Ignore("manual only")
|
||||
public class ExternalPropertiesWithXmlIntegrationTest {
|
||||
public class ExternalPropertiesWithXmlManualTest {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
|
@ -12,7 +12,7 @@ import java.sql.SQLException;
|
|||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
|
||||
public class SpringRetryTest {
|
||||
public class SpringRetryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private MyService myService;
|
|
@ -8,7 +8,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
|||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { ThreadPoolTaskSchedulerConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class ThreadPoolTaskSchedulerTest {
|
||||
public class ThreadPoolTaskSchedulerIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void testThreadPoolTaskSchedulerAnnotation() throws InterruptedException {
|
||||
Thread.sleep(2550);
|
|
@ -5,7 +5,7 @@ import org.baeldung.properties.basic.PropertiesWithMultipleXmlsIntegrationTest;
|
|||
import org.baeldung.properties.basic.PropertiesWithXmlIntegrationTest;
|
||||
import org.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest;
|
||||
import org.baeldung.properties.external.ExternalPropertiesWithMultipleXmlsIntegrationTest;
|
||||
import org.baeldung.properties.external.ExternalPropertiesWithXmlIntegrationTest;
|
||||
import org.baeldung.properties.external.ExternalPropertiesWithXmlManualTest;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Suite;
|
||||
import org.junit.runners.Suite.SuiteClasses;
|
||||
|
@ -15,7 +15,7 @@ import org.junit.runners.Suite.SuiteClasses;
|
|||
PropertiesWithXmlIntegrationTest.class,
|
||||
ExternalPropertiesWithJavaIntegrationTest.class,
|
||||
ExternalPropertiesWithMultipleXmlsIntegrationTest.class,
|
||||
ExternalPropertiesWithXmlIntegrationTest.class,
|
||||
ExternalPropertiesWithXmlManualTest.class,
|
||||
ExtendedPropertiesWithJavaIntegrationTest.class,
|
||||
PropertiesWithMultipleXmlsIntegrationTest.class,
|
||||
})// @formatter:on
|
||||
|
|
|
@ -1,39 +1,39 @@
|
|||
package com.baeldung.intro;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
public class AppTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mvc;
|
||||
|
||||
@Test
|
||||
public void getIndex() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(equalTo("Index Page")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getLocal() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(equalTo("/local")));
|
||||
}
|
||||
|
||||
package com.baeldung.intro;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
public class AppLiveTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mvc;
|
||||
|
||||
@Test
|
||||
public void getIndex() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(equalTo("Index Page")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getLocal() throws Exception {
|
||||
mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(equalTo("/local")));
|
||||
}
|
||||
|
||||
}
|
|
@ -3,4 +3,4 @@
|
|||
- [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory)
|
||||
- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)
|
||||
- [Constructor Dependency Injection in Spring](http://www.baeldung.com/constructor-injection-in-spring)
|
||||
- [Constructor Injection in Spring with Lombok](http://inprogress.baeldung.com/constructor-injection-in-spring-with-lombok)
|
||||
- [Constructor Injection in Spring with Lombok](http://www.baeldung.com/spring-injection-lombok)
|
||||
|
|
|
@ -10,4 +10,5 @@
|
|||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
*.ear
|
||||
/target/
|
||||
|
|
|
@ -1,4 +1,3 @@
|
|||
|
||||
package com.baeldung.hibernate.oneToMany.main;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
@ -13,85 +12,86 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
|||
import org.hibernate.cfg.Configuration;
|
||||
import org.hibernate.dialect.HSQLDialect;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.hibernate.oneToMany.model.Cart;
|
||||
import com.baeldung.hibernate.oneToMany.model.Items;
|
||||
|
||||
//@RunWith(SpringJUnit4ClassRunner.class)
|
||||
public class HibernateOneToManyAnnotationMainTest {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
private Session session;
|
||||
private Session session;
|
||||
|
||||
public HibernateOneToManyAnnotationMainTest() {
|
||||
}
|
||||
public HibernateOneToManyAnnotationMainTest() {
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeTests() {
|
||||
Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class).setProperty("hibernate.dialect", HSQLDialect.class.getName())
|
||||
.setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()).setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa")
|
||||
.setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update");
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
|
||||
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||
}
|
||||
@BeforeClass
|
||||
public static void beforeTests() {
|
||||
Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class)
|
||||
.setProperty("hibernate.dialect", HSQLDialect.class.getName())
|
||||
.setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
|
||||
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test")
|
||||
.setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "")
|
||||
.setProperty("hibernate.hbm2ddl.auto", "update");
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
|
||||
.applySettings(configuration.getProperties()).build();
|
||||
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
@Before
|
||||
public void setUp() {
|
||||
session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
}
|
||||
|
||||
}
|
||||
@Test
|
||||
public void givenSession_checkIfDatabaseIsEmpty() {
|
||||
Cart cart = (Cart) session.get(Cart.class, new Long(1));
|
||||
assertNull(cart);
|
||||
|
||||
@Test
|
||||
public void givenSession_checkIfDatabaseIsEmpty() {
|
||||
Cart cart = (Cart) session.get(Cart.class, new Long(1));
|
||||
assertNull(cart);
|
||||
}
|
||||
|
||||
}
|
||||
@Test
|
||||
public void givenSession_checkIfDatabaseIsPopulated_afterCommit() {
|
||||
Cart cart = new Cart();
|
||||
Set<Items> cartItems = new HashSet<>();
|
||||
cartItems = cart.getItems();
|
||||
Assert.assertNull(cartItems);
|
||||
Items item1 = new Items();
|
||||
item1.setItemId("I10");
|
||||
item1.setItemTotal(10);
|
||||
item1.setQuantity(1);
|
||||
item1.setCart(cart);
|
||||
assertNotNull(item1);
|
||||
Set<Items> itemsSet = new HashSet<Items>();
|
||||
itemsSet.add(item1);
|
||||
assertNotNull(itemsSet);
|
||||
cart.setItems(itemsSet);
|
||||
assertNotNull(cart);
|
||||
session.persist(cart);
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
|
||||
@Test
|
||||
public void testAddItemsToCart() {
|
||||
Cart cart = new Cart();
|
||||
Set<Items> cartItems = new HashSet<>();
|
||||
cartItems = cart.getItems();
|
||||
Assert.assertNull(cartItems);
|
||||
Items item1 = new Items("I10", 10, 1, cart);
|
||||
assertNotNull(item1);
|
||||
Set<Items> itemsSet = new HashSet<Items>();
|
||||
cart.setItems(itemsSet);
|
||||
assertNotNull(cart);
|
||||
System.out.println("Items added to cart");
|
||||
session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
cart = (Cart) session.get(Cart.class, new Long(1));
|
||||
assertNotNull(cart);
|
||||
}
|
||||
|
||||
}
|
||||
@After
|
||||
public void tearDown() {
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSession_checkIfDatabaseIsPopulated_afterCommit() {
|
||||
Cart cart = new Cart();
|
||||
Set<Items> cartItems = new HashSet<>();
|
||||
cartItems = cart.getItems();
|
||||
Assert.assertNull(cartItems);
|
||||
Items item1 = new Items();
|
||||
item1.setItemId("I10");
|
||||
item1.setItemTotal(10);
|
||||
item1.setQuantity(1);
|
||||
item1.setCart(cart);
|
||||
assertNotNull(item1);
|
||||
Set<Items> itemsSet = new HashSet<Items>();
|
||||
itemsSet.add(item1);
|
||||
assertNotNull(itemsSet);
|
||||
cart.setItems(itemsSet);
|
||||
assertNotNull(cart);
|
||||
session.persist(cart);
|
||||
session.getTransaction().commit();
|
||||
cart = (Cart) session.get(Cart.class, new Long(1));
|
||||
assertNotNull(cart);
|
||||
session.close();
|
||||
|
||||
}
|
||||
@AfterClass
|
||||
public static void afterTests() {
|
||||
sessionFactory.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -6,9 +6,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.web.controller;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class RequestMappingShortcutsController {
|
||||
|
||||
@GetMapping("/get")
|
||||
public @ResponseBody ResponseEntity<String> get() {
|
||||
return new ResponseEntity<String>("GET Response", HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/get/{id}")
|
||||
public @ResponseBody ResponseEntity<String> getById(@PathVariable String id) {
|
||||
return new ResponseEntity<String>("GET Response : " + id, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PostMapping("/post")
|
||||
public @ResponseBody ResponseEntity<String> post() {
|
||||
return new ResponseEntity<String>("POST Response", HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PutMapping("/put")
|
||||
public @ResponseBody ResponseEntity<String> put() {
|
||||
return new ResponseEntity<String>("PUT Response", HttpStatus.OK);
|
||||
}
|
||||
|
||||
@DeleteMapping("/delete")
|
||||
public @ResponseBody ResponseEntity<String> delete() {
|
||||
return new ResponseEntity<String>("DELETE Response", HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PatchMapping("/patch")
|
||||
public @ResponseBody ResponseEntity<String> patch() {
|
||||
return new ResponseEntity<String>("PATCH Response", HttpStatus.OK);
|
||||
}
|
||||
|
||||
}
|
|
@ -22,7 +22,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
|||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = BeanNameUrlHandlerMappingConfig.class)
|
||||
public class BeanNameMappingConfigTest {
|
||||
public class BeanNameMappingConfigIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webAppContext;
|
|
@ -22,7 +22,7 @@ import com.baeldung.config.ControllerClassNameHandlerMappingConfig;
|
|||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = ControllerClassNameHandlerMappingConfig.class)
|
||||
public class ControllerClassNameHandlerMappingTest {
|
||||
public class ControllerClassNameHandlerMappingIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webAppContext;
|
|
@ -1,7 +1,10 @@
|
|||
package com.baeldung.handlermappings;
|
||||
|
||||
import com.baeldung.config.HandlerMappingDefaultConfig;
|
||||
import com.baeldung.config.HandlerMappingPrioritiesConfig;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
@ -14,15 +17,12 @@ import org.springframework.test.web.servlet.MockMvc;
|
|||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
|
||||
import com.baeldung.config.HandlerMappingDefaultConfig;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = HandlerMappingDefaultConfig.class)
|
||||
public class HandlerMappingDefaultConfigTest {
|
||||
public class HandlerMappingDefaultConfigIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webAppContext;
|
|
@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
|||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = HandlerMappingPrioritiesConfig.class)
|
||||
public class HandlerMappingPriorityConfigTest {
|
||||
public class HandlerMappingPriorityConfigIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webAppContext;
|
|
@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
|||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = SimpleUrlHandlerMappingConfig.class)
|
||||
public class SimpleUrlMappingConfigTest {
|
||||
public class SimpleUrlMappingConfigIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webAppContext;
|
|
@ -0,0 +1,92 @@
|
|||
package com.baeldung.web.controller;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.ResultMatcher;
|
||||
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
|
||||
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import com.baeldung.spring.web.config.WebConfig;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = WebConfig.class)
|
||||
public class RequestMapingShortcutsUnitTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext ctx;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Before
|
||||
public void setup () {
|
||||
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.ctx);
|
||||
this.mockMvc = builder.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giventUrl_whenGetRequest_thenFindGetResponse() throws Exception {
|
||||
|
||||
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/get");
|
||||
|
||||
ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("GET Response");
|
||||
|
||||
this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giventUrl_whenPostRequest_thenFindPostResponse() throws Exception {
|
||||
|
||||
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/post");
|
||||
|
||||
ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("POST Response");
|
||||
|
||||
this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giventUrl_whenPutRequest_thenFindPutResponse() throws Exception {
|
||||
|
||||
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put("/put");
|
||||
|
||||
ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PUT Response");
|
||||
|
||||
this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giventUrl_whenDeleteRequest_thenFindDeleteResponse() throws Exception {
|
||||
|
||||
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.delete("/delete");
|
||||
|
||||
ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("DELETE Response");
|
||||
|
||||
this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giventUrl_whenPatchRequest_thenFindPatchResponse() throws Exception {
|
||||
|
||||
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.patch("/patch");
|
||||
|
||||
ResultMatcher contentMatcher = MockMvcResultMatchers.content().string("PATCH Response");
|
||||
|
||||
this.mockMvc.perform(builder).andExpect(contentMatcher).andExpect(MockMvcResultMatchers.status().isOk());
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,88 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-security-cache-control</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.4.3.RELEASE</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax.servlet-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.jayway.restassured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.cachecontrol;
|
||||
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class AppRunner {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(AppRunner.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.cachecontrol;
|
||||
|
||||
|
||||
import com.baeldung.cachecontrol.model.TimestampDto;
|
||||
import com.baeldung.cachecontrol.model.UserDto;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Controller
|
||||
public class ResourceEndpoint {
|
||||
|
||||
@RequestMapping(value = "/default/users/{name}", method = RequestMethod.GET)
|
||||
public ResponseEntity<UserDto> getUserWithDefaultCaching(@PathVariable(value = "name") String name) {
|
||||
return ResponseEntity.ok(new UserDto(name));
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/users/{name}", method = RequestMethod.GET)
|
||||
public ResponseEntity<UserDto> getUser(@PathVariable(value = "name") String name) {
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS))
|
||||
.body(new UserDto(name));
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/timestamp", method = RequestMethod.GET)
|
||||
public ResponseEntity<TimestampDto> getServerTimestamp() {
|
||||
return ResponseEntity.ok()
|
||||
.cacheControl(CacheControl.noStore())
|
||||
.body(new TimestampDto(LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli()));
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/private/users/{name}", method = RequestMethod.GET)
|
||||
public ResponseEntity<UserDto> getUserNotCached(@PathVariable("name") String name) {
|
||||
return ResponseEntity.ok()
|
||||
.body(new UserDto(name));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.cachecontrol.config;
|
||||
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.cachecontrol.model;
|
||||
|
||||
|
||||
public class TimestampDto {
|
||||
public final Long timestamp;
|
||||
|
||||
public TimestampDto(Long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.cachecontrol.model;
|
||||
|
||||
|
||||
public class UserDto {
|
||||
public final String name;
|
||||
|
||||
public UserDto(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,72 @@
|
|||
package com.baeldung.cachecontrol;
|
||||
|
||||
import com.jayway.restassured.http.ContentType;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.context.embedded.LocalServerPort;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static com.jayway.restassured.RestAssured.given;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AppRunner.class)
|
||||
public class ResourceEndpointTest {
|
||||
|
||||
@LocalServerPort
|
||||
private int serverPort;
|
||||
|
||||
@Test
|
||||
public void whenGetRequestForUser_shouldRespondWithDefaultCacheHeaders() {
|
||||
given()
|
||||
.when()
|
||||
.get(getBaseUrl() + "/default/users/Michael")
|
||||
.then()
|
||||
.headers("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate")
|
||||
.header("Pragma", "no-cache");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestForUser_shouldRespondMaxAgeCacheControl() {
|
||||
given()
|
||||
.when()
|
||||
.get(getBaseUrl() + "/users/Michael")
|
||||
.then()
|
||||
.header("Cache-Control", "max-age=60");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServiceEndpoint_whenGetRequestForUser_shouldResponseWithCacheControlMaxAge() {
|
||||
given()
|
||||
.when()
|
||||
.get(getBaseUrl() + "/users/Michael")
|
||||
.then()
|
||||
.contentType(ContentType.JSON).and().statusCode(200).and()
|
||||
.header("Cache-Control", "max-age=60");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServiceEndpoint_whenGetRequestForNotCacheableContent_shouldResponseWithCacheControlNoCache() {
|
||||
given()
|
||||
.when()
|
||||
.get(getBaseUrl() + "/timestamp")
|
||||
.then()
|
||||
.contentType(ContentType.JSON).and().statusCode(200).and()
|
||||
.header("Cache-Control", "no-store");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServiceEndpoint_whenGetRequestForPrivateUser_shouldResponseWithSecurityDefaultCacheControl() {
|
||||
given()
|
||||
.when()
|
||||
.get(getBaseUrl() + "/private/users/Michael")
|
||||
.then()
|
||||
.contentType(ContentType.JSON).and().statusCode(200).and()
|
||||
.header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
|
||||
}
|
||||
|
||||
private String getBaseUrl() {
|
||||
return String.format("http://localhost:%d", serverPort);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue