Merge branch 'master' into sla-pr/1092-tim

This commit is contained in:
slavisa-baeldung 2017-02-08 14:38:48 +01:00
commit c39a596981
109 changed files with 3082 additions and 535 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

BIN
apache-poi/temp.xls Normal file

Binary file not shown.

BIN
apache-poi/temp.xlsx Normal file

Binary file not shown.

View File

@ -1,8 +1,10 @@
package com.baeldung.thrift; package com.baeldung.thrift;
import org.apache.thrift.transport.TTransportException;
public class Application { public class Application {
public static void main(String[] args) { public static void main(String[] args) throws TTransportException {
CrossPlatformServiceServer server = new CrossPlatformServiceServer(); CrossPlatformServiceServer server = new CrossPlatformServiceServer();
server.start(); server.start();
} }

View File

@ -6,25 +6,22 @@ import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport; import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
public class CrossPlatformServiceServer { public class CrossPlatformServiceServer {
private TServer server; private TServer server;
public void start() { public void start() throws TTransportException {
try { TServerTransport serverTransport = new TServerSocket(9090);
TServerTransport serverTransport = new TServerSocket(9090); server = new TSimpleServer(new TServer.Args(serverTransport)
server = new TSimpleServer(new TServer.Args(serverTransport) .processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl())));
.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."); System.out.println("done.");
} catch (Exception e) {
e.printStackTrace();
}
} }
public void stop() { public void stop() {

View File

@ -1,5 +1,6 @@
package com.baeldung.thrift; package com.baeldung.thrift;
import org.apache.thrift.transport.TTransportException;
import org.junit.After; import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
@ -11,7 +12,13 @@ public class CrossPlatformServiceTest {
@Before @Before
public void setUp() { public void setUp() {
new Thread(() -> server.start()).start(); new Thread(() -> {
try {
server.start();
} catch (TTransportException e) {
e.printStackTrace();
}
}).start();
try { try {
// wait for the server start up // wait for the server start up
Thread.sleep(1000); Thread.sleep(1000);

View File

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

View File

@ -3,6 +3,7 @@ package com.baeldung.algorithms;
import java.util.Scanner; import java.util.Scanner;
import com.baeldung.algorithms.annealing.SimulatedAnnealing; import com.baeldung.algorithms.annealing.SimulatedAnnealing;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
import com.baeldung.algorithms.slope_one.SlopeOne; import com.baeldung.algorithms.slope_one.SlopeOne;
public class RunAlgorithm { public class RunAlgorithm {
@ -12,6 +13,7 @@ public class RunAlgorithm {
System.out.println("Run algorithm:"); System.out.println("Run algorithm:");
System.out.println("1 - Simulated Annealing"); System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One"); System.out.println("2 - Slope One");
System.out.println("3 - Simple Genetic Algorithm");
int decision = in.nextInt(); int decision = in.nextInt();
switch (decision) { switch (decision) {
case 1: case 1:
@ -20,6 +22,9 @@ public class RunAlgorithm {
case 2: case 2:
SlopeOne.slopeOne(3); SlopeOne.slopeOne(3);
break; break;
case 3:
SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
break;
default: default:
System.out.println("Unknown option"); System.out.println("Unknown option");
break; break;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -8,7 +8,7 @@ public class CharArrayToStringUnitTest {
@Test @Test
public void givenCharArray_whenCallingStringConstructor_shouldConvertToString() { 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 result = new String(charArray);
String expectedValue = "character"; String expectedValue = "character";
@ -16,8 +16,8 @@ public class CharArrayToStringUnitTest {
} }
@Test @Test
public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString(){ public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_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, 4, 3); String result = new String(charArray, 4, 3);
String expectedValue = "act"; String expectedValue = "act";
@ -25,8 +25,8 @@ public class CharArrayToStringUnitTest {
} }
@Test @Test
public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString(){ public void givenCharArray_whenCallingStringCopyValueOf_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 = String.copyValueOf(charArray); String result = String.copyValueOf(charArray);
String expectedValue = "character"; String expectedValue = "character";
@ -34,8 +34,8 @@ public class CharArrayToStringUnitTest {
} }
@Test @Test
public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString(){ public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_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 = String.copyValueOf(charArray, 0, 4); String result = String.copyValueOf(charArray, 0, 4);
String expectedValue = "char"; String expectedValue = "char";
@ -43,8 +43,8 @@ public class CharArrayToStringUnitTest {
} }
@Test @Test
public void givenCharArray_whenCallingStringValueOf_shouldConvertToString(){ public void givenCharArray_whenCallingStringValueOf_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 = String.valueOf(charArray); String result = String.valueOf(charArray);
String expectedValue = "character"; String expectedValue = "character";
@ -52,8 +52,8 @@ public class CharArrayToStringUnitTest {
} }
@Test @Test
public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString(){ public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_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 = String.valueOf(charArray, 3, 4); String result = String.valueOf(charArray, 3, 4);
String expectedValue = "ract"; String expectedValue = "ract";

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,9 +2,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>logmdc</artifactId> <artifactId>log-mdc</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>logmdc</name> <name>log-mdc</name>
<packaging>war</packaging> <packaging>war</packaging>
<description>tutorial on logging with MDC and NDC</description> <description>tutorial on logging with MDC and NDC</description>

View File

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

View File

@ -94,6 +94,7 @@
<module>rest-assured</module> <module>rest-assured</module>
<module>rest-testing</module> <module>rest-testing</module>
<module>resteasy</module> <module>resteasy</module>
<module>rxjava</module>
<module>selenium-junit-testng</module> <module>selenium-junit-testng</module>
<module>solr-fulltext-search</module> <module>solr-fulltext-search</module>
@ -146,6 +147,7 @@
<module>spring-rest-docs</module> <module>spring-rest-docs</module>
<module>spring-rest</module> <module>spring-rest</module>
<module>spring-security-basic-auth</module> <module>spring-security-basic-auth</module>
<module>spring-security-cache-control</module>
<module>spring-security-client/spring-security-jsp-authentication</module> <module>spring-security-client/spring-security-jsp-authentication</module>
<module>spring-security-client/spring-security-jsp-authorize</module> <module>spring-security-client/spring-security-jsp-authorize</module>
<module>spring-security-client/spring-security-jsp-config</module> <module>spring-security-client/spring-security-jsp-config</module>

41
rxjava/pom.xml Normal file
View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,9 +1,5 @@
package com.baeldung.intro; 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.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -14,10 +10,14 @@ import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
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) @RunWith(SpringRunner.class)
@SpringBootTest @SpringBootTest
@AutoConfigureMockMvc @AutoConfigureMockMvc
public class AppTest { public class AppLiveTest {
@Autowired @Autowired
private MockMvc mvc; private MockMvc mvc;

View File

@ -3,4 +3,4 @@
- [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory) - [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory)
- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) - [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 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)

View File

@ -6,13 +6,13 @@ import org.springframework.stereotype.Component;
@Component @Component
@AllArgsConstructor @AllArgsConstructor
public class Apologizer { public class ApologizeService {
private final Translator translator; private final Translator translator;
private final String message; private final String message;
@Autowired @Autowired
public Apologizer(Translator translator) { public ApologizeService(Translator translator) {
this(translator, "sorry"); this(translator, "sorry");
} }

View File

@ -4,11 +4,11 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
public class Fareweller { public class FarewellService {
private final Translator translator; private final Translator translator;
public Fareweller(Translator translator) { public FarewellService(Translator translator) {
this.translator = translator; this.translator = translator;
} }

View File

@ -4,7 +4,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
public class Greeter { public class GreetingService {
@Autowired @Autowired
private Translator translator; private Translator translator;

View File

@ -1,12 +1,11 @@
package com.baeldung.lombok; package com.baeldung.lombok;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
@AllArgsConstructor @AllArgsConstructor
public class Thanker { public class ThankingService {
private final Translator translator; private final Translator translator;

View File

@ -14,12 +14,12 @@ import static org.mockito.Mockito.when;
@ContextConfiguration( @ContextConfiguration(
loader = AnnotationConfigContextLoader.class, loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class) classes = TestConfig.class)
public class ApologizerAutowiringTest { public class ApologizeServiceAutowiringTest {
private final static String TRANSLATED = "TRANSLATED"; private final static String TRANSLATED = "TRANSLATED";
@Autowired @Autowired
private Apologizer apologizer; private ApologizeService apologizeService;
@Autowired @Autowired
private Translator translator; private Translator translator;
@ -27,7 +27,7 @@ public class ApologizerAutowiringTest {
@Test @Test
public void apologizeWithTranslatedMessage() { public void apologizeWithTranslatedMessage() {
when(translator.translate("sorry")).thenReturn(TRANSLATED); when(translator.translate("sorry")).thenReturn(TRANSLATED);
assertEquals(TRANSLATED, apologizer.apologize()); assertEquals(TRANSLATED, apologizeService.apologize());
} }
} }

View File

@ -6,7 +6,7 @@ import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class ApologizerTest { public class ApologizeServiceTest {
private final static String MESSAGE = "MESSAGE"; private final static String MESSAGE = "MESSAGE";
private final static String TRANSLATED = "TRANSLATED"; private final static String TRANSLATED = "TRANSLATED";
@ -14,8 +14,8 @@ public class ApologizerTest {
@Test @Test
public void apologizeWithCustomTranslatedMessage() { public void apologizeWithCustomTranslatedMessage() {
Translator translator = mock(Translator.class); Translator translator = mock(Translator.class);
Apologizer apologizer = new Apologizer(translator, MESSAGE); ApologizeService apologizeService = new ApologizeService(translator, MESSAGE);
when(translator.translate(MESSAGE)).thenReturn(TRANSLATED); when(translator.translate(MESSAGE)).thenReturn(TRANSLATED);
assertEquals(TRANSLATED, apologizer.apologize()); assertEquals(TRANSLATED, apologizeService.apologize());
} }
} }

View File

@ -17,7 +17,7 @@ import static org.mockito.Mockito.when;
public class FarewellAutowiringTest { public class FarewellAutowiringTest {
@Autowired @Autowired
private Fareweller fareweller; private FarewellService farewellService;
@Autowired @Autowired
private Translator translator; private Translator translator;
@ -26,6 +26,6 @@ public class FarewellAutowiringTest {
public void sayByeWithTranslatedMessage() { public void sayByeWithTranslatedMessage() {
String translated = "translated"; String translated = "translated";
when(translator.translate("bye")).thenReturn(translated); when(translator.translate("bye")).thenReturn(translated);
assertEquals(translated, fareweller.farewell()); assertEquals(translated, farewellService.farewell());
} }
} }

View File

@ -6,7 +6,7 @@ import static org.junit.Assert.*;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class FarewellerTest { public class FarewellServiceTest {
private final static String TRANSLATED = "TRANSLATED"; private final static String TRANSLATED = "TRANSLATED";
@ -14,7 +14,7 @@ public class FarewellerTest {
public void sayByeWithTranslatedMessage() { public void sayByeWithTranslatedMessage() {
Translator translator = mock(Translator.class); Translator translator = mock(Translator.class);
when(translator.translate("bye")).thenReturn(TRANSLATED); when(translator.translate("bye")).thenReturn(TRANSLATED);
Fareweller fareweller = new Fareweller(translator); FarewellService farewellService = new FarewellService(translator);
assertEquals(TRANSLATED, fareweller.farewell()); assertEquals(TRANSLATED, farewellService.farewell());
} }
} }

View File

@ -14,10 +14,10 @@ import static org.mockito.Mockito.when;
@ContextConfiguration( @ContextConfiguration(
loader = AnnotationConfigContextLoader.class, loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class) classes = TestConfig.class)
public class GreeterTest { public class GreetingServiceTest {
@Autowired @Autowired
private Greeter greeter; private GreetingService greetingService;
@Autowired @Autowired
private Translator translator; private Translator translator;
@ -26,12 +26,12 @@ public class GreeterTest {
public void greetWithTranslatedMessage() { public void greetWithTranslatedMessage() {
String translated = "translated"; String translated = "translated";
when(translator.translate("hello")).thenReturn(translated); when(translator.translate("hello")).thenReturn(translated);
assertEquals(translated, greeter.greet()); assertEquals(translated, greetingService.greet());
} }
@Test(expected = NullPointerException.class) @Test(expected = NullPointerException.class)
public void throwWhenInstantiated() { public void throwWhenInstantiated() {
Greeter greeter = new Greeter(); GreetingService greetingService = new GreetingService();
greeter.greet(); greetingService.greet();
} }
} }

View File

@ -14,10 +14,10 @@ import static org.mockito.Mockito.when;
@ContextConfiguration( @ContextConfiguration(
loader = AnnotationConfigContextLoader.class, loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class) classes = TestConfig.class)
public class ThankerAutowiringTest { public class ThankingServiceAutowiringTest {
@Autowired @Autowired
private Thanker thanker; private ThankingService thankingService;
@Autowired @Autowired
private Translator translator; private Translator translator;
@ -26,6 +26,6 @@ public class ThankerAutowiringTest {
public void thankWithTranslatedMessage() { public void thankWithTranslatedMessage() {
String translated = "translated"; String translated = "translated";
when(translator.translate("thank you")).thenReturn(translated); when(translator.translate("thank you")).thenReturn(translated);
assertEquals(translated, thanker.thank()); assertEquals(translated, thankingService.thank());
} }
} }

View File

@ -6,7 +6,7 @@ import static org.junit.Assert.*;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
public class ThankerTest { public class ThankingServiceTest {
private final static String TRANSLATED = "TRANSLATED"; private final static String TRANSLATED = "TRANSLATED";
@ -14,7 +14,7 @@ public class ThankerTest {
public void thankWithTranslatedMessage() { public void thankWithTranslatedMessage() {
Translator translator = mock(Translator.class); Translator translator = mock(Translator.class);
when(translator.translate("thank you")).thenReturn(TRANSLATED); when(translator.translate("thank you")).thenReturn(TRANSLATED);
Thanker thanker = new Thanker(translator); ThankingService thankingService = new ThankingService(translator);
assertEquals(TRANSLATED, thanker.thank()); assertEquals(TRANSLATED, thankingService.thank());
} }
} }

View File

@ -11,3 +11,4 @@
*.jar *.jar
*.war *.war
*.ear *.ear
/target/

View File

@ -7,32 +7,31 @@ import org.hibernate.service.ServiceRegistry;
public class HibernateAnnotationUtil { public class HibernateAnnotationUtil {
private static SessionFactory sessionFactory; private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() { private static SessionFactory buildSessionFactory() {
try { try {
// Create the SessionFactory from hibernate-annotation.cfg.xml // Create the SessionFactory from hibernate-annotation.cfg.xml
Configuration configuration = new Configuration(); Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml"); configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded"); System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created"); System.out.println("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory; return sessionFactory;
} } catch (Throwable ex) {
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex); System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace(); ex.printStackTrace();
throw new ExceptionInInitializerError(ex); throw new ExceptionInInitializerError(ex);
} }
} }
public static SessionFactory getSessionFactory() { public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory(); if (sessionFactory == null)
sessionFactory = buildSessionFactory();
return sessionFactory; return sessionFactory;
} }
} }

View File

@ -13,48 +13,49 @@ import com.baeldung.hibernate.oneToMany.model.Items;
public class HibernateOneToManyAnnotationMain { public class HibernateOneToManyAnnotationMain {
public static void main(String[] args) { public static void main(String[] args) {
Cart cart = new Cart(); Cart cart = new Cart();
cart.setName("MyCart"); cart.setName("MyCart");
Items item1 = new Items("I10", 10, 1, cart); Items item1 = new Items("I10", 10, 1, cart);
Items item2 = new Items("I20", 20, 2, cart); Items item2 = new Items("I20", 20, 2, cart);
Set<Items> itemsSet = new HashSet<Items>(); Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1); itemsSet.add(item2); itemsSet.add(item1);
itemsSet.add(item2);
cart.setItems(itemsSet); cart.setItems(itemsSet);
cart.setTotal(10*1 + 20*2); cart.setTotal(10 * 1 + 20 * 2);
SessionFactory sessionFactory = null; SessionFactory sessionFactory = null;
Session session = null; Session session = null;
Transaction tx = null; Transaction tx = null;
try{ try {
//Get Session // Get Session
sessionFactory = HibernateAnnotationUtil.getSessionFactory(); sessionFactory = HibernateAnnotationUtil.getSessionFactory();
session = sessionFactory.getCurrentSession(); session = sessionFactory.getCurrentSession();
System.out.println("Session created"); System.out.println("Session created");
//start transaction // start transaction
tx = session.beginTransaction(); tx = session.beginTransaction();
//Save the Model object // Save the Model object
session.save(cart); session.save(cart);
session.save(item1); session.save(item1);
session.save(item2); session.save(item2);
//Commit transaction // Commit transaction
tx.commit(); tx.commit();
System.out.println("Cart ID="+cart.getId()); System.out.println("Cart ID=" + cart.getId());
System.out.println("item1 ID="+item1.getId()+", Foreign Key Cart ID="+item1.getCart().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()); System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId());
}catch(Exception e){ } catch (Exception e) {
System.out.println("Exception occured. "+e.getMessage()); System.out.println("Exception occured. " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
}finally{ } finally {
if(!sessionFactory.isClosed()){ if (!sessionFactory.isClosed()) {
System.out.println("Closing SessionFactory"); System.out.println("Closing SessionFactory");
sessionFactory.close(); sessionFactory.close();
} }
} }
} }
} }

View File

@ -11,46 +11,53 @@ import javax.persistence.OneToMany;
import javax.persistence.Table; import javax.persistence.Table;
@Entity @Entity
@Table(name="CART") @Table(name = "CART")
public class Cart { public class Cart {
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="cart_id") @Column(name = "cart_id")
private long id; private long id;
@Column(name="total") @Column(name = "total")
private double total; private double total;
@Column(name="name") @Column(name = "name")
private String name; private String name;
@OneToMany(mappedBy="cart") @OneToMany(mappedBy = "cart")
private Set<Items> items; private Set<Items> items;
public long getId() { public long getId() {
return id; return id;
} }
public void setId(long id) {
this.id = id; public void setId(long id) {
} this.id = id;
public double getTotal() { }
return total;
} public double getTotal() {
public void setTotal(double total) { return total;
this.total = total; }
}
public String getName() { public void setTotal(double total) {
return name; this.total = total;
} }
public void setName(String name) {
this.name = name; public String getName() {
} return name;
public Set<Items> getItems() { }
return items;
} public void setName(String name) {
public void setItems(Set<Items> items) { this.name = name;
this.items = items; }
}
public Set<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
}
} }

View File

@ -10,65 +10,76 @@ import javax.persistence.ManyToOne;
import javax.persistence.Table; import javax.persistence.Table;
@Entity @Entity
@Table(name="ITEMS") @Table(name = "ITEMS")
public class Items { public class Items {
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id") @Column(name = "id")
private long id; private long id;
@Column(name="item_id") @Column(name = "item_id")
private String itemId; private String itemId;
@Column(name="item_total") @Column(name = "item_total")
private double itemTotal; private double itemTotal;
@Column(name="quantity") @Column(name = "quantity")
private int quantity; private int quantity;
@ManyToOne @ManyToOne
@JoinColumn(name="cart_id", nullable=false) @JoinColumn(name = "cart_id", nullable = false)
private Cart cart; private Cart cart;
//Hibernate requires no-args constructor // Hibernate requires no-args constructor
public Items(){} public Items() {
}
public Items(String itemId, double total, int qty, Cart c){ public Items(String itemId, double total, int qty, Cart c) {
this.itemId=itemId; this.itemId = itemId;
this.itemTotal=total; this.itemTotal = total;
this.quantity=qty; this.quantity = qty;
this.cart=c; this.cart = c;
} }
public String getItemId() {
return itemId; public String getItemId() {
} return itemId;
public void setItemId(String itemId) { }
this.itemId = itemId;
} public void setItemId(String itemId) {
public double getItemTotal() { this.itemId = itemId;
return itemTotal; }
}
public void setItemTotal(double itemTotal) { public double getItemTotal() {
this.itemTotal = itemTotal; return itemTotal;
} }
public int getQuantity() {
return quantity; public void setItemTotal(double itemTotal) {
} this.itemTotal = itemTotal;
public void setQuantity(int quantity) { }
this.quantity = quantity;
} public int getQuantity() {
public Cart getCart() { return quantity;
return cart; }
}
public void setCart(Cart cart) { public void setQuantity(int quantity) {
this.cart = cart; this.quantity = quantity;
} }
public long getId() {
return id; public Cart getCart() {
} return cart;
public void setId(long id) { }
this.id = id;
} public void setCart(Cart cart) {
this.cart = cart;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
} }

View File

@ -1,89 +1,97 @@
package com.baeldung.hibernate.oneToMany.main; 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.HashSet;
import java.util.Set; import java.util.Set;
import static org.hamcrest.Matchers.hasSize;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.HSQLDialect; import org.hibernate.dialect.HSQLDialect;
import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; 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 { public class HibernateOneToManyAnnotationMainTest {
private static SessionFactory sessionFactory; private static SessionFactory sessionFactory;
private Session session; private Session session;
public HibernateOneToManyAnnotationMainTest() { public HibernateOneToManyAnnotationMainTest() {
} }
@BeforeClass
public static void beforeTests() {
Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class)
.setProperty("hibernate.dialect", HSQLDialect.class.getName())
.setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test")
.setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "")
.setProperty("hibernate.hbm2ddl.auto", "update");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
@BeforeClass @Before
public static void beforeTests() { public void setUp() {
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()) session = sessionFactory.openSession();
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update"); session.beginTransaction();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); }
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
@Before @Test
public void setUp() { public void givenSession_checkIfDatabaseIsEmpty() {
session = sessionFactory.openSession(); Cart cart = (Cart) session.get(Cart.class, new Long(1));
session.beginTransaction(); 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);
}
@Test @After
public void testAddItemsToCart() { public void tearDown() {
Cart cart = new Cart(); session.getTransaction().commit();
Set <Items> cartItems = new HashSet<>(); session.close();
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();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
} }

View File

@ -9,7 +9,7 @@
<packaging>war</packaging> <packaging>war</packaging>
<properties> <properties>
<jersey.version>2.25</jersey.version> <jersey.version>2.25.1</jersey.version>
<jcl.slf4j.version>1.7.22</jcl.slf4j.version> <jcl.slf4j.version>1.7.22</jcl.slf4j.version>
<logback.version>1.1.8</logback.version> <logback.version>1.1.8</logback.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>

View File

@ -18,7 +18,7 @@ public class RestClient {
} }
public Employee getJsonEmployee(int id) { 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) { public Response createXmlEmployee(Employee emp) {
@ -26,6 +26,6 @@ public class RestClient {
} }
public Employee getXmlEmployee(int id) { 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);
} }
} }

View File

@ -6,9 +6,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class Application { public class Application {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(Application.class, args); SpringApplication.run(Application.class, args);
}
}
} }

View File

@ -46,6 +46,23 @@
<artifactId>commons-fileupload</artifactId> <artifactId>commons-fileupload</artifactId>
<version>${fileupload.version}</version> <version>${fileupload.version}</version>
</dependency> </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> </dependencies>
<profiles> <profiles>
<!-- Local --> <!-- Local -->
@ -98,6 +115,7 @@
<hibernate-validator.version>5.3.3.Final</hibernate-validator.version> <hibernate-validator.version>5.3.3.Final</hibernate-validator.version>
<deploy-path>enter-location-of-server</deploy-path> <deploy-path>enter-location-of-server</deploy-path>
<fileupload.version>1.3.2</fileupload.version> <fileupload.version>1.3.2</fileupload.version>
<org.springframework.security.version>4.2.1.RELEASE</org.springframework.security.version>
</properties> </properties>
</project> </project>

View File

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

View File

@ -3,6 +3,7 @@ package com.baeldung.springmvcforms.configuration;
import org.springframework.web.WebApplicationInitializer; import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
@ -24,6 +25,9 @@ public class WebInitializer implements WebApplicationInitializer {
servlet.setLoadOnStartup(1); servlet.setLoadOnStartup(1);
servlet.addMapping("/"); servlet.addMapping("/");
container.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain"))
.addMappingForUrlPatterns(null, false, "/*");
} }
// @Override // @Override
// public void onStartup(ServletContext container) { // public void onStartup(ServletContext container) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,22 +1,24 @@
package com.baeldung.excel; package com.baeldung.excel;
import jxl.*; import jxl.Sheet;
import java.util.Map; import jxl.Workbook;
import java.util.HashMap; import jxl.format.Colour;
import java.util.ArrayList;
import jxl.read.biff.BiffException; import jxl.read.biff.BiffException;
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Service;
import jxl.write.*; import jxl.write.*;
import jxl.write.Number; 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 @Service
public class JExcelHelper { public class JExcelHelper {
public Map<Integer, ArrayList<String>> readJExcel(String fileLocation) throws IOException, BiffException { 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)); Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
Sheet sheet = workbook.getSheet(0); Sheet sheet = workbook.getSheet(0);
@ -24,7 +26,7 @@ public class JExcelHelper {
int columns = sheet.getColumns(); int columns = sheet.getColumns();
for (int i = 0; i < rows; i++) { 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++) { for (int j = 0; j < columns; j++) {
data.get(i).add(sheet.getCell(j, i).getContents()); data.get(i).add(sheet.getCell(j, i).getContents());
} }

View File

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

View File

@ -22,7 +22,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration @WebAppConfiguration
@ContextConfiguration(classes = BeanNameUrlHandlerMappingConfig.class) @ContextConfiguration(classes = BeanNameUrlHandlerMappingConfig.class)
public class BeanNameMappingConfigTest { public class BeanNameMappingConfigIntegrationTest {
@Autowired @Autowired
private WebApplicationContext webAppContext; private WebApplicationContext webAppContext;

View File

@ -22,7 +22,7 @@ import com.baeldung.config.ControllerClassNameHandlerMappingConfig;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration @WebAppConfiguration
@ContextConfiguration(classes = ControllerClassNameHandlerMappingConfig.class) @ContextConfiguration(classes = ControllerClassNameHandlerMappingConfig.class)
public class ControllerClassNameHandlerMappingTest { public class ControllerClassNameHandlerMappingIntegrationTest {
@Autowired @Autowired
private WebApplicationContext webAppContext; private WebApplicationContext webAppContext;

View File

@ -1,7 +1,10 @@
package com.baeldung.handlermappings; package com.baeldung.handlermappings;
import com.baeldung.config.HandlerMappingDefaultConfig; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import com.baeldung.config.HandlerMappingPrioritiesConfig; 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.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; 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.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import com.baeldung.config.HandlerMappingDefaultConfig;
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;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration @WebAppConfiguration
@ContextConfiguration(classes = HandlerMappingDefaultConfig.class) @ContextConfiguration(classes = HandlerMappingDefaultConfig.class)
public class HandlerMappingDefaultConfigTest { public class HandlerMappingDefaultConfigIntegrationTest {
@Autowired @Autowired
private WebApplicationContext webAppContext; private WebApplicationContext webAppContext;

View File

@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration @WebAppConfiguration
@ContextConfiguration(classes = HandlerMappingPrioritiesConfig.class) @ContextConfiguration(classes = HandlerMappingPrioritiesConfig.class)
public class HandlerMappingPriorityConfigTest { public class HandlerMappingPriorityConfigIntegrationTest {
@Autowired @Autowired
private WebApplicationContext webAppContext; private WebApplicationContext webAppContext;

View File

@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration @WebAppConfiguration
@ContextConfiguration(classes = SimpleUrlHandlerMappingConfig.class) @ContextConfiguration(classes = SimpleUrlHandlerMappingConfig.class)
public class SimpleUrlMappingConfigTest { public class SimpleUrlMappingConfigIntegrationTest {
@Autowired @Autowired
private WebApplicationContext webAppContext; private WebApplicationContext webAppContext;

View File

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

View File

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

View File

@ -0,0 +1,12 @@
package com.baeldung.cachecontrol;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AppRunner {
public static void main(String[] args) {
SpringApplication.run(AppRunner.class, args);
}
}

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