Merge branch 'master' into sla-pr/1092-tim
This commit is contained in:
commit
c39a596981
|
@ -1,2 +1,3 @@
|
|||
### Relevant Articles:
|
||||
- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi)
|
||||
- [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel)
|
||||
|
|
|
@ -9,6 +9,7 @@
|
|||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<poi.version>3.15</poi.version>
|
||||
<jexcel.version>1.0.6</jexcel.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
|
@ -37,5 +38,10 @@
|
|||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jxls</groupId>
|
||||
<artifactId>jxls-jexcel</artifactId>
|
||||
<version>${jexcel.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
|
|
@ -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();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
Binary file not shown.
Binary file not shown.
|
@ -1,8 +1,10 @@
|
|||
package com.baeldung.thrift;
|
||||
|
||||
import org.apache.thrift.transport.TTransportException;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
public static void main(String[] args) throws TTransportException {
|
||||
CrossPlatformServiceServer server = new CrossPlatformServiceServer();
|
||||
server.start();
|
||||
}
|
||||
|
|
|
@ -6,25 +6,22 @@ import org.apache.thrift.server.TServer;
|
|||
import org.apache.thrift.server.TSimpleServer;
|
||||
import org.apache.thrift.transport.TServerSocket;
|
||||
import org.apache.thrift.transport.TServerTransport;
|
||||
import org.apache.thrift.transport.TTransportException;
|
||||
|
||||
public class CrossPlatformServiceServer {
|
||||
|
||||
private TServer server;
|
||||
|
||||
public void start() {
|
||||
try {
|
||||
TServerTransport serverTransport = new TServerSocket(9090);
|
||||
server = new TSimpleServer(new TServer.Args(serverTransport)
|
||||
.processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl())));
|
||||
public void start() throws TTransportException {
|
||||
TServerTransport serverTransport = new TServerSocket(9090);
|
||||
server = new TSimpleServer(new TServer.Args(serverTransport)
|
||||
.processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl())));
|
||||
|
||||
System.out.print("Starting the server... ");
|
||||
System.out.print("Starting the server... ");
|
||||
|
||||
server.serve();
|
||||
server.serve();
|
||||
|
||||
System.out.println("done.");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("done.");
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
package com.baeldung.thrift;
|
||||
|
||||
import org.apache.thrift.transport.TTransportException;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
|
@ -11,7 +12,13 @@ public class CrossPlatformServiceTest {
|
|||
|
||||
@Before
|
||||
public void setUp() {
|
||||
new Thread(() -> server.start()).start();
|
||||
new Thread(() -> {
|
||||
try {
|
||||
server.start();
|
||||
} catch (TTransportException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}).start();
|
||||
try {
|
||||
// wait for the server start up
|
||||
Thread.sleep(1000);
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java</artifactId>
|
||||
|
@ -10,6 +10,44 @@
|
|||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j.driver</groupId>
|
||||
<artifactId>neo4j-java-driver</artifactId>
|
||||
<version>1.1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j-jdbc-driver</artifactId>
|
||||
<version>3.0.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j-ogm-core</artifactId>
|
||||
<version>2.1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.neo4j</groupId>
|
||||
<artifactId>neo4j-ogm-embedded-driver</artifactId>
|
||||
<version>2.1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.inject</groupId>
|
||||
<artifactId>guice</artifactId>
|
||||
<version>4.1.0</version>
|
||||
<classifier>no_aop</classifier>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
|
@ -63,7 +101,6 @@
|
|||
<artifactId>grep4j</artifactId>
|
||||
<version>${grep4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- web -->
|
||||
|
||||
<!-- marshalling -->
|
||||
|
@ -154,6 +191,12 @@
|
|||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
|
@ -263,7 +306,8 @@
|
|||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
|
@ -371,6 +415,7 @@
|
|||
<mockito.version>1.10.19</mockito.version>
|
||||
<testng.version>6.10</testng.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
|
|
|
@ -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;
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.concurrent.priorityblockingqueue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.concurrent.PriorityBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.util.Lists.newArrayList;
|
||||
|
||||
public class PriorityBlockingQueueUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUnorderedValues_whenPolling_thenShouldOrderQueue() throws InterruptedException {
|
||||
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
|
||||
ArrayList<Integer> polledElements = new ArrayList<>();
|
||||
|
||||
queue.add(1);
|
||||
queue.add(5);
|
||||
queue.add(2);
|
||||
queue.add(3);
|
||||
queue.add(4);
|
||||
|
||||
queue.drainTo(polledElements);
|
||||
|
||||
assertThat(polledElements).containsExactly(1, 2, 3, 4, 5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPollingEmptyQueue_thenShouldBlockThread() throws InterruptedException {
|
||||
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
|
||||
|
||||
final Thread thread = new Thread(() -> {
|
||||
System.out.println("Polling...");
|
||||
while (true) {
|
||||
try {
|
||||
Integer poll = queue.take();
|
||||
System.out.println("Polled: " + poll);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
|
||||
Thread.sleep(TimeUnit.SECONDS.toMillis(5));
|
||||
System.out.println("Adding to queue");
|
||||
|
||||
queue.addAll(newArrayList(1, 5, 6, 1, 2, 6, 7));
|
||||
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -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.assertNotEquals;
|
||||
|
||||
public class ConcurrentMapAggregateStatusTest {
|
||||
public class ConcurrentMapAggregateStatusManualTest {
|
||||
|
||||
private ExecutorService executorService;
|
||||
private Map<String, Integer> concurrentMap;
|
|
@ -10,7 +10,7 @@ import java.util.concurrent.ConcurrentMap;
|
|||
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
public class ConcurrentMapNullKeyValueTest {
|
||||
public class ConcurrentMapNullKeyValueManualTest {
|
||||
|
||||
ConcurrentMap<String, Object> concurrentMap;
|
||||
|
|
@ -11,7 +11,7 @@ import java.util.concurrent.*;
|
|||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ConcurrentMapPerformanceTest {
|
||||
public class ConcurrentMapPerformanceManualTest {
|
||||
|
||||
@Test
|
||||
public void givenMaps_whenGetPut500KTimes_thenConcurrentMapFaster() throws Exception {
|
|
@ -10,7 +10,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
|||
|
||||
import static org.testng.Assert.*;
|
||||
|
||||
public class ConcurrentNavigableMapTests {
|
||||
public class ConcurrentNavigableMapManualTests {
|
||||
|
||||
@Test
|
||||
public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throws InterruptedException {
|
||||
|
@ -18,9 +18,7 @@ public class ConcurrentNavigableMapTests {
|
|||
|
||||
updateMapConcurrently(skipListMap, 4);
|
||||
|
||||
Iterator<Integer> skipListIter = skipListMap
|
||||
.keySet()
|
||||
.iterator();
|
||||
Iterator<Integer> skipListIter = skipListMap.keySet().iterator();
|
||||
int previous = skipListIter.next();
|
||||
while (skipListIter.hasNext()) {
|
||||
int current = skipListIter.next();
|
|
@ -10,7 +10,7 @@ import java.util.concurrent.TimeUnit;
|
|||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ConcurretMapMemoryConsistencyTest {
|
||||
public class ConcurretMapMemoryConsistencyManualTest {
|
||||
|
||||
@Test
|
||||
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
|
|
@ -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,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;
|
||||
|
||||
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;
|
||||
|
@ -13,29 +13,26 @@ import java.util.stream.Stream;
|
|||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ThreadPoolInParallelStream {
|
||||
|
||||
public class ThreadPoolInParallelStreamTest {
|
||||
|
||||
@Test
|
||||
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal()
|
||||
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());
|
||||
}
|
||||
}
|
|
@ -57,6 +57,32 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- logging -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
|
@ -112,6 +138,9 @@
|
|||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,6 +1,5 @@
|
|||
package org.baeldung.guava;
|
||||
|
||||
|
||||
public class CustomEvent {
|
||||
private String action;
|
||||
|
|
@ -6,17 +6,16 @@ class EventBusWrapper {
|
|||
|
||||
private static EventBus eventBus = new EventBus();
|
||||
|
||||
static void register(Object object){
|
||||
static void register(Object object) {
|
||||
eventBus.register(object);
|
||||
}
|
||||
|
||||
static void unregister(Object object){
|
||||
static void unregister(Object object) {
|
||||
eventBus.unregister(object);
|
||||
}
|
||||
|
||||
static void post(Object object){
|
||||
static void post(Object object) {
|
||||
eventBus.post(object);
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
public void setUp() {
|
||||
listener = new EventListener();
|
||||
EventBusWrapper.register(listener);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
public void tearDown() {
|
||||
EventBusWrapper.unregister(listener);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringEvent_whenEventHandled_thenSuccess() throws Exception {
|
||||
public void givenStringEvent_whenEventHandled_thenSuccess() {
|
||||
listener.resetEventsHandled();
|
||||
|
||||
EventBusWrapper.post("String Event");
|
||||
|
@ -31,7 +31,7 @@ public class GuavaEventBusTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomEvent_whenEventHandled_thenSuccess() throws Exception {
|
||||
public void givenCustomEvent_whenEventHandled_thenSuccess() {
|
||||
listener.resetEventsHandled();
|
||||
|
||||
CustomEvent customEvent = new CustomEvent("Custom Event");
|
||||
|
|
|
@ -3,7 +3,7 @@ package org.baeldung.guava;
|
|||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import java.util.Arrays;
|
||||
import org.junit.Test;
|
||||
import static com.google.common.base.Preconditions.*;
|
||||
import com.google.common.base.*;
|
||||
|
||||
public class GuavaPreConditionsTest {
|
||||
|
||||
|
@ -11,10 +11,7 @@ public class GuavaPreConditionsTest {
|
|||
public void whenCheckArgumentEvaluatesFalse_throwsException() {
|
||||
int age = -18;
|
||||
|
||||
assertThatThrownBy(() -> checkArgument(age > 0))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage(null)
|
||||
.hasNoCause();
|
||||
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0)).isInstanceOf(IllegalArgumentException.class).hasMessage(null).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -22,10 +19,7 @@ public class GuavaPreConditionsTest {
|
|||
final int age = -18;
|
||||
final String message = "Age can't be zero or less than zero";
|
||||
|
||||
assertThatThrownBy(() -> checkArgument(age > 0, message))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage(message)
|
||||
.hasNoCause();
|
||||
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message)).isInstanceOf(IllegalArgumentException.class).hasMessage(message).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -33,19 +27,14 @@ public class GuavaPreConditionsTest {
|
|||
final int age = -18;
|
||||
final String message = "Age can't be zero or less than zero, you supplied %s.";
|
||||
|
||||
assertThatThrownBy(() -> checkArgument(age > 0, message, age))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage(message, age)
|
||||
.hasNoCause();
|
||||
assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message, age)).isInstanceOf(IllegalArgumentException.class).hasMessage(message, age).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfIntegers_whenCheckElementIndexEvaluatesFalse_throwsException() {
|
||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||
|
||||
assertThatThrownBy(() -> checkElementIndex(6, numbers.length - 1))
|
||||
.isInstanceOf(IndexOutOfBoundsException.class)
|
||||
.hasNoCause();
|
||||
assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -53,20 +42,7 @@ public class GuavaPreConditionsTest {
|
|||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||
final String message = "Please check the bound of an array and retry";
|
||||
|
||||
assertThatThrownBy(() -> checkElementIndex(6, numbers.length - 1, message))
|
||||
.isInstanceOf(IndexOutOfBoundsException.class)
|
||||
.hasMessageStartingWith(message)
|
||||
.hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullString_whenCheckNotNullCalled_throwsException() {
|
||||
final String nullObject = null;
|
||||
|
||||
assertThatThrownBy(() -> checkNotNull(nullObject))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessage(null)
|
||||
.hasNoCause();
|
||||
assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -74,10 +50,7 @@ public class GuavaPreConditionsTest {
|
|||
final String nullObject = null;
|
||||
final String message = "Please check the Object supplied, its null!";
|
||||
|
||||
assertThatThrownBy(() -> checkNotNull(nullObject, message))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessage(message)
|
||||
.hasNoCause();
|
||||
assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message)).isInstanceOf(NullPointerException.class).hasMessage(message).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -85,19 +58,14 @@ public class GuavaPreConditionsTest {
|
|||
final String nullObject = null;
|
||||
final String message = "Please check the Object supplied, its %s!";
|
||||
|
||||
assertThatThrownBy(() -> checkNotNull(nullObject, message, nullObject))
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessage(message, nullObject)
|
||||
.hasNoCause();
|
||||
assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message, new Object[] { null })).isInstanceOf(NullPointerException.class).hasMessage(message, nullObject).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfIntegers_whenCheckPositionIndexEvaluatesFalse_throwsException() {
|
||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||
|
||||
assertThatThrownBy(() -> checkPositionIndex(6, numbers.length - 1))
|
||||
.isInstanceOf(IndexOutOfBoundsException.class)
|
||||
.hasNoCause();
|
||||
assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -105,30 +73,14 @@ public class GuavaPreConditionsTest {
|
|||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||
final String message = "Please check the bound of an array and retry";
|
||||
|
||||
assertThatThrownBy(() -> checkPositionIndex(6, numbers.length - 1, message))
|
||||
.isInstanceOf(IndexOutOfBoundsException.class)
|
||||
.hasMessageStartingWith(message)
|
||||
.hasNoCause();
|
||||
assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayOfIntegers_whenCheckPositionIndexesEvaluatesFalse_throwsException() {
|
||||
final int[] numbers = { 1, 2, 3, 4, 5 };
|
||||
|
||||
assertThatThrownBy(() -> checkPositionIndexes(6, 0, numbers.length - 1))
|
||||
.isInstanceOf(IndexOutOfBoundsException.class)
|
||||
.hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidStates_whenCheckStateEvaluatesFalse_throwsException() {
|
||||
final int[] validStates = { -1, 0, 1 };
|
||||
final int givenState = 10;
|
||||
|
||||
assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessage(null)
|
||||
.hasNoCause();
|
||||
assertThatThrownBy(() -> Preconditions.checkPositionIndexes(6, 0, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -137,10 +89,7 @@ public class GuavaPreConditionsTest {
|
|||
final int givenState = 10;
|
||||
final String message = "You have entered an invalid state";
|
||||
|
||||
assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0, message))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageStartingWith(message)
|
||||
.hasNoCause();
|
||||
assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message)).isInstanceOf(IllegalStateException.class).hasMessageStartingWith(message).hasNoCause();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -149,9 +98,7 @@ public class GuavaPreConditionsTest {
|
|||
final int givenState = 10;
|
||||
final String message = "State can't be %s, It can be one of %s.";
|
||||
|
||||
assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates)))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessage(message, givenState, Arrays.toString(validStates))
|
||||
.hasNoCause();
|
||||
assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates))).isInstanceOf(IllegalStateException.class)
|
||||
.hasMessage(message, givenState, Arrays.toString(validStates)).hasNoCause();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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>
|
||||
|
||||
|
|
|
@ -138,15 +138,15 @@ public class MetricsTest {
|
|||
|
||||
long elapsed1 = context1.stop();
|
||||
|
||||
assertEquals(5000000000L, elapsed1, 10000000);
|
||||
assertEquals(5000000000L, elapsed1, 1000000000);
|
||||
assertThat(timer.getCount(), equalTo(1L));
|
||||
assertEquals(0.2, timer.getMeanRate(), 0.1);
|
||||
assertEquals(0.2, timer.getMeanRate(), 0.2);
|
||||
|
||||
Timer.Context context2 = timer.time();
|
||||
TimeUnit.SECONDS.sleep(2);
|
||||
context2.close();
|
||||
|
||||
assertThat(timer.getCount(), equalTo(2L));
|
||||
assertEquals(0.3, timer.getMeanRate(), 0.1);
|
||||
assertEquals(0.3, timer.getMeanRate(), 0.2);
|
||||
}
|
||||
}
|
||||
|
|
2
pom.xml
2
pom.xml
|
@ -94,6 +94,7 @@
|
|||
<module>rest-assured</module>
|
||||
<module>rest-testing</module>
|
||||
<module>resteasy</module>
|
||||
<module>rxjava</module>
|
||||
|
||||
<module>selenium-junit-testng</module>
|
||||
<module>solr-fulltext-search</module>
|
||||
|
@ -146,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>
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>rxjava</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.reactivex</groupId>
|
||||
<artifactId>rxjava</artifactId>
|
||||
<version>${rx.java.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<rx.java.version>1.2.5</rx.java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,43 @@
|
|||
package com.baelding.rxjava;
|
||||
|
||||
import rx.Observable;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ComputeFunction {
|
||||
public static void compute(Integer v) {
|
||||
try {
|
||||
System.out.println("compute integer v: " + v);
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void compute(List<Integer> v) {
|
||||
try {
|
||||
System.out.println("compute integer v: " + v);
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void compute(Observable<Integer> v) {
|
||||
try {
|
||||
v.forEach(System.out::println);
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void compute(Long v) {
|
||||
try {
|
||||
System.out.println("compute integer v: " + v);
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
|
|
|
@ -6,13 +6,13 @@ import org.springframework.stereotype.Component;
|
|||
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class Apologizer {
|
||||
public class ApologizeService {
|
||||
|
||||
private final Translator translator;
|
||||
private final String message;
|
||||
|
||||
@Autowired
|
||||
public Apologizer(Translator translator) {
|
||||
public ApologizeService(Translator translator) {
|
||||
this(translator, "sorry");
|
||||
}
|
||||
|
|
@ -4,11 +4,11 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class Fareweller {
|
||||
public class FarewellService {
|
||||
|
||||
private final Translator translator;
|
||||
|
||||
public Fareweller(Translator translator) {
|
||||
public FarewellService(Translator translator) {
|
||||
this.translator = translator;
|
||||
}
|
||||
|
|
@ -4,7 +4,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class Greeter {
|
||||
public class GreetingService {
|
||||
|
||||
@Autowired
|
||||
private Translator translator;
|
|
@ -1,12 +1,11 @@
|
|||
package com.baeldung.lombok;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class Thanker {
|
||||
public class ThankingService {
|
||||
|
||||
private final Translator translator;
|
||||
|
|
@ -14,12 +14,12 @@ import static org.mockito.Mockito.when;
|
|||
@ContextConfiguration(
|
||||
loader = AnnotationConfigContextLoader.class,
|
||||
classes = TestConfig.class)
|
||||
public class ApologizerAutowiringTest {
|
||||
public class ApologizeServiceAutowiringTest {
|
||||
|
||||
private final static String TRANSLATED = "TRANSLATED";
|
||||
|
||||
@Autowired
|
||||
private Apologizer apologizer;
|
||||
private ApologizeService apologizeService;
|
||||
|
||||
@Autowired
|
||||
private Translator translator;
|
||||
|
@ -27,7 +27,7 @@ public class ApologizerAutowiringTest {
|
|||
@Test
|
||||
public void apologizeWithTranslatedMessage() {
|
||||
when(translator.translate("sorry")).thenReturn(TRANSLATED);
|
||||
assertEquals(TRANSLATED, apologizer.apologize());
|
||||
assertEquals(TRANSLATED, apologizeService.apologize());
|
||||
}
|
||||
|
||||
}
|
|
@ -6,7 +6,7 @@ import static org.junit.Assert.assertEquals;
|
|||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class ApologizerTest {
|
||||
public class ApologizeServiceTest {
|
||||
|
||||
private final static String MESSAGE = "MESSAGE";
|
||||
private final static String TRANSLATED = "TRANSLATED";
|
||||
|
@ -14,8 +14,8 @@ public class ApologizerTest {
|
|||
@Test
|
||||
public void apologizeWithCustomTranslatedMessage() {
|
||||
Translator translator = mock(Translator.class);
|
||||
Apologizer apologizer = new Apologizer(translator, MESSAGE);
|
||||
ApologizeService apologizeService = new ApologizeService(translator, MESSAGE);
|
||||
when(translator.translate(MESSAGE)).thenReturn(TRANSLATED);
|
||||
assertEquals(TRANSLATED, apologizer.apologize());
|
||||
assertEquals(TRANSLATED, apologizeService.apologize());
|
||||
}
|
||||
}
|
|
@ -17,7 +17,7 @@ import static org.mockito.Mockito.when;
|
|||
public class FarewellAutowiringTest {
|
||||
|
||||
@Autowired
|
||||
private Fareweller fareweller;
|
||||
private FarewellService farewellService;
|
||||
|
||||
@Autowired
|
||||
private Translator translator;
|
||||
|
@ -26,6 +26,6 @@ public class FarewellAutowiringTest {
|
|||
public void sayByeWithTranslatedMessage() {
|
||||
String translated = "translated";
|
||||
when(translator.translate("bye")).thenReturn(translated);
|
||||
assertEquals(translated, fareweller.farewell());
|
||||
assertEquals(translated, farewellService.farewell());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,7 +6,7 @@ import static org.junit.Assert.*;
|
|||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class FarewellerTest {
|
||||
public class FarewellServiceTest {
|
||||
|
||||
private final static String TRANSLATED = "TRANSLATED";
|
||||
|
||||
|
@ -14,7 +14,7 @@ public class FarewellerTest {
|
|||
public void sayByeWithTranslatedMessage() {
|
||||
Translator translator = mock(Translator.class);
|
||||
when(translator.translate("bye")).thenReturn(TRANSLATED);
|
||||
Fareweller fareweller = new Fareweller(translator);
|
||||
assertEquals(TRANSLATED, fareweller.farewell());
|
||||
FarewellService farewellService = new FarewellService(translator);
|
||||
assertEquals(TRANSLATED, farewellService.farewell());
|
||||
}
|
||||
}
|
|
@ -14,10 +14,10 @@ import static org.mockito.Mockito.when;
|
|||
@ContextConfiguration(
|
||||
loader = AnnotationConfigContextLoader.class,
|
||||
classes = TestConfig.class)
|
||||
public class GreeterTest {
|
||||
public class GreetingServiceTest {
|
||||
|
||||
@Autowired
|
||||
private Greeter greeter;
|
||||
private GreetingService greetingService;
|
||||
|
||||
@Autowired
|
||||
private Translator translator;
|
||||
|
@ -26,12 +26,12 @@ public class GreeterTest {
|
|||
public void greetWithTranslatedMessage() {
|
||||
String translated = "translated";
|
||||
when(translator.translate("hello")).thenReturn(translated);
|
||||
assertEquals(translated, greeter.greet());
|
||||
assertEquals(translated, greetingService.greet());
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void throwWhenInstantiated() {
|
||||
Greeter greeter = new Greeter();
|
||||
greeter.greet();
|
||||
GreetingService greetingService = new GreetingService();
|
||||
greetingService.greet();
|
||||
}
|
||||
}
|
|
@ -14,10 +14,10 @@ import static org.mockito.Mockito.when;
|
|||
@ContextConfiguration(
|
||||
loader = AnnotationConfigContextLoader.class,
|
||||
classes = TestConfig.class)
|
||||
public class ThankerAutowiringTest {
|
||||
public class ThankingServiceAutowiringTest {
|
||||
|
||||
@Autowired
|
||||
private Thanker thanker;
|
||||
private ThankingService thankingService;
|
||||
|
||||
@Autowired
|
||||
private Translator translator;
|
||||
|
@ -26,6 +26,6 @@ public class ThankerAutowiringTest {
|
|||
public void thankWithTranslatedMessage() {
|
||||
String translated = "translated";
|
||||
when(translator.translate("thank you")).thenReturn(translated);
|
||||
assertEquals(translated, thanker.thank());
|
||||
assertEquals(translated, thankingService.thank());
|
||||
}
|
||||
}
|
|
@ -6,7 +6,7 @@ import static org.junit.Assert.*;
|
|||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class ThankerTest {
|
||||
public class ThankingServiceTest {
|
||||
|
||||
private final static String TRANSLATED = "TRANSLATED";
|
||||
|
||||
|
@ -14,7 +14,7 @@ public class ThankerTest {
|
|||
public void thankWithTranslatedMessage() {
|
||||
Translator translator = mock(Translator.class);
|
||||
when(translator.translate("thank you")).thenReturn(TRANSLATED);
|
||||
Thanker thanker = new Thanker(translator);
|
||||
assertEquals(TRANSLATED, thanker.thank());
|
||||
ThankingService thankingService = new ThankingService(translator);
|
||||
assertEquals(TRANSLATED, thankingService.thank());
|
||||
}
|
||||
}
|
|
@ -10,4 +10,5 @@
|
|||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
*.ear
|
||||
/target/
|
||||
|
|
|
@ -7,32 +7,31 @@ import org.hibernate.service.ServiceRegistry;
|
|||
|
||||
public class HibernateAnnotationUtil {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
private static SessionFactory buildSessionFactory() {
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
private static SessionFactory buildSessionFactory() {
|
||||
try {
|
||||
// Create the SessionFactory from hibernate-annotation.cfg.xml
|
||||
Configuration configuration = new Configuration();
|
||||
configuration.configure("hibernate-annotation.cfg.xml");
|
||||
System.out.println("Hibernate Annotation Configuration loaded");
|
||||
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
|
||||
System.out.println("Hibernate Annotation serviceRegistry created");
|
||||
|
||||
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||
|
||||
|
||||
Configuration configuration = new Configuration();
|
||||
configuration.configure("hibernate-annotation.cfg.xml");
|
||||
System.out.println("Hibernate Annotation Configuration loaded");
|
||||
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
|
||||
System.out.println("Hibernate Annotation serviceRegistry created");
|
||||
|
||||
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||
|
||||
return sessionFactory;
|
||||
}
|
||||
catch (Throwable ex) {
|
||||
} catch (Throwable ex) {
|
||||
System.err.println("Initial SessionFactory creation failed." + ex);
|
||||
ex.printStackTrace();
|
||||
throw new ExceptionInInitializerError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory() {
|
||||
if(sessionFactory == null) sessionFactory = buildSessionFactory();
|
||||
|
||||
public static SessionFactory getSessionFactory() {
|
||||
if (sessionFactory == null)
|
||||
sessionFactory = buildSessionFactory();
|
||||
return sessionFactory;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -13,48 +13,49 @@ import com.baeldung.hibernate.oneToMany.model.Items;
|
|||
|
||||
public class HibernateOneToManyAnnotationMain {
|
||||
|
||||
public static void main(String[] args) {
|
||||
public static void main(String[] args) {
|
||||
|
||||
Cart cart = new Cart();
|
||||
cart.setName("MyCart");
|
||||
|
||||
Items item1 = new Items("I10", 10, 1, cart);
|
||||
Items item2 = new Items("I20", 20, 2, cart);
|
||||
Set<Items> itemsSet = new HashSet<Items>();
|
||||
itemsSet.add(item1); itemsSet.add(item2);
|
||||
|
||||
cart.setItems(itemsSet);
|
||||
cart.setTotal(10*1 + 20*2);
|
||||
|
||||
SessionFactory sessionFactory = null;
|
||||
Session session = null;
|
||||
Transaction tx = null;
|
||||
try{
|
||||
//Get Session
|
||||
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
|
||||
session = sessionFactory.getCurrentSession();
|
||||
System.out.println("Session created");
|
||||
//start transaction
|
||||
tx = session.beginTransaction();
|
||||
//Save the Model object
|
||||
session.save(cart);
|
||||
session.save(item1);
|
||||
session.save(item2);
|
||||
//Commit transaction
|
||||
tx.commit();
|
||||
System.out.println("Cart ID="+cart.getId());
|
||||
System.out.println("item1 ID="+item1.getId()+", Foreign Key Cart ID="+item1.getCart().getId());
|
||||
System.out.println("item2 ID="+item2.getId()+", Foreign Key Cart ID="+item1.getCart().getId());
|
||||
|
||||
}catch(Exception e){
|
||||
System.out.println("Exception occured. "+e.getMessage());
|
||||
e.printStackTrace();
|
||||
}finally{
|
||||
if(!sessionFactory.isClosed()){
|
||||
System.out.println("Closing SessionFactory");
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
Cart cart = new Cart();
|
||||
cart.setName("MyCart");
|
||||
|
||||
Items item1 = new Items("I10", 10, 1, cart);
|
||||
Items item2 = new Items("I20", 20, 2, cart);
|
||||
Set<Items> itemsSet = new HashSet<Items>();
|
||||
itemsSet.add(item1);
|
||||
itemsSet.add(item2);
|
||||
|
||||
cart.setItems(itemsSet);
|
||||
cart.setTotal(10 * 1 + 20 * 2);
|
||||
|
||||
SessionFactory sessionFactory = null;
|
||||
Session session = null;
|
||||
Transaction tx = null;
|
||||
try {
|
||||
// Get Session
|
||||
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
|
||||
session = sessionFactory.getCurrentSession();
|
||||
System.out.println("Session created");
|
||||
// start transaction
|
||||
tx = session.beginTransaction();
|
||||
// Save the Model object
|
||||
session.save(cart);
|
||||
session.save(item1);
|
||||
session.save(item2);
|
||||
// Commit transaction
|
||||
tx.commit();
|
||||
System.out.println("Cart ID=" + cart.getId());
|
||||
System.out.println("item1 ID=" + item1.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId());
|
||||
System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId());
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Exception occured. " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (!sessionFactory.isClosed()) {
|
||||
System.out.println("Closing SessionFactory");
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -11,46 +11,53 @@ import javax.persistence.OneToMany;
|
|||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name="CART")
|
||||
@Table(name = "CART")
|
||||
public class Cart {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy=GenerationType.IDENTITY)
|
||||
@Column(name="cart_id")
|
||||
private long id;
|
||||
|
||||
@Column(name="total")
|
||||
private double total;
|
||||
|
||||
@Column(name="name")
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy="cart")
|
||||
private Set<Items> items;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
public double getTotal() {
|
||||
return total;
|
||||
}
|
||||
public void setTotal(double total) {
|
||||
this.total = total;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public Set<Items> getItems() {
|
||||
return items;
|
||||
}
|
||||
public void setItems(Set<Items> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "cart_id")
|
||||
private long id;
|
||||
|
||||
@Column(name = "total")
|
||||
private double total;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "cart")
|
||||
private Set<Items> items;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public double getTotal() {
|
||||
return total;
|
||||
}
|
||||
|
||||
public void setTotal(double total) {
|
||||
this.total = total;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<Items> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public void setItems(Set<Items> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -10,65 +10,76 @@ import javax.persistence.ManyToOne;
|
|||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name="ITEMS")
|
||||
@Table(name = "ITEMS")
|
||||
public class Items {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy=GenerationType.IDENTITY)
|
||||
@Column(name="id")
|
||||
private long id;
|
||||
|
||||
@Column(name="item_id")
|
||||
private String itemId;
|
||||
|
||||
@Column(name="item_total")
|
||||
private double itemTotal;
|
||||
|
||||
@Column(name="quantity")
|
||||
private int quantity;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name="cart_id", nullable=false)
|
||||
private Cart cart;
|
||||
|
||||
//Hibernate requires no-args constructor
|
||||
public Items(){}
|
||||
|
||||
public Items(String itemId, double total, int qty, Cart c){
|
||||
this.itemId=itemId;
|
||||
this.itemTotal=total;
|
||||
this.quantity=qty;
|
||||
this.cart=c;
|
||||
}
|
||||
public String getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
public void setItemId(String itemId) {
|
||||
this.itemId = itemId;
|
||||
}
|
||||
public double getItemTotal() {
|
||||
return itemTotal;
|
||||
}
|
||||
public void setItemTotal(double itemTotal) {
|
||||
this.itemTotal = itemTotal;
|
||||
}
|
||||
public int getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
public void setQuantity(int quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
public Cart getCart() {
|
||||
return cart;
|
||||
}
|
||||
public void setCart(Cart cart) {
|
||||
this.cart = cart;
|
||||
}
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private long id;
|
||||
|
||||
@Column(name = "item_id")
|
||||
private String itemId;
|
||||
|
||||
@Column(name = "item_total")
|
||||
private double itemTotal;
|
||||
|
||||
@Column(name = "quantity")
|
||||
private int quantity;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "cart_id", nullable = false)
|
||||
private Cart cart;
|
||||
|
||||
// Hibernate requires no-args constructor
|
||||
public Items() {
|
||||
}
|
||||
|
||||
public Items(String itemId, double total, int qty, Cart c) {
|
||||
this.itemId = itemId;
|
||||
this.itemTotal = total;
|
||||
this.quantity = qty;
|
||||
this.cart = c;
|
||||
}
|
||||
|
||||
public String getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
|
||||
public void setItemId(String itemId) {
|
||||
this.itemId = itemId;
|
||||
}
|
||||
|
||||
public double getItemTotal() {
|
||||
return itemTotal;
|
||||
}
|
||||
|
||||
public void setItemTotal(double itemTotal) {
|
||||
this.itemTotal = itemTotal;
|
||||
}
|
||||
|
||||
public int getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(int quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public Cart getCart() {
|
||||
return cart;
|
||||
}
|
||||
|
||||
public void setCart(Cart cart) {
|
||||
this.cart = cart;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,89 +1,97 @@
|
|||
|
||||
package com.baeldung.hibernate.oneToMany.main;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import com.baeldung.hibernate.oneToMany.model.Cart;
|
||||
import com.baeldung.hibernate.oneToMany.model.Items;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
import org.hibernate.dialect.HSQLDialect;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import com.baeldung.hibernate.oneToMany.model.Cart;
|
||||
import com.baeldung.hibernate.oneToMany.model.Items;
|
||||
|
||||
public class HibernateOneToManyAnnotationMainTest {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
private Session session;
|
||||
|
||||
public HibernateOneToManyAnnotationMainTest() {
|
||||
}
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeTests() {
|
||||
Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
|
||||
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update");
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
|
||||
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
private Session session;
|
||||
|
||||
public HibernateOneToManyAnnotationMainTest() {
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeTests() {
|
||||
Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class)
|
||||
.setProperty("hibernate.dialect", HSQLDialect.class.getName())
|
||||
.setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
|
||||
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test")
|
||||
.setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "")
|
||||
.setProperty("hibernate.hbm2ddl.auto", "update");
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
|
||||
.applySettings(configuration.getProperties()).build();
|
||||
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSession_checkIfDatabaseIsEmpty() {
|
||||
Cart cart = (Cart) session.get(Cart.class, new Long(1));
|
||||
assertNull(cart);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSession_checkIfDatabaseIsPopulated_afterCommit() {
|
||||
Cart cart = new Cart();
|
||||
Set<Items> cartItems = new HashSet<>();
|
||||
cartItems = cart.getItems();
|
||||
Assert.assertNull(cartItems);
|
||||
Items item1 = new Items();
|
||||
item1.setItemId("I10");
|
||||
item1.setItemTotal(10);
|
||||
item1.setQuantity(1);
|
||||
item1.setCart(cart);
|
||||
assertNotNull(item1);
|
||||
Set<Items> itemsSet = new HashSet<Items>();
|
||||
itemsSet.add(item1);
|
||||
assertNotNull(itemsSet);
|
||||
cart.setItems(itemsSet);
|
||||
assertNotNull(cart);
|
||||
session.persist(cart);
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
|
||||
session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
cart = (Cart) session.get(Cart.class, new Long(1));
|
||||
assertNotNull(cart);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void afterTests() {
|
||||
sessionFactory.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddItemsToCart() {
|
||||
Cart cart = new Cart();
|
||||
Set <Items> cartItems = new HashSet<>();
|
||||
cartItems = cart.getItems();
|
||||
Assert.assertNull(cartItems);
|
||||
Items item1 = new Items("I10", 10, 1, cart);
|
||||
assertNotNull(item1);
|
||||
Set<Items> itemsSet = new HashSet<Items>();
|
||||
cart.setItems(itemsSet);
|
||||
assertNotNull(cart);
|
||||
System.out.println("Items added to cart");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSaveCart(){
|
||||
Cart cart = new Cart();
|
||||
Set <Items> cartItems = new HashSet<>();
|
||||
cartItems = cart.getItems();
|
||||
Assert.assertNull(cartItems);
|
||||
Items item1 = new Items();
|
||||
item1.setItemId("I10");
|
||||
item1.setItemTotal(10);
|
||||
item1.setQuantity(1);
|
||||
item1.setCart(cart);
|
||||
assertNotNull(item1);
|
||||
Set<Items> itemsSet = new HashSet<Items>();
|
||||
itemsSet.add(item1);
|
||||
assertNotNull(itemsSet);
|
||||
cart.setItems(itemsSet);
|
||||
assertNotNull(cart);
|
||||
session.persist(cart);
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -9,7 +9,7 @@
|
|||
<packaging>war</packaging>
|
||||
|
||||
<properties>
|
||||
<jersey.version>2.25</jersey.version>
|
||||
<jersey.version>2.25.1</jersey.version>
|
||||
<jcl.slf4j.version>1.7.22</jcl.slf4j.version>
|
||||
<logback.version>1.1.8</logback.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
|
|
|
@ -18,7 +18,7 @@ public class RestClient {
|
|||
}
|
||||
|
||||
public Employee getJsonEmployee(int id) {
|
||||
return client.target(REST_URI).path(new Integer(id).toString()).request(MediaType.APPLICATION_JSON).get(Employee.class);
|
||||
return client.target(REST_URI).path(String.valueOf(id)).request(MediaType.APPLICATION_JSON).get(Employee.class);
|
||||
}
|
||||
|
||||
public Response createXmlEmployee(Employee emp) {
|
||||
|
@ -26,6 +26,6 @@ public class RestClient {
|
|||
}
|
||||
|
||||
public Employee getXmlEmployee(int id) {
|
||||
return client.target(REST_URI).path(new Integer(id).toString()).request(MediaType.APPLICATION_XML).get(Employee.class);
|
||||
return client.target(REST_URI).path(String.valueOf(id)).request(MediaType.APPLICATION_XML).get(Employee.class);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -46,6 +46,23 @@
|
|||
<artifactId>commons-fileupload</artifactId>
|
||||
<version>${fileupload.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-web</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-taglibs</artifactId>
|
||||
<version>${org.springframework.security.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
<profiles>
|
||||
<!-- Local -->
|
||||
|
@ -98,6 +115,7 @@
|
|||
<hibernate-validator.version>5.3.3.Final</hibernate-validator.version>
|
||||
<deploy-path>enter-location-of-server</deploy-path>
|
||||
<fileupload.version>1.3.2</fileupload.version>
|
||||
<org.springframework.security.version>4.2.1.RELEASE</org.springframework.security.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,122 @@
|
|||
package com.baeldung.springmvcforms.configuration;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.TestingAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
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;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
public UserDetailsService userDetailsService() throws Exception {
|
||||
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
|
||||
manager.createUser(User.withUsername("user")
|
||||
.password("userPass")
|
||||
.roles("USER")
|
||||
.build());
|
||||
manager.createUser(User.withUsername("admin")
|
||||
.password("adminPass")
|
||||
.roles("ADMIN")
|
||||
.build());
|
||||
return manager;
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@Order(1)
|
||||
public static class App1ConfigurationAdapter extends WebSecurityConfigurerAdapter {
|
||||
|
||||
public App1ConfigurationAdapter() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.inMemoryAuthentication()
|
||||
.withUser("admin")
|
||||
.password("admin")
|
||||
.roles("ADMIN");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.antMatcher("/admin*")
|
||||
.authorizeRequests()
|
||||
.anyRequest()
|
||||
.hasRole("ADMIN")
|
||||
// log in
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage("/loginAdmin")
|
||||
.loginProcessingUrl("/admin_login")
|
||||
.failureUrl("/loginAdmin?error=loginError")
|
||||
.defaultSuccessUrl("/adminPage")
|
||||
// logout
|
||||
.and()
|
||||
.logout()
|
||||
.logoutUrl("/admin_logout")
|
||||
.logoutSuccessUrl("/protectedLinks")
|
||||
.deleteCookies("JSESSIONID")
|
||||
.and()
|
||||
.exceptionHandling()
|
||||
.accessDeniedPage("/403")
|
||||
.and()
|
||||
.csrf()
|
||||
.disable();
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@Order(2)
|
||||
public static class App2ConfigurationAdapter extends WebSecurityConfigurerAdapter {
|
||||
|
||||
public App2ConfigurationAdapter() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.inMemoryAuthentication()
|
||||
.withUser("user")
|
||||
.password("user")
|
||||
.roles("USER");
|
||||
}
|
||||
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.antMatcher("/user*")
|
||||
.authorizeRequests()
|
||||
.anyRequest()
|
||||
.hasRole("USER")
|
||||
// log in
|
||||
.and()
|
||||
.formLogin()
|
||||
.loginPage("/loginUser")
|
||||
.loginProcessingUrl("/user_login")
|
||||
.failureUrl("/loginUser?error=loginError")
|
||||
.defaultSuccessUrl("/userPage")
|
||||
// logout
|
||||
.and()
|
||||
.logout()
|
||||
.logoutUrl("/user_logout")
|
||||
.logoutSuccessUrl("/protectedLinks")
|
||||
.deleteCookies("JSESSIONID")
|
||||
.and()
|
||||
.exceptionHandling()
|
||||
.accessDeniedPage("/403")
|
||||
.and()
|
||||
.csrf()
|
||||
.disable();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -3,6 +3,7 @@ package com.baeldung.springmvcforms.configuration;
|
|||
import org.springframework.web.WebApplicationInitializer;
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.filter.DelegatingFilterProxy;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
|
@ -24,6 +25,9 @@ public class WebInitializer implements WebApplicationInitializer {
|
|||
|
||||
servlet.setLoadOnStartup(1);
|
||||
servlet.addMapping("/");
|
||||
|
||||
container.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain"))
|
||||
.addMappingForUrlPatterns(null, false, "/*");
|
||||
}
|
||||
// @Override
|
||||
// public void onStartup(ServletContext container) {
|
||||
|
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.springmvcforms.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
public class UsersController {
|
||||
|
||||
@RequestMapping("/protectedLinks")
|
||||
public String getAnonymousPage() {
|
||||
return "protectedLinks";
|
||||
}
|
||||
|
||||
@RequestMapping("/userPage")
|
||||
public String getUserPage() {
|
||||
return "userPage";
|
||||
}
|
||||
|
||||
@RequestMapping("/adminPage")
|
||||
public String getAdminPage() {
|
||||
return "adminPage";
|
||||
}
|
||||
|
||||
@RequestMapping("/loginAdmin")
|
||||
public String getAdminLoginPage() {
|
||||
return "loginAdmin";
|
||||
}
|
||||
|
||||
@RequestMapping("/loginUser")
|
||||
public String getUserLoginPage() {
|
||||
return "loginUser";
|
||||
}
|
||||
|
||||
@RequestMapping("/403")
|
||||
public String getAccessDeniedPage() {
|
||||
return "403";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title></title>
|
||||
</head>
|
||||
<body>
|
||||
Your do not have permission to view this page.
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,16 @@
|
|||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Insert title here</title>
|
||||
</head>
|
||||
<body>
|
||||
Welcome admin! <a href="<c:url value='/admin_logout' /> " >Logout</a>
|
||||
|
||||
<br /><br />
|
||||
<a href="<c:url value='/protectedLinks' /> " >Back to links</a>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,38 @@
|
|||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Insert title here</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<p>Admin login page</p>
|
||||
<form name="f" action="admin_login" method="POST">
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td>User:</td>
|
||||
<td><input type="text" name="username" value=""></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Password:</td>
|
||||
<td><input type="password" name="password" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><input name="submit" type="submit" value="submit" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</form>
|
||||
|
||||
<%
|
||||
if (request.getParameter("error") != null) {
|
||||
out.println("Login failed!");
|
||||
}
|
||||
%>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,37 @@
|
|||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Login</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<p>User login page</p>
|
||||
|
||||
<form name="f" action="user_login" method="POST">
|
||||
<table>
|
||||
<tr>
|
||||
<td>User:</td>
|
||||
<td><input type="text" name="username" value=""></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Password:</td>
|
||||
<td><input type="password" name="password" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><input name="submit" type="submit" value="submit" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</form>
|
||||
<%
|
||||
if (request.getParameter("error") != null) {
|
||||
out.println("Login failed!");
|
||||
}
|
||||
%>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,16 @@
|
|||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Insert title here</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<a href="<c:url value="/userPage" />">User page</a>
|
||||
<br />
|
||||
<a href="<c:url value="/adminPage" />">Admin page</a>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,15 @@
|
|||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
|
||||
<title>Insert title here</title>
|
||||
</head>
|
||||
<body>
|
||||
Welcome user! <a href="<c:url value='/user_logout' /> " >Logout</a>
|
||||
<br /><br />
|
||||
<a href="<c:url value='/protectedLinks' /> " >Back to links</a>
|
||||
</body>
|
||||
</html>
|
|
@ -1,22 +1,24 @@
|
|||
package com.baeldung.excel;
|
||||
|
||||
import jxl.*;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.ArrayList;
|
||||
import jxl.Sheet;
|
||||
import jxl.Workbook;
|
||||
import jxl.format.Colour;
|
||||
import jxl.read.biff.BiffException;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import jxl.write.*;
|
||||
import jxl.write.Number;
|
||||
import jxl.format.Colour;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class JExcelHelper {
|
||||
|
||||
public Map<Integer, ArrayList<String>> readJExcel(String fileLocation) throws IOException, BiffException {
|
||||
Map<Integer, ArrayList<String>> data = new HashMap<Integer, ArrayList<String>>();
|
||||
Map<Integer, ArrayList<String>> data = new HashMap<>();
|
||||
|
||||
Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
|
||||
Sheet sheet = workbook.getSheet(0);
|
||||
|
@ -24,7 +26,7 @@ public class JExcelHelper {
|
|||
int columns = sheet.getColumns();
|
||||
|
||||
for (int i = 0; i < rows; i++) {
|
||||
data.put(i, new ArrayList<String>());
|
||||
data.put(i, new ArrayList<>());
|
||||
for (int j = 0; j < columns; j++) {
|
||||
data.get(i).add(sheet.getCell(j, i).getContents());
|
||||
}
|
||||
|
|
|
@ -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>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue