diff --git a/apache-poi/README.md b/apache-poi/README.md index cef6810c97..10fe8ba2e7 100644 --- a/apache-poi/README.md +++ b/apache-poi/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi) +- [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel) diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml index d94b2e2ad1..d8a2cc72e0 100644 --- a/apache-poi/pom.xml +++ b/apache-poi/pom.xml @@ -9,6 +9,7 @@ 3.6.0 4.12 3.15 + 1.0.6 @@ -37,5 +38,10 @@ poi-ooxml ${poi.version} + + org.jxls + jxls-jexcel + ${jexcel.version} + diff --git a/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java b/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java new file mode 100644 index 0000000000..4ad3fc766c --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java @@ -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> readJExcel(String fileLocation) throws IOException, BiffException { + Map> 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()); + 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(); + } + } + + } +} \ No newline at end of file diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java new file mode 100644 index 0000000000..b6b0cbef20 --- /dev/null +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java @@ -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> readExcel(String fileLocation) throws IOException { + + Map> 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()); + 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(); + + } + } + } + +} \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java new file mode 100644 index 0000000000..8ee465be34 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java @@ -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> 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)); + } + +} \ No newline at end of file diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java new file mode 100644 index 0000000000..34fa64dd94 --- /dev/null +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java @@ -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> 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)); + } + +} \ No newline at end of file diff --git a/apache-poi/temp.xls b/apache-poi/temp.xls new file mode 100644 index 0000000000..1fad76d88d Binary files /dev/null and b/apache-poi/temp.xls differ diff --git a/apache-poi/temp.xlsx b/apache-poi/temp.xlsx new file mode 100644 index 0000000000..da67ca9e9e Binary files /dev/null and b/apache-poi/temp.xlsx differ diff --git a/apache-thrift/src/main/java/com/baeldung/thrift/Application.java b/apache-thrift/src/main/java/com/baeldung/thrift/Application.java index 09d5cc74f3..3321a0927a 100644 --- a/apache-thrift/src/main/java/com/baeldung/thrift/Application.java +++ b/apache-thrift/src/main/java/com/baeldung/thrift/Application.java @@ -1,8 +1,10 @@ package com.baeldung.thrift; +import org.apache.thrift.transport.TTransportException; + public class Application { - public static void main(String[] args) { + public static void main(String[] args) throws TTransportException { CrossPlatformServiceServer server = new CrossPlatformServiceServer(); server.start(); } diff --git a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java index 9a21512b52..32c7891ef2 100644 --- a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java +++ b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java @@ -6,25 +6,22 @@ import org.apache.thrift.server.TServer; import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TServerTransport; +import org.apache.thrift.transport.TTransportException; public class CrossPlatformServiceServer { private TServer server; - public void start() { - try { - TServerTransport serverTransport = new TServerSocket(9090); - server = new TSimpleServer(new TServer.Args(serverTransport) - .processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl()))); + public void start() throws TTransportException { + TServerTransport serverTransport = new TServerSocket(9090); + server = new TSimpleServer(new TServer.Args(serverTransport) + .processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl()))); - System.out.print("Starting the server... "); + System.out.print("Starting the server... "); - server.serve(); + server.serve(); - System.out.println("done."); - } catch (Exception e) { - e.printStackTrace(); - } + System.out.println("done."); } public void stop() { diff --git a/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java b/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java index 8a7022a281..4ba9ef2914 100644 --- a/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java +++ b/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java @@ -1,5 +1,6 @@ package com.baeldung.thrift; +import org.apache.thrift.transport.TTransportException; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -11,7 +12,13 @@ public class CrossPlatformServiceTest { @Before public void setUp() { - new Thread(() -> server.start()).start(); + new Thread(() -> { + try { + server.start(); + } catch (TTransportException e) { + e.printStackTrace(); + } + }).start(); try { // wait for the server start up Thread.sleep(1000); diff --git a/core-java/pom.xml b/core-java/pom.xml index 85afee2968..2b6f065c85 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung core-java @@ -10,6 +10,44 @@ + + org.neo4j + neo4j + 3.1.0 + + + + org.neo4j.driver + neo4j-java-driver + 1.1.1 + + + + org.neo4j + neo4j-jdbc-driver + 3.0.1 + + + + org.neo4j + neo4j-ogm-core + 2.1.1 + + + + org.neo4j + neo4j-ogm-embedded-driver + 2.1.1 + + + + com.google.inject + guice + 4.1.0 + no_aop + test + + net.sourceforge.collections @@ -63,7 +101,6 @@ grep4j ${grep4j.version} - @@ -154,6 +191,12 @@ ${mockito.version} test + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + commons-codec @@ -263,7 +306,8 @@ true - + org.baeldung.executable.ExecutableMavenJar @@ -371,6 +415,7 @@ 1.10.19 6.10 3.6.1 + 1.7.0 3.6.0 diff --git a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java index 113ac1cc53..476e873f90 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java +++ b/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java @@ -3,6 +3,7 @@ package com.baeldung.algorithms; import java.util.Scanner; import com.baeldung.algorithms.annealing.SimulatedAnnealing; +import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; import com.baeldung.algorithms.slope_one.SlopeOne; public class RunAlgorithm { @@ -12,6 +13,7 @@ public class RunAlgorithm { System.out.println("Run algorithm:"); System.out.println("1 - Simulated Annealing"); System.out.println("2 - Slope One"); + System.out.println("3 - Simple Genetic Algorithm"); int decision = in.nextInt(); switch (decision) { case 1: @@ -20,6 +22,9 @@ public class RunAlgorithm { case 2: SlopeOne.slopeOne(3); break; + case 3: + SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"); + break; default: System.out.println("Unknown option"); break; diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java new file mode 100644 index 0000000000..2a740777f3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java @@ -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; + } + +} diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java new file mode 100644 index 0000000000..47677d7d88 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java @@ -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 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); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java new file mode 100644 index 0000000000..c7e2a6b381 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java @@ -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; + } + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java index e53a2413d1..bcd559dd3b 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java +++ b/core-java/src/main/java/com/baeldung/concurrent/future/SquareCalculator.java @@ -15,6 +15,6 @@ public class SquareCalculator { return executor.submit(() -> { Thread.sleep(1000); return input * input; - }); + }); } } diff --git a/core-java/src/main/java/com/baeldung/graph/Car.java b/core-java/src/main/java/com/baeldung/graph/Car.java new file mode 100644 index 0000000000..1dc65a0d4b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/graph/Car.java @@ -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; +} diff --git a/core-java/src/main/java/com/baeldung/graph/Company.java b/core-java/src/main/java/com/baeldung/graph/Company.java new file mode 100644 index 0000000000..1fe892b331 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/graph/Company.java @@ -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; + } +} diff --git a/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java b/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java new file mode 100644 index 0000000000..afc05e356a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java @@ -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 + '}'; + } +} diff --git a/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java b/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java new file mode 100644 index 0000000000..2029784e91 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java @@ -0,0 +1,5 @@ +package com.baeldung.java_8_features.groupingby; + +public enum BlogPostType { + NEWS, REVIEW, GUIDE +} diff --git a/core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java b/core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java new file mode 100644 index 0000000000..a0c36bb63e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java @@ -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)); + } +} diff --git a/core-java/src/main/java/com/baeldung/strategy/Discounter.java b/core-java/src/main/java/com/baeldung/strategy/Discounter.java new file mode 100644 index 0000000000..00bf4855d1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/strategy/Discounter.java @@ -0,0 +1,23 @@ +package com.baeldung.strategy; + +import java.math.BigDecimal; +import java.util.function.UnaryOperator; + +public interface Discounter extends UnaryOperator { + + 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)); + } +} diff --git a/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java b/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java new file mode 100644 index 0000000000..990d10073b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/strategy/EasterDiscounter.java @@ -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)); + } +} diff --git a/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java b/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java index 2f7830bbf4..3488f8b390 100644 --- a/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java +++ b/core-java/src/test/java/com/baeldung/CharArrayToStringUnitTest.java @@ -8,55 +8,55 @@ public class CharArrayToStringUnitTest { @Test public void givenCharArray_whenCallingStringConstructor_shouldConvertToString() { - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = new String(charArray); String expectedValue = "character"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = new String(charArray, 4, 3); String expectedValue = "act"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = String.copyValueOf(charArray); String expectedValue = "character"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = String.copyValueOf(charArray, 0, 4); String expectedValue = "char"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringValueOf_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringValueOf_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = String.valueOf(charArray); String expectedValue = "character"; - + assertEquals(expectedValue, result); } - + @Test - public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString(){ - char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'}; + public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString() { + char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' }; String result = String.valueOf(charArray, 3, 4); String expectedValue = "ract"; - + assertEquals(expectedValue, result); } } diff --git a/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java b/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java index 2e7dc24a17..cd996e58e2 100644 --- a/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java +++ b/core-java/src/test/java/com/baeldung/StringToCharArrayUnitTest.java @@ -6,15 +6,15 @@ import org.junit.Test; public class StringToCharArrayUnitTest { -@Test -public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() { - String givenString = "characters"; + @Test + public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() { + String givenString = "characters"; - char[] result = givenString.toCharArray(); + char[] result = givenString.toCharArray(); - char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' }; + char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' }; - assertArrayEquals(expectedCharArray, result); -} + assertArrayEquals(expectedCharArray, result); + } } diff --git a/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java b/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java new file mode 100644 index 0000000000..6b720898eb --- /dev/null +++ b/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java @@ -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")); + } + +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java new file mode 100644 index 0000000000..0272726465 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueUnitTest.java @@ -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 queue = new PriorityBlockingQueue<>(); + ArrayList 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 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)); + } +} diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java b/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java new file mode 100644 index 0000000000..b41588b71e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/graph/Neo4JServerTest.java @@ -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(); + } +} diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java b/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java new file mode 100644 index 0000000000..00bd47d029 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/graph/Neo4jOgmTest.java @@ -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 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 firstResult = result.iterator().next(); + + Assert.assertEquals(firstResult.size(), 1); + + Company actual = (Company) firstResult.get("company"); + Assert.assertEquals(actual.getName(), baeldung.getName()); + } +} diff --git a/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java b/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java new file mode 100644 index 0000000000..6956c2c39f --- /dev/null +++ b/core-java/src/test/java/com/baeldung/graph/Neo4jTest.java @@ -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 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 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 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 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 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 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 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"); + } +} diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusTest.java rename to core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java index 73a4cdc0cd..ec865f71c4 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java @@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -public class ConcurrentMapAggregateStatusTest { +public class ConcurrentMapAggregateStatusManualTest { private ExecutorService executorService; private Map concurrentMap; diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueTest.java rename to core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java index 62a3d10add..33e3326427 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java @@ -10,7 +10,7 @@ import java.util.concurrent.ConcurrentMap; import static org.junit.Assert.assertNull; -public class ConcurrentMapNullKeyValueTest { +public class ConcurrentMapNullKeyValueManualTest { ConcurrentMap concurrentMap; diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceTest.java rename to core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java index a0efa89351..5c1612ca60 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java @@ -11,7 +11,7 @@ import java.util.concurrent.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class ConcurrentMapPerformanceTest { +public class ConcurrentMapPerformanceManualTest { @Test public void givenMaps_whenGetPut500KTimes_thenConcurrentMapFaster() throws Exception { diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java similarity index 95% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java rename to core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java index 93087626a4..d102680aa4 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapTests.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTests.java @@ -10,7 +10,7 @@ import java.util.concurrent.atomic.AtomicInteger; import static org.testng.Assert.*; -public class ConcurrentNavigableMapTests { +public class ConcurrentNavigableMapManualTests { @Test public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throws InterruptedException { @@ -18,9 +18,7 @@ public class ConcurrentNavigableMapTests { updateMapConcurrently(skipListMap, 4); - Iterator skipListIter = skipListMap - .keySet() - .iterator(); + Iterator skipListIter = skipListMap.keySet().iterator(); int previous = skipListIter.next(); while (skipListIter.hasNext()) { int current = skipListIter.next(); diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyTest.java rename to core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java index 63a96dd5ee..43cbb2d293 100644 --- a/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyTest.java +++ b/core-java/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java @@ -10,7 +10,7 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; -public class ConcurretMapMemoryConsistencyTest { +public class ConcurretMapMemoryConsistencyManualTest { @Test public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception { diff --git a/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java b/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java new file mode 100644 index 0000000000..f7a7bd5fe0 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java @@ -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 integers = newArrayList(1, 2, 3); + + for (Integer integer : integers) { + integers.remove(1); + } + } + + @Test + public void givenIterating_whenUsingIteratorRemove_thenNoError() throws InterruptedException { + + List integers = newArrayList(1, 2, 3); + + for (Iterator 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 integers = newArrayList(1, 2, 3); + List 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 integers = newArrayList(1, 2, 3); + + integers.removeIf(i -> i == 2); + + assertThat(integers).containsExactly(1, 3); + } + + @Test + public void whenUsingStream_thenRemoveElements() { + Collection integers = newArrayList(1, 2, 3); + + List collected = integers + .stream() + .filter(i -> i != 2) + .map(Object::toString) + .collect(toList()); + + assertThat(collected).containsExactly("1", "3"); + } + +} diff --git a/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java new file mode 100644 index 0000000000..4452b4db9a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java @@ -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 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> 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 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 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> 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> 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> 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 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 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> 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>> 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 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()); + } + +} diff --git a/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java b/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java new file mode 100644 index 0000000000..7ca1d000be --- /dev/null +++ b/core-java/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java @@ -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 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 combinedDiscounters = Discounter + .christmas() + .andThen(newYear()); + + combinedDiscounters.apply(BigDecimal.valueOf(100)); + } +} diff --git a/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java b/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java new file mode 100644 index 0000000000..1c5a261eea --- /dev/null +++ b/core-java/src/test/java/com/baeldung/weakhashmap/WeakHashMapTest.java @@ -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 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 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; + } + } +} diff --git a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java index 4febe7c9fc..08f98025c3 100644 --- a/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/JavaRandomUnitTest.java @@ -1,12 +1,12 @@ package org.baeldung.java; -import java.nio.charset.Charset; -import java.util.Random; - import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.math3.random.RandomDataGenerator; import org.junit.Test; +import java.nio.charset.Charset; +import java.util.Random; + public class JavaRandomUnitTest { // tests - random long @@ -164,7 +164,7 @@ public class JavaRandomUnitTest { final int targetStringLength = 10; final StringBuilder buffer = new StringBuilder(targetStringLength); for (int i = 0; i < targetStringLength; i++) { - final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit)); + final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit + 1)); buffer.append((char) randomLimitedInt); } final String generatedString = buffer.toString(); diff --git a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStream.java b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java similarity index 76% rename from core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStream.java rename to core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java index b8c0991b8d..c2eb1cff5d 100644 --- a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStream.java +++ b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java @@ -1,5 +1,5 @@ package org.baeldung.java.streams; - + import org.junit.Test; import java.util.ArrayList; @@ -13,29 +13,26 @@ import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class ThreadPoolInParallelStream { - +public class ThreadPoolInParallelStreamTest { + @Test - public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() - throws InterruptedException, ExecutionException { + public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException { long firstNum = 1; long lastNum = 1_000_000; - List aList = LongStream.rangeClosed(firstNum, lastNum).boxed() - .collect(Collectors.toList()); + List aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList()); ForkJoinPool customThreadPool = new ForkJoinPool(4); - long actualTotal = customThreadPool.submit(() -> aList.parallelStream() - .reduce(0L, Long::sum)).get(); - - assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); + long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get(); + + assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); } - + @Test - public void givenList_whenCallingParallelStream_shouldBeParallelStream(){ + public void givenList_whenCallingParallelStream_shouldBeParallelStream() { List aList = new ArrayList<>(); Stream parallelStream = aList.parallelStream(); - + assertTrue(parallelStream.isParallel()); } } diff --git a/guava/pom.xml b/guava/pom.xml index f65a9a2081..0edbb90efd 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -57,6 +57,32 @@ test + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + org.assertj assertj-core @@ -112,6 +138,9 @@ 3.6.0 2.19.1 + + 1.7.21 + 1.1.7 \ No newline at end of file diff --git a/guava/src/test/java/org/baeldung/guava/CustomEvent.java b/guava/src/main/java/org/baeldung/guava/CustomEvent.java similarity index 99% rename from guava/src/test/java/org/baeldung/guava/CustomEvent.java rename to guava/src/main/java/org/baeldung/guava/CustomEvent.java index 78348065b2..2d5c3382d4 100644 --- a/guava/src/test/java/org/baeldung/guava/CustomEvent.java +++ b/guava/src/main/java/org/baeldung/guava/CustomEvent.java @@ -1,6 +1,5 @@ package org.baeldung.guava; - public class CustomEvent { private String action; diff --git a/guava/src/test/java/org/baeldung/guava/EventBusWrapper.java b/guava/src/main/java/org/baeldung/guava/EventBusWrapper.java similarity index 69% rename from guava/src/test/java/org/baeldung/guava/EventBusWrapper.java rename to guava/src/main/java/org/baeldung/guava/EventBusWrapper.java index eddaca0baf..243bc9e6ea 100644 --- a/guava/src/test/java/org/baeldung/guava/EventBusWrapper.java +++ b/guava/src/main/java/org/baeldung/guava/EventBusWrapper.java @@ -6,17 +6,16 @@ class EventBusWrapper { private static EventBus eventBus = new EventBus(); - static void register(Object object){ + static void register(Object object) { eventBus.register(object); } - static void unregister(Object object){ + static void unregister(Object object) { eventBus.unregister(object); } - static void post(Object object){ + static void post(Object object) { eventBus.post(object); } - } diff --git a/guava/src/main/java/org/baeldung/guava/EventListener.java b/guava/src/main/java/org/baeldung/guava/EventListener.java new file mode 100644 index 0000000000..02f22ce6b9 --- /dev/null +++ b/guava/src/main/java/org/baeldung/guava/EventListener.java @@ -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; + } +} diff --git a/guava/src/test/java/org/baeldung/guava/EventListener.java b/guava/src/test/java/org/baeldung/guava/EventListener.java deleted file mode 100644 index 17a3ac093e..0000000000 --- a/guava/src/test/java/org/baeldung/guava/EventListener.java +++ /dev/null @@ -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; - } -} diff --git a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java index bd966187ab..1db361d22c 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaEventBusTest.java @@ -11,18 +11,18 @@ public class GuavaEventBusTest { private EventListener listener; @Before - public void setUp() throws Exception { + public void setUp() { listener = new EventListener(); EventBusWrapper.register(listener); } @After - public void tearDown() throws Exception { + public void tearDown() { EventBusWrapper.unregister(listener); } @Test - public void givenStringEvent_whenEventHandled_thenSuccess() throws Exception { + public void givenStringEvent_whenEventHandled_thenSuccess() { listener.resetEventsHandled(); EventBusWrapper.post("String Event"); @@ -31,7 +31,7 @@ public class GuavaEventBusTest { } @Test - public void givenCustomEvent_whenEventHandled_thenSuccess() throws Exception { + public void givenCustomEvent_whenEventHandled_thenSuccess() { listener.resetEventsHandled(); CustomEvent customEvent = new CustomEvent("Custom Event"); diff --git a/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java b/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java index 55e3c7db00..2d98418d48 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaPreConditionsTest.java @@ -3,7 +3,7 @@ package org.baeldung.guava; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Arrays; import org.junit.Test; -import static com.google.common.base.Preconditions.*; +import com.google.common.base.*; public class GuavaPreConditionsTest { @@ -11,10 +11,7 @@ public class GuavaPreConditionsTest { public void whenCheckArgumentEvaluatesFalse_throwsException() { int age = -18; - assertThatThrownBy(() -> checkArgument(age > 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage(null) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkArgument(age > 0)).isInstanceOf(IllegalArgumentException.class).hasMessage(null).hasNoCause(); } @Test @@ -22,10 +19,7 @@ public class GuavaPreConditionsTest { final int age = -18; final String message = "Age can't be zero or less than zero"; - assertThatThrownBy(() -> checkArgument(age > 0, message)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage(message) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message)).isInstanceOf(IllegalArgumentException.class).hasMessage(message).hasNoCause(); } @Test @@ -33,19 +27,14 @@ public class GuavaPreConditionsTest { final int age = -18; final String message = "Age can't be zero or less than zero, you supplied %s."; - assertThatThrownBy(() -> checkArgument(age > 0, message, age)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage(message, age) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message, age)).isInstanceOf(IllegalArgumentException.class).hasMessage(message, age).hasNoCause(); } @Test public void givenArrayOfIntegers_whenCheckElementIndexEvaluatesFalse_throwsException() { final int[] numbers = { 1, 2, 3, 4, 5 }; - assertThatThrownBy(() -> checkElementIndex(6, numbers.length - 1)) - .isInstanceOf(IndexOutOfBoundsException.class) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause(); } @Test @@ -53,20 +42,7 @@ public class GuavaPreConditionsTest { final int[] numbers = { 1, 2, 3, 4, 5 }; final String message = "Please check the bound of an array and retry"; - assertThatThrownBy(() -> checkElementIndex(6, numbers.length - 1, message)) - .isInstanceOf(IndexOutOfBoundsException.class) - .hasMessageStartingWith(message) - .hasNoCause(); - } - - @Test - public void givenNullString_whenCheckNotNullCalled_throwsException() { - final String nullObject = null; - - assertThatThrownBy(() -> checkNotNull(nullObject)) - .isInstanceOf(NullPointerException.class) - .hasMessage(null) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkElementIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause(); } @Test @@ -74,10 +50,7 @@ public class GuavaPreConditionsTest { final String nullObject = null; final String message = "Please check the Object supplied, its null!"; - assertThatThrownBy(() -> checkNotNull(nullObject, message)) - .isInstanceOf(NullPointerException.class) - .hasMessage(message) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message)).isInstanceOf(NullPointerException.class).hasMessage(message).hasNoCause(); } @Test @@ -85,19 +58,14 @@ public class GuavaPreConditionsTest { final String nullObject = null; final String message = "Please check the Object supplied, its %s!"; - assertThatThrownBy(() -> checkNotNull(nullObject, message, nullObject)) - .isInstanceOf(NullPointerException.class) - .hasMessage(message, nullObject) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message, new Object[] { null })).isInstanceOf(NullPointerException.class).hasMessage(message, nullObject).hasNoCause(); } @Test public void givenArrayOfIntegers_whenCheckPositionIndexEvaluatesFalse_throwsException() { final int[] numbers = { 1, 2, 3, 4, 5 }; - assertThatThrownBy(() -> checkPositionIndex(6, numbers.length - 1)) - .isInstanceOf(IndexOutOfBoundsException.class) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause(); } @Test @@ -105,30 +73,14 @@ public class GuavaPreConditionsTest { final int[] numbers = { 1, 2, 3, 4, 5 }; final String message = "Please check the bound of an array and retry"; - assertThatThrownBy(() -> checkPositionIndex(6, numbers.length - 1, message)) - .isInstanceOf(IndexOutOfBoundsException.class) - .hasMessageStartingWith(message) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkPositionIndex(6, numbers.length - 1, message)).isInstanceOf(IndexOutOfBoundsException.class).hasMessageStartingWith(message).hasNoCause(); } @Test public void givenArrayOfIntegers_whenCheckPositionIndexesEvaluatesFalse_throwsException() { final int[] numbers = { 1, 2, 3, 4, 5 }; - assertThatThrownBy(() -> checkPositionIndexes(6, 0, numbers.length - 1)) - .isInstanceOf(IndexOutOfBoundsException.class) - .hasNoCause(); - } - - @Test - public void givenValidStates_whenCheckStateEvaluatesFalse_throwsException() { - final int[] validStates = { -1, 0, 1 }; - final int givenState = 10; - - assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0)) - .isInstanceOf(IllegalStateException.class) - .hasMessage(null) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkPositionIndexes(6, 0, numbers.length - 1)).isInstanceOf(IndexOutOfBoundsException.class).hasNoCause(); } @Test @@ -137,10 +89,7 @@ public class GuavaPreConditionsTest { final int givenState = 10; final String message = "You have entered an invalid state"; - assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0, message)) - .isInstanceOf(IllegalStateException.class) - .hasMessageStartingWith(message) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message)).isInstanceOf(IllegalStateException.class).hasMessageStartingWith(message).hasNoCause(); } @Test @@ -149,9 +98,7 @@ public class GuavaPreConditionsTest { final int givenState = 10; final String message = "State can't be %s, It can be one of %s."; - assertThatThrownBy(() -> checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates))) - .isInstanceOf(IllegalStateException.class) - .hasMessage(message, givenState, Arrays.toString(validStates)) - .hasNoCause(); + assertThatThrownBy(() -> Preconditions.checkState(Arrays.binarySearch(validStates, givenState) > 0, message, givenState, Arrays.toString(validStates))).isInstanceOf(IllegalStateException.class) + .hasMessage(message, givenState, Arrays.toString(validStates)).hasNoCause(); } -} +} \ No newline at end of file diff --git a/log-mdc/pom.xml b/log-mdc/pom.xml index 28c8bb820e..931e68a178 100644 --- a/log-mdc/pom.xml +++ b/log-mdc/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - logmdc + log-mdc 0.0.1-SNAPSHOT - logmdc + log-mdc war tutorial on logging with MDC and NDC diff --git a/metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java b/metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java index f670acfaef..e876de6e65 100644 --- a/metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/core/MetricsTest.java @@ -138,15 +138,15 @@ public class MetricsTest { long elapsed1 = context1.stop(); - assertEquals(5000000000L, elapsed1, 10000000); + assertEquals(5000000000L, elapsed1, 1000000000); assertThat(timer.getCount(), equalTo(1L)); - assertEquals(0.2, timer.getMeanRate(), 0.1); + assertEquals(0.2, timer.getMeanRate(), 0.2); Timer.Context context2 = timer.time(); TimeUnit.SECONDS.sleep(2); context2.close(); assertThat(timer.getCount(), equalTo(2L)); - assertEquals(0.3, timer.getMeanRate(), 0.1); + assertEquals(0.3, timer.getMeanRate(), 0.2); } } diff --git a/pom.xml b/pom.xml index 06feb5e4f5..a24e3d4667 100644 --- a/pom.xml +++ b/pom.xml @@ -94,6 +94,7 @@ rest-assured rest-testing resteasy + rxjava selenium-junit-testng solr-fulltext-search @@ -146,6 +147,7 @@ spring-rest-docs spring-rest spring-security-basic-auth + spring-security-cache-control spring-security-client/spring-security-jsp-authentication spring-security-client/spring-security-jsp-authorize spring-security-client/spring-security-jsp-config diff --git a/rxjava/pom.xml b/rxjava/pom.xml new file mode 100644 index 0000000000..6a351d98bd --- /dev/null +++ b/rxjava/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + com.baeldung + rxjava + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + io.reactivex + rxjava + ${rx.java.version} + + + junit + junit + ${junit.version} + + + + + 4.12 + 1.2.5 + + + \ No newline at end of file diff --git a/rxjava/src/main/java/com/baelding/rxjava/ComputeFunction.java b/rxjava/src/main/java/com/baelding/rxjava/ComputeFunction.java new file mode 100644 index 0000000000..924862ab37 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/ComputeFunction.java @@ -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 v) { + try { + System.out.println("compute integer v: " + v); + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public static void compute(Observable 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(); + } + } +} diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureTest.java new file mode 100644 index 0000000000..33f94a9c6f --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureTest.java @@ -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 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 testSubscriber = new TestSubscriber<>(); + PublishSubject source = PublishSubject. 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> testSubscriber = new TestSubscriber<>(); + PublishSubject source = PublishSubject. 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> testSubscriber = new TestSubscriber<>(); + PublishSubject source = PublishSubject. 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 testSubscriber = new TestSubscriber<>(); + PublishSubject source = PublishSubject. 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 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 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); + + } +} diff --git a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java similarity index 95% rename from spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java rename to spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java index 2ea2822b9a..a8a7bda91c 100644 --- a/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/properties/external/ExternalPropertiesWithXmlManualTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { ExternalPropertiesWithXmlConfig.class }, loader = AnnotationConfigContextLoader.class) @Ignore("manual only") -public class ExternalPropertiesWithXmlIntegrationTest { +public class ExternalPropertiesWithXmlManualTest { @Autowired private Environment env; diff --git a/spring-all/src/test/java/org/baeldung/springretry/SpringRetryTest.java b/spring-all/src/test/java/org/baeldung/springretry/SpringRetryIntegrationTest.java similarity index 96% rename from spring-all/src/test/java/org/baeldung/springretry/SpringRetryTest.java rename to spring-all/src/test/java/org/baeldung/springretry/SpringRetryIntegrationTest.java index 2f3411957e..d7d0943e6b 100644 --- a/spring-all/src/test/java/org/baeldung/springretry/SpringRetryTest.java +++ b/spring-all/src/test/java/org/baeldung/springretry/SpringRetryIntegrationTest.java @@ -12,7 +12,7 @@ import java.sql.SQLException; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class) -public class SpringRetryTest { +public class SpringRetryIntegrationTest { @Autowired private MyService myService; diff --git a/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerTest.java b/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerIntegrationTest.java similarity index 90% rename from spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerTest.java rename to spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerIntegrationTest.java index cc247cb384..d95857d384 100644 --- a/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerTest.java +++ b/spring-all/src/test/java/org/baeldung/taskscheduler/ThreadPoolTaskSchedulerIntegrationTest.java @@ -8,7 +8,8 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { ThreadPoolTaskSchedulerConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ThreadPoolTaskSchedulerTest { +public class ThreadPoolTaskSchedulerIntegrationTest { + @Test public void testThreadPoolTaskSchedulerAnnotation() throws InterruptedException { Thread.sleep(2550); diff --git a/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java b/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java index f9845f42a7..470ae9e538 100644 --- a/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java +++ b/spring-all/src/test/java/org/baeldung/test/IntegrationTestSuite.java @@ -5,7 +5,7 @@ import org.baeldung.properties.basic.PropertiesWithMultipleXmlsIntegrationTest; import org.baeldung.properties.basic.PropertiesWithXmlIntegrationTest; import org.baeldung.properties.external.ExternalPropertiesWithJavaIntegrationTest; import org.baeldung.properties.external.ExternalPropertiesWithMultipleXmlsIntegrationTest; -import org.baeldung.properties.external.ExternalPropertiesWithXmlIntegrationTest; +import org.baeldung.properties.external.ExternalPropertiesWithXmlManualTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @@ -15,7 +15,7 @@ import org.junit.runners.Suite.SuiteClasses; PropertiesWithXmlIntegrationTest.class, ExternalPropertiesWithJavaIntegrationTest.class, ExternalPropertiesWithMultipleXmlsIntegrationTest.class, - ExternalPropertiesWithXmlIntegrationTest.class, + ExternalPropertiesWithXmlManualTest.class, ExtendedPropertiesWithJavaIntegrationTest.class, PropertiesWithMultipleXmlsIntegrationTest.class, })// @formatter:on diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java similarity index 95% rename from spring-boot/src/test/java/com/baeldung/intro/AppTest.java rename to spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java index 749fe68838..772709dc30 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -1,39 +1,39 @@ -package com.baeldung.intro; - -import static org.hamcrest.Matchers.equalTo; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -public class AppTest { - - @Autowired - private MockMvc mvc; - - @Test - public void getIndex() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("Index Page"))); - } - - @Test - public void getLocal() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("/local"))); - } - +package com.baeldung.intro; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import static org.hamcrest.Matchers.equalTo; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class AppLiveTest { + + @Autowired + private MockMvc mvc; + + @Test + public void getIndex() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(equalTo("Index Page"))); + } + + @Test + public void getLocal() throws Exception { + mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string(equalTo("/local"))); + } + } \ No newline at end of file diff --git a/spring-core/README.md b/spring-core/README.md index f6aaaf44a0..a32d30939f 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -3,4 +3,4 @@ - [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory) - [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) - [Constructor Dependency Injection in Spring](http://www.baeldung.com/constructor-injection-in-spring) -- [Constructor Injection in Spring with Lombok](http://inprogress.baeldung.com/constructor-injection-in-spring-with-lombok) +- [Constructor Injection in Spring with Lombok](http://www.baeldung.com/spring-injection-lombok) diff --git a/spring-core/src/main/java/com/baeldung/lombok/Apologizer.java b/spring-core/src/main/java/com/baeldung/lombok/ApologizeService.java similarity index 83% rename from spring-core/src/main/java/com/baeldung/lombok/Apologizer.java rename to spring-core/src/main/java/com/baeldung/lombok/ApologizeService.java index ddce9cdc52..25ef65cad2 100644 --- a/spring-core/src/main/java/com/baeldung/lombok/Apologizer.java +++ b/spring-core/src/main/java/com/baeldung/lombok/ApologizeService.java @@ -6,13 +6,13 @@ import org.springframework.stereotype.Component; @Component @AllArgsConstructor -public class Apologizer { +public class ApologizeService { private final Translator translator; private final String message; @Autowired - public Apologizer(Translator translator) { + public ApologizeService(Translator translator) { this(translator, "sorry"); } diff --git a/spring-core/src/main/java/com/baeldung/lombok/Fareweller.java b/spring-core/src/main/java/com/baeldung/lombok/FarewellService.java similarity index 79% rename from spring-core/src/main/java/com/baeldung/lombok/Fareweller.java rename to spring-core/src/main/java/com/baeldung/lombok/FarewellService.java index b10ebb72b9..4e8c4993cb 100644 --- a/spring-core/src/main/java/com/baeldung/lombok/Fareweller.java +++ b/spring-core/src/main/java/com/baeldung/lombok/FarewellService.java @@ -4,11 +4,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class Fareweller { +public class FarewellService { private final Translator translator; - public Fareweller(Translator translator) { + public FarewellService(Translator translator) { this.translator = translator; } diff --git a/spring-core/src/main/java/com/baeldung/lombok/Greeter.java b/spring-core/src/main/java/com/baeldung/lombok/GreetingService.java similarity index 90% rename from spring-core/src/main/java/com/baeldung/lombok/Greeter.java rename to spring-core/src/main/java/com/baeldung/lombok/GreetingService.java index ddbc024ce7..0e03e177e1 100644 --- a/spring-core/src/main/java/com/baeldung/lombok/Greeter.java +++ b/spring-core/src/main/java/com/baeldung/lombok/GreetingService.java @@ -4,7 +4,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class Greeter { +public class GreetingService { @Autowired private Translator translator; diff --git a/spring-core/src/main/java/com/baeldung/lombok/Thanker.java b/spring-core/src/main/java/com/baeldung/lombok/ThankingService.java similarity index 76% rename from spring-core/src/main/java/com/baeldung/lombok/Thanker.java rename to spring-core/src/main/java/com/baeldung/lombok/ThankingService.java index 784100c258..f3bdf8bb7f 100644 --- a/spring-core/src/main/java/com/baeldung/lombok/Thanker.java +++ b/spring-core/src/main/java/com/baeldung/lombok/ThankingService.java @@ -1,12 +1,11 @@ package com.baeldung.lombok; import lombok.AllArgsConstructor; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @AllArgsConstructor -public class Thanker { +public class ThankingService { private final Translator translator; diff --git a/spring-core/src/test/java/com/baeldung/lombok/ApologizerAutowiringTest.java b/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringTest.java similarity index 84% rename from spring-core/src/test/java/com/baeldung/lombok/ApologizerAutowiringTest.java rename to spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringTest.java index 3e7c775f91..755fc5868b 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/ApologizerAutowiringTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceAutowiringTest.java @@ -14,12 +14,12 @@ import static org.mockito.Mockito.when; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = TestConfig.class) -public class ApologizerAutowiringTest { +public class ApologizeServiceAutowiringTest { private final static String TRANSLATED = "TRANSLATED"; @Autowired - private Apologizer apologizer; + private ApologizeService apologizeService; @Autowired private Translator translator; @@ -27,7 +27,7 @@ public class ApologizerAutowiringTest { @Test public void apologizeWithTranslatedMessage() { when(translator.translate("sorry")).thenReturn(TRANSLATED); - assertEquals(TRANSLATED, apologizer.apologize()); + assertEquals(TRANSLATED, apologizeService.apologize()); } } \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/lombok/ApologizerTest.java b/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceTest.java similarity index 72% rename from spring-core/src/test/java/com/baeldung/lombok/ApologizerTest.java rename to spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceTest.java index 28bd08c89f..ab545e7adf 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/ApologizerTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/ApologizeServiceTest.java @@ -6,7 +6,7 @@ import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ApologizerTest { +public class ApologizeServiceTest { private final static String MESSAGE = "MESSAGE"; private final static String TRANSLATED = "TRANSLATED"; @@ -14,8 +14,8 @@ public class ApologizerTest { @Test public void apologizeWithCustomTranslatedMessage() { Translator translator = mock(Translator.class); - Apologizer apologizer = new Apologizer(translator, MESSAGE); + ApologizeService apologizeService = new ApologizeService(translator, MESSAGE); when(translator.translate(MESSAGE)).thenReturn(TRANSLATED); - assertEquals(TRANSLATED, apologizer.apologize()); + assertEquals(TRANSLATED, apologizeService.apologize()); } } diff --git a/spring-core/src/test/java/com/baeldung/lombok/FarewellAutowiringTest.java b/spring-core/src/test/java/com/baeldung/lombok/FarewellAutowiringTest.java index d55d44fb3e..592e309236 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/FarewellAutowiringTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/FarewellAutowiringTest.java @@ -17,7 +17,7 @@ import static org.mockito.Mockito.when; public class FarewellAutowiringTest { @Autowired - private Fareweller fareweller; + private FarewellService farewellService; @Autowired private Translator translator; @@ -26,6 +26,6 @@ public class FarewellAutowiringTest { public void sayByeWithTranslatedMessage() { String translated = "translated"; when(translator.translate("bye")).thenReturn(translated); - assertEquals(translated, fareweller.farewell()); + assertEquals(translated, farewellService.farewell()); } } diff --git a/spring-core/src/test/java/com/baeldung/lombok/FarewellerTest.java b/spring-core/src/test/java/com/baeldung/lombok/FarewellServiceTest.java similarity index 70% rename from spring-core/src/test/java/com/baeldung/lombok/FarewellerTest.java rename to spring-core/src/test/java/com/baeldung/lombok/FarewellServiceTest.java index a02ad1d8ac..9ad593a489 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/FarewellerTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/FarewellServiceTest.java @@ -6,7 +6,7 @@ import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class FarewellerTest { +public class FarewellServiceTest { private final static String TRANSLATED = "TRANSLATED"; @@ -14,7 +14,7 @@ public class FarewellerTest { public void sayByeWithTranslatedMessage() { Translator translator = mock(Translator.class); when(translator.translate("bye")).thenReturn(TRANSLATED); - Fareweller fareweller = new Fareweller(translator); - assertEquals(TRANSLATED, fareweller.farewell()); + FarewellService farewellService = new FarewellService(translator); + assertEquals(TRANSLATED, farewellService.farewell()); } } \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/lombok/GreeterTest.java b/spring-core/src/test/java/com/baeldung/lombok/GreetingServiceTest.java similarity index 79% rename from spring-core/src/test/java/com/baeldung/lombok/GreeterTest.java rename to spring-core/src/test/java/com/baeldung/lombok/GreetingServiceTest.java index 0f66eaf301..d0207d681b 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/GreeterTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/GreetingServiceTest.java @@ -14,10 +14,10 @@ import static org.mockito.Mockito.when; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = TestConfig.class) -public class GreeterTest { +public class GreetingServiceTest { @Autowired - private Greeter greeter; + private GreetingService greetingService; @Autowired private Translator translator; @@ -26,12 +26,12 @@ public class GreeterTest { public void greetWithTranslatedMessage() { String translated = "translated"; when(translator.translate("hello")).thenReturn(translated); - assertEquals(translated, greeter.greet()); + assertEquals(translated, greetingService.greet()); } @Test(expected = NullPointerException.class) public void throwWhenInstantiated() { - Greeter greeter = new Greeter(); - greeter.greet(); + GreetingService greetingService = new GreetingService(); + greetingService.greet(); } } \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/lombok/ThankerAutowiringTest.java b/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringTest.java similarity index 84% rename from spring-core/src/test/java/com/baeldung/lombok/ThankerAutowiringTest.java rename to spring-core/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringTest.java index 59aded5831..b2a338b18f 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/ThankerAutowiringTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceAutowiringTest.java @@ -14,10 +14,10 @@ import static org.mockito.Mockito.when; @ContextConfiguration( loader = AnnotationConfigContextLoader.class, classes = TestConfig.class) -public class ThankerAutowiringTest { +public class ThankingServiceAutowiringTest { @Autowired - private Thanker thanker; + private ThankingService thankingService; @Autowired private Translator translator; @@ -26,6 +26,6 @@ public class ThankerAutowiringTest { public void thankWithTranslatedMessage() { String translated = "translated"; when(translator.translate("thank you")).thenReturn(translated); - assertEquals(translated, thanker.thank()); + assertEquals(translated, thankingService.thank()); } } \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/lombok/ThankerTest.java b/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceTest.java similarity index 71% rename from spring-core/src/test/java/com/baeldung/lombok/ThankerTest.java rename to spring-core/src/test/java/com/baeldung/lombok/ThankingServiceTest.java index 466762fa50..7dc663622b 100644 --- a/spring-core/src/test/java/com/baeldung/lombok/ThankerTest.java +++ b/spring-core/src/test/java/com/baeldung/lombok/ThankingServiceTest.java @@ -6,7 +6,7 @@ import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ThankerTest { +public class ThankingServiceTest { private final static String TRANSLATED = "TRANSLATED"; @@ -14,7 +14,7 @@ public class ThankerTest { public void thankWithTranslatedMessage() { Translator translator = mock(Translator.class); when(translator.translate("thank you")).thenReturn(TRANSLATED); - Thanker thanker = new Thanker(translator); - assertEquals(TRANSLATED, thanker.thank()); + ThankingService thankingService = new ThankingService(translator); + assertEquals(TRANSLATED, thankingService.thank()); } } \ No newline at end of file diff --git a/spring-hibernate4/.gitignore b/spring-hibernate4/.gitignore index 83c05e60c8..478cca6dac 100644 --- a/spring-hibernate4/.gitignore +++ b/spring-hibernate4/.gitignore @@ -10,4 +10,5 @@ # Packaged files # *.jar *.war -*.ear \ No newline at end of file +*.ear +/target/ diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java index ba54985853..e522dab48d 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java @@ -7,32 +7,31 @@ import org.hibernate.service.ServiceRegistry; public class HibernateAnnotationUtil { - private static SessionFactory sessionFactory; - - private static SessionFactory buildSessionFactory() { + private static SessionFactory sessionFactory; + + private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate-annotation.cfg.xml - Configuration configuration = new Configuration(); - configuration.configure("hibernate-annotation.cfg.xml"); - System.out.println("Hibernate Annotation Configuration loaded"); - - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); - System.out.println("Hibernate Annotation serviceRegistry created"); - - SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); - - + Configuration configuration = new Configuration(); + configuration.configure("hibernate-annotation.cfg.xml"); + System.out.println("Hibernate Annotation Configuration loaded"); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); + System.out.println("Hibernate Annotation serviceRegistry created"); + + SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); + return sessionFactory; - } - catch (Throwable ex) { + } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } } - - public static SessionFactory getSessionFactory() { - if(sessionFactory == null) sessionFactory = buildSessionFactory(); + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) + sessionFactory = buildSessionFactory(); return sessionFactory; } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java index d5c41bcfab..63b6450bf4 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java @@ -13,48 +13,49 @@ import com.baeldung.hibernate.oneToMany.model.Items; public class HibernateOneToManyAnnotationMain { - public static void main(String[] args) { + public static void main(String[] args) { - Cart cart = new Cart(); - cart.setName("MyCart"); - - Items item1 = new Items("I10", 10, 1, cart); - Items item2 = new Items("I20", 20, 2, cart); - Set itemsSet = new HashSet(); - itemsSet.add(item1); itemsSet.add(item2); - - cart.setItems(itemsSet); - cart.setTotal(10*1 + 20*2); - - SessionFactory sessionFactory = null; - Session session = null; - Transaction tx = null; - try{ - //Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - System.out.println("Session created"); - //start transaction - tx = session.beginTransaction(); - //Save the Model object - session.save(cart); - session.save(item1); - session.save(item2); - //Commit transaction - tx.commit(); - System.out.println("Cart ID="+cart.getId()); - System.out.println("item1 ID="+item1.getId()+", Foreign Key Cart ID="+item1.getCart().getId()); - System.out.println("item2 ID="+item2.getId()+", Foreign Key Cart ID="+item1.getCart().getId()); - - }catch(Exception e){ - System.out.println("Exception occured. "+e.getMessage()); - e.printStackTrace(); - }finally{ - if(!sessionFactory.isClosed()){ - System.out.println("Closing SessionFactory"); - sessionFactory.close(); - } - } - } + Cart cart = new Cart(); + cart.setName("MyCart"); + + Items item1 = new Items("I10", 10, 1, cart); + Items item2 = new Items("I20", 20, 2, cart); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + itemsSet.add(item2); + + cart.setItems(itemsSet); + cart.setTotal(10 * 1 + 20 * 2); + + SessionFactory sessionFactory = null; + Session session = null; + Transaction tx = null; + try { + // Get Session + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + session = sessionFactory.getCurrentSession(); + System.out.println("Session created"); + // start transaction + tx = session.beginTransaction(); + // Save the Model object + session.save(cart); + session.save(item1); + session.save(item2); + // Commit transaction + tx.commit(); + System.out.println("Cart ID=" + cart.getId()); + System.out.println("item1 ID=" + item1.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); + System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); + + } catch (Exception e) { + System.out.println("Exception occured. " + e.getMessage()); + e.printStackTrace(); + } finally { + if (!sessionFactory.isClosed()) { + System.out.println("Closing SessionFactory"); + sessionFactory.close(); + } + } + } } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java index fdbfda2279..61a32ba43f 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java @@ -11,46 +11,53 @@ import javax.persistence.OneToMany; import javax.persistence.Table; @Entity -@Table(name="CART") +@Table(name = "CART") public class Cart { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="cart_id") - private long id; - - @Column(name="total") - private double total; - - @Column(name="name") - private String name; - - @OneToMany(mappedBy="cart") - private Set items; - - public long getId() { - return id; - } - public void setId(long id) { - this.id = id; - } - public double getTotal() { - return total; - } - public void setTotal(double total) { - this.total = total; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public Set getItems() { - return items; - } - public void setItems(Set items) { - this.items = items; - } - + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "cart_id") + private long id; + + @Column(name = "total") + private double total; + + @Column(name = "name") + private String name; + + @OneToMany(mappedBy = "cart") + private Set items; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getTotal() { + return total; + } + + public void setTotal(double total) { + this.total = total; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Set getItems() { + return items; + } + + public void setItems(Set items) { + this.items = items; + } + } diff --git a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java index 630bf0a12e..40ee6fdea1 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java +++ b/spring-hibernate4/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java @@ -10,65 +10,76 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity -@Table(name="ITEMS") +@Table(name = "ITEMS") public class Items { - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") - private long id; - - @Column(name="item_id") - private String itemId; - - @Column(name="item_total") - private double itemTotal; - - @Column(name="quantity") - private int quantity; - - @ManyToOne - @JoinColumn(name="cart_id", nullable=false) - private Cart cart; - - //Hibernate requires no-args constructor - public Items(){} - - public Items(String itemId, double total, int qty, Cart c){ - this.itemId=itemId; - this.itemTotal=total; - this.quantity=qty; - this.cart=c; - } - public String getItemId() { - return itemId; - } - public void setItemId(String itemId) { - this.itemId = itemId; - } - public double getItemTotal() { - return itemTotal; - } - public void setItemTotal(double itemTotal) { - this.itemTotal = itemTotal; - } - public int getQuantity() { - return quantity; - } - public void setQuantity(int quantity) { - this.quantity = quantity; - } - public Cart getCart() { - return cart; - } - public void setCart(Cart cart) { - this.cart = cart; - } - public long getId() { - return id; - } - public void setId(long id) { - this.id = id; - } - + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "item_id") + private String itemId; + + @Column(name = "item_total") + private double itemTotal; + + @Column(name = "quantity") + private int quantity; + + @ManyToOne + @JoinColumn(name = "cart_id", nullable = false) + private Cart cart; + + // Hibernate requires no-args constructor + public Items() { + } + + public Items(String itemId, double total, int qty, Cart c) { + this.itemId = itemId; + this.itemTotal = total; + this.quantity = qty; + this.cart = c; + } + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public double getItemTotal() { + return itemTotal; + } + + public void setItemTotal(double itemTotal) { + this.itemTotal = itemTotal; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public Cart getCart() { + return cart; + } + + public void setCart(Cart cart) { + this.cart = cart; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + } diff --git a/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainTest.java b/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainTest.java index 539298ae1e..688329e329 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainTest.java @@ -1,89 +1,97 @@ - package com.baeldung.hibernate.oneToMany.main; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; -import com.baeldung.hibernate.oneToMany.model.Cart; -import com.baeldung.hibernate.oneToMany.model.Items; import java.util.HashSet; import java.util.Set; -import static org.hamcrest.Matchers.hasSize; + import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.dialect.HSQLDialect; import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import static org.junit.Assert.*; - +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Items; public class HibernateOneToManyAnnotationMainTest { - - private static SessionFactory sessionFactory; - private Session session; - - public HibernateOneToManyAnnotationMainTest() { - } - - - @BeforeClass - public static void beforeTests() { - Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update"); - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); - sessionFactory = configuration.buildSessionFactory(serviceRegistry); - } - - @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); - - } - - + private static SessionFactory sessionFactory; + + private Session session; + + public HibernateOneToManyAnnotationMainTest() { + } + + @BeforeClass + public static void beforeTests() { + Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class) + .setProperty("hibernate.dialect", HSQLDialect.class.getName()) + .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test") + .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "") + .setProperty("hibernate.hbm2ddl.auto", "update"); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(configuration.getProperties()).build(); + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenSession_checkIfDatabaseIsEmpty() { + Cart cart = (Cart) session.get(Cart.class, new Long(1)); + assertNull(cart); + + } + + @Test + public void givenSession_checkIfDatabaseIsPopulated_afterCommit() { + Cart cart = new Cart(); + Set 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 itemsSet = new HashSet(); + itemsSet.add(item1); + assertNotNull(itemsSet); + cart.setItems(itemsSet); + assertNotNull(cart); + session.persist(cart); + session.getTransaction().commit(); + session.close(); + + session = sessionFactory.openSession(); + session.beginTransaction(); + cart = (Cart) session.get(Cart.class, new Long(1)); + assertNotNull(cart); + } + + @After + public void tearDown() { + session.getTransaction().commit(); + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } - @Test - public void testAddItemsToCart() { - Cart cart = new Cart(); - Set cartItems = new HashSet<>(); - cartItems = cart.getItems(); - Assert.assertNull(cartItems); - Items item1 = new Items("I10", 10, 1, cart); - assertNotNull(item1); - Set itemsSet = new HashSet(); - cart.setItems(itemsSet); - assertNotNull(cart); - System.out.println("Items added to cart"); - - } - - @Test - public void testSaveCart(){ - Cart cart = new Cart(); - Set 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 itemsSet = new HashSet(); - itemsSet.add(item1); - assertNotNull(itemsSet); - cart.setItems(itemsSet); - assertNotNull(cart); - session.persist(cart); - session.getTransaction().commit(); - session.close(); - - } - - } diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 293850d41e..41ebb9a6b5 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -9,7 +9,7 @@ war - 2.25 + 2.25.1 1.7.22 1.1.8 4.12 diff --git a/spring-jersey/src/main/java/com/baeldung/client/rest/RestClient.java b/spring-jersey/src/main/java/com/baeldung/client/rest/RestClient.java index 0e45b68b14..34f7d45601 100644 --- a/spring-jersey/src/main/java/com/baeldung/client/rest/RestClient.java +++ b/spring-jersey/src/main/java/com/baeldung/client/rest/RestClient.java @@ -18,7 +18,7 @@ public class RestClient { } public Employee getJsonEmployee(int id) { - return client.target(REST_URI).path(new Integer(id).toString()).request(MediaType.APPLICATION_JSON).get(Employee.class); + return client.target(REST_URI).path(String.valueOf(id)).request(MediaType.APPLICATION_JSON).get(Employee.class); } public Response createXmlEmployee(Employee emp) { @@ -26,6 +26,6 @@ public class RestClient { } public Employee getXmlEmployee(int id) { - return client.target(REST_URI).path(new Integer(id).toString()).request(MediaType.APPLICATION_XML).get(Employee.class); + return client.target(REST_URI).path(String.valueOf(id)).request(MediaType.APPLICATION_XML).get(Employee.class); } } diff --git a/spring-mobile/src/main/java/com/baeldung/Application.java b/spring-mobile/src/main/java/com/baeldung/Application.java index d384ab09b3..7275477b8d 100644 --- a/spring-mobile/src/main/java/com/baeldung/Application.java +++ b/spring-mobile/src/main/java/com/baeldung/Application.java @@ -6,9 +6,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + + } } diff --git a/spring-mvc-forms/pom.xml b/spring-mvc-forms/pom.xml index 31a0c38791..f17d695c35 100644 --- a/spring-mvc-forms/pom.xml +++ b/spring-mvc-forms/pom.xml @@ -46,6 +46,23 @@ commons-fileupload ${fileupload.version} + + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} + + @@ -98,6 +115,7 @@ 5.3.3.Final enter-location-of-server 1.3.2 + 4.2.1.RELEASE diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/SecurityConfig.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/SecurityConfig.java new file mode 100644 index 0000000000..e35844138d --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/SecurityConfig.java @@ -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(); + } + } + +} diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java index c602ea6454..fdc155e101 100644 --- a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/configuration/WebInitializer.java @@ -3,6 +3,7 @@ package com.baeldung.springmvcforms.configuration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.ServletContext; @@ -24,6 +25,9 @@ public class WebInitializer implements WebApplicationInitializer { servlet.setLoadOnStartup(1); servlet.addMapping("/"); + + container.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain")) + .addMappingForUrlPatterns(null, false, "/*"); } // @Override // public void onStartup(ServletContext container) { diff --git a/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/UsersController.java b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/UsersController.java new file mode 100644 index 0000000000..c0858d427f --- /dev/null +++ b/spring-mvc-forms/src/main/java/com/baeldung/springmvcforms/controller/UsersController.java @@ -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"; + } +} diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/403.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/403.jsp new file mode 100644 index 0000000000..e665793e10 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/403.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + + + + +Your do not have permission to view this page. + + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/adminPage.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/adminPage.jsp new file mode 100644 index 0000000000..a210b690b0 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/adminPage.jsp @@ -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" %> + + + + +Insert title here + + +Welcome admin! Logout + +

+Back to links + + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/loginAdmin.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/loginAdmin.jsp new file mode 100644 index 0000000000..a6b2ee7914 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/loginAdmin.jsp @@ -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"%> + + + + +Insert title here + + + +

Admin login page

+
+ + + + + + + + + + + + + +
User:
Password:
+ +
+ + <% + if (request.getParameter("error") != null) { + out.println("Login failed!"); + } + %> + + + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/loginUser.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/loginUser.jsp new file mode 100644 index 0000000000..e65c11edaf --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/loginUser.jsp @@ -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"%> + + + + +Login + + + +

User login page

+ +
+ + + + + + + + + + + + +
User:
Password:
+ +
+ <% + if (request.getParameter("error") != null) { + out.println("Login failed!"); + } + %> + + + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/protectedLinks.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/protectedLinks.jsp new file mode 100644 index 0000000000..b8453903ba --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/protectedLinks.jsp @@ -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" %> + + + + +Insert title here + + + +">User page +
+">Admin page + + \ No newline at end of file diff --git a/spring-mvc-forms/src/main/webapp/WEB-INF/views/userPage.jsp b/spring-mvc-forms/src/main/webapp/WEB-INF/views/userPage.jsp new file mode 100644 index 0000000000..4c1bd47502 --- /dev/null +++ b/spring-mvc-forms/src/main/webapp/WEB-INF/views/userPage.jsp @@ -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" %> + + + + +Insert title here + + +Welcome user! Logout +

+Back to links + + \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java b/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java index eb65987e8b..d0e33bf471 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java +++ b/spring-mvc-java/src/main/java/com/baeldung/excel/JExcelHelper.java @@ -1,22 +1,24 @@ package com.baeldung.excel; -import jxl.*; -import java.util.Map; -import java.util.HashMap; -import java.util.ArrayList; +import jxl.Sheet; +import jxl.Workbook; +import jxl.format.Colour; import jxl.read.biff.BiffException; -import java.io.File; -import java.io.IOException; -import org.springframework.stereotype.Service; import jxl.write.*; import jxl.write.Number; -import jxl.format.Colour; +import org.springframework.stereotype.Service; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; @Service public class JExcelHelper { public Map> readJExcel(String fileLocation) throws IOException, BiffException { - Map> data = new HashMap>(); + Map> data = new HashMap<>(); Workbook workbook = Workbook.getWorkbook(new File(fileLocation)); Sheet sheet = workbook.getSheet(0); @@ -24,7 +26,7 @@ public class JExcelHelper { int columns = sheet.getColumns(); for (int i = 0; i < rows; i++) { - data.put(i, new ArrayList()); + data.put(i, new ArrayList<>()); for (int j = 0; j < columns; j++) { data.get(i).add(sheet.getCell(j, i).getContents()); } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java new file mode 100644 index 0000000000..5d4cbe9d78 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/RequestMappingShortcutsController.java @@ -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 get() { + return new ResponseEntity("GET Response", HttpStatus.OK); + } + + @GetMapping("/get/{id}") + public @ResponseBody ResponseEntity getById(@PathVariable String id) { + return new ResponseEntity("GET Response : " + id, HttpStatus.OK); + } + + @PostMapping("/post") + public @ResponseBody ResponseEntity post() { + return new ResponseEntity("POST Response", HttpStatus.OK); + } + + @PutMapping("/put") + public @ResponseBody ResponseEntity put() { + return new ResponseEntity("PUT Response", HttpStatus.OK); + } + + @DeleteMapping("/delete") + public @ResponseBody ResponseEntity delete() { + return new ResponseEntity("DELETE Response", HttpStatus.OK); + } + + @PatchMapping("/patch") + public @ResponseBody ResponseEntity patch() { + return new ResponseEntity("PATCH Response", HttpStatus.OK); + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java similarity index 96% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java index f58e5cb0a1..f2c2c05f29 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/BeanNameMappingConfigIntegrationTest.java @@ -22,7 +22,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = BeanNameUrlHandlerMappingConfig.class) -public class BeanNameMappingConfigTest { +public class BeanNameMappingConfigIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java similarity index 96% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java index 6fdd168d0b..b84998470d 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java @@ -22,7 +22,7 @@ import com.baeldung.config.ControllerClassNameHandlerMappingConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = ControllerClassNameHandlerMappingConfig.class) -public class ControllerClassNameHandlerMappingTest { +public class ControllerClassNameHandlerMappingIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java similarity index 93% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java index 01be65b829..cb89c01fed 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingDefaultConfigIntegrationTest.java @@ -1,7 +1,10 @@ package com.baeldung.handlermappings; -import com.baeldung.config.HandlerMappingDefaultConfig; -import com.baeldung.config.HandlerMappingPrioritiesConfig; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,15 +17,12 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; +import com.baeldung.config.HandlerMappingDefaultConfig; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = HandlerMappingDefaultConfig.class) -public class HandlerMappingDefaultConfigTest { +public class HandlerMappingDefaultConfigIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java similarity index 96% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java index d6329ca6c1..55007aec28 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/HandlerMappingPriorityConfigIntegrationTest.java @@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = HandlerMappingPrioritiesConfig.class) -public class HandlerMappingPriorityConfigTest { +public class HandlerMappingPriorityConfigIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java similarity index 96% rename from spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigTest.java rename to spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java index 636339f152..ad35307330 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/SimpleUrlMappingConfigIntegrationTest.java @@ -21,7 +21,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = SimpleUrlHandlerMappingConfig.class) -public class SimpleUrlMappingConfigTest { +public class SimpleUrlMappingConfigIntegrationTest { @Autowired private WebApplicationContext webAppContext; diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsUnitTest.java new file mode 100644 index 0000000000..d02a7140b5 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/RequestMapingShortcutsUnitTest.java @@ -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()); + + } + +} diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml new file mode 100644 index 0000000000..c30b0cd1aa --- /dev/null +++ b/spring-security-cache-control/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + + com.baeldung + spring-security-cache-control + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 1.4.3.RELEASE + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.security + spring-security-core + + + org.springframework.security + spring-security-config + + + org.springframework.security + spring-security-web + + + org.springframework.boot + spring-boot-starter-test + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + + junit + junit + test + + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + + org.mockito + mockito-core + test + + + + org.springframework + spring-test + + + + com.jayway.restassured + rest-assured + ${rest-assured.version} + + + + + 3.1.0 + 2.9.0 + + + \ No newline at end of file diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/AppRunner.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/AppRunner.java new file mode 100644 index 0000000000..28ff90a570 --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/AppRunner.java @@ -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); + } +} \ No newline at end of file diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java new file mode 100644 index 0000000000..038df43165 --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/ResourceEndpoint.java @@ -0,0 +1,48 @@ +package com.baeldung.cachecontrol; + +import com.baeldung.cachecontrol.model.TimestampDto; +import com.baeldung.cachecontrol.model.UserDto; +import org.springframework.http.CacheControl; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.concurrent.TimeUnit; + +@Controller +public class ResourceEndpoint { + + @GetMapping(value = "/default/users/{name}") + public ResponseEntity getUserWithDefaultCaching(@PathVariable String name) { + return ResponseEntity.ok(new UserDto(name)); + } + + @GetMapping("/users/{name}") + public ResponseEntity getUser(@PathVariable String name) { + return ResponseEntity + .ok() + .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)) + .body(new UserDto(name)); + } + + @GetMapping("/timestamp") + public ResponseEntity getServerTimestamp() { + return ResponseEntity + .ok() + .cacheControl(CacheControl.noStore()) + .body(new TimestampDto(LocalDateTime + .now() + .toInstant(ZoneOffset.UTC) + .toEpochMilli())); + } + + @GetMapping("/private/users/{name}") + public ResponseEntity getUserNotCached(@PathVariable String name) { + return ResponseEntity + .ok() + .body(new UserDto(name)); + } +} diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java new file mode 100644 index 0000000000..b4127e9b71 --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/config/SpringSecurityConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.cachecontrol.config; + + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception {} +} diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/TimestampDto.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/TimestampDto.java new file mode 100644 index 0000000000..cb3befacac --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/TimestampDto.java @@ -0,0 +1,10 @@ +package com.baeldung.cachecontrol.model; + + +public class TimestampDto { + public final Long timestamp; + + public TimestampDto(Long timestamp) { + this.timestamp = timestamp; + } +} diff --git a/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/UserDto.java b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/UserDto.java new file mode 100644 index 0000000000..a41cb31d80 --- /dev/null +++ b/spring-security-cache-control/src/main/java/com/baeldung/cachecontrol/model/UserDto.java @@ -0,0 +1,11 @@ +package com.baeldung.cachecontrol.model; + + +public class UserDto { + public final String name; + + public UserDto(String name) { + this.name = name; + } + +} diff --git a/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java new file mode 100644 index 0000000000..6d532f98fc --- /dev/null +++ b/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointTest.java @@ -0,0 +1,72 @@ +package com.baeldung.cachecontrol; + +import com.jayway.restassured.http.ContentType; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static com.jayway.restassured.RestAssured.given; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AppRunner.class) +public class ResourceEndpointTest { + + @LocalServerPort + private int serverPort; + + @Test + public void whenGetRequestForUser_shouldRespondWithDefaultCacheHeaders() { + given() + .when() + .get(getBaseUrl() + "/default/users/Michael") + .then() + .headers("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate") + .header("Pragma", "no-cache"); + } + + @Test + public void whenGetRequestForUser_shouldRespondMaxAgeCacheControl() { + given() + .when() + .get(getBaseUrl() + "/users/Michael") + .then() + .header("Cache-Control", "max-age=60"); + } + + @Test + public void givenServiceEndpoint_whenGetRequestForUser_shouldResponseWithCacheControlMaxAge() { + given() + .when() + .get(getBaseUrl() + "/users/Michael") + .then() + .contentType(ContentType.JSON).and().statusCode(200).and() + .header("Cache-Control", "max-age=60"); + } + + @Test + public void givenServiceEndpoint_whenGetRequestForNotCacheableContent_shouldResponseWithCacheControlNoCache() { + given() + .when() + .get(getBaseUrl() + "/timestamp") + .then() + .contentType(ContentType.JSON).and().statusCode(200).and() + .header("Cache-Control", "no-store"); + } + + @Test + public void givenServiceEndpoint_whenGetRequestForPrivateUser_shouldResponseWithSecurityDefaultCacheControl() { + given() + .when() + .get(getBaseUrl() + "/private/users/Michael") + .then() + .contentType(ContentType.JSON).and().statusCode(200).and() + .header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); + } + + private String getBaseUrl() { + return String.format("http://localhost:%d", serverPort); + } + +} \ No newline at end of file diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index 7987eebb66..953cfd6b6b 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -342,8 +342,8 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.3.6.RELEASE + 4.2.1.RELEASE 5.2.5.Final @@ -351,7 +351,7 @@ 4.4.5 - 4.5.2 + 4.5.3 1.7.21 diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java new file mode 100644 index 0000000000..a2f51d343b --- /dev/null +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java @@ -0,0 +1,39 @@ +package org.baeldung.client; + +import java.net.URI; + +import org.apache.http.HttpHost; +import org.apache.http.client.AuthCache; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; +import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; + +public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpComponentsClientHttpRequestFactory { + + HttpHost host; + + public HttpComponentsClientHttpRequestFactoryBasicAuth(HttpHost host) { + super(); + this.host = host; + } + + protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { + return createHttpContext(); + } + + private HttpContext createHttpContext() { + + AuthCache authCache = new BasicAuthCache(); + + BasicScheme basicAuth = new BasicScheme(); + authCache.put(host, basicAuth); + + BasicHttpContext localcontext = new BasicHttpContext(); + localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); + return localcontext; + } +} \ No newline at end of file diff --git a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java index 0cec0dc5c3..5e15648e9b 100644 --- a/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java +++ b/spring-security-rest-basic-auth/src/main/java/org/baeldung/client/RestTemplateFactory.java @@ -1,15 +1,10 @@ package org.baeldung.client; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.HttpHost; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.http.client.ClientHttpRequestFactory; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.client.support.BasicAuthorizationInterceptor; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; @@ -40,16 +35,10 @@ public class RestTemplateFactory implements FactoryBean, Initializ @Override public void afterPropertiesSet() { - final int timeout = 5; - - final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); - - final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(new AuthScope("localhost", 8082, AuthScope.ANY_REALM), new UsernamePasswordCredentials("user1", "user1Pass")); - final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).setDefaultCredentialsProvider(credentialsProvider).build(); - - final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client); + HttpHost host = new HttpHost("localhost", 8082, "http"); + final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host); restTemplate = new RestTemplate(requestFactory); + restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user1", "user1Pass")); } } \ No newline at end of file