commit
6d9c24ad9e
17
.travis.yml
Normal file
17
.travis.yml
Normal file
@ -0,0 +1,17 @@
|
||||
language: java
|
||||
|
||||
install: travis_wait 40 mvn -q clean install -Dgib.enabled=true
|
||||
|
||||
jdk:
|
||||
- oraclejdk8
|
||||
|
||||
sudo: false
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- oracle-java8-installer
|
||||
|
||||
cache:
|
||||
directories:
|
||||
- .autoconf
|
||||
- $HOME/.m2
|
51
apache-bval/pom.xml
Normal file
51
apache-bval/pom.xml
Normal file
@ -0,0 +1,51 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>apache-bval</groupId>
|
||||
<artifactId>apache-bval</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.bval</groupId>
|
||||
<artifactId>bval-jsr</artifactId>
|
||||
<version>${bval.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>1.1.0.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.bval</groupId>
|
||||
<artifactId>bval-extras</artifactId>
|
||||
<version>${bval.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<properties>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<bval.version>1.1.2</bval.version>
|
||||
</properties>
|
||||
</project>
|
120
apache-bval/src/main/java/com/baeldung/model/User.java
Normal file
120
apache-bval/src/main/java/com/baeldung/model/User.java
Normal file
@ -0,0 +1,120 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
import org.apache.bval.constraints.Email;
|
||||
import org.apache.bval.constraints.NotEmpty;
|
||||
import org.apache.bval.extras.constraints.checkdigit.IBAN;
|
||||
import org.apache.bval.extras.constraints.creditcard.Visa;
|
||||
import org.apache.bval.extras.constraints.file.Directory;
|
||||
import org.apache.bval.extras.constraints.net.InetAddress;
|
||||
|
||||
import com.baeldung.validation.Password;
|
||||
|
||||
public class User {
|
||||
@NotNull
|
||||
@Email
|
||||
private String email;
|
||||
|
||||
@NotEmpty
|
||||
@Password
|
||||
private String password;
|
||||
|
||||
@Size(min = 1, max = 20)
|
||||
private String name;
|
||||
|
||||
@Min(18)
|
||||
private int age;
|
||||
|
||||
@Visa
|
||||
private String cardNumber = "";
|
||||
|
||||
@IBAN
|
||||
private String iban = "";
|
||||
|
||||
@InetAddress
|
||||
private String website = "";
|
||||
|
||||
@Directory
|
||||
private File mainDirectory=new File(".");
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String email, String password, String name, int age) {
|
||||
super();
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getCardNumber() {
|
||||
return cardNumber;
|
||||
}
|
||||
|
||||
public void setCardNumber(String cardNumber) {
|
||||
this.cardNumber = cardNumber;
|
||||
}
|
||||
|
||||
public String getIban() {
|
||||
return iban;
|
||||
}
|
||||
|
||||
public void setIban(String iban) {
|
||||
this.iban = iban;
|
||||
}
|
||||
|
||||
public String getWebsite() {
|
||||
return website;
|
||||
}
|
||||
|
||||
public void setWebsite(String website) {
|
||||
this.website = website;
|
||||
}
|
||||
|
||||
public File getMainDirectory() {
|
||||
return mainDirectory;
|
||||
}
|
||||
|
||||
public void setMainDirectory(File mainDirectory) {
|
||||
this.mainDirectory = mainDirectory;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.validation;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.Payload;
|
||||
|
||||
import static java.lang.annotation.ElementType.*;
|
||||
|
||||
@Constraint(validatedBy = { PasswordValidator.class })
|
||||
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface Password {
|
||||
String message() default "Invalid password";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
|
||||
int length() default 6;
|
||||
|
||||
int nonAlpha() default 1;
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.validation;
|
||||
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
|
||||
public class PasswordValidator implements ConstraintValidator<Password, String> {
|
||||
|
||||
private int length;
|
||||
private int nonAlpha;
|
||||
|
||||
@Override
|
||||
public void initialize(Password password) {
|
||||
this.length = password.length();
|
||||
this.nonAlpha = password.nonAlpha();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(String value, ConstraintValidatorContext context) {
|
||||
if (value.length() < length) {
|
||||
return false;
|
||||
}
|
||||
int nonAlphaNr = 0;
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
if (!Character.isLetterOrDigit(value.charAt(i))) {
|
||||
nonAlphaNr++;
|
||||
}
|
||||
}
|
||||
if (nonAlphaNr < nonAlpha) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,97 @@
|
||||
package com.baeldung.validation;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import javax.validation.ValidatorFactory;
|
||||
|
||||
import org.apache.bval.jsr.ApacheValidationProvider;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import com.baeldung.model.User;
|
||||
|
||||
public class ValidationTest {
|
||||
private static ValidatorFactory validatorFactory;
|
||||
private static Validator validator;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
validatorFactory = Validation.byProvider(ApacheValidationProvider.class)
|
||||
.configure()
|
||||
.buildValidatorFactory();
|
||||
validator = validatorFactory.getValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUser_whenValidate_thenValidationViolations() {
|
||||
User user = new User("ana@yahoo.com", "pass", "nameTooLong_______________", 15);
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertTrue("no violations", violations.size() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidAge_whenValidateProperty_thenConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 12);
|
||||
|
||||
Set<ConstraintViolation<User>> propertyViolations = validator.validateProperty(user, "age");
|
||||
assertEquals("size is not 1", 1, propertyViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidAge_whenValidateValue_thenNoConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 18);
|
||||
|
||||
Set<ConstraintViolation<User>> valueViolations = validator.validateValue(User.class, "age", 20);
|
||||
assertEquals("size is not 0", 0, valueViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidateNonJSR_thenCorrect() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 20);
|
||||
user.setCardNumber("1234");
|
||||
user.setIban("1234");
|
||||
user.setWebsite("10.0.2.50");
|
||||
user.setMainDirectory(new File("."));
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "iban");
|
||||
assertEquals("size is not 1", 1, violations.size());
|
||||
|
||||
violations = validator.validateProperty(user, "website");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
|
||||
violations = validator.validateProperty(user, "mainDirectory");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidPassword_whenValidatePassword_thenConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "password", "Ana", 20);
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "password");
|
||||
assertEquals("message incorrect", "Invalid password", violations.iterator()
|
||||
.next()
|
||||
.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidPassword_whenValidatePassword_thenNoConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "password#", "Ana", 20);
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "password");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void close() {
|
||||
if (validatorFactory != null) {
|
||||
validatorFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,2 +1,3 @@
|
||||
### Relevant Articles:
|
||||
- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi)
|
||||
- [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel)
|
||||
|
@ -9,6 +9,7 @@
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<poi.version>3.15</poi.version>
|
||||
<jexcel.version>1.0.6</jexcel.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
@ -37,5 +38,10 @@
|
||||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jxls</groupId>
|
||||
<artifactId>jxls-jexcel</artifactId>
|
||||
<version>${jexcel.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
@ -1,24 +1,21 @@
|
||||
package com.baeldung.excel;
|
||||
package com.baeldung.jexcel;
|
||||
|
||||
import jxl.Sheet;
|
||||
import jxl.Workbook;
|
||||
import jxl.format.Colour;
|
||||
import jxl.*;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import jxl.read.biff.BiffException;
|
||||
import jxl.write.*;
|
||||
import jxl.write.Number;
|
||||
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;
|
||||
import jxl.write.*;
|
||||
import jxl.write.Number;
|
||||
import jxl.format.Colour;
|
||||
|
||||
@Service
|
||||
public class JExcelHelper {
|
||||
|
||||
public Map<Integer, ArrayList<String>> readJExcel(String fileLocation) throws IOException, BiffException {
|
||||
Map<Integer, ArrayList<String>> data = new HashMap<>();
|
||||
public Map<Integer, List<String>> readJExcel(String fileLocation) throws IOException, BiffException {
|
||||
Map<Integer, List<String>> data = new HashMap<>();
|
||||
|
||||
Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
|
||||
Sheet sheet = workbook.getSheet(0);
|
||||
@ -26,7 +23,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<String>());
|
||||
for (int j = 0; j < columns; j++) {
|
||||
data.get(i).add(sheet.getCell(j, i).getContents());
|
||||
}
|
||||
@ -65,12 +62,7 @@ public class JExcelHelper {
|
||||
sheet.addCell(cellLabel);
|
||||
Number cellNumber = new Number(1, 2, 20, cellFormat);
|
||||
sheet.addCell(cellNumber);
|
||||
|
||||
cellLabel = new Label(0, 3, "Ana Johnson", cellFormat);
|
||||
sheet.addCell(cellLabel);
|
||||
cellNumber = new Number(1, 3, 30, cellFormat);
|
||||
sheet.addCell(cellNumber);
|
||||
|
||||
|
||||
workbook.write();
|
||||
} finally {
|
||||
if (workbook != null) {
|
@ -0,0 +1,128 @@
|
||||
package com.baeldung.poi.excel;
|
||||
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellType;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.IndexedColors;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFFont;
|
||||
import org.apache.poi.ss.usermodel.DateUtil;
|
||||
import org.apache.poi.ss.usermodel.FillPatternType;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ExcelPOIHelper {
|
||||
|
||||
public Map<Integer, List<String>> readExcel(String fileLocation) throws IOException {
|
||||
|
||||
Map<Integer, List<String>> data = new HashMap<>();
|
||||
FileInputStream file = new FileInputStream(new File(fileLocation));
|
||||
Workbook workbook = new XSSFWorkbook(file);
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
int i = 0;
|
||||
for (Row row : sheet) {
|
||||
data.put(i, new ArrayList<String>());
|
||||
for (Cell cell : row) {
|
||||
switch (cell.getCellTypeEnum()) {
|
||||
case STRING:
|
||||
data.get(i)
|
||||
.add(cell.getRichStringCellValue()
|
||||
.getString());
|
||||
break;
|
||||
case NUMERIC:
|
||||
if (DateUtil.isCellDateFormatted(cell)) {
|
||||
data.get(i)
|
||||
.add(cell.getDateCellValue() + "");
|
||||
} else {
|
||||
data.get(i)
|
||||
.add((int)cell.getNumericCellValue() + "");
|
||||
}
|
||||
break;
|
||||
case BOOLEAN:
|
||||
data.get(i)
|
||||
.add(cell.getBooleanCellValue() + "");
|
||||
break;
|
||||
case FORMULA:
|
||||
data.get(i)
|
||||
.add(cell.getCellFormula() + "");
|
||||
break;
|
||||
default:
|
||||
data.get(i)
|
||||
.add(" ");
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
if (workbook != null){
|
||||
workbook.close();
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
public void writeExcel() throws IOException {
|
||||
Workbook workbook = new XSSFWorkbook();
|
||||
|
||||
try {
|
||||
Sheet sheet = workbook.createSheet("Persons");
|
||||
sheet.setColumnWidth(0, 6000);
|
||||
sheet.setColumnWidth(1, 4000);
|
||||
|
||||
Row header = sheet.createRow(0);
|
||||
|
||||
CellStyle headerStyle = workbook.createCellStyle();
|
||||
|
||||
headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
|
||||
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
|
||||
XSSFFont font = ((XSSFWorkbook) workbook).createFont();
|
||||
font.setFontName("Arial");
|
||||
font.setFontHeightInPoints((short) 16);
|
||||
font.setBold(true);
|
||||
headerStyle.setFont(font);
|
||||
|
||||
Cell headerCell = header.createCell(0);
|
||||
headerCell.setCellValue("Name");
|
||||
headerCell.setCellStyle(headerStyle);
|
||||
|
||||
headerCell = header.createCell(1);
|
||||
headerCell.setCellValue("Age");
|
||||
headerCell.setCellStyle(headerStyle);
|
||||
|
||||
CellStyle style = workbook.createCellStyle();
|
||||
style.setWrapText(true);
|
||||
|
||||
Row row = sheet.createRow(2);
|
||||
Cell cell = row.createCell(0);
|
||||
cell.setCellValue("John Smith");
|
||||
cell.setCellStyle(style);
|
||||
|
||||
cell = row.createCell(1);
|
||||
cell.setCellValue(20);
|
||||
cell.setCellStyle(style);
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx";
|
||||
|
||||
FileOutputStream outputStream = new FileOutputStream(fileLocation);
|
||||
workbook.write(outputStream);
|
||||
} finally {
|
||||
if (workbook != null) {
|
||||
|
||||
workbook.close();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
56
apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java
Normal file
56
apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java
Normal file
@ -0,0 +1,56 @@
|
||||
package com.baeldung.jexcel;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import jxl.read.biff.BiffException;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.jexcel.JExcelHelper;
|
||||
|
||||
import jxl.write.WriteException;
|
||||
import jxl.read.biff.BiffException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
|
||||
public class JExcelTest {
|
||||
|
||||
private JExcelHelper jExcelHelper;
|
||||
private static String FILE_NAME = "temp.xls";
|
||||
private String fileLocation;
|
||||
|
||||
@Before
|
||||
public void generateExcelFile() throws IOException, WriteException {
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
|
||||
|
||||
jExcelHelper = new JExcelHelper();
|
||||
jExcelHelper.writeJExcel();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingJExcelFile_thenCorrect() throws IOException, BiffException {
|
||||
Map<Integer, List<String>> data = jExcelHelper.readJExcel(fileLocation);
|
||||
|
||||
assertEquals("Name", data.get(0)
|
||||
.get(0));
|
||||
assertEquals("Age", data.get(0)
|
||||
.get(1));
|
||||
|
||||
assertEquals("John Smith", data.get(2)
|
||||
.get(0));
|
||||
assertEquals("20", data.get(2)
|
||||
.get(1));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.baeldung.poi.excel;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import jxl.read.biff.BiffException;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.poi.excel.ExcelPOIHelper;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
|
||||
public class ExcelTest {
|
||||
|
||||
private ExcelPOIHelper excelPOIHelper;
|
||||
private static String FILE_NAME = "temp.xlsx";
|
||||
private String fileLocation;
|
||||
|
||||
@Before
|
||||
public void generateExcelFile() throws IOException {
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
|
||||
|
||||
excelPOIHelper = new ExcelPOIHelper();
|
||||
excelPOIHelper.writeExcel();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingPOIExcelFile_thenCorrect() throws IOException {
|
||||
Map<Integer, List<String>> data = excelPOIHelper.readExcel(fileLocation);
|
||||
|
||||
assertEquals("Name", data.get(0)
|
||||
.get(0));
|
||||
assertEquals("Age", data.get(0)
|
||||
.get(1));
|
||||
|
||||
assertEquals("John Smith", data.get(1)
|
||||
.get(0));
|
||||
assertEquals("20", data.get(1)
|
||||
.get(1));
|
||||
}
|
||||
|
||||
}
|
BIN
apache-poi/temp.xls
Normal file
BIN
apache-poi/temp.xls
Normal file
Binary file not shown.
BIN
apache-poi/temp.xlsx
Normal file
BIN
apache-poi/temp.xlsx
Normal file
Binary file not shown.
101
apache-velocity/pom.xml
Normal file
101
apache-velocity/pom.xml
Normal file
@ -0,0 +1,101 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<artifactId>apache-velocity</artifactId>
|
||||
|
||||
<packaging>war</packaging>
|
||||
<name>apache-velocity</name>
|
||||
|
||||
<properties>
|
||||
<jdk.version>1.8</jdk.version>
|
||||
<jstl.version>1.2</jstl.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
<logback.version>1.0.13</logback.version>
|
||||
<jcl-over-slf4j.version>1.7.5</jcl-over-slf4j.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<org.apache.httpcomponents.version>4.5.2</org.apache.httpcomponents.version>
|
||||
<velocity-version>1.7</velocity-version>
|
||||
<velocity-tools-version>2.0</velocity-tools-version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.velocity</groupId>
|
||||
<artifactId>velocity</artifactId>
|
||||
<version>${velocity-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.velocity</groupId>
|
||||
<artifactId>velocity-tools</artifactId>
|
||||
<version>${velocity-tools-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${jcl-over-slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${org.apache.httpcomponents.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>apache-velocity</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${jdk.version}</source>
|
||||
<target>${jdk.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<systemPropertyVariables>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.apache.velocity.model;
|
||||
|
||||
public class Product {
|
||||
|
||||
private String name;
|
||||
private double price;
|
||||
|
||||
public Product(String name, double price) {
|
||||
this.name = name;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Product{" + "name='" + name + '\'' + ", price=" + price + '}';
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.apache.velocity.service;
|
||||
|
||||
import com.baeldung.apache.velocity.model.Product;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class ProductService {
|
||||
|
||||
Logger logger = LoggerFactory.getLogger(ProductService.class);
|
||||
|
||||
public List<Product> getProducts() {
|
||||
logger.debug("Product service returning list of products");
|
||||
|
||||
return Arrays.asList(new Product("Laptop", 31000.00), new Product("Mobile", 16000.00),
|
||||
new Product("Tablet", 15000.00), new Product("Camera", 23000.00));
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.apache.velocity.servlet;
|
||||
|
||||
import com.baeldung.apache.velocity.model.Product;
|
||||
import com.baeldung.apache.velocity.service.ProductService;
|
||||
import org.apache.velocity.Template;
|
||||
import org.apache.velocity.context.Context;
|
||||
import org.apache.velocity.tools.view.VelocityLayoutServlet;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.List;
|
||||
|
||||
public class LayoutServlet extends VelocityLayoutServlet {
|
||||
ProductService service = new ProductService();
|
||||
|
||||
@Override
|
||||
public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) {
|
||||
|
||||
Logger logger= LoggerFactory.getLogger(LayoutServlet.class);
|
||||
|
||||
List<Product> products = service.getProducts();
|
||||
|
||||
context.put("products", products);
|
||||
|
||||
Template template = null;
|
||||
|
||||
try {
|
||||
template = getTemplate("templates/layoutdemo.vm");
|
||||
|
||||
response.setHeader("Template Returned", "Success");
|
||||
} catch (Exception e) {
|
||||
logger.error("Error while reading the template ",e);
|
||||
}
|
||||
|
||||
return template;
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.baeldung.apache.velocity.servlet;
|
||||
|
||||
import com.baeldung.apache.velocity.model.Product;
|
||||
import com.baeldung.apache.velocity.service.ProductService;
|
||||
import org.apache.velocity.Template;
|
||||
import org.apache.velocity.context.Context;
|
||||
import org.apache.velocity.tools.view.VelocityViewServlet;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.List;
|
||||
|
||||
public class ProductServlet extends VelocityViewServlet {
|
||||
|
||||
ProductService service = new ProductService();
|
||||
|
||||
@Override
|
||||
public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) {
|
||||
|
||||
Logger logger= LoggerFactory.getLogger(ProductServlet.class);
|
||||
|
||||
List<Product> products = service.getProducts();
|
||||
|
||||
context.put("products", products);
|
||||
|
||||
Template template = null;
|
||||
|
||||
try {
|
||||
template = getTemplate("templates/index.vm");
|
||||
response.setHeader("Template Returned", "Success");
|
||||
} catch (Exception e) {
|
||||
logger.error("Error while reading the template ", e);
|
||||
}
|
||||
|
||||
return template;
|
||||
|
||||
}
|
||||
}
|
23
apache-velocity/src/main/resources/logback.xml
Normal file
23
apache-velocity/src/main/resources/logback.xml
Normal file
@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||
|
||||
<Pattern>
|
||||
%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
|
||||
</Pattern>
|
||||
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<logger name="com.baeldung.apache.velocity.service" level="debug"
|
||||
additivity="false">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</logger>
|
||||
|
||||
<root level="error">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
@ -0,0 +1,4 @@
|
||||
resource.loader=webapp
|
||||
webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader
|
||||
webapp.resource.loader.path = .
|
||||
webapp.resource.loader.cache = true
|
49
apache-velocity/src/main/webapp/WEB-INF/web.xml
Normal file
49
apache-velocity/src/main/webapp/WEB-INF/web.xml
Normal file
@ -0,0 +1,49 @@
|
||||
<!DOCTYPE web-app PUBLIC
|
||||
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
|
||||
"http://java.sun.com/dtd/web-app_2_3.dtd" >
|
||||
|
||||
<web-app>
|
||||
<display-name>apache-velocity</display-name>
|
||||
<servlet>
|
||||
<servlet-name>ProductServlet</servlet-name>
|
||||
<servlet-class>com.baeldung.apache.velocity.servlet.ProductServlet</servlet-class>
|
||||
</servlet>
|
||||
|
||||
<servlet>
|
||||
<servlet-name>LayoutServlet</servlet-name>
|
||||
<servlet-class>com.baeldung.apache.velocity.servlet.LayoutServlet</servlet-class>
|
||||
</servlet>
|
||||
<servlet>
|
||||
<servlet-name>velocityLayout</servlet-name>
|
||||
<servlet-class>org.apache.velocity.tools.view.VelocityLayoutServlet</servlet-class>
|
||||
|
||||
<init-param>
|
||||
<param-name>org.apache.velocity.properties</param-name>
|
||||
<param-value>/WEB-INF/velocity.properties</param-value>
|
||||
</init-param>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>ProductServlet</servlet-name>
|
||||
<url-pattern>/</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<servlet-mapping>
|
||||
<servlet-name>LayoutServlet</servlet-name>
|
||||
<url-pattern>/layout</url-pattern>
|
||||
</servlet-mapping>
|
||||
<servlet-mapping>
|
||||
<servlet-name>velocityLayout</servlet-name>
|
||||
<url-pattern>*.vm</url-pattern>
|
||||
</servlet-mapping>
|
||||
<!-- session timeout -->
|
||||
<session-config>
|
||||
<session-timeout>
|
||||
30
|
||||
</session-timeout>
|
||||
</session-config>
|
||||
|
||||
<!-- welcome file -->
|
||||
<welcome-file-list>
|
||||
<welcome-file>index.html</welcome-file>
|
||||
</welcome-file-list>
|
||||
</web-app>
|
4
apache-velocity/src/main/webapp/fragments/footer.vm
Normal file
4
apache-velocity/src/main/webapp/fragments/footer.vm
Normal file
@ -0,0 +1,4 @@
|
||||
<div
|
||||
style="background: #63B175; text-align: center; padding: 5px; margin-top: 10px;">
|
||||
@Copyright baeldung.com
|
||||
</div>
|
5
apache-velocity/src/main/webapp/fragments/header.vm
Normal file
5
apache-velocity/src/main/webapp/fragments/header.vm
Normal file
@ -0,0 +1,5 @@
|
||||
<div style="background: #63B175; height: 80px; padding: 5px;">
|
||||
<div style="float: left">
|
||||
<h1> Layout Demo Page</h1>
|
||||
</div>
|
||||
</div>
|
22
apache-velocity/src/main/webapp/layout/Default.vm
Normal file
22
apache-velocity/src/main/webapp/layout/Default.vm
Normal file
@ -0,0 +1,22 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Velocity</title>
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
#parse("/fragments/header.vm")
|
||||
</div>
|
||||
|
||||
|
||||
<div>
|
||||
|
||||
<!-- View index.vm is inserted here -->
|
||||
$screen_content
|
||||
|
||||
</div>
|
||||
|
||||
<div>
|
||||
#parse("/fragments/footer.vm")
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
63
apache-velocity/src/main/webapp/templates/index.vm
Normal file
63
apache-velocity/src/main/webapp/templates/index.vm
Normal file
@ -0,0 +1,63 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<TITLE>Online Electronic Store</TITLE>
|
||||
<style>
|
||||
body {background-color: powderblue;}
|
||||
h1 {color: blue;}
|
||||
p {color: red;}
|
||||
table.gridtable {
|
||||
font-family: verdana,arial,sans-serif;
|
||||
font-size:11px;
|
||||
color:#333333;
|
||||
border-width: 1px;
|
||||
border-color: #666666;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
table.gridtable th {
|
||||
border-width: 1px;
|
||||
padding: 8px;
|
||||
border-style: solid;
|
||||
border-color: #666666;
|
||||
background-color: #dedede;
|
||||
}
|
||||
table.gridtable td {
|
||||
border-width: 1px;
|
||||
padding: 8px;
|
||||
border-style: solid;
|
||||
border-color: #666666;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
</HEAD>
|
||||
<BODY>
|
||||
<CENTER>
|
||||
<h1>Today's Offers</h1>
|
||||
<BR/>
|
||||
<BR/>
|
||||
<h2>$products.size() Products on Sale!</h2>
|
||||
<BR/>
|
||||
We are proud to offer these fine products
|
||||
at these amazing prices.
|
||||
<BR/>
|
||||
<BR/>
|
||||
#set( $count = 1 )
|
||||
<TABLE class="gridtable">
|
||||
<TR>
|
||||
<TH>Serial #</TH><TH>Product Name</TH><TH>Price</TH>
|
||||
</TR>
|
||||
#foreach( $product in $products )
|
||||
<TR>
|
||||
<TD>$count)</TD>
|
||||
<TD>$product.getName()</TD>
|
||||
<TD>$product.getPrice()</TD>
|
||||
</TR>
|
||||
#set( $count = $count + 1 )
|
||||
#end
|
||||
</TABLE>
|
||||
<BR/>
|
||||
</CENTER>
|
||||
|
||||
</BODY>
|
||||
</HTML>
|
27
apache-velocity/src/main/webapp/templates/layoutdemo.vm
Normal file
27
apache-velocity/src/main/webapp/templates/layoutdemo.vm
Normal file
@ -0,0 +1,27 @@
|
||||
#set( $layout = "layout.vm" )
|
||||
<CENTER>
|
||||
<h1>Today's Offers</h1>
|
||||
<BR/>
|
||||
<BR/>
|
||||
<h2>$products.size() Products on Sale!</h2>
|
||||
<BR/>
|
||||
We are proud to offer these fine products
|
||||
at these amazing prices.
|
||||
<BR/>
|
||||
<BR/>
|
||||
#set( $count = 1 )
|
||||
<TABLE class="gridtable">
|
||||
<TR>
|
||||
<TH>Serial #</TH><TH>Product Name</TH><TH>Price</TH>
|
||||
</TR>
|
||||
#foreach( $product in $products )
|
||||
<TR>
|
||||
<TD>$count)</TD>
|
||||
<TD>$product.getName()</TD>
|
||||
<TD>$product.getPrice()</TD>
|
||||
</TR>
|
||||
#set( $count = $count + 1 )
|
||||
#end
|
||||
</TABLE>
|
||||
<BR/>
|
||||
</CENTER>
|
@ -0,0 +1,26 @@
|
||||
package com.baeldung.apache.velocity.servlet;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
||||
public class LayoutServletLiveTest {
|
||||
|
||||
@Test
|
||||
public void whenRequestUsingHttpClient_thenCorrectResponse() throws Exception {
|
||||
|
||||
HttpClient client = new DefaultHttpClient();
|
||||
HttpGet method= new HttpGet("http://localhost:8080/layout");
|
||||
|
||||
HttpResponse httpResponse = client.execute(method);
|
||||
|
||||
assertEquals("Success", httpResponse.getHeaders("Template Returned")[0].getValue());
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.apache.velocity.servlet;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ProductServletLiveTest {
|
||||
|
||||
@Test
|
||||
public void whenRequestUsingHttpClient_thenCorrectResponse() throws Exception {
|
||||
|
||||
HttpClient client = new DefaultHttpClient();
|
||||
HttpGet method= new HttpGet("http://localhost:8080/");
|
||||
|
||||
HttpResponse httpResponse = client.execute(method);
|
||||
|
||||
assertEquals("Success", httpResponse.getHeaders("Template Returned")[0].getValue());
|
||||
|
||||
}
|
||||
}
|
0
core-java/0.004102810554955205
Normal file
0
core-java/0.004102810554955205
Normal file
0
core-java/0.04832801936270381
Normal file
0
core-java/0.04832801936270381
Normal file
0
core-java/0.5633433244738808
Normal file
0
core-java/0.5633433244738808
Normal file
0
core-java/0.5967303215007616
Normal file
0
core-java/0.5967303215007616
Normal file
0
core-java/0.6256429734439612
Normal file
0
core-java/0.6256429734439612
Normal file
0
core-java/0.9252611327674576
Normal file
0
core-java/0.9252611327674576
Normal file
0
core-java/0.9799201796740292
Normal file
0
core-java/0.9799201796740292
Normal file
@ -57,3 +57,4 @@
|
||||
- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future)
|
||||
- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
|
||||
- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch)
|
||||
- [How to Design a Genetic Algorithm in Java](http://www.baeldung.com/java-genetic-algorithm)
|
||||
|
@ -1,5 +1,5 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java</artifactId>
|
||||
@ -9,7 +9,7 @@
|
||||
<name>core-java</name>
|
||||
|
||||
<dependencies>
|
||||
|
||||
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
@ -63,7 +63,6 @@
|
||||
<artifactId>grep4j</artifactId>
|
||||
<version>${grep4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- web -->
|
||||
|
||||
<!-- marshalling -->
|
||||
@ -154,6 +153,12 @@
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
@ -263,7 +268,8 @@
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
@ -371,6 +377,7 @@
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
<testng.version>6.10</testng.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
|
@ -24,7 +24,8 @@ public class RunAlgorithm {
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
case 3:
|
||||
SimpleGeneticAlgorithm.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
|
||||
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
|
||||
ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
|
@ -5,40 +5,40 @@ import lombok.Data;
|
||||
@Data
|
||||
public class Individual {
|
||||
|
||||
protected int defaultGeneLength = 64;
|
||||
private byte[] genes = new byte[defaultGeneLength];
|
||||
private int fitness = 0;
|
||||
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;
|
||||
}
|
||||
}
|
||||
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 byte getSingleGene(int index) {
|
||||
return genes[index];
|
||||
}
|
||||
|
||||
protected void setSingleGene(int index, byte value) {
|
||||
genes[index] = value;
|
||||
fitness = 0;
|
||||
}
|
||||
protected void setSingleGene(int index, byte value) {
|
||||
genes[index] = value;
|
||||
fitness = 0;
|
||||
}
|
||||
|
||||
public int getFitness() {
|
||||
if (fitness == 0) {
|
||||
fitness = SimpleGeneticAlgorithm.getFitness(this);
|
||||
}
|
||||
return fitness;
|
||||
}
|
||||
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;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
String geneString = "";
|
||||
for (int i = 0; i < genes.length; i++) {
|
||||
geneString += getSingleGene(i);
|
||||
}
|
||||
return geneString;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -8,33 +8,33 @@ import lombok.Data;
|
||||
@Data
|
||||
public class Population {
|
||||
|
||||
private List<Individual> individuals;
|
||||
private List<Individual> individuals;
|
||||
|
||||
public Population(int size, boolean createNew) {
|
||||
individuals = new ArrayList<>();
|
||||
if (createNew) {
|
||||
createNewPopulation(size);
|
||||
}
|
||||
}
|
||||
public Population(int size, boolean createNew) {
|
||||
individuals = new ArrayList<>();
|
||||
if (createNew) {
|
||||
createNewPopulation(size);
|
||||
}
|
||||
}
|
||||
|
||||
protected Individual getIndividual(int index) {
|
||||
return individuals.get(index);
|
||||
}
|
||||
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;
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
private void createNewPopulation(int size) {
|
||||
for (int i = 0; i < size; i++) {
|
||||
Individual newIndividual = new Individual();
|
||||
individuals.add(i, newIndividual);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -5,115 +5,113 @@ 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];
|
||||
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);
|
||||
public boolean runAlgorithm(int populationSize, String solution) {
|
||||
if (solution.length() != SimpleGeneticAlgorithm.solution.length) {
|
||||
throw new RuntimeException("The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes");
|
||||
}
|
||||
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;
|
||||
}
|
||||
int generationCount = 1;
|
||||
while (myPop.getFittest().getFitness() < getMaxFitness()) {
|
||||
System.out.println("Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness());
|
||||
myPop = 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);
|
||||
public 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;
|
||||
}
|
||||
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 < 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));
|
||||
}
|
||||
for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) {
|
||||
mutate(newPopulation.getIndividual(i));
|
||||
}
|
||||
|
||||
return newPopulation;
|
||||
}
|
||||
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 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 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;
|
||||
}
|
||||
private 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 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 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
protected void setSolution(String newSolution) {
|
||||
solution = new byte[newSolution.length()];
|
||||
for (int i = 0; i < newSolution.length(); i++) {
|
||||
String character = newSolution.substring(i, i + 1);
|
||||
if (character.contains("0") || character.contains("1")) {
|
||||
solution[i] = Byte.parseByte(character);
|
||||
} else {
|
||||
solution[i] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -15,6 +15,6 @@ public class SquareCalculator {
|
||||
return executor.submit(() -> {
|
||||
Thread.sleep(1000);
|
||||
return input * input;
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class Person {
|
||||
private String name;
|
||||
private Integer age;
|
||||
|
||||
public Person(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
public class BlogPost {
|
||||
private String title;
|
||||
private String author;
|
||||
private BlogPostType type;
|
||||
private int likes;
|
||||
|
||||
public BlogPost(String title, String author, BlogPostType type, int likes) {
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.type = type;
|
||||
this.likes = likes;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public BlogPostType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public int getLikes() {
|
||||
return likes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "BlogPost{" + "title='" + title + '\'' + ", type=" + type + ", likes=" + likes + '}';
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.java_8_features.groupingby;
|
||||
|
||||
public enum BlogPostType {
|
||||
NEWS, REVIEW, GUIDE
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.strategy;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class ChristmasDiscounter implements Discounter {
|
||||
|
||||
@Override
|
||||
public BigDecimal apply(BigDecimal amount) {
|
||||
return amount.multiply(BigDecimal.valueOf(0.9));
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.strategy;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
public interface Discounter extends UnaryOperator<BigDecimal> {
|
||||
|
||||
default Discounter combine(Discounter after) {
|
||||
return value -> after.apply(this.apply(value));
|
||||
}
|
||||
|
||||
static Discounter christmas() {
|
||||
return (amount) -> amount.multiply(BigDecimal.valueOf(0.9));
|
||||
}
|
||||
|
||||
static Discounter newYear() {
|
||||
return (amount) -> amount.multiply(BigDecimal.valueOf(0.8));
|
||||
}
|
||||
|
||||
static Discounter easter() {
|
||||
return (amount) -> amount.multiply(BigDecimal.valueOf(0.5));
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.strategy;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class EasterDiscounter implements Discounter {
|
||||
|
||||
@Override
|
||||
public BigDecimal apply(BigDecimal amount) {
|
||||
return amount.multiply(BigDecimal.valueOf(0.5));
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class InfiniteStreams {
|
||||
public static void main(String[] args) {
|
||||
doWhileOldWay();
|
||||
|
||||
doWhileStreamWay();
|
||||
|
||||
}
|
||||
|
||||
private static void doWhileOldWay() {
|
||||
|
||||
int i = 0;
|
||||
while (i < 10) {
|
||||
System.out.println(i);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
private static void doWhileStreamWay() {
|
||||
Stream<Integer> integers = Stream.iterate(0, i -> i + 1);
|
||||
integers.limit(10).forEach(System.out::println);
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class JoinerSplitter {
|
||||
|
||||
public static String join ( String[] arrayOfString ) {
|
||||
return Arrays.asList(arrayOfString)
|
||||
.stream()
|
||||
.map(x -> x)
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
public static String joinWithPrefixPostFix ( String[] arrayOfString ) {
|
||||
return Arrays.asList(arrayOfString)
|
||||
.stream()
|
||||
.map(x -> x)
|
||||
.collect(Collectors.joining(",","[","]"));
|
||||
}
|
||||
|
||||
public static List<String> split ( String str ) {
|
||||
return Stream.of(str.split(","))
|
||||
.map (elem -> new String(elem))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static List<Character> splitToListOfChar ( String str ) {
|
||||
return str.chars()
|
||||
.mapToObj(item -> (char) item)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
@ -8,55 +8,55 @@ public class CharArrayToStringUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenCallingStringConstructor_shouldConvertToString() {
|
||||
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
|
||||
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
|
||||
String result = new String(charArray);
|
||||
String expectedValue = "character";
|
||||
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString(){
|
||||
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
|
||||
public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString() {
|
||||
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
|
||||
String result = new String(charArray, 4, 3);
|
||||
String expectedValue = "act";
|
||||
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString(){
|
||||
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
|
||||
public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString() {
|
||||
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
|
||||
String result = String.copyValueOf(charArray);
|
||||
String expectedValue = "character";
|
||||
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString(){
|
||||
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
|
||||
public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString() {
|
||||
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
|
||||
String result = String.copyValueOf(charArray, 0, 4);
|
||||
String expectedValue = "char";
|
||||
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenCallingStringValueOf_shouldConvertToString(){
|
||||
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
|
||||
public void givenCharArray_whenCallingStringValueOf_shouldConvertToString() {
|
||||
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
|
||||
String result = String.valueOf(charArray);
|
||||
String expectedValue = "character";
|
||||
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString(){
|
||||
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
|
||||
public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString() {
|
||||
char[] charArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r' };
|
||||
String result = String.valueOf(charArray, 3, 4);
|
||||
String expectedValue = "ract";
|
||||
|
||||
|
||||
assertEquals(expectedValue, result);
|
||||
}
|
||||
}
|
||||
|
@ -6,15 +6,15 @@ import org.junit.Test;
|
||||
|
||||
public class StringToCharArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() {
|
||||
String givenString = "characters";
|
||||
@Test
|
||||
public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() {
|
||||
String givenString = "characters";
|
||||
|
||||
char[] result = givenString.toCharArray();
|
||||
char[] result = givenString.toCharArray();
|
||||
|
||||
char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' };
|
||||
char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' };
|
||||
|
||||
assertArrayEquals(expectedCharArray, result);
|
||||
}
|
||||
assertArrayEquals(expectedCharArray, result);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,16 +0,0 @@
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
|
||||
|
||||
public class BinaryGeneticAlgorithmTest {
|
||||
|
||||
@Test
|
||||
public void testGA() {
|
||||
Assert.assertTrue(SimpleGeneticAlgorithm.runAlgorithm(50,
|
||||
"1011000100000100010000100000100111001000000100000100000000001111"));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
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() {
|
||||
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
|
||||
Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"));
|
||||
}
|
||||
|
||||
}
|
@ -32,13 +32,14 @@ public class PriorityBlockingQueueUnitTest {
|
||||
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
|
||||
|
||||
final Thread thread = new Thread(() -> {
|
||||
System.out.println("Polling...");
|
||||
while (true) {
|
||||
try {
|
||||
Integer poll = queue.take();
|
||||
System.out.println("Polled: " + poll);
|
||||
} catch (InterruptedException e) {}
|
||||
}
|
||||
System.out.println("Polling...");
|
||||
while (true) {
|
||||
try {
|
||||
Integer poll = queue.take();
|
||||
System.out.println("Polled: " + poll);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
|
||||
|
@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
public class ConcurrentMapAggregateStatusTest {
|
||||
public class ConcurrentMapAggregateStatusManualTest {
|
||||
|
||||
private ExecutorService executorService;
|
||||
private Map<String, Integer> concurrentMap;
|
@ -10,7 +10,7 @@ import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
public class ConcurrentMapNullKeyValueTest {
|
||||
public class ConcurrentMapNullKeyValueManualTest {
|
||||
|
||||
ConcurrentMap<String, Object> concurrentMap;
|
||||
|
@ -11,7 +11,7 @@ import java.util.concurrent.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ConcurrentMapPerformanceTest {
|
||||
public class ConcurrentMapPerformanceManualTest {
|
||||
|
||||
@Test
|
||||
public void givenMaps_whenGetPut500KTimes_thenConcurrentMapFaster() throws Exception {
|
@ -10,7 +10,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.testng.Assert.*;
|
||||
|
||||
public class ConcurrentNavigableMapTests {
|
||||
public class ConcurrentNavigableMapManualTests {
|
||||
|
||||
@Test
|
||||
public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throws InterruptedException {
|
||||
@ -18,9 +18,7 @@ public class ConcurrentNavigableMapTests {
|
||||
|
||||
updateMapConcurrently(skipListMap, 4);
|
||||
|
||||
Iterator<Integer> skipListIter = skipListMap
|
||||
.keySet()
|
||||
.iterator();
|
||||
Iterator<Integer> skipListIter = skipListMap.keySet().iterator();
|
||||
int previous = skipListIter.next();
|
||||
while (skipListIter.hasNext()) {
|
||||
int current = skipListIter.next();
|
@ -10,7 +10,7 @@ import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ConcurretMapMemoryConsistencyTest {
|
||||
public class ConcurretMapMemoryConsistencyManualTest {
|
||||
|
||||
@Test
|
||||
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
|
@ -0,0 +1,80 @@
|
||||
package com.baeldung.java.concurrentmodification;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.util.Lists.newArrayList;
|
||||
|
||||
public class ConcurrentModificationUnitTest {
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void givenIterating_whenRemoving_thenThrowException() throws InterruptedException {
|
||||
|
||||
List<Integer> integers = newArrayList(1, 2, 3);
|
||||
|
||||
for (Integer integer : integers) {
|
||||
integers.remove(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIterating_whenUsingIteratorRemove_thenNoError() throws InterruptedException {
|
||||
|
||||
List<Integer> integers = newArrayList(1, 2, 3);
|
||||
|
||||
for (Iterator<Integer> iterator = integers.iterator(); iterator.hasNext();) {
|
||||
Integer integer = iterator.next();
|
||||
if(integer == 2) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(integers).containsExactly(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIterating_whenUsingRemovalList_thenNoError() throws InterruptedException {
|
||||
|
||||
List<Integer> integers = newArrayList(1, 2, 3);
|
||||
List<Integer> toRemove = newArrayList();
|
||||
|
||||
for (Integer integer : integers) {
|
||||
if(integer == 2) {
|
||||
toRemove.add(integer);
|
||||
}
|
||||
}
|
||||
integers.removeAll(toRemove);
|
||||
|
||||
assertThat(integers).containsExactly(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingRemoveIf_thenRemoveElements() throws InterruptedException {
|
||||
|
||||
Collection<Integer> integers = newArrayList(1, 2, 3);
|
||||
|
||||
integers.removeIf(i -> i == 2);
|
||||
|
||||
assertThat(integers).containsExactly(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStream_thenRemoveElements() {
|
||||
Collection<Integer> integers = newArrayList(1, 2, 3);
|
||||
|
||||
List<String> collected = integers
|
||||
.stream()
|
||||
.filter(i -> i != 2)
|
||||
.map(Object::toString)
|
||||
.collect(toList());
|
||||
|
||||
assertThat(collected).containsExactly("1", "3");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,231 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.groupingby.BlogPost;
|
||||
import com.baeldung.java_8_features.groupingby.BlogPostType;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import static java.util.Comparator.comparingInt;
|
||||
import static java.util.stream.Collectors.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8GroupingByCollectorUnitTest {
|
||||
|
||||
private static final List<BlogPost> posts = Arrays.asList(
|
||||
new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15),
|
||||
new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
|
||||
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20),
|
||||
new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35),
|
||||
new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
|
||||
Map<BlogPostType, List<BlogPost>> postsPerType = posts
|
||||
.stream()
|
||||
.collect(groupingBy(BlogPost::getType));
|
||||
|
||||
assertEquals(2, postsPerType
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType
|
||||
.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
|
||||
Map<BlogPostType, String> postsPerType = posts
|
||||
.stream()
|
||||
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
|
||||
|
||||
assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
|
||||
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
|
||||
assertEquals("Post titles: [Tech review 1, Tech review 2]", postsPerType.get(BlogPostType.REVIEW));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
|
||||
Map<BlogPostType, Integer> likesPerType = posts
|
||||
.stream()
|
||||
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
|
||||
|
||||
assertEquals(50, likesPerType
|
||||
.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(20, likesPerType
|
||||
.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
assertEquals(20, likesPerType
|
||||
.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
|
||||
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts
|
||||
.stream()
|
||||
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
|
||||
|
||||
assertEquals(2, postsPerType
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType
|
||||
.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
|
||||
Map<BlogPostType, Set<BlogPost>> postsPerType = posts
|
||||
.stream()
|
||||
.collect(groupingBy(BlogPost::getType, toSet()));
|
||||
|
||||
assertEquals(2, postsPerType
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType
|
||||
.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
|
||||
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts
|
||||
.parallelStream()
|
||||
.collect(groupingByConcurrent(BlogPost::getType));
|
||||
|
||||
assertEquals(2, postsPerType
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType
|
||||
.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
|
||||
Map<BlogPostType, Double> averageLikesPerType = posts
|
||||
.stream()
|
||||
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
|
||||
|
||||
assertEquals(25, averageLikesPerType
|
||||
.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(20, averageLikesPerType
|
||||
.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
assertEquals(10, averageLikesPerType
|
||||
.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
|
||||
Map<BlogPostType, Long> numberOfPostsPerType = posts
|
||||
.stream()
|
||||
.collect(groupingBy(BlogPost::getType, counting()));
|
||||
|
||||
assertEquals(2, numberOfPostsPerType
|
||||
.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(1, numberOfPostsPerType
|
||||
.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
assertEquals(2, numberOfPostsPerType
|
||||
.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
|
||||
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts
|
||||
.stream()
|
||||
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
|
||||
|
||||
assertTrue(maxLikesPerPostType
|
||||
.get(BlogPostType.NEWS)
|
||||
.isPresent());
|
||||
assertEquals(35, maxLikesPerPostType
|
||||
.get(BlogPostType.NEWS)
|
||||
.get()
|
||||
.getLikes());
|
||||
|
||||
assertTrue(maxLikesPerPostType
|
||||
.get(BlogPostType.GUIDE)
|
||||
.isPresent());
|
||||
assertEquals(20, maxLikesPerPostType
|
||||
.get(BlogPostType.GUIDE)
|
||||
.get()
|
||||
.getLikes());
|
||||
|
||||
assertTrue(maxLikesPerPostType
|
||||
.get(BlogPostType.REVIEW)
|
||||
.isPresent());
|
||||
assertEquals(15, maxLikesPerPostType
|
||||
.get(BlogPostType.REVIEW)
|
||||
.get()
|
||||
.getLikes());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
|
||||
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts
|
||||
.stream()
|
||||
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
|
||||
|
||||
assertEquals(1, map
|
||||
.get("Author 1")
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, map
|
||||
.get("Author 1")
|
||||
.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(1, map
|
||||
.get("Author 1")
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
|
||||
assertEquals(1, map
|
||||
.get("Author 2")
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, map
|
||||
.get("Author 2")
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
assertNull(map
|
||||
.get("Author 2")
|
||||
.get(BlogPostType.GUIDE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
|
||||
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts
|
||||
.stream()
|
||||
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
|
||||
|
||||
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);
|
||||
|
||||
assertEquals(2, newsLikeStatistics.getCount());
|
||||
assertEquals(50, newsLikeStatistics.getSum());
|
||||
assertEquals(25.0, newsLikeStatistics.getAverage(), 0.001);
|
||||
assertEquals(35, newsLikeStatistics.getMax());
|
||||
assertEquals(15, newsLikeStatistics.getMin());
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,47 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.Person;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Java8MaxMinTest {
|
||||
|
||||
@Test
|
||||
public void whenListIsOfIntegerThenMaxCanBeDoneUsingIntegerComparator() {
|
||||
//given
|
||||
final List<Integer> listOfIntegers = Arrays.asList(1, 2, 3, 4, 56, 7, 89, 10);
|
||||
final Integer expectedResult = 89;
|
||||
|
||||
//then
|
||||
final Integer max = listOfIntegers
|
||||
.stream()
|
||||
.mapToInt(v -> v)
|
||||
.max().orElseThrow(NoSuchElementException::new);
|
||||
|
||||
assertEquals("Should be 89", expectedResult, max);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListIsOfPersonObjectThenMinCanBeDoneUsingCustomComparatorThroughLambda() {
|
||||
//given
|
||||
final Person alex = new Person("Alex", 23);
|
||||
final Person john = new Person("John", 40);
|
||||
final Person peter = new Person("Peter", 32);
|
||||
final List<Person> people = Arrays.asList(alex, john, peter);
|
||||
|
||||
//then
|
||||
final Person minByAge = people
|
||||
.stream()
|
||||
.min(Comparator.comparing(Person::getAge))
|
||||
.orElseThrow(NoSuchElementException::new);
|
||||
|
||||
assertEquals("Should be Alex", alex, minByAge);
|
||||
}
|
||||
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.test.comparison;
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@ -15,7 +15,7 @@ public class DivisibilityTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumber_whenDivisiblebyTwo_thenCorrect() {
|
||||
public void givenNumber_whenDivisibleByTwo_thenCorrect() {
|
||||
assertEquals(number % 2, 0);
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Parameterized;
|
||||
import org.junit.runners.Parameterized.Parameters;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
@RunWith(value = Parameterized.class)
|
||||
public class ParametrizedTests {
|
||||
|
||||
private int value;
|
||||
private boolean isEven;
|
||||
|
||||
public ParametrizedTests(int value, boolean isEven) {
|
||||
this.value = value;
|
||||
this.isEven = isEven;
|
||||
}
|
||||
|
||||
@Parameters
|
||||
public static Collection<Object[]> data() {
|
||||
Object[][] data = new Object[][]{{1, false}, {2, true}, {4, true}};
|
||||
return Arrays.asList(data);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParametrizedNumber_ifEvenCheckOK_thenCorrect() {
|
||||
Assert.assertEquals(isEven, value % 2 == 0);
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
public class RegistrationTest {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationTest.class);
|
||||
|
||||
@Test
|
||||
public void whenCalledFromSuite_thanOK() {
|
||||
LOGGER.info("Registration successful");
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class SignInTest {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(SignInTest.class);
|
||||
|
||||
@Test
|
||||
public void whenCalledFromSuite_thanOK() {
|
||||
LOGGER.info("SignIn successful");
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.test.comparison;
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
@ -1,10 +1,10 @@
|
||||
package com.baeldung.test.comparison;
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Suite;
|
||||
|
||||
@RunWith(Suite.class)
|
||||
@Suite.SuiteClasses({ StringCaseTest.class, DivisibilityTest.class })
|
||||
@Suite.SuiteClasses({ RegistrationTest.class, SignInTest.class })
|
||||
public class SuiteTest {
|
||||
|
||||
}
|
@ -1,8 +1,4 @@
|
||||
package com.baeldung.test.comparison;
|
||||
|
||||
import java.security.Security;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
@ -12,6 +8,9 @@ import org.junit.BeforeClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class SummationServiceTest {
|
||||
private static List<Integer> numbers;
|
||||
|
@ -0,0 +1,73 @@
|
||||
package com.baeldung.strategy;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static com.baeldung.strategy.Discounter.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StrategyDesignPatternUnitTest {
|
||||
@Test
|
||||
public void shouldDivideByTwo_WhenApplyingStaffDiscounter() {
|
||||
Discounter staffDiscounter = new EasterDiscounter();
|
||||
|
||||
final BigDecimal discountedValue = staffDiscounter
|
||||
.apply(BigDecimal.valueOf(100));
|
||||
|
||||
assertThat(discountedValue)
|
||||
.isEqualByComparingTo(BigDecimal.valueOf(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithAnonyousTypes() {
|
||||
Discounter staffDiscounter = new Discounter() {
|
||||
@Override
|
||||
public BigDecimal apply( BigDecimal amount) {
|
||||
return amount.multiply(BigDecimal.valueOf(0.5));
|
||||
}
|
||||
};
|
||||
|
||||
final BigDecimal discountedValue = staffDiscounter
|
||||
.apply(BigDecimal.valueOf(100));
|
||||
|
||||
assertThat(discountedValue)
|
||||
.isEqualByComparingTo(BigDecimal.valueOf(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithLamda() {
|
||||
Discounter staffDiscounter = amount -> amount.multiply(BigDecimal.valueOf(0.5));
|
||||
|
||||
final BigDecimal discountedValue = staffDiscounter
|
||||
.apply(BigDecimal.valueOf(100));
|
||||
|
||||
assertThat(discountedValue)
|
||||
.isEqualByComparingTo(BigDecimal.valueOf(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldApplyAllDiscounts() {
|
||||
List<Discounter> discounters = Arrays.asList(christmas(), newYear(), easter());
|
||||
|
||||
BigDecimal amount = BigDecimal.valueOf(100);
|
||||
|
||||
final Discounter combinedDiscounter = discounters
|
||||
.stream()
|
||||
.reduce(v -> v, Discounter::combine);
|
||||
|
||||
combinedDiscounter.apply(amount);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldChainDiscounters() {
|
||||
final Function<BigDecimal, BigDecimal> combinedDiscounters = Discounter
|
||||
.christmas()
|
||||
.andThen(newYear());
|
||||
|
||||
combinedDiscounters.apply(BigDecimal.valueOf(100));
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class InfiniteStreamTest {
|
||||
|
||||
@Test
|
||||
public void givenInfiniteStream_whenUseIntermediateLimitMethod_thenShouldTerminateInFiniteTime() {
|
||||
//given
|
||||
Stream<Integer> infiniteStream = Stream.iterate(0, i -> i + 2);
|
||||
|
||||
//when
|
||||
List<Integer> collect = infiniteStream
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(collect, Arrays.asList(0, 2, 4, 6, 8, 10, 12, 14, 16, 18));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInfiniteStreamOfRandomInts_whenUseLimit_shouldTerminateInFiniteTime() {
|
||||
//given
|
||||
Supplier<UUID> randomUUIDSupplier = UUID::randomUUID;
|
||||
Stream<UUID> infiniteStreamOfRandomUUID = Stream.generate(randomUUIDSupplier);
|
||||
|
||||
//when
|
||||
List<UUID> randomInts = infiniteStreamOfRandomUUID
|
||||
.skip(10)
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(randomInts.size(), 10);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.string.JoinerSplitter;
|
||||
|
||||
public class JoinerSplitterTest {
|
||||
|
||||
@Test
|
||||
public void provided_array_convert_to_stream_and_convert_to_string() {
|
||||
|
||||
String[] programming_languages = {"java", "python", "nodejs", "ruby"};
|
||||
|
||||
String expectation = "java,python,nodejs,ruby";
|
||||
|
||||
String result = JoinerSplitter.join(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_transformedToStream_convertToPrefixPostfixString() {
|
||||
|
||||
String[] programming_languages = {"java", "python",
|
||||
"nodejs", "ruby"};
|
||||
String expectation = "[java,python,nodejs,ruby]";
|
||||
|
||||
String result = JoinerSplitter.joinWithPrefixPostFix(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToList() {
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<String> expectation = new ArrayList<String>();
|
||||
expectation.add("java");
|
||||
expectation.add("python");
|
||||
expectation.add("nodejs");
|
||||
expectation.add("ruby");
|
||||
|
||||
List<String> result = JoinerSplitter.split(programming_languages);
|
||||
|
||||
assertEquals(result, expectation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_transformedToStream_convertToListOfChar() {
|
||||
|
||||
String programming_languages = "java,python,nodejs,ruby";
|
||||
|
||||
List<Character> expectation = new ArrayList<Character>();
|
||||
char[] charArray = programming_languages.toCharArray();
|
||||
for (char c : charArray) {
|
||||
expectation.add(c);
|
||||
}
|
||||
|
||||
List<Character> result = JoinerSplitter.splitToListOfChar(programming_languages);
|
||||
assertEquals(result, expectation);
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
package com.baeldung.test.comparison;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class DependentTests {
|
||||
|
||||
private EmailValidator emailValidator;
|
||||
private LoginValidator loginValidator;
|
||||
private String validEmail = "abc@qwe.com";
|
||||
|
||||
@BeforeClass
|
||||
public void setup() {
|
||||
emailValidator = new EmailValidator();
|
||||
loginValidator = new LoginValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmail_ifValid_thenTrue() {
|
||||
boolean valid = emailValidator.validate(validEmail);
|
||||
Assert.assertEquals(valid, true);
|
||||
}
|
||||
|
||||
@Test(dependsOnMethods = { "givenEmail_ifValid_thenTrue" })
|
||||
public void givenValidEmail_whenLoggedin_thenTrue() {
|
||||
boolean valid = loginValidator.validate();
|
||||
Assert.assertEquals(valid, true);
|
||||
}
|
||||
}
|
||||
|
||||
class EmailValidator {
|
||||
|
||||
public boolean validate(String validEmail) {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class LoginValidator {
|
||||
|
||||
public boolean validate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
package com.baeldung.test.comparison;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Parameterized;
|
||||
import org.junit.runners.Parameterized.Parameters;
|
||||
|
||||
@RunWith(value = Parameterized.class)
|
||||
public class MyParameterisedUnitTest {
|
||||
|
||||
private String name;
|
||||
private NameCheck nameCheck;
|
||||
|
||||
@Before
|
||||
public void initialSetup() {
|
||||
nameCheck = new NameCheck();
|
||||
}
|
||||
|
||||
public MyParameterisedUnitTest(String myName) {
|
||||
this.name = myName;
|
||||
}
|
||||
|
||||
@Parameters
|
||||
public static Collection<Object[]> data() {
|
||||
Object[][] data = new Object[][] { { "Peter" }, { "Sam" }, { "Tim" }, { "Lucy" } };
|
||||
return Arrays.asList(data);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenValidLength_thenTrue() {
|
||||
boolean valid = nameCheck.nameCheck(name);
|
||||
Assert.assertEquals(valid, true);
|
||||
}
|
||||
}
|
||||
|
||||
class NameCheck {
|
||||
|
||||
public boolean nameCheck(String name) {
|
||||
if (name.length() > 0)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
@ -1,81 +0,0 @@
|
||||
package com.baeldung.test.comparison;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.DataProvider;
|
||||
import org.testng.annotations.Parameters;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class MyParameterisedUnitTestNg {
|
||||
|
||||
private PrimeNumberCheck primeNumberChecker;
|
||||
|
||||
@BeforeClass
|
||||
public void intialSetup() {
|
||||
primeNumberChecker = new PrimeNumberCheck();
|
||||
}
|
||||
|
||||
@Test(enabled = false)
|
||||
@Parameters({ "num", "expectedResult" })
|
||||
public void givenNumber_ifPrime_thenCorrect(int number, boolean expectedResult) {
|
||||
Assert.assertEquals(expectedResult, primeNumberChecker.validate(number));
|
||||
}
|
||||
|
||||
@DataProvider(name = "test1")
|
||||
public static Object[][] primeNumbers() {
|
||||
return new Object[][] { { 2, true }, { 6, false }, { 19, true }, { 22, false }, { 23, true } };
|
||||
}
|
||||
|
||||
@Test(dataProvider = "test1")
|
||||
public void givenNumber_whenPrime_thenCorrect(Integer inputNumber, Boolean expectedResult) {
|
||||
Assert.assertEquals(expectedResult, primeNumberChecker.validate(inputNumber));
|
||||
}
|
||||
|
||||
@Test(dataProvider = "myDataProvider")
|
||||
public void parameterCheckTest(User user) {
|
||||
Assert.assertEquals("sam", user.getName());
|
||||
Assert.assertEquals(12, user.getAge());
|
||||
}
|
||||
|
||||
@DataProvider(name = "myDataProvider")
|
||||
public Object[][] parameterProvider() {
|
||||
User usr = new User();
|
||||
usr.setName("sam");
|
||||
usr.setAge(12);
|
||||
return new Object[][] { { usr } };
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class PrimeNumberCheck {
|
||||
|
||||
public Object validate(int number) {
|
||||
for (int i = 2; i < number; i++) {
|
||||
if (number % i == 0)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class User {
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
package com.baeldung.test.comparison;
|
||||
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class RegistrationTest {
|
||||
|
||||
@Test
|
||||
public void givenEmail_ifValid_thenCorrect() {
|
||||
|
||||
}
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
package com.baeldung.test.comparison;
|
||||
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
public class SignInTest {
|
||||
|
||||
@Test
|
||||
public void givenUsername_ifValid_thenCorrect() {
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
package com.baeldung.weakhashmap;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.jayway.awaitility.Awaitility.await;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class WeakHashMapTest {
|
||||
|
||||
@Test
|
||||
public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObject() {
|
||||
//given
|
||||
WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>();
|
||||
BigImage bigImage = new BigImage("image_id");
|
||||
UniqueImageName imageName = new UniqueImageName("name_of_big_image");
|
||||
|
||||
map.put(imageName, bigImage);
|
||||
assertTrue(map.containsKey(imageName));
|
||||
|
||||
//when big image key is not reference anywhere
|
||||
imageName = null;
|
||||
System.gc();
|
||||
|
||||
//then GC will finally reclaim that object
|
||||
await().atMost(10, TimeUnit.SECONDS).until(map::isEmpty);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObjectButLeaveReferencedObject() {
|
||||
//given
|
||||
WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>();
|
||||
BigImage bigImageFirst = new BigImage("foo");
|
||||
UniqueImageName imageNameFirst = new UniqueImageName("name_of_big_image");
|
||||
|
||||
BigImage bigImageSecond = new BigImage("foo_2");
|
||||
UniqueImageName imageNameSecond = new UniqueImageName("name_of_big_image_2");
|
||||
|
||||
map.put(imageNameFirst, bigImageFirst);
|
||||
map.put(imageNameSecond, bigImageSecond);
|
||||
assertTrue(map.containsKey(imageNameFirst));
|
||||
assertTrue(map.containsKey(imageNameSecond));
|
||||
|
||||
//when
|
||||
imageNameFirst = null;
|
||||
System.gc();
|
||||
|
||||
//then
|
||||
await().atMost(10, TimeUnit.SECONDS).until(() -> map.size() == 1);
|
||||
await().atMost(10, TimeUnit.SECONDS).until(() -> map.containsKey(imageNameSecond));
|
||||
}
|
||||
|
||||
|
||||
class BigImage {
|
||||
public final String imageId;
|
||||
|
||||
BigImage(String imageId) {
|
||||
this.imageId = imageId;
|
||||
}
|
||||
}
|
||||
|
||||
class UniqueImageName {
|
||||
public final String imageName;
|
||||
|
||||
UniqueImageName(String imageName) {
|
||||
this.imageName = imageName;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,12 +1,12 @@
|
||||
package org.baeldung.java;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Random;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.apache.commons.math3.random.RandomDataGenerator;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Random;
|
||||
|
||||
public class JavaRandomUnitTest {
|
||||
|
||||
// tests - random long
|
||||
@ -164,7 +164,7 @@ public class JavaRandomUnitTest {
|
||||
final int targetStringLength = 10;
|
||||
final StringBuilder buffer = new StringBuilder(targetStringLength);
|
||||
for (int i = 0; i < targetStringLength; i++) {
|
||||
final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit));
|
||||
final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit + 1));
|
||||
buffer.append((char) randomLimitedInt);
|
||||
}
|
||||
final String generatedString = buffer.toString();
|
||||
|
@ -1,5 +1,5 @@
|
||||
package org.baeldung.java.streams;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@ -14,28 +14,25 @@ import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ThreadPoolInParallelStreamTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal()
|
||||
throws InterruptedException, ExecutionException {
|
||||
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {
|
||||
long firstNum = 1;
|
||||
long lastNum = 1_000_000;
|
||||
|
||||
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed()
|
||||
.collect(Collectors.toList());
|
||||
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
|
||||
|
||||
ForkJoinPool customThreadPool = new ForkJoinPool(4);
|
||||
long actualTotal = customThreadPool.submit(() -> aList.parallelStream()
|
||||
.reduce(0L, Long::sum)).get();
|
||||
|
||||
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
|
||||
long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
|
||||
|
||||
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenList_whenCallingParallelStream_shouldBeParallelStream(){
|
||||
public void givenList_whenCallingParallelStream_shouldBeParallelStream() {
|
||||
List<Long> aList = new ArrayList<>();
|
||||
Stream<Long> parallelStream = aList.parallelStream();
|
||||
|
||||
|
||||
assertTrue(parallelStream.isParallel());
|
||||
}
|
||||
}
|
||||
|
@ -1,49 +0,0 @@
|
||||
package temp;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import junit.framework.Assert;
|
||||
|
||||
public class SummationServiceTest {
|
||||
|
||||
private static List<Integer> numbers;
|
||||
|
||||
@BeforeClass
|
||||
public static void initialize() {
|
||||
numbers = new ArrayList<>();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDown() {
|
||||
numbers = null;
|
||||
}
|
||||
|
||||
@Before
|
||||
public void runBeforeEachTest() {
|
||||
numbers.add(1);
|
||||
numbers.add(2);
|
||||
numbers.add(3);
|
||||
}
|
||||
|
||||
@After
|
||||
public void runAfterEachTest() {
|
||||
numbers.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumbers_sumEquals_thenCorrect() {
|
||||
int sum = 0;
|
||||
for (int num : numbers)
|
||||
sum += num;
|
||||
assertEquals(6, sum);
|
||||
}
|
||||
}
|
@ -1,10 +0,0 @@
|
||||
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
|
||||
<suite name="My test suite">
|
||||
<test name="testing">
|
||||
<parameter name="num" value="2"/>
|
||||
<parameter name="expectedResult" value="true"/>
|
||||
<classes>
|
||||
<class name="com.baeldung.test.comparison.MyParameterisedUnitTestNg"/>
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
@ -1,13 +0,0 @@
|
||||
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
|
||||
<suite name="regression_test">
|
||||
<test name="testing">
|
||||
<groups>
|
||||
<run>
|
||||
<include name="sanity" />
|
||||
</run>
|
||||
</groups>
|
||||
<classes>
|
||||
<class name="com.baeldung.test.comparison.SummationServiceTestTestNg" />
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
@ -1,9 +0,0 @@
|
||||
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
|
||||
<suite name="Evaluation_Suite">
|
||||
<test name="Sanity">
|
||||
<classes>
|
||||
<class name="com.baeldung.test.comparison.RegistrationTest" />
|
||||
<class name="com.baeldung.test.comparison.SignInTest" />
|
||||
</classes>
|
||||
</test>
|
||||
</suite>
|
@ -102,10 +102,10 @@
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<couchbase.client.version>2.3.6</couchbase.client.version>
|
||||
<spring-framework.version>4.3.4.RELEASE</spring-framework.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<couchbase.client.version>2.4.0</couchbase.client.version>
|
||||
<spring-framework.version>4.3.5.RELEASE</spring-framework.version>
|
||||
<logback.version>1.1.8</logback.version>
|
||||
<org.slf4j.version>1.7.22</org.slf4j.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
|
@ -0,0 +1,6 @@
|
||||
package com.baeldung.couchbase.mapreduce;
|
||||
|
||||
public interface CouchbaseKeyGenerator<T> {
|
||||
|
||||
String generateKey(T t);
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.baeldung.couchbase.mapreduce;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class DuplicateKeyException extends Exception {
|
||||
|
||||
public DuplicateKeyException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.couchbase.mapreduce;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class RandomUUIDGenerator<T> implements CouchbaseKeyGenerator<T> {
|
||||
|
||||
@Override
|
||||
public String generateKey(T t) {
|
||||
return UUID.randomUUID().toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package com.baeldung.couchbase.mapreduce;
|
||||
|
||||
public class StudentGrade {
|
||||
|
||||
private String name;
|
||||
private String course;
|
||||
private Integer grade;
|
||||
private Integer hours;
|
||||
|
||||
public StudentGrade() { }
|
||||
|
||||
public StudentGrade(String name, String course, Integer grade, Integer hours) {
|
||||
this.name = name;
|
||||
this.course = course;
|
||||
this.grade = grade;
|
||||
this.hours = hours;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getCourse() {
|
||||
return course;
|
||||
}
|
||||
|
||||
public void setCourse(String course) {
|
||||
this.course = course;
|
||||
}
|
||||
|
||||
public Integer getGrade() {
|
||||
return grade;
|
||||
}
|
||||
|
||||
public void setGrade(Integer grade) {
|
||||
this.grade = grade;
|
||||
}
|
||||
|
||||
public Integer getHours() {
|
||||
return hours;
|
||||
}
|
||||
|
||||
public void setHours(Integer hours) {
|
||||
this.hours = hours;
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.baeldung.couchbase.mapreduce;
|
||||
|
||||
public class StudentGradeKeyGenerator implements CouchbaseKeyGenerator<StudentGrade> {
|
||||
|
||||
@Override
|
||||
public String generateKey(StudentGrade g) {
|
||||
return g.getName() + ":" + g.getCourse();
|
||||
}
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package com.baeldung.couchbase.mapreduce;
|
||||
|
||||
import com.couchbase.client.deps.com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.couchbase.client.java.document.json.JsonArray;
|
||||
import com.couchbase.client.java.view.ViewQuery;
|
||||
|
||||
public class StudentGradeQueryBuilder {
|
||||
|
||||
final ObjectMapper om = new ObjectMapper();
|
||||
|
||||
public ViewQuery findAll() {
|
||||
return ViewQuery.from("studentGrades", "findByCourse");
|
||||
}
|
||||
|
||||
public ViewQuery findByCourse(String course) {
|
||||
return ViewQuery.from("studentGrades", "findByCourse")
|
||||
.key(course);
|
||||
}
|
||||
|
||||
public ViewQuery findByCourses(String... courses) {
|
||||
return ViewQuery.from("studentGrades", "findByCourse")
|
||||
.keys(JsonArray.from(courses));
|
||||
}
|
||||
|
||||
public ViewQuery findByGradeInRange(int lower, int upper, boolean inclusiveEnd) {
|
||||
return ViewQuery.from("studentGrades", "findByGrade")
|
||||
.startKey(lower)
|
||||
.endKey(upper)
|
||||
.inclusiveEnd(inclusiveEnd);
|
||||
}
|
||||
|
||||
public ViewQuery findByGradeLessThan(int upper) {
|
||||
return ViewQuery.from("studentGrades", "findByGrade")
|
||||
.endKey(upper)
|
||||
.inclusiveEnd(false);
|
||||
}
|
||||
|
||||
public ViewQuery findByGradeGreaterThan(int lower) {
|
||||
return ViewQuery.from("studentGrades", "findByGrade")
|
||||
.startKey(lower);
|
||||
}
|
||||
|
||||
public ViewQuery findByCourseAndGradeInRange(String course, int minGrade, int maxGrade, boolean inclusiveEnd) {
|
||||
return ViewQuery.from("studentGrades", "findByCourseAndGrade")
|
||||
.startKey(JsonArray.from(course, minGrade))
|
||||
.endKey(JsonArray.from(course, maxGrade))
|
||||
.inclusiveEnd(inclusiveEnd);
|
||||
}
|
||||
|
||||
public ViewQuery findTopGradesByCourse(String course, int limit) {
|
||||
return ViewQuery.from("studentGrades", "findByCourseAndGrade")
|
||||
.startKey(JsonArray.from(course, 100))
|
||||
.endKey(JsonArray.from(course, 0))
|
||||
.inclusiveEnd(true)
|
||||
.descending()
|
||||
.limit(limit);
|
||||
}
|
||||
|
||||
public ViewQuery countStudentsByCourse() {
|
||||
return ViewQuery.from("studentGrades", "countStudentsByCourse")
|
||||
.reduce()
|
||||
.groupLevel(1);
|
||||
}
|
||||
|
||||
public ViewQuery sumCreditsByStudent() {
|
||||
return ViewQuery.from("studentGrades", "sumCreditsByStudent")
|
||||
.reduce()
|
||||
.groupLevel(1);
|
||||
}
|
||||
}
|
@ -0,0 +1,169 @@
|
||||
package com.baeldung.couchbase.mapreduce;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import com.couchbase.client.deps.com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.couchbase.client.java.Bucket;
|
||||
import com.couchbase.client.java.CouchbaseCluster;
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
import com.couchbase.client.java.document.json.JsonArray;
|
||||
import com.couchbase.client.java.document.json.JsonObject;
|
||||
import com.couchbase.client.java.view.ViewQuery;
|
||||
import com.couchbase.client.java.view.ViewResult;
|
||||
import com.couchbase.client.java.view.ViewRow;
|
||||
|
||||
public class StudentGradeService {
|
||||
|
||||
final CouchbaseKeyGenerator<StudentGrade> keyGenerator;
|
||||
final CouchbaseCluster cluster;
|
||||
final Bucket bucket;
|
||||
final ObjectMapper om = new ObjectMapper();
|
||||
final StudentGradeQueryBuilder queryBuilder;
|
||||
|
||||
public StudentGradeService(CouchbaseKeyGenerator<StudentGrade> keyGenerator) {
|
||||
this.keyGenerator = keyGenerator;
|
||||
this.queryBuilder = new StudentGradeQueryBuilder();
|
||||
cluster = CouchbaseCluster.create("127.0.0.1");
|
||||
bucket = cluster.openBucket("baeldung-tutorial");
|
||||
}
|
||||
|
||||
public String insert(StudentGrade studentGrade) throws DuplicateKeyException {
|
||||
String id = keyGenerator.generateKey(studentGrade);
|
||||
if(bucket.exists(id)) {
|
||||
throw new DuplicateKeyException("document already exists with key " + id);
|
||||
}
|
||||
JsonObject content = JsonObject.empty()
|
||||
.put("type", "StudentGrade")
|
||||
.put("name", studentGrade.getName())
|
||||
.put("course", studentGrade.getCourse())
|
||||
.put("grade", studentGrade.getGrade())
|
||||
.put("hours", studentGrade.getHours());
|
||||
JsonDocument doc = JsonDocument.create(id, content);
|
||||
bucket.insert(doc);
|
||||
return id;
|
||||
}
|
||||
|
||||
public List<JsonDocument> findAll() {
|
||||
ViewQuery query = queryBuilder.findAll();
|
||||
ViewResult result = bucket.query(query);
|
||||
return extractDocuments(result);
|
||||
}
|
||||
|
||||
private List<JsonDocument> extractDocuments(ViewResult result) {
|
||||
List<JsonDocument> docs = new ArrayList<>();
|
||||
for(ViewRow row : result.allRows()) {
|
||||
JsonDocument doc = row.document();
|
||||
docs.add(doc);
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
|
||||
public List<JsonDocument> findByCourse(String course) {
|
||||
ViewQuery query = queryBuilder.findByCourse(course);
|
||||
ViewResult result = bucket.query(query);
|
||||
return extractDocuments(result);
|
||||
}
|
||||
|
||||
public List<JsonDocument> findByCourses(String... courses) {
|
||||
ViewQuery query = queryBuilder.findByCourses(courses);
|
||||
ViewResult result = bucket.query(query);
|
||||
return extractDocuments(result);
|
||||
}
|
||||
|
||||
public List<JsonDocument> findByGradeInRange(int lower, int upper, boolean inclusiveEnd) {
|
||||
ViewQuery query = queryBuilder.findByGradeInRange(lower, upper, inclusiveEnd);
|
||||
ViewResult result = bucket.query(query);
|
||||
return extractDocuments(result);
|
||||
}
|
||||
|
||||
public List<JsonDocument> findByGradeLessThan(int upper) {
|
||||
ViewQuery query = queryBuilder.findByGradeLessThan(upper);
|
||||
ViewResult result = bucket.query(query);
|
||||
return extractDocuments(result);
|
||||
}
|
||||
|
||||
public List<JsonDocument> findByGradeGreaterThan(int lower) {
|
||||
ViewQuery query = queryBuilder.findByGradeGreaterThan(lower);
|
||||
ViewResult result = bucket.query(query);
|
||||
return extractDocuments(result);
|
||||
}
|
||||
|
||||
public List<JsonDocument> findByCourseAndGradeInRange(String course, int minGrade, int maxGrade, boolean inclusiveEnd) {
|
||||
ViewQuery query = queryBuilder.findByCourseAndGradeInRange(course, minGrade, maxGrade, inclusiveEnd);
|
||||
ViewResult result = bucket.query(query);
|
||||
return extractDocuments(result);
|
||||
}
|
||||
|
||||
public List<JsonDocument> findTopGradesByCourse(String course, int limit) {
|
||||
ViewQuery query = queryBuilder.findTopGradesByCourse(course, limit);
|
||||
ViewResult result = bucket.query(query);
|
||||
return extractDocuments(result);
|
||||
}
|
||||
|
||||
public Map<String, Long> countStudentsByCourse() {
|
||||
ViewQuery query = ViewQuery.from("studentGrades", "countStudentsByCourse")
|
||||
.reduce()
|
||||
.groupLevel(1);
|
||||
ViewResult result = bucket.query(query);
|
||||
|
||||
Map<String, Long> numStudentsByCourse = new HashMap<>();
|
||||
for(ViewRow row : result.allRows()) {
|
||||
JsonArray keyArray = (JsonArray) row.key();
|
||||
String course = keyArray.getString(0);
|
||||
long count = Long.valueOf(row.value().toString());
|
||||
numStudentsByCourse.put(course, count);
|
||||
}
|
||||
|
||||
return numStudentsByCourse;
|
||||
}
|
||||
|
||||
public Map<String, Long> sumCreditHoursByStudent() {
|
||||
ViewQuery query = ViewQuery.from("studentGrades", "sumHoursByStudent")
|
||||
.reduce()
|
||||
.groupLevel(1);
|
||||
ViewResult result = bucket.query(query);
|
||||
|
||||
Map<String, Long> creditHoursByStudent = new HashMap<>();
|
||||
for(ViewRow row : result.allRows()) {
|
||||
String course = (String) row.key();
|
||||
long sum = Long.valueOf(row.value().toString());
|
||||
creditHoursByStudent.put(course, sum);
|
||||
}
|
||||
|
||||
return creditHoursByStudent;
|
||||
}
|
||||
|
||||
public Map<String, Long> sumGradePointsByStudent() {
|
||||
ViewQuery query = ViewQuery.from("studentGrades", "sumGradePointsByStudent")
|
||||
.reduce()
|
||||
.groupLevel(1);
|
||||
ViewResult result = bucket.query(query);
|
||||
|
||||
Map<String, Long> gradePointsByStudent = new HashMap<>();
|
||||
for(ViewRow row : result.allRows()) {
|
||||
String course = (String) row.key();
|
||||
long sum = Long.valueOf(row.value().toString());
|
||||
gradePointsByStudent.put(course, sum);
|
||||
}
|
||||
|
||||
return gradePointsByStudent;
|
||||
}
|
||||
|
||||
public Map<String, Float> calculateGpaByStudent() {
|
||||
Map<String, Long> creditHoursByStudent = sumCreditHoursByStudent();
|
||||
Map<String, Long> gradePointsByStudent = sumGradePointsByStudent();
|
||||
|
||||
Map<String, Float> result = new HashMap<>();
|
||||
for(Entry<String, Long> creditHoursEntry : creditHoursByStudent.entrySet()) {
|
||||
String name = creditHoursEntry.getKey();
|
||||
long totalHours = creditHoursEntry.getValue();
|
||||
long totalGradePoints = gradePointsByStudent.get(name);
|
||||
result.put(name, ((float) totalGradePoints / totalHours));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
@ -0,0 +1,150 @@
|
||||
package com.baeldung.couchbase.mapreduce;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.couchbase.client.java.document.JsonDocument;
|
||||
import com.couchbase.client.java.view.ViewResult;
|
||||
import com.couchbase.client.java.view.ViewRow;
|
||||
|
||||
public class StudentGradeServiceIntegrationTest {
|
||||
private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceIntegrationTest.class);
|
||||
|
||||
static StudentGradeService studentGradeService;
|
||||
static Set<String> gradeIds = new HashSet<>();
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpBeforeClass() throws Exception {
|
||||
studentGradeService = new StudentGradeService(new StudentGradeKeyGenerator());
|
||||
insertStudentGrade(new StudentGrade("John Doe", "History", 80, 3));
|
||||
insertStudentGrade(new StudentGrade("Jane Doe", "History", 89, 3));
|
||||
insertStudentGrade(new StudentGrade("Bob Smith", "History", 90, 3));
|
||||
insertStudentGrade(new StudentGrade("Mary Jones", "History", 92, 3));
|
||||
insertStudentGrade(new StudentGrade("Jane Doe", "Math", 59, 3));
|
||||
insertStudentGrade(new StudentGrade("Bob Smith", "Math", 91, 3));
|
||||
insertStudentGrade(new StudentGrade("Mary Jones", "Math", 86, 3));
|
||||
insertStudentGrade(new StudentGrade("John Doe", "Science", 85, 4));
|
||||
insertStudentGrade(new StudentGrade("Bob Smith", "Science", 97, 4));
|
||||
insertStudentGrade(new StudentGrade("Mary Jones", "Science", 84, 4));
|
||||
}
|
||||
|
||||
private static void insertStudentGrade(StudentGrade studentGrade) {
|
||||
try {
|
||||
String id = studentGradeService.insert(studentGrade);
|
||||
gradeIds.add(id);
|
||||
} catch (DuplicateKeyException e) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindAll_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findAll();
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindByCourse_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findByCourse("History");
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindByCourses_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findByCourses("History", "Science");
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindByGradeInRange_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findByGradeInRange(80, 89, true);
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindByGradeLessThan_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findByGradeLessThan(60);
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindByGradeGreaterThan_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findByGradeGreaterThan(90);
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindByCourseAndGradeInRange_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findByCourseAndGradeInRange("Math", 80, 89, true);
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenFindTopGradesByCourse_thenSuccess() {
|
||||
List<JsonDocument> docs = studentGradeService.findTopGradesByCourse("Science", 2);
|
||||
printDocuments(docs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenCountStudentsByCourse_thenSuccess() {
|
||||
Map<String, Long> map = studentGradeService.countStudentsByCourse();
|
||||
printMap(map);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSumCreditHoursByStudent_thenSuccess() {
|
||||
Map<String, Long> map = studentGradeService.sumCreditHoursByStudent();
|
||||
printMap(map);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSumGradePointsByStudent_thenSuccess() {
|
||||
Map<String, Long> map = studentGradeService.sumGradePointsByStudent();
|
||||
printMap(map);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenCalculateGpaByStudent_thenSuccess() {
|
||||
Map<String, Float> map = studentGradeService.calculateGpaByStudent();
|
||||
printGpaMap(map);
|
||||
}
|
||||
|
||||
private void printMap(Map<String, Long> map) {
|
||||
for(Map.Entry<String, Long> entry : map.entrySet()) {
|
||||
logger.info(entry.getKey() + "=" + entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
private void printGpaMap(Map<String, Float> map) {
|
||||
for(Map.Entry<String, Float> entry : map.entrySet()) {
|
||||
logger.info(entry.getKey() + "=" + entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
private void printDocuments(List<JsonDocument> docs) {
|
||||
for(JsonDocument doc : docs) {
|
||||
String key = doc.id();
|
||||
logger.info(key + " = " + doc.content().toString());
|
||||
}
|
||||
}
|
||||
|
||||
private void printViewResultDocuments(ViewResult result) {
|
||||
for(ViewRow row : result.allRows()) {
|
||||
JsonDocument doc = row.document();
|
||||
String key = doc.id();
|
||||
logger.info(key + "=" + doc.content().toString());
|
||||
}
|
||||
}
|
||||
|
||||
private void printViewResultRows(ViewResult result) {
|
||||
for(ViewRow row : result.allRows()) {
|
||||
logger.info(row.toString());
|
||||
}
|
||||
}
|
||||
}
|
17
couchbase-sdk/src/test/resources/logback.xml
Normal file
17
couchbase-sdk/src/test/resources/logback.xml
Normal file
@ -0,0 +1,17 @@
|
||||
<configuration>
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="com.baeldung" level="DEBUG" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
@ -57,6 +57,32 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- logging -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
@ -112,6 +138,9 @@
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,6 +1,5 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
|
||||
public class CustomEvent {
|
||||
private String action;
|
||||
|
38
guava/src/main/java/org/baeldung/guava/EventListener.java
Normal file
38
guava/src/main/java/org/baeldung/guava/EventListener.java
Normal file
@ -0,0 +1,38 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
import com.google.common.eventbus.DeadEvent;
|
||||
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++;
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void handleDeadEvent(DeadEvent deadEvent) {
|
||||
LOG.info("unhandled event [" + deadEvent.getEvent() + "]");
|
||||
eventsHandled++;
|
||||
}
|
||||
|
||||
public int getEventsHandled() {
|
||||
return eventsHandled;
|
||||
}
|
||||
|
||||
public void resetEventsHandled() {
|
||||
eventsHandled = 0;
|
||||
}
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
import com.google.common.eventbus.EventBus;
|
||||
|
||||
class EventBusWrapper {
|
||||
|
||||
private static EventBus eventBus = new EventBus();
|
||||
|
||||
static void register(Object object){
|
||||
eventBus.register(object);
|
||||
}
|
||||
|
||||
static void unregister(Object object){
|
||||
eventBus.unregister(object);
|
||||
}
|
||||
|
||||
static void post(Object object){
|
||||
eventBus.post(object);
|
||||
}
|
||||
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user