Merge pull request #18 from eugenp/master

Latest Changes
This commit is contained in:
PRITAM BANERJEE 2017-02-26 04:25:24 -08:00 committed by GitHub
commit db2b2d8929
522 changed files with 11645 additions and 2099 deletions

17
.travis.yml Normal file
View 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

3
JGit/README.md Normal file
View File

@ -0,0 +1,3 @@
## Relevant articles:
- [A Guide to JGit](http://www.baeldung.com/jgit)

4
algorithms/README.md Normal file
View File

@ -0,0 +1,4 @@
## Relevant articles:
- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)

View File

@ -41,4 +41,23 @@
</plugins>
</pluginManagement>
</build>
</project>
<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.7</version>
<configuration>
<instrumentation>
<ignores>
<ignore>com/baeldung/algorithms/dijkstra/*</ignore>
</ignores>
<excludes>
<exclude>com/baeldung/algorithms/dijkstra/*</exclude>
</excludes>
</instrumentation>
</configuration>
</plugin>
</plugins>
</reporting>
</project>

2
apache-bval/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Intro to Apache BVal](http://www.baeldung.com/apache-bval)

51
apache-bval/pom.xml Normal file
View 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>

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

BIN
apache-poi/temp.xls Normal file

Binary file not shown.

BIN
apache-poi/temp.xlsx Normal file

Binary file not shown.

50
apache-solrj/pom.xml Normal file
View File

@ -0,0 +1,50 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-solrj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>apache-solrj</name>
<properties>
<junit.version>4.12</junit.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>6.4.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,43 @@
package com.baeldung.solrjava;
import java.io.IOException;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.common.SolrInputDocument;
public class SolrJavaIntegration {
private HttpSolrClient solrClient;
public SolrJavaIntegration(String clientUrl) {
solrClient = new HttpSolrClient.Builder(clientUrl).build();
solrClient.setParser(new XMLResponseParser());
}
public void addSolrDocument(String documentId, String itemName, String itemPrice) throws SolrServerException, IOException {
SolrInputDocument document = new SolrInputDocument();
document.addField("id", documentId);
document.addField("name", itemName);
document.addField("price", itemPrice);
solrClient.add(document);
solrClient.commit();
}
public void deleteSolrDocument(String documentId) throws SolrServerException, IOException {
solrClient.deleteById(documentId);
solrClient.commit();
}
protected HttpSolrClient getSolrClient() {
return solrClient;
}
protected void setSolrClient(HttpSolrClient solrClient) {
this.solrClient = solrClient;
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.solrjava;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.junit.Before;
import org.junit.Test;
public class SolrJavaIntegrationTest {
private SolrJavaIntegration solrJavaIntegration;
@Before
public void setUp() throws Exception {
solrJavaIntegration = new SolrJavaIntegration("http://localhost:8983/solr/bigboxstore");
solrJavaIntegration.addSolrDocument("123456", "Kenmore Dishwasher", "599.99");
}
@Test
public void whenAdd_thenVerifyAdded() throws SolrServerException, IOException {
SolrQuery query = new SolrQuery();
query.set("q", "id:123456");
QueryResponse response = null;
response = solrJavaIntegration.getSolrClient().query(query);
SolrDocumentList docList = response.getResults();
assertEquals(docList.getNumFound(), 1);
for (SolrDocument doc : docList) {
assertEquals((String) doc.getFieldValue("id"), "123456");
assertEquals((Double) doc.getFieldValue("price"), (Double) 599.99);
}
}
@Test
public void whenDelete_thenVerifyDeleted() throws SolrServerException, IOException {
solrJavaIntegration.deleteSolrDocument("123456");
SolrQuery query = new SolrQuery();
query.set("q", "id:123456");
QueryResponse response = null;
response = solrJavaIntegration.getSolrClient().query(query);
SolrDocumentList docList = response.getResults();
assertEquals(docList.getNumFound(), 0);
}
}

3
apache-thrift/README.md Normal file
View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Working with Apache Thrift](http://www.baeldung.com/apache-thrift)

View File

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

View File

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

View File

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

View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Introduction to Apache Velocity](http://www.baeldung.com/apache-velocity)

101
apache-velocity/pom.xml Normal file
View 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>

View File

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

View File

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

View File

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

View File

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

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

View File

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

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

View File

@ -0,0 +1,4 @@
<div
style="background: #63B175; text-align: center; padding: 5px; margin-top: 10px;">
@Copyright baeldung.com
</div>

View File

@ -0,0 +1,5 @@
<div style="background: #63B175; height: 80px; padding: 5px;">
<div style="float: left">
<h1> Layout Demo Page</h1>
</div>
</div>

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

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

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

View File

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

View File

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

View File

@ -7,17 +7,36 @@
<packaging>jar</packaging>
<name>aws</name>
<properties>
<commons-io.version>2.5</commons-io.version>
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
<gson.version>2.8.0</gson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.1.0</version>
<version>${aws-lambda-java-core.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>${aws-lambda-java-events.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
</dependencies>
@ -26,7 +45,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<version>3.0.0</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>

View File

@ -0,0 +1,49 @@
package com.baeldung.lambda.dynamodb;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.PutItemOutcome;
import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec;
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.baeldung.lambda.dynamodb.bean.PersonRequest;
import com.baeldung.lambda.dynamodb.bean.PersonResponse;
public class SavePersonHandler implements RequestHandler<PersonRequest, PersonResponse> {
private DynamoDB dynamoDb;
private String DYNAMODB_TABLE_NAME = "Person";
private Regions REGION = Regions.US_WEST_2;
public PersonResponse handleRequest(PersonRequest personRequest, Context context) {
this.initDynamoDbClient();
persistData(personRequest);
PersonResponse personResponse = new PersonResponse();
personResponse.setMessage("Saved Successfully!!!");
return personResponse;
}
private PutItemOutcome persistData(PersonRequest personRequest) throws ConditionalCheckFailedException {
return this.dynamoDb.getTable(DYNAMODB_TABLE_NAME)
.putItem(
new PutItemSpec().withItem(new Item()
.withNumber("id", personRequest.getId())
.withString("firstName", personRequest.getFirstName())
.withString("lastName", personRequest.getLastName())
.withNumber("age", personRequest.getAge())
.withString("address", personRequest.getAddress())));
}
private void initDynamoDbClient() {
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
client.setRegion(Region.getRegion(REGION));
this.dynamoDb = new DynamoDB(client);
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.lambda.dynamodb.bean;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class PersonRequest {
private int id;
private String firstName;
private String lastName;
private int age;
private String address;
public static void main(String[] args) {
PersonRequest personRequest = new PersonRequest();
personRequest.setId(1);
personRequest.setFirstName("John");
personRequest.setLastName("Doe");
personRequest.setAge(30);
personRequest.setAddress("United States");
System.out.println(personRequest);
}
public String toString() {
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(this);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.lambda.dynamodb.bean;
import com.google.gson.Gson;
public class PersonResponse {
private String message;
public String toString() {
final Gson gson = new Gson();
return gson.toJson(this);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@ -6,3 +6,5 @@
### Relevant Articles:
- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)

View File

@ -21,6 +21,11 @@
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${ch.qos.logback.version}</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
@ -76,9 +81,9 @@
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<ch.qos.logback.version>1.2.1</ch.qos.logback.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<!-- testing -->

View File

@ -0,0 +1,133 @@
package com.baeldung.java9.process;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by sanaulla on 2/23/2017.
*/
public class ProcessAPIEnhancementsTest {
Logger log = LoggerFactory.getLogger(ProcessAPIEnhancementsTest.class);
@Test
public void givenCurrentProcess_whenInvokeGetInfo_thenSuccess() throws IOException {
ProcessHandle processHandle = ProcessHandle.current();
ProcessHandle.Info processInfo = processHandle.info();
assertNotNull(processHandle.getPid());
assertEquals(false, processInfo.arguments()
.isPresent());
assertEquals(true, processInfo.command()
.isPresent());
assertTrue(processInfo.command()
.get()
.contains("java"));
assertEquals(true, processInfo.startInstant()
.isPresent());
assertEquals(true, processInfo.totalCpuDuration()
.isPresent());
assertEquals(true, processInfo.user()
.isPresent());
}
@Test
public void givenSpawnProcess_whenInvokeGetInfo_thenSuccess() throws IOException {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder = new ProcessBuilder(javaCmd, "-version");
Process process = processBuilder.inheritIO()
.start();
ProcessHandle processHandle = process.toHandle();
ProcessHandle.Info processInfo = processHandle.info();
assertNotNull(processHandle.getPid());
assertEquals(false, processInfo.arguments()
.isPresent());
assertEquals(true, processInfo.command()
.isPresent());
assertTrue(processInfo.command()
.get()
.contains("java"));
assertEquals(true, processInfo.startInstant()
.isPresent());
assertEquals(true, processInfo.totalCpuDuration()
.isPresent());
assertEquals(true, processInfo.user()
.isPresent());
}
@Test
public void givenLiveProcesses_whenInvokeGetInfo_thenSuccess() {
Stream<ProcessHandle> liveProcesses = ProcessHandle.allProcesses();
liveProcesses.filter(ProcessHandle::isAlive)
.forEach(ph -> {
assertNotNull(ph.getPid());
assertEquals(true, ph.info()
.command()
.isPresent());
assertEquals(true, ph.info()
.startInstant()
.isPresent());
assertEquals(true, ph.info()
.totalCpuDuration()
.isPresent());
assertEquals(true, ph.info()
.user()
.isPresent());
});
}
@Test
public void givenProcess_whenGetChildProcess_thenSuccess() throws IOException {
int childProcessCount = 5;
for (int i = 0; i < childProcessCount; i++) {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
processBuilder.inheritIO().start();
}
Stream<ProcessHandle> children = ProcessHandle.current()
.children();
children.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.getPid(), ph.info()
.command()));
Stream<ProcessHandle> descendants = ProcessHandle.current()
.descendants();
descendants.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.getPid(), ph.info()
.command()));
}
@Test
public void givenProcess_whenAddExitCallback_thenSuccess() throws Exception {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
Process process = processBuilder.inheritIO()
.start();
ProcessHandle processHandle = process.toHandle();
log.info("PID: {} has started", processHandle.getPid());
CompletableFuture<ProcessHandle> onProcessExit = processHandle.onExit();
onProcessExit.get();
assertEquals(false, processHandle.isAlive());
onProcessExit.thenAccept(ph -> {
log.info("PID: {} has stopped", ph.getPid());
});
}
}

View File

View File

View File

View File

View File

View File

View File

View File

@ -57,3 +57,25 @@
- [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)
- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map)
- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue)
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception)
- [Guide to WeakHashMap in Java](http://www.baeldung.com/java-weakhashmap)
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams)
- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Spring Security Cache Control Headers](http://www.baeldung.com/spring-security-cache-control-headers)
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
- [Guide to the Guava BiMap](http://www.baeldung.com/guava-bimap)
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany)
- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions)
- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)
- [A Guide to LinkedHashMap in Java](http://www.baeldung.com/java-linked-hashmap)
- [A Guide to TreeMap in Java](http://www.baeldung.com/java-treemap)

View File

@ -1,5 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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>

View File

@ -3,28 +3,35 @@ package com.baeldung.algorithms;
import java.util.Scanner;
import com.baeldung.algorithms.annealing.SimulatedAnnealing;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
import com.baeldung.algorithms.slope_one.SlopeOne;
public class RunAlgorithm {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Run algorithm:");
System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One");
int decision = in.nextInt();
switch (decision) {
case 1:
System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
break;
case 2:
SlopeOne.slopeOne(3);
break;
default:
System.out.println("Unknown option");
break;
}
in.close();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Run algorithm:");
System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One");
System.out.println("3 - Simple Genetic Algorithm");
int decision = in.nextInt();
switch (decision) {
case 1:
System.out.println(
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
break;
case 2:
SlopeOne.slopeOne(3);
break;
case 3:
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
break;
default:
System.out.println("Unknown option");
break;
}
in.close();
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.algorithms.ga.binary;
import lombok.Data;
@Data
public class Individual {
protected int defaultGeneLength = 64;
private byte[] genes = new byte[defaultGeneLength];
private int fitness = 0;
public Individual() {
for (int i = 0; i < genes.length; i++) {
byte gene = (byte) Math.round(Math.random());
genes[i] = gene;
}
}
protected byte getSingleGene(int index) {
return genes[index];
}
protected void setSingleGene(int index, byte value) {
genes[index] = value;
fitness = 0;
}
public int getFitness() {
if (fitness == 0) {
fitness = SimpleGeneticAlgorithm.getFitness(this);
}
return fitness;
}
@Override
public String toString() {
String geneString = "";
for (int i = 0; i < genes.length; i++) {
geneString += getSingleGene(i);
}
return geneString;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.algorithms.ga.binary;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
@Data
public class Population {
private List<Individual> individuals;
public Population(int size, boolean createNew) {
individuals = new ArrayList<>();
if (createNew) {
createNewPopulation(size);
}
}
protected Individual getIndividual(int index) {
return individuals.get(index);
}
protected Individual getFittest() {
Individual fittest = individuals.get(0);
for (int i = 0; i < individuals.size(); i++) {
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
fittest = getIndividual(i);
}
}
return fittest;
}
private void createNewPopulation(int size) {
for (int i = 0; i < size; i++) {
Individual newIndividual = new Individual();
individuals.add(i, newIndividual);
}
}
}

View File

@ -0,0 +1,117 @@
package com.baeldung.algorithms.ga.binary;
import lombok.Data;
@Data
public class SimpleGeneticAlgorithm {
private static final double uniformRate = 0.5;
private static final double mutationRate = 0.025;
private static final int tournamentSize = 5;
private static final boolean elitism = true;
private static byte[] solution = new byte[64];
public 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() < 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 Population evolvePopulation(Population pop) {
int elitismOffset;
Population newPopulation = new Population(pop.getIndividuals().size(), false);
if (elitism) {
newPopulation.getIndividuals().add(0, pop.getFittest());
elitismOffset = 1;
} else {
elitismOffset = 0;
}
for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) {
Individual indiv1 = tournamentSelection(pop);
Individual indiv2 = tournamentSelection(pop);
Individual newIndiv = crossover(indiv1, indiv2);
newPopulation.getIndividuals().add(i, newIndiv);
}
for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) {
mutate(newPopulation.getIndividual(i));
}
return newPopulation;
}
private 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 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 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 int getMaxFitness() {
int maxFitness = solution.length;
return maxFitness;
}
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;
}
}
}
}

View File

@ -15,6 +15,6 @@ public class SquareCalculator {
return executor.submit(() -> {
Thread.sleep(1000);
return input * input;
});
});
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.concurrent.locks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Stack;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import static java.lang.Thread.sleep;
public class ReentrantLockWithCondition {
static Logger logger = LoggerFactory.getLogger(ReentrantLockWithCondition.class);
Stack<String> stack = new Stack<>();
int CAPACITY = 5;
ReentrantLock lock = new ReentrantLock();
Condition stackEmptyCondition = lock.newCondition();
Condition stackFullCondition = lock.newCondition();
public void pushToStack(String item) throws InterruptedException {
try {
lock.lock();
if (stack.size() == CAPACITY) {
logger.info(Thread.currentThread().getName() + " wait on stack full");
stackFullCondition.await();
}
logger.info("Pushing the item " + item);
stack.push(item);
stackEmptyCondition.signalAll();
} finally {
lock.unlock();
}
}
public String popFromStack() throws InterruptedException {
try {
lock.lock();
if (stack.size() == 0) {
logger.info(Thread.currentThread().getName() + " wait on stack empty");
stackEmptyCondition.await();
}
return stack.pop();
} finally {
stackFullCondition.signalAll();
lock.unlock();
}
}
public static void main(String[] args) {
final int threadCount = 2;
ReentrantLockWithCondition object = new ReentrantLockWithCondition();
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
service.execute(() -> {
for (int i = 0; i < 10; i++) {
try {
object.pushToStack("Item " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
service.execute(() -> {
for (int i = 0; i < 10; i++) {
try {
logger.info("Item popped " + object.popFromStack());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
service.shutdown();
}
}

View File

@ -0,0 +1,92 @@
package com.baeldung.concurrent.locks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import static java.lang.Thread.sleep;
public class SharedObjectWithLock {
Logger logger = LoggerFactory.getLogger(SharedObjectWithLock.class);
ReentrantLock lock = new ReentrantLock(true);
int counter = 0;
public void perform() {
lock.lock();
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
try {
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
counter++;
} catch (Exception exception) {
logger.error(" Interrupted Exception ", exception);
} finally {
lock.unlock();
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
}
}
public void performTryLock() {
logger.info("Thread - " + Thread.currentThread().getName() + " attempting to acquire the lock");
try {
boolean isLockAcquired = lock.tryLock(2, TimeUnit.SECONDS);
if (isLockAcquired) {
try {
logger.info("Thread - " + Thread.currentThread().getName() + " acquired the lock");
logger.info("Thread - " + Thread.currentThread().getName() + " processing");
sleep(1000);
} finally {
lock.unlock();
logger.info("Thread - " + Thread.currentThread().getName() + " released the lock");
}
}
} catch (InterruptedException exception) {
logger.error(" Interrupted Exception ", exception);
}
logger.info("Thread - " + Thread.currentThread().getName() + " could not acquire the lock");
}
public ReentrantLock getLock() {
return lock;
}
boolean isLocked() {
return lock.isLocked();
}
boolean hasQueuedThreads() {
return lock.hasQueuedThreads();
}
int getCounter() {
return counter;
}
public static void main(String[] args) {
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
service.execute(() -> {
object.perform();
});
service.execute(() -> {
object.performTryLock();
});
service.shutdown();
}
}

View File

@ -0,0 +1,104 @@
package com.baeldung.concurrent.locks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.StampedLock;
import static java.lang.Thread.sleep;
public class StampedLockDemo {
Map<String, String> map = new HashMap<>();
Logger logger = LoggerFactory.getLogger(StampedLockDemo.class);
private final StampedLock lock = new StampedLock();
public void put(String key, String value) throws InterruptedException {
long stamp = lock.writeLock();
try {
logger.info(Thread.currentThread().getName() + " acquired the write lock with stamp " + stamp);
map.put(key, value);
} finally {
lock.unlockWrite(stamp);
logger.info(Thread.currentThread().getName() + " unlocked the write lock with stamp " + stamp);
}
}
public String get(String key) throws InterruptedException {
long stamp = lock.readLock();
logger.info(Thread.currentThread().getName() + " acquired the read lock with stamp " + stamp);
try {
sleep(5000);
return map.get(key);
} finally {
lock.unlockRead(stamp);
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
}
}
public String readWithOptimisticLock(String key) throws InterruptedException {
long stamp = lock.tryOptimisticRead();
String value = map.get(key);
if (!lock.validate(stamp)) {
stamp = lock.readLock();
try {
sleep(5000);
return map.get(key);
} finally {
lock.unlock(stamp);
logger.info(Thread.currentThread().getName() + " unlocked the read lock with stamp " + stamp);
}
}
return value;
}
public static void main(String[] args) {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
StampedLockDemo object = new StampedLockDemo();
Runnable writeTask = () -> {
try {
object.put("key1", "value1");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Runnable readTask = () -> {
try {
object.get("key1");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Runnable readOptimisticTask = () -> {
try {
object.readWithOptimisticLock("key1");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
service.submit(writeTask);
service.submit(writeTask);
service.submit(readTask);
service.submit(readOptimisticTask);
service.shutdown();
}
}

View File

@ -0,0 +1,120 @@
package com.baeldung.concurrent.locks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static java.lang.Thread.sleep;
public class SynchronizedHashMapWithRWLock {
static Map<String, String> syncHashMap = new HashMap<>();
Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class);
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Lock readLock = lock.readLock();
private final Lock writeLock = lock.writeLock();
public void put(String key, String value) throws InterruptedException {
try {
writeLock.lock();
logger.info(Thread.currentThread().getName() + " writing");
syncHashMap.put(key, value);
sleep(1000);
} finally {
writeLock.unlock();
}
}
public String get(String key) {
try {
readLock.lock();
logger.info(Thread.currentThread().getName() + " reading");
return syncHashMap.get(key);
} finally {
readLock.unlock();
}
}
public String remove(String key) {
try {
writeLock.lock();
return syncHashMap.remove(key);
} finally {
writeLock.unlock();
}
}
public boolean containsKey(String key) {
try {
readLock.lock();
return syncHashMap.containsKey(key);
} finally {
readLock.unlock();
}
}
boolean isReadLockAvailable() {
return readLock.tryLock();
}
public static void main(String[] args) throws InterruptedException {
final int threadCount = 3;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
service.execute(new Thread(new Writer(object), "Writer"));
service.execute(new Thread(new Reader(object), "Reader1"));
service.execute(new Thread(new Reader(object), "Reader2"));
service.shutdown();
}
private static class Reader implements Runnable {
SynchronizedHashMapWithRWLock object;
public Reader(SynchronizedHashMapWithRWLock object) {
this.object = object;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
object.get("key" + i);
}
}
}
private static class Writer implements Runnable {
SynchronizedHashMapWithRWLock object;
public Writer(SynchronizedHashMapWithRWLock object) {
this.object = object;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
object.put("key" + i, "value" + i);
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,75 @@
package com.baeldung.concurrent.locks;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static junit.framework.TestCase.assertEquals;
public class SharedObjectWithLockManualTest {
@Test
public void whenLockAcquired_ThenLockedIsTrue() {
final SharedObjectWithLock object = new SharedObjectWithLock();
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeThreads(object, threadCount, service);
assertEquals(true, object.isLocked());
service.shutdown();
}
@Test
public void whenLocked_ThenQueuedThread() {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
executeThreads(object, threadCount, service);
assertEquals(object.hasQueuedThreads(), true);
service.shutdown();
}
public void whenTryLock_ThenQueuedThread() {
final SharedObjectWithLock object = new SharedObjectWithLock();
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeThreads(object, threadCount, service);
assertEquals(true, object.isLocked());
service.shutdown();
}
@Test
public void whenGetCount_ThenCorrectCount() throws InterruptedException {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
executeThreads(object, threadCount, service);
Thread.sleep(1000);
assertEquals(object.getCounter(), 4);
service.shutdown();
}
private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++) {
service.execute(() -> {
object.perform();
});
}
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.concurrent.locks;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static junit.framework.TestCase.assertEquals;
public class SynchronizedHashMapWithRWLockManualTest {
@Test
public void whenWriting_ThenNoReading() {
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 3;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeWriterThreads(object, threadCount, service);
assertEquals(object.isReadLockAvailable(), false);
service.shutdown();
}
@Test
public void whenReading_ThenMultipleReadingAllowed() {
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 5;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeReaderThreads(object, threadCount, service);
assertEquals(object.isReadLockAvailable(), true);
service.shutdown();
}
private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++) {
service.execute(() -> {
try {
object.put("key" + threadCount, "value" + threadCount);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++)
service.execute(() -> {
object.get("key" + threadCount);
});
}
}

View File

@ -1,12 +1,10 @@
package com.baeldung.concurrent.priorityblockingqueue;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.util.ArrayList;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.util.Lists.newArrayList;
@ -24,11 +22,7 @@ public class PriorityBlockingQueueUnitTest {
queue.add(3);
queue.add(4);
polledElements.add(queue.poll());
polledElements.add(queue.poll());
polledElements.add(queue.poll());
polledElements.add(queue.poll());
polledElements.add(queue.poll());
queue.drainTo(polledElements);
assertThat(polledElements).containsExactly(1, 2, 3, 4, 5);
}
@ -38,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();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,2 +0,0 @@
### Relevant Articles:
- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)

View File

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

View File

@ -0,0 +1,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);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.junit4vstestng;
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
public class DivisibilityTest {
private static int number;
@BeforeClass
public static void setup() {
number = 40;
}
@Test
public void givenNumber_whenDivisibleByTwo_thenCorrect() {
assertEquals(number % 2, 0);
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,22 @@
package com.baeldung.junit4vstestng;
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
public class StringCaseTest {
private static String data;
@BeforeClass
public static void setup() {
data = "HELLO BAELDUNG";
}
@Test
public void givenString_whenAllCaps_thenCorrect() {
assertEquals(data.toUpperCase(), data);
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.junit4vstestng;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ RegistrationTest.class, SignInTest.class })
public class SuiteTest {
}

View File

@ -0,0 +1,58 @@
package com.baeldung.junit4vstestng;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
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;
@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 = numbers.stream()
.reduce(0, Integer::sum);
Assert.assertEquals(6, sum);
}
@Ignore
@Test
public void givenEmptyList_sumEqualsZero_thenCorrect() {
int sum = numbers.stream()
.reduce(0, Integer::sum);
Assert.assertEquals(6, sum);
}
@Test(expected = ArithmeticException.class)
public void givenNumber_whenThrowsException_thenCorrect() {
int i = 1 / 0;
}
}

View File

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

View File

@ -0,0 +1,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);
}
}

View File

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

View File

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

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