Merge remote-tracking branch 'refs/remotes/eugenp/master'

This commit is contained in:
iaforek 2017-04-04 15:36:39 +01:00
commit 0b1bc56504
1001 changed files with 37205 additions and 4235 deletions

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
*/bin/*
*.class
# Package Files #

View File

@ -1,11 +1,13 @@
language: java
install: travis_wait 40 mvn -q clean install -Dgib.enabled=true
install: travis_wait 60 mvn -q test
before_script:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -XX:-UseGCOverheadLimit'" > ~/.mavenrc
jdk:
- oraclejdk8
sudo: false
addons:
apt:
packages:
@ -15,3 +17,5 @@ cache:
directories:
- .autoconf
- $HOME/.m2

3
Twitter4J/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [Introduction to Twitter4J](http://www.baeldung.com/twitter4j)

View File

@ -3,3 +3,4 @@
- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java)

View File

@ -10,9 +10,15 @@
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@ -0,0 +1,13 @@
package com.baeldung.algorithms.primechecker;
import java.math.BigInteger;
public class BigIntegerPrimeChecker implements PrimeChecker{
@Override
public boolean isPrime(int number) {
BigInteger bigInt = BigInteger.valueOf(number);
return bigInt.isProbablePrime(100);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.algorithms.primechecker;
import java.util.stream.IntStream;
public class BruteForcePrimeChecker implements PrimeChecker{
@Override
public boolean isPrime(int number) {
return IntStream.range(2, number).noneMatch(n -> (number % n == 0));
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.algorithms.primechecker;
import java.util.stream.IntStream;
public class OptimisedPrimeChecker implements PrimeChecker{
@Override
public boolean isPrime(int number) {
return IntStream.range(2, (int)Math.sqrt(number) + 1)
.noneMatch(n -> (number % n == 0));
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.algorithms.primechecker;
public interface PrimeChecker {
public boolean isPrime( int number );
}

View File

@ -0,0 +1,12 @@
package com.baeldung.algorithms.primechecker;
import org.apache.commons.math3.primes.Primes;
public class PrimesPrimeChecker implements PrimeChecker{
@Override
public boolean isPrime(int number) {
return Primes.isPrime(number);
}
}

View File

@ -21,12 +21,12 @@ public final class RtState implements State {
}
public State transit(final CharSequence c) {
for(final Transition t : this.transitions) {
if(t.isPossible(c)) {
return t.state();
}
}
throw new IllegalArgumentException("Input not accepted: " + c);
return transitions
.stream()
.filter(t -> t.isPossible(c))
.map(Transition::state)
.findAny()
.orElseThrow(() -> new IllegalArgumentException("Input not accepted: " + c));
}
public boolean isFinal() {

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.primechecker;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.BigIntegerPrimeChecker;
import com.baeldung.algorithms.primechecker.PrimeChecker;
public class BigIntegerPrimeCheckerTest {
PrimeChecker primeChecker = new BigIntegerPrimeChecker();
@Test
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
assertTrue(primeChecker.isPrime(13));
assertTrue(primeChecker.isPrime(1009));
}
@Test
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
assertTrue(!primeChecker.isPrime(50));
assertTrue(!primeChecker.isPrime(1001));
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.algorithms.primechecker;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.BruteForcePrimeChecker;
import static org.junit.Assert.*;
public class BruteForcePrimeCheckerTest {
BruteForcePrimeChecker primeChecker = new BruteForcePrimeChecker();
@Test
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
assertTrue(primeChecker.isPrime(13));
assertTrue(primeChecker.isPrime(1009));
}
@Test
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
assertTrue(!primeChecker.isPrime(50));
assertTrue(!primeChecker.isPrime(1001));
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.primechecker;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.OptimisedPrimeChecker;
import com.baeldung.algorithms.primechecker.PrimeChecker;
public class OptimisedPrimeCheckerTest {
PrimeChecker primeChecker = new OptimisedPrimeChecker();
@Test
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
assertTrue(primeChecker.isPrime(13));
assertTrue(primeChecker.isPrime(1009));
}
@Test
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
assertTrue(!primeChecker.isPrime(50));
assertTrue(!primeChecker.isPrime(1001));
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.algorithms.primechecker;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.primechecker.PrimeChecker;
import com.baeldung.algorithms.primechecker.PrimesPrimeChecker;
public class PrimesPrimeCheckerTest {
PrimeChecker primeChecker = new PrimesPrimeChecker();
@Test
public void givenPrimeNumber_whenCheckIsPrime_thenTrue() {
assertTrue(primeChecker.isPrime(13));
assertTrue(primeChecker.isPrime(1009));
}
@Test
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse() {
assertTrue(!primeChecker.isPrime(50));
assertTrue(!primeChecker.isPrime(1001));
}
}

View File

@ -1 +1,3 @@
*.docx
temp.xls
temp.xlsx

Binary file not shown.

3
aws/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [AWS Lambda Using DynamoDB With Java](http://www.baeldung.com/aws-lambda-dynamodb-java)

3
axon/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [A Guide to the Axon Framework](http://www.baeldung.com/axon-cqrs-event-sourcing)

View File

@ -9,3 +9,6 @@
- [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)
- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java9-completablefuture-api-improvements/)
- [Spring Security Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login)
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)

View File

@ -0,0 +1 @@
javac -d mods --module-source-path src/modules $(find src/modules -name "*.java")

View File

@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.student.client^
src/modules/com.baeldung.student.client/module-info.java^
src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java

View File

@ -0,0 +1,2 @@
javac -d mods/com.baeldung.student.model src/modules/com.baeldung.student.model/module-info.java^
src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java

View File

@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.student.service.dbimpl^
src/modules/com.baeldung.student.service.dbimpl/module-info.java^
src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java

View File

@ -0,0 +1,3 @@
javac --module-path mods -d mods/com.baeldung.student.service^
src/modules/com.baeldung.student.service/module-info.java^
src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java

View File

@ -0,0 +1 @@
java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient

View File

@ -0,0 +1 @@
java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient

View File

@ -0,0 +1,16 @@
package com.baeldung.student.client;
import com.baeldung.student.service.StudentService;
import com.baeldung.student.service.dbimpl.StudentDbService;
import com.baeldung.student.model.Student;
public class StudentClient {
public static void main(String[] args) {
StudentService service = new StudentDbService();
service.create(new Student());
service.read("17SS0001");
service.update(new Student());
service.delete("17SS0001");
}
}

View File

@ -0,0 +1,3 @@
module com.baeldung.student.client{
requires com.baeldung.student.service.dbimpl;
}

View File

@ -0,0 +1,15 @@
package com.baeldung.student.model;
import java.util.Date;
public class Student {
private String registrationId;
public String getRegistrationId() {
return registrationId;
}
public void setRegistrationId(String registrationId) {
this.registrationId = registrationId;
}
}

View File

@ -0,0 +1,3 @@
module com.baeldung.student.model{
exports com.baeldung.student.model;
}

View File

@ -0,0 +1,30 @@
package com.baeldung.student.service.dbimpl;
import com.baeldung.student.service.StudentService;
import com.baeldung.student.model.Student;
import java.util.logging.*;
public class StudentDbService implements StudentService {
private static Logger logger = Logger.getLogger("StudentDbService");
public String create(Student student) {
logger.log(Level.INFO, "Creating student in DB...");
return student.getRegistrationId();
}
public Student read(String registrationId) {
logger.log(Level.INFO, "Reading student from DB...");
return new Student();
}
public Student update(Student student) {
logger.log(Level.INFO, "Updating sutdent in DB...");
return student;
}
public String delete(String registrationId) {
logger.log(Level.INFO, "Deleteing sutdent in DB...");
return registrationId;
}
}

View File

@ -0,0 +1,5 @@
module com.baeldung.student.service.dbimpl{
requires transitive com.baeldung.student.service;
exports com.baeldung.student.service.dbimpl;
requires java.logging;
}

View File

@ -0,0 +1,14 @@
package com.baeldung.student.service;
import com.baeldung.student.model.Student;
public interface StudentService {
public String create(Student student);
public Student read(String registrationId);
public Student update(Student student);
public String delete(String registrationId);
}

View File

@ -0,0 +1,4 @@
module com.baeldung.student.service{
requires transitive com.baeldung.student.model;
exports com.baeldung.student.service;
}

View File

@ -79,3 +79,10 @@
- [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)
- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks)
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)

View File

@ -198,7 +198,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
@ -250,6 +249,7 @@
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>

View File

@ -0,0 +1,61 @@
package com.baeldung.arraycopy.model;
public class Address implements Cloneable {
private String country;
private String state;
private String city;
private String street;
private String zipcode;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
@Override
protected Object clone() throws CloneNotSupportedException {
super.clone();
Address address = new Address();
address.setCity(this.city);
address.setCountry(this.country);
address.setState(this.state);
address.setStreet(this.street);
address.setZipcode(this.zipcode);
return address;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.arraycopy.model;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = -2454619097207585825L;
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,17 +0,0 @@
package com.baeldung.list.flattennestedlist;
import java.util.ArrayList;
import java.util.List;
public class FlattenNestedList {
public List<String> flattenListOfLists(List<List<String>> lol) {
// flatten the list
List<String> ls = new ArrayList<>();
lol.forEach((k) -> ls.addAll(k));
return ls;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.pow;
import java.text.DecimalFormat;
public class PowerExample {
public static void main(String[] args) {
int intResult = (int) Math.pow(2, 3);
System.out.println("Math.pow(2, 3) = " + intResult);
double dblResult = Math.pow(4.2, 3);
System.out.println("Math.pow(4.2, 3) = " + Math.pow(4.2, 3));
DecimalFormat df = new DecimalFormat(".00");
System.out.println("Math.pow(4.2, 3) rounded = " + df.format(dblResult));
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.stringtokenizer;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Application {
public List<String> getTokens(String str) {
List<String> tokens = new ArrayList<String>();
// StringTokenizer tokenizer = new StringTokenizer( str );
StringTokenizer tokenizer = new StringTokenizer( str , "," );
// StringTokenizer tokenizer = new StringTokenizer( str , "," , true );
while (tokenizer.hasMoreElements()) {
tokens.add( tokenizer.nextToken() );
// tokens.add( tokenizer.nextToken( "," ) );
}
return tokens;
}
}

View File

@ -0,0 +1,168 @@
package com.baeldung.arraycopy;
import com.baeldung.arraycopy.model.Address;
import com.baeldung.arraycopy.model.Employee;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
public class ArrayCopyUtilTest {
private static Employee[] employees;
private static final int MAX = 2;
@BeforeClass
public static void setup(){
createEmployeesArray();
}
private static void createEmployeesArray() {
employees = new Employee[MAX];
Employee employee;
for(int i = 0; i < MAX; i++) {
employee = new Employee();
employee.setName("Emp"+i);
employee.setId(i);
employees[i] = employee;
}
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaSystemsArrayCopy_thenSuccessful(){
int[] array = {23, 43, 55};
int[] copiedArray = new int[3];
System.arraycopy(array, 0, copiedArray, 0, 3);
Assert.assertArrayEquals(copiedArray, array);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaSystemsArrayCopy_thenSuccessful(){
int[] array = {23, 43, 55, 12, 65, 88, 92};
int[] copiedArray = new int[3];
System.arraycopy(array, 2, copiedArray, 0, 3);
Assert.assertTrue(3 == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[2]);
Assert.assertTrue(copiedArray[1] == array[3]);
Assert.assertTrue(copiedArray[2] == array[4]);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaArraysCopyOfRange_thenSuccessful(){
int[] array = {23, 43, 55, 12, 65, 88, 92};
int[] copiedArray = Arrays.copyOfRange(array, 1, 4);
Assert.assertTrue(3 == copiedArray.length);
Assert.assertTrue(copiedArray[0] == array[1]);
Assert.assertTrue(copiedArray[1] == array[2]);
Assert.assertTrue(copiedArray[2] == array[3]);
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaArraysCopyOf_thenValueChangeIsSuccessful(){
int[] array = {23, 43, 55, 12};
int newLength = array.length;
int[] copiedArray = Arrays.copyOf(array, newLength);
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
Assert.assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
Assert.assertTrue(copiedArray[1] != array[1]);
}
@Test
public void givenArrayOfNonPrimitiveType_whenCopiedViaArraysCopyOf_thenDoShallowCopy(){
Employee[] copiedArray = Arrays.copyOf(employees, employees.length);
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element caused change in the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArrayOfPrimitiveType_whenCopiedViaArrayClone_thenValueChangeIsSuccessful(){
int[] array = {23, 43, 55, 12};
int[] copiedArray = array.clone();
Assert.assertArrayEquals(copiedArray, array);
array[0] = 9;
Assert.assertTrue(copiedArray[0] != array[0]);
copiedArray[1] = 12;
Assert.assertTrue(copiedArray[1] != array[1]);
}
@Test
public void givenArraysOfNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
Employee[] copiedArray = employees.clone();
Assert.assertArrayEquals(copiedArray, employees);;
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element changed the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfCloneableNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
Address[] addresses = createAddressArray();
Address[] copiedArray = addresses.clone();
addresses[0].setCity(addresses[0].getCity()+"_Changed");
Assert.assertArrayEquals(copiedArray, addresses);
}
@Test
public void givenArraysOfSerializableNonPrimitiveType_whenCopiedViaSerializationUtils_thenDoDeepCopy(){
Employee[] copiedArray = SerializationUtils.clone(employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
Assert.assertFalse(
copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfNonPrimitiveType_whenCopiedViaStream_thenDoShallowCopy(){
Employee[] copiedArray = Arrays.stream(employees).toArray(Employee[]::new);
Assert.assertArrayEquals(copiedArray, employees);
employees[0].setName(employees[0].getName()+"_Changed");
//change in employees' element didn't change in the copied array
Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
}
@Test
public void givenArraysOfPrimitiveType_whenCopiedViaStream_thenSuccessful(){
String[] strArray = {"orange", "red", "green'"};
String[] copiedArray = Arrays.stream(strArray).toArray(String[]::new);
Assert.assertArrayEquals(copiedArray, strArray);
}
private Address[] createAddressArray(){
Address[] addresses = new Address[1];
addresses[0] = createAddress();
return addresses;
}
private Address createAddress() {
Address address = new Address();
address.setCountry("USA");
address.setState("CA");
address.setCity("San Francisco");
address.setStreet("Street 1");
address.setZipcode("59999");
return address;
}
}

View File

@ -12,7 +12,7 @@ import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
public class CountdownLatchExampleTest {
public class CountdownLatchExampleIntegrationTest {
@Test
public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException {
// Given

View File

@ -1,5 +1,6 @@
package com.baeldung.enums;
import com.baeldung.enums.Pizza.PizzaStatusEnum;
import org.junit.Test;
import java.util.ArrayList;
@ -69,11 +70,31 @@ public class PizzaUnitTest {
}
@Test
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
public void whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
Pizza pz = new Pizza();
pz.setStatus(Pizza.PizzaStatusEnum.READY);
pz.deliver();
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
}
@Test
public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() {
String pizzaEnumValue = "READY";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY);
}
@Test(expected = IllegalArgumentException.class)
public void whenConvertedIntoEnum_thenThrowsException() {
String pizzaEnumValue = "rEAdY";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
}
@Test(expected = IllegalArgumentException.class)
public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() {
String pizzaEnumValue = "invalid";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
}
}

View File

@ -60,7 +60,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingComparing_thenCheckingSort() {
public void whenComparing_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
@ -68,7 +68,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingComparingWithComparator_thenCheckingSort() {
public void whenComparingWithComparator_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName, (s1, s2) -> {
return s2.compareTo(s1);
});
@ -78,7 +78,16 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingComparingInt_thenCheckingSort() {
public void whenReversed_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
Arrays.sort(employees, employeeNameComparatorReversed);
// System.out.println(Arrays.toString(employees));
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
}
@Test
public void whenComparingInt_thenSortedByAge() {
Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
Arrays.sort(employees, employeeAgeComparator);
// System.out.println(Arrays.toString(employees));
@ -86,7 +95,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingComparingLong_thenCheckingSort() {
public void whenComparingLong_thenSortedByMobile() {
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
Arrays.sort(employees, employeeMobileComparator);
// System.out.println(Arrays.toString(employees));
@ -94,7 +103,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingComparingDouble_thenCheckingSort() {
public void whenComparingDouble_thenSortedBySalary() {
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
Arrays.sort(employees, employeeSalaryComparator);
// System.out.println(Arrays.toString(employees));
@ -102,7 +111,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingNaturalOrder_thenCheckingSort() {
public void whenNaturalOrder_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
@ -110,7 +119,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingReverseOrder_thenCheckingSort() {
public void whenReverseOrder_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees));
@ -118,7 +127,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingNullFirst_thenCheckingSort() {
public void whenNullsFirst_thenSortedByNameWithNullsFirst() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
@ -127,7 +136,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingNullLast_thenCheckingSort() {
public void whenNullsLast_thenSortedByNameWithNullsLast() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
@ -136,7 +145,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingThenComparing_thenCheckingSort() {
public void whenThenComparing_thenSortedByAgeName() {
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
@ -145,7 +154,7 @@ public class Java8ComparatorTest {
}
@Test
public void givenEmployeeArray_whenUsingThenComparingInt_thenCheckingSort() {
public void whenThenComparing_thenSortedByNameAge() {
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
@ -153,40 +162,6 @@ public class Java8ComparatorTest {
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
}
@Before
public void printData() {
// System.out.println("employees");
// System.out.println(Arrays.toString(employees));
//
// System.out.println("employeesArrayWithNulls");
// System.out.println(Arrays.toString(employeesArrayWithNulls));
//
// System.out.println("sortedEmployeesByName");
// System.out.println(Arrays.toString(sortedEmployeesByName));
//
// System.out.println("sortedEmployeesByNameDesc");
// System.out.println(Arrays.toString(sortedEmployeesByNameDesc));
//
// System.out.println("sortedEmployeesByAge");
// System.out.println(Arrays.toString(sortedEmployeesByAge));
//
// System.out.println("sortedEmployeesByMobile");
// System.out.println(Arrays.toString(sortedEmployeesByMobile));
//
// System.out.println("sortedEmployeesBySalary");
// System.out.println(Arrays.toString(sortedEmployeesBySalary));
//
// System.out.println("sortedEmployeesArray_WithNullsFirst");
// System.out.println(Arrays.toString(sortedEmployeesArray_WithNullsFirst));
//
// System.out.println("sortedEmployeesArray_WithNullsLast");
// System.out.println(Arrays.toString(sortedEmployeesArray_WithNullsLast));
//
// System.out.println("sortedEmployeesByNameAge");
// System.out.println(Arrays.toString(sortedEmployeesByNameAge));
//
// System.out.println("someMoreEmployees");
// System.out.println(Arrays.toString(someMoreEmployees));
//
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.junit4vstestng;
import static org.junit.Assert.assertTrue;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SortedTests {
@Test
public void a_givenString_whenChangedtoInt_thenTrue() {
assertTrue(Integer.valueOf("10") instanceof Integer);
}
@Test
public void b_givenInt_whenChangedtoString_thenTrue() {
assertTrue(String.valueOf(10) instanceof String);
}
}

View File

@ -1,52 +1,48 @@
package com.baeldung.list.flattennestedlist;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Before;
import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FlattenNestedListTest {
List<List<String>> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
private static final Logger LOGGER = LoggerFactory.getLogger(FlattenNestedListTest.class);
private FlattenNestedList flol;
@Test
public void givenNestedList_thenFlattenNestedListImperative() {
List<String> ls = flattenListOfListsImperatively(lol);
@Before
public void setup() {
flol = new FlattenNestedList();
assertNotNull(ls);
assertTrue(ls.size() == 8);
// assert content
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
}
@Test
public void givenListOfListOfString_flattenNestedList() {
// create the list to flatten
List<String> ls1 = Arrays.asList("one:one", "one:two", "one:three");
List<String> ls2 = Arrays.asList("two:one", "two:two", "two:three");
List<String> ls3 = Arrays.asList("three:one", "three:two", "three:three");
List<List<String>> lol = new ArrayList<>();
lol.addAll(Arrays.asList(ls1, ls2, ls3));
// show nested list
LOGGER.debug("\nNested list: ");
lol.forEach((nl) -> LOGGER.debug(nl + ""));
// flatten it
List<String> ls = flol.flattenListOfLists(lol);
public void givenNestedList_thenFlattenNestedListStream() {
List<String> ls = flattenListOfListsStream(lol);
assertNotNull(ls);
assertTrue(ls.size() == 9);
// show flattened list
LOGGER.debug("\nFlattened list:");
ls.forEach((l) -> LOGGER.debug(l));
assertTrue(ls.size() == 8);
// assert content
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
}
public <T> List<T> flattenListOfListsImperatively(List<List<T>> list) {
List<T> ls = new ArrayList<>();
list.forEach(ls::addAll);
return ls;
}
public <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream().flatMap(Collection::stream).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.stringtokenizer;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ApplicationTest {
Application application = new Application();
List<String> expectedTokens = new ArrayList<String>();
@Before
public void init() {
expectedTokens.add( "Welcome" );
expectedTokens.add( "to" );
expectedTokens.add( "baeldung.com" );
}
@Test
public void givenString_thenGetListOfString() {
String str = "Welcome,to,baeldung.com";
List<String> actualTokens = application.getTokens(str);
assertEquals(expectedTokens, actualTokens);
}
}

View File

@ -7,7 +7,7 @@ import java.io.*;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
public class JavaProcessUnitTest {
public class JavaProcessUnitIntegrationTest {
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
private static class StreamGobbler implements Runnable {

View File

@ -13,7 +13,7 @@ import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ThreadPoolInParallelStreamTest {
public class ThreadPoolInParallelStreamIntegrationTest {
@Test
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {

View File

@ -145,6 +145,7 @@
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>

47
groovy-spock/pom.xml Normal file
View File

@ -0,0 +1,47 @@
<?xml version="1.0"?>
<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>org.spockframework</groupId>
<artifactId>groovy-spock</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spock Framework - Example Project</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>1.0-groovy-2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.7</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,89 @@
import spock.lang.Specification
class FirstSpecification extends Specification {
def "one plus one should equal two"() {
expect:
1 + 1 == 2
}
def "two plus two should equal four"() {
given:
int left = 2
int right = 2
when:
int result = left + right
then:
result == 4
}
def "Should be able to remove from list"() {
given:
def list = [1, 2, 3, 4]
when:
list.remove(0)
then:
list == [2, 3, 4]
}
def "Should get an index out of bounds when removing a non-existent item"() {
given:
def list = [1, 2, 3, 4]
when:
list.remove(20)
then:
thrown(IndexOutOfBoundsException)
list.size() == 4
}
def "numbers to the power of two"(int a, int b, int c) {
expect:
Math.pow(a, b) == c
where:
a | b | c
1 | 2 | 1
2 | 2 | 4
3 | 2 | 9
}
def "Should return default value for mock"() {
given:
def paymentGateway = Mock(PaymentGateway)
when:
def result = paymentGateway.makePayment(12.99)
then:
!result
}
def "Should return true value for mock"() {
given:
def paymentGateway = Mock(PaymentGateway)
paymentGateway.makePayment(20) >> true
when:
def result = paymentGateway.makePayment(20)
then:
result
}
def "Should verify notify was called"() {
given:
def notifier = Mock(Notifier)
when:
notifier.notify('foo')
then:
1 * notifier.notify('foo')
}
}

View File

@ -0,0 +1,3 @@
interface Notifier {
void notify(String message)
}

View File

@ -0,0 +1,3 @@
interface PaymentGateway {
boolean makePayment(BigDecimal amount)
}

View File

@ -24,3 +24,4 @@
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
- [Guide to Guavas Reflection Utilities](http://www.baeldung.com/guava-reflection)

View File

@ -0,0 +1,192 @@
package org.baeldung.guava;
import com.google.common.math.DoubleMath;
import com.google.common.math.IntMath;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.math.BigInteger;
import java.math.RoundingMode;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class GuavaMathTest {
@Test
public void testIntMathAdd() {
try {
IntMath.checkedAdd(Integer.MAX_VALUE, 1);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
try {
IntMath.checkedAdd(Integer.MIN_VALUE, -1);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
int result1 = IntMath.checkedAdd(2, 1);
assertThat(result1, equalTo(3));
int result2 = IntMath.saturatedAdd(Integer.MAX_VALUE, 100);
assertThat(result2, equalTo(Integer.MAX_VALUE));
int result3 = IntMath.saturatedAdd(Integer.MIN_VALUE, -100);
assertThat(result3, equalTo(Integer.MIN_VALUE));
}
@Test
public void testIntMathSubtract() {
try {
IntMath.checkedSubtract(Integer.MIN_VALUE, 1);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
try {
IntMath.checkedSubtract(Integer.MAX_VALUE, -1);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
};
int result1 = IntMath.checkedSubtract(200, 100);
assertThat(result1, equalTo(100));
int result2 = IntMath.saturatedSubtract(Integer.MIN_VALUE, 1);
assertThat(result2, equalTo(Integer.MIN_VALUE));
int result3 = IntMath.saturatedSubtract(Integer.MAX_VALUE, -1);
assertThat(result3, equalTo(Integer.MAX_VALUE));
}
@Test
public void testIntMathMultiply() {
try {
IntMath.checkedMultiply(Integer.MAX_VALUE, 2);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
try {
IntMath.checkedMultiply(Integer.MIN_VALUE, 2);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
int result1 = IntMath.checkedMultiply(21, 3);
assertThat(result1, equalTo(63));
int result2 = IntMath.saturatedMultiply(Integer.MAX_VALUE, 2);
assertThat(result2, equalTo(Integer.MAX_VALUE));
int result3 = IntMath.saturatedMultiply(Integer.MIN_VALUE, 2);
assertThat(result3, equalTo(Integer.MIN_VALUE));
}
@Test
public void testIntMathPow() {
try {
IntMath.checkedPow(Integer.MAX_VALUE, 2);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
try {
IntMath.checkedPow(Integer.MIN_VALUE, 3);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
int result1 = IntMath.saturatedPow(3, 3);
assertThat(result1, equalTo(27));
int result2 = IntMath.saturatedPow(Integer.MAX_VALUE, 2);
assertThat(result2, equalTo(Integer.MAX_VALUE));
int result3 = IntMath.saturatedPow(Integer.MIN_VALUE, 3);
assertThat(result3, equalTo(Integer.MIN_VALUE));
}
@Test
public void testIntMathRound() {
int result1 = IntMath.divide(3, 2, RoundingMode.DOWN);
assertThat(result1, equalTo(1));
int result2 = IntMath.divide(3, 2, RoundingMode.UP);
assertThat(result2, equalTo(2));
int result3 = IntMath.log2(5, RoundingMode.FLOOR);
assertThat(result3, equalTo(2));
int result4 = IntMath.log2(5, RoundingMode.CEILING);
assertThat(result4, equalTo(3));
int result5 = IntMath.log10(11, RoundingMode.HALF_UP);
assertThat(result5, equalTo(1));
int result6 = IntMath.sqrt(4, RoundingMode.UNNECESSARY);
assertThat(result6, equalTo(2));
try {
IntMath.sqrt(5, RoundingMode.UNNECESSARY);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
}
@Test
public void testIntMathAdditionalFunctions() {
int result1 = IntMath.gcd(15, 20);
assertThat(result1, equalTo(5));
int result2 = IntMath.mod(8, 3);
assertThat(result2, equalTo(2));
boolean result3 = IntMath.isPowerOfTwo(8);
assertTrue(result3);
boolean result4 = IntMath.isPowerOfTwo(9);
assertFalse(result4);
int result5 = IntMath.factorial(4);
assertThat(result5, equalTo(24));
int result6 = IntMath.binomial(7, 3);
assertThat(result6, equalTo(35));
}
@Test
public void should_detect_integer() {
boolean result1 = DoubleMath.isMathematicalInteger(2.0);
assertThat(result1, equalTo(true));
boolean result2 = DoubleMath.isMathematicalInteger(2.1);
assertThat(result2, equalTo(false));
}
@Test
public void should_round_to_integer_types() {
int result3 = DoubleMath.roundToInt(2.5, RoundingMode.DOWN);
assertThat(result3, equalTo(2));
long result4 = DoubleMath.roundToLong(2.5, RoundingMode.HALF_UP);
assertThat(result4, equalTo(3L));
BigInteger result5 = DoubleMath.roundToBigInteger(2.5, RoundingMode.UP);
assertThat(result5, equalTo(new BigInteger("3")));
}
@Test
public void should_calculate_log_2() {
int result6 = DoubleMath.log2(10, RoundingMode.UP);
assertThat(result6, equalTo(4));
}
}

1
guava21/README.md Normal file
View File

@ -0,0 +1 @@
## Relevant articles:

41
guava21/pom.xml Normal file
View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.guava</groupId>
<artifactId>tutorial</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,27 @@
package com.baeldung.guava.tutorial;
import com.google.common.util.concurrent.AtomicLongMap;
public class AtomicLongMapTutorials {
private AtomicLongMap<String> atomicLongMap;
public AtomicLongMapTutorials() {
atomicLongMap = AtomicLongMap.create();
}
public void addKeys() {
atomicLongMap.addAndGet("apple", 250);
atomicLongMap.addAndGet("bat", 350);
atomicLongMap.addAndGet("cat", 450);
atomicLongMap.addAndGet("dog", 550);
}
public static void main(String[] args) {
AtomicLongMapTutorials atomicLongMapTutorials = new AtomicLongMapTutorials();
atomicLongMapTutorials.addKeys();
System.out.println(atomicLongMapTutorials.atomicLongMap.get("2"));
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Comparators;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ComparatorsExamples {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 4, 6, 7, 8, 9, 10);
boolean isInAscendingOrder = Comparators.isInOrder(integers, new AscedingOrderComparator());
System.out.println(isInAscendingOrder);
}
private static class AscedingOrderComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Streams;
import java.util.stream.Stream;
public class ConcatStreams {
public static Stream concatStreams(Stream stream1, Stream stream2, Stream stream3) {
return Streams.concat(stream1, stream2, stream3);
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
public class InternerBuilderExample {
public static void main(String[] args) {
Interner<Integer> interners = Interners.<Integer> newBuilder()
.concurrencyLevel(2)
.strong().<Integer> build();
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.guava.tutorial;
import com.google.common.util.concurrent.Monitor;
import java.util.ArrayList;
import java.util.List;
public class MonitorExample {
private List<String> students = new ArrayList<String>();
private static final int MAX_SIZE = 100;
private Monitor monitor = new Monitor();
public void addToCourse(String item) throws InterruptedException {
Monitor.Guard studentsBelowCapacity = monitor.newGuard(this::isStudentsCapacityUptoLimit);
monitor.enterWhen(studentsBelowCapacity);
try {
students.add(item);
} finally {
monitor.leave();
}
}
public Boolean isStudentsCapacityUptoLimit() {
return students.size() > MAX_SIZE;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.MoreCollectors;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class MoreCollectorsExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1);
Optional<Integer> number = numbers
.stream()
.map(e -> e * 2)
.collect(MoreCollectors.toOptional());
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.guava.tutorial;
import com.google.common.collect.Streams;
import java.util.*;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
public class StreamsUtility {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
//Using Collection
Stream<Integer> streamFromCollection = Streams.stream(numbers);
//Using Iterator
Stream<Integer> streamFromIterator = Streams.stream(numbers.iterator());
//Using Iterable
Stream<Integer> streamFromIterable = Streams.stream((Iterable<Integer>) numbers);
//Using Optional
Stream<Integer> streamFromOptional = Streams.stream(Optional.of(1));
//Using OptionalLong to LongStream
LongStream streamFromOptionalLong = Streams.stream(OptionalLong.of(1));
//Using OptionalInt to IntStream
IntStream streamFromOptionalInt = Streams.stream(OptionalInt.of(1));
//Using OptionalDouble to DoubleStream
DoubleStream streamFromOptionalDouble = Streams.stream(OptionalDouble.of(1.0));
Stream<Integer> concatenatedStreams = Streams.concat(streamFromCollection, streamFromIterable, streamFromIterator);
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
//This will return 10
Optional<Integer> lastItem = Streams.findLast(integers.stream());
Streams.zip(Stream.of("candy", "chocolate", "bar"), Stream.of("$1", "$2", "$3"), (arg1, arg2) -> arg1 + ":" + arg2);
}
}

View File

@ -0,0 +1,54 @@
import com.google.common.util.concurrent.AtomicLongMap;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AtomicLongMapTests {
private static final String SPRING_COURSE_KEY = "Spring";
private static final String HIBERNATE_COURSE_KEY = "hibernate";
private static final String GUAVA_COURSE_KEY = "Guava";
AtomicLongMap<String> courses = AtomicLongMap.create();
public void setUp() {
courses.put(SPRING_COURSE_KEY, 1056);
courses.put(HIBERNATE_COURSE_KEY, 259);
courses.put(GUAVA_COURSE_KEY, 78);
}
@Test
public void accumulateAndGet_withLongBinaryOperator_thenSuccessful() {
long noOfStudents = 56;
long oldValue = courses.get(SPRING_COURSE_KEY);
long totalNotesRequired = courses.accumulateAndGet("Guava", noOfStudents, (x, y) -> (x * y));
assertEquals(totalNotesRequired, oldValue * noOfStudents);
}
@Test
public void getAndAccumulate_withLongBinaryOperator_thenSuccessful() {
long noOfStudents = 56;
long beforeUpdate = courses.get(SPRING_COURSE_KEY);
long onUpdate = courses.accumulateAndGet("Guava", noOfStudents, (x, y) -> (x * y));
long afterUpdate = courses.get(SPRING_COURSE_KEY);
assertEquals(onUpdate, afterUpdate);
assertEquals(afterUpdate, beforeUpdate * noOfStudents);
}
@Test
public void updateAndGet_withLongUnaryOperator_thenSuccessful() {
long beforeUpdate = courses.get(SPRING_COURSE_KEY);
long onUpdate = courses.updateAndGet("Guava", (x) -> (x / 2));
long afterUpdate = courses.get(SPRING_COURSE_KEY);
assertEquals(onUpdate, afterUpdate);
assertEquals(afterUpdate, beforeUpdate / 2);
}
}

View File

@ -0,0 +1,77 @@
import com.google.common.collect.Comparators;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
public class ComparatorsUnitTests {
@Test
public void isInOrderTest() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 4, 6, 7, 8, 9, 10);
boolean isInAscendingOrder = Comparators.isInOrder(numbers, new AscendingOrderComparator<Number>());
Assert.assertTrue(isInAscendingOrder);
}
@Test
public void isInStrictOrderTest() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 3, 6, 7, 8, 9, 10);
boolean isInAscendingOrder = Comparators.isInOrder(numbers, new AscendingOrderComparator<Number>());
Assert.assertFalse(isInAscendingOrder);
}
private class AscendingOrderComparator<I extends Number> implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
@Override
public Comparator<Integer> reversed() {
return null;
}
@Override
public Comparator<Integer> thenComparing(Comparator<? super Integer> other) {
return null;
}
@Override
public <U> Comparator<Integer> thenComparing(Function<? super Integer, ? extends U> keyExtractor, Comparator<? super U> keyComparator) {
return null;
}
@Override
public <U extends Comparable<? super U>> Comparator<Integer> thenComparing(Function<? super Integer, ? extends U> keyExtractor) {
return null;
}
@Override
public Comparator<Integer> thenComparingInt(ToIntFunction<? super Integer> keyExtractor) {
return null;
}
@Override
public Comparator<Integer> thenComparingLong(ToLongFunction<? super Integer> keyExtractor) {
return null;
}
@Override
public Comparator<Integer> thenComparingDouble(ToDoubleFunction<? super Integer> keyExtractor) {
return null;
}
}
}

View File

@ -0,0 +1,158 @@
import com.google.common.collect.Streams;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
public class GauavaStreamsTests {
List<Integer> numbers;
@Before
public void setUp() {
numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
}
@Test
public void createStreamsWithCollection() {
//Deprecated API to create stream from collection
Stream streamFromCollection = Streams.stream(numbers);
//Assert.assertNotNull(streamFromCollection);
StreamUtility.assertStreamEquals(streamFromCollection, numbers.stream());
}
@Test
public void createStreamsWithIterable() {
Iterable<Integer> numbersIterable = (Iterable<Integer>) numbers;
Stream streamFromIterable = Streams.stream(numbersIterable);
Assert.assertNotNull(streamFromIterable);
StreamUtility.assertStreamEquals(streamFromIterable, numbers.stream());
}
@Test
public void createStreamsWithIterator() {
Iterator<Integer> numbersIterator = numbers.iterator();
Stream streamFromIterator = Streams.stream(numbersIterator);
Assert.assertNotNull(streamFromIterator);
StreamUtility.assertStreamEquals(streamFromIterator, numbers.stream());
}
@Test
public void createStreamsWithOptional() {
Stream streamFromOptional = Streams.stream(Optional.of(1));
Assert.assertNotNull(streamFromOptional);
Assert.assertEquals(streamFromOptional.count(), 1);
}
@Test
public void createStreamsWithOptionalLong() {
LongStream streamFromOptionalLong = Streams.stream(OptionalLong.of(1));
Assert.assertNotNull(streamFromOptionalLong);
Assert.assertEquals(streamFromOptionalLong.count(), 1);
}
@Test
public void createStreamsWithOptionalInt() {
IntStream streamFromOptionalInt = Streams.stream(OptionalInt.of(1));
//Assert.assertNotNull(streamFromOptionalInt);
Assert.assertEquals(streamFromOptionalInt.count(), 1);
}
@Test
public void createStreamsWithOptionalDouble() {
DoubleStream streamFromOptionalDouble = Streams.stream(OptionalDouble.of(1.0));
//Assert.assertNotNull(streamFromOptionalDouble);
Assert.assertEquals(streamFromOptionalDouble.count(), 1);
}
@Test
public void concatStreamsOfSameType() {
Stream oddNumbers = Arrays
.asList(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
.stream();
Stream evenNumbers = Arrays
.asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
.stream();
Stream combinedStreams = Streams.concat(oddNumbers, evenNumbers);
//Assert.assertNotNull(combinedStreams);
StreamUtility.assertStreamEquals(combinedStreams, Stream.concat(oddNumbers, evenNumbers));
}
@Test
public void concatStreamsOfTypeLongStream() {
LongStream firstTwenty = LongStream.range(1, 20);
LongStream nextTwenty = LongStream.range(21, 40);
LongStream combinedStreams = Streams.concat(firstTwenty, nextTwenty);
Assert.assertNotNull(combinedStreams);
StreamUtility.assertStreamEquals(combinedStreams, LongStream.concat(firstTwenty, nextTwenty));
}
@Test
public void concatStreamsOfTypeIntStream() {
IntStream firstTwenty = IntStream.range(1, 20);
IntStream nextTwenty = IntStream.range(21, 40);
IntStream combinedStreams = Streams.concat(firstTwenty, nextTwenty);
Assert.assertNotNull(combinedStreams);
StreamUtility.assertStreamEquals(combinedStreams, IntStream.concat(firstTwenty, nextTwenty));
}
@Test
public void findLastOfStream() {
Optional<Integer> lastElement = Streams.findLast(numbers.stream());
Assert.assertNotNull(lastElement.get());
Assert.assertEquals(lastElement.get(), numbers.get(20));
}
@Test
public void mapWithIndexTest() {
Stream stringSream = Stream.of("a", "b", "c");
Stream<String> mappedStream = Streams.mapWithIndex(stringSream, (str, index) -> str + ":" + index);
//Assert.assertNotNull(mappedStream);
Assert.assertEquals(mappedStream
.findFirst()
.get(), "a:0");
}
@Test
public void streamsZipTest() {
Stream stringSream = Stream.of("a", "b", "c");
Stream intStream = Stream.of(1, 2, 3);
Stream<String> mappedStream = Streams.zip(stringSream, intStream, (str, index) -> str + ":" + index);
//Assert.assertNotNull(mappedStream);
Assert.assertEquals(mappedStream
.findFirst()
.get(), "a:1");
}
}

View File

@ -0,0 +1,18 @@
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
import org.junit.Assert;
import org.junit.Test;
public class InternBuilderUnitTests {
@Test
public void interBuilderTest() {
Interner<Integer> interners = Interners.<Integer> newBuilder()
.concurrencyLevel(2)
.strong().<Integer> build();
Assert.assertNotNull(interners);
}
}

View File

@ -0,0 +1,53 @@
import com.google.common.util.concurrent.Monitor;
import org.junit.Assert;
import org.junit.Test;
public class MonitorUnitTests {
@Test
public void whenGaurdConditionIsTrue_IsSuccessful() {
Monitor monitor = new Monitor();
boolean enteredInCriticalSection = false;
Monitor.Guard gaurdCondition = monitor.newGuard(this::returnTrue);
if (monitor.enterIf(gaurdCondition)) {
try {
System.out.println("Entered in critical section");
enteredInCriticalSection = true;
} finally {
monitor.leave();
}
}
Assert.assertTrue(enteredInCriticalSection);
}
@Test
public void whenGaurdConditionIsFalse_IsSuccessful() {
Monitor monitor = new Monitor();
boolean enteredInCriticalSection = false;
Monitor.Guard gaurdCondition = monitor.newGuard(this::returnFalse);
if (monitor.enterIf(gaurdCondition)) {
try {
System.out.println("Entered in critical section");
enteredInCriticalSection = true;
} finally {
monitor.leave();
}
}
Assert.assertFalse(enteredInCriticalSection);
}
private boolean returnTrue() {
return true;
}
private boolean returnFalse() {
return false;
}
}

View File

@ -0,0 +1,36 @@
import com.google.common.collect.MoreCollectors;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class MoreCollectorsUnitTests {
@Test
public void toOptionalTest() {
List<Integer> numbers = Arrays.asList(1);
Optional<Integer> number = numbers
.stream()
.map(e -> e * 2)
.collect(MoreCollectors.toOptional());
Assert.assertEquals(number.get(), new Integer(2));
}
@Test
public void onlyElementTest() {
List<Integer> numbers = Arrays.asList(1);
Integer number = numbers
.stream()
.map(e -> e * 2)
.collect(MoreCollectors.onlyElement());
Assert.assertEquals(number, new Integer(2));
}
}

View File

@ -0,0 +1,66 @@
import org.junit.Assert;
import java.util.Iterator;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
public class StreamUtility {
public static <T> boolean assertStreamEquals(Stream<T> stream1, Stream<T> stream2) {
Iterator<T> iterator1 = stream1.iterator();
Iterator<T> iterator2 = stream2.iterator();
while (iterator1.hasNext()) {
Assert.assertEquals(iterator1.next(), iterator2.next());
}
Assert.assertFalse(iterator2.hasNext());
return true;
}
public static boolean assertStreamEquals(LongStream stream1, LongStream stream2) {
Iterator iterator1 = stream1.iterator();
Iterator iterator2 = stream2.iterator();
while (iterator1.hasNext()) {
Assert.assertEquals(iterator1.next(), iterator2.next());
}
Assert.assertFalse(iterator2.hasNext());
return true;
}
public static boolean assertStreamEquals(DoubleStream stream1, DoubleStream stream2) {
Iterator iterator1 = stream1.iterator();
Iterator iterator2 = stream2.iterator();
while (iterator1.hasNext()) {
Assert.assertEquals(iterator1.next(), iterator2.next());
}
Assert.assertFalse(iterator2.hasNext());
return true;
}
public static boolean assertStreamEquals(IntStream stream1, IntStream stream2) {
Iterator iterator1 = stream1.iterator();
Iterator iterator2 = stream2.iterator();
while (iterator1.hasNext()) {
Assert.assertEquals(iterator1.next(), iterator2.next());
}
Assert.assertFalse(iterator2.hasNext());
return true;
}
}

4
guice/README.md Normal file
View File

@ -0,0 +1,4 @@
## Google Guice Tutorials Project
### Relevant Articles
- [Guide to Google Guice](http://www.baeldung.com/guice)

3
hbase/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [HBase with Java](http://www.baeldung.com/hbase)

View File

@ -33,6 +33,7 @@
<groupId>org.apache.hbase</groupId>
<artifactId>hbase</artifactId>
<version>${hbase.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>junit</groupId>

View File

@ -26,3 +26,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance)
- [Guide to @JsonFormat in Jackson](http://www.baeldung.com/jackson-jsonformat)
- [A Guide to Optional with Jackson](http://www.baeldung.com/jackson-optional)
- [Map Serialization and Deserialization with Jackson](http://www.baeldung.com/jackson-map)

View File

@ -195,7 +195,7 @@
<properties>
<!-- marshalling -->
<jackson.version>2.8.6</jackson.version>
<jackson.version>2.8.7</jackson.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>

View File

@ -0,0 +1,24 @@
package com.baeldung.jackson.entities;
import java.util.Map;
import com.baeldung.jackson.serialization.MyPairDeserializer;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class ClassWithAMap {
@JsonProperty("map")
@JsonDeserialize(keyUsing = MyPairDeserializer.class)
private final Map<MyPair, String> map;
@JsonCreator
public ClassWithAMap(Map<MyPair, String> map) {
this.map = map;
}
public Map<MyPair, String> getMap() {
return map;
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.jackson.entities;
import com.fasterxml.jackson.annotation.JsonValue;
public class MyPair {
private String first;
private String second;
public MyPair(String first, String second) {
this.first = first;
this.second = second;
}
public MyPair(String both) {
String[] pairs = both.split("and");
this.first = pairs[0].trim();
this.second = pairs[1].trim();
}
@Override
@JsonValue
public String toString() {
return first + " and " + second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((first == null) ? 0 : first.hashCode());
result = prime * result + ((second == null) ? 0 : second.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MyPair)) {
return false;
}
MyPair other = (MyPair) obj;
if (first == null) {
if (other.first != null) {
return false;
}
} else if (!first.equals(other.first)) {
return false;
}
if (second == null) {
if (other.second != null) {
return false;
}
} else if (!second.equals(other.second)) {
return false;
}
return true;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSecond() {
return second;
}
public void setSecond(String second) {
this.second = second;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.jackson.serialization;
import java.io.IOException;
import com.baeldung.jackson.entities.MyPair;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.KeyDeserializer;
public class MyPairDeserializer extends KeyDeserializer {
@Override
public MyPair deserializeKey(String key, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
return new MyPair(key);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.jackson.serialization;
import java.io.IOException;
import java.io.StringWriter;
import com.baeldung.jackson.entities.MyPair;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
public class MyPairSerializer extends JsonSerializer<MyPair> {
private final ObjectMapper mapper = new ObjectMapper();
@Override
public void serialize(MyPair value, JsonGenerator gen,
SerializerProvider serializers) throws IOException,
JsonProcessingException {
StringWriter writer = new StringWriter();
mapper.writeValue(writer, value);
gen.writeFieldName(writer.toString());
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.jackson.deserialization;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.jackson.entities.ClassWithAMap;
import com.baeldung.jackson.entities.MyPair;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonMapDeserializeTest {
private Map<MyPair, String> map;
private Map<MyPair, MyPair> cmap;
final ObjectMapper mapper = new ObjectMapper();
@Test
public void whenSimpleMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"key\": \"value\"}";
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
};
final Map<String, String> map = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals("value", map.get("key"));
}
@Test
public void whenObjectStringMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() {
};
map = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello")));
ClassWithAMap classWithMap = mapper.readValue(jsonInput,
ClassWithAMap.class);
Assert.assertEquals("Comedy",
classWithMap.getMap().get(new MyPair("Abbott", "Costello")));
}
@Test
public void whenObjectObjectMapDeserialize_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}";
TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {
};
cmap = mapper.readValue(jsonInput, typeRef);
Assert.assertEquals(new MyPair("Comedy", "1940s"),
cmap.get(new MyPair("Abbott", "Costello")));
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.jackson.serialization;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.jackson.entities.MyPair;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.MapSerializer;
public class JacksonMapSerializeTest {
@JsonSerialize(keyUsing = MyPairSerializer.class)
private Map<MyPair, String> map;
@JsonSerialize(keyUsing = MapSerializer.class)
private Map<MyPair, MyPair> cmap;
@JsonSerialize(keyUsing = MyPairSerializer.class)
private MyPair mapKey;
@JsonSerialize(keyUsing = MyPairSerializer.class)
private MyPair mapValue;
final ObjectMapper mapper = new ObjectMapper();
@Test
public void whenSimpleMapSerialize_thenCorrect()
throws JsonProcessingException {
Map<String, String> map = new HashMap<>();
map.put("key", "value");
final String jsonResult = mapper.writeValueAsString(map);
Assert.assertEquals("{\"key\":\"value\"}", jsonResult);
}
@Test
public void whenCustomObjectStringMapSerialize_thenCorrect()
throws JsonProcessingException {
map = new HashMap<>();
MyPair key = new MyPair("Abbott", "Costello");
map.put(key, "Comedy");
final String jsonResult = mapper.writeValueAsString(map);
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult);
}
@Test
public void whenCustomObjectObjectMapSerialize_thenCorrect()
throws JsonProcessingException {
cmap = new HashMap<>();
mapKey = new MyPair("Abbott", "Costello");
mapValue = new MyPair("Comedy", "1940's");
cmap.put(mapKey, mapValue);
final String jsonResult = mapper.writeValueAsString(cmap);
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}",
jsonResult);
}
}

View File

@ -0,0 +1,119 @@
package com.baeldung.jackson.streaming;
import com.fasterxml.jackson.core.*;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertEquals;
public class JacksonStreamingAPITest {
@Test
public void givenJsonGenerator_whenAppendJsonToIt_thenGenerateJson() throws IOException {
//given
ByteArrayOutputStream stream = new ByteArrayOutputStream();
JsonFactory jfactory = new JsonFactory();
JsonGenerator jGenerator = jfactory.createGenerator(stream, JsonEncoding.UTF8);
//when
jGenerator.writeStartObject();
jGenerator.writeStringField("name", "Tom");
jGenerator.writeNumberField("age", 25);
jGenerator.writeFieldName("address");
jGenerator.writeStartArray();
jGenerator.writeString("Poland");
jGenerator.writeString("5th avenue");
jGenerator.writeEndArray();
jGenerator.writeEndObject();
jGenerator.close();
//then
String json = new String(stream.toByteArray(), "UTF-8");
assertEquals(json, "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}");
}
@Test
public void givenJson_whenReadItUsingStreamAPI_thenShouldCreateProperJsonObject() throws IOException {
//given
String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}";
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createParser(json);
String parsedName = null;
Integer parsedAge = null;
List<String> addresses = new LinkedList<>();
//when
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if ("name".equals(fieldname)) {
jParser.nextToken();
parsedName = jParser.getText();
}
if ("age".equals(fieldname)) {
jParser.nextToken();
parsedAge = jParser.getIntValue();
}
if ("address".equals(fieldname)) {
jParser.nextToken();
while (jParser.nextToken() != JsonToken.END_ARRAY) {
addresses.add(jParser.getText());
}
}
}
jParser.close();
//then
assertEquals(parsedName, "Tom");
assertEquals(parsedAge, (Integer) 25);
assertEquals(addresses, Arrays.asList("Poland", "5th avenue"));
}
@Test
public void givenJson_whenWantToExtractPartOfIt_thenShouldExtractOnlyNeededFieldWithoutGoingThroughWholeJSON() throws IOException {
//given
String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}";
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createParser(json);
String parsedName = null;
Integer parsedAge = null;
List<String> addresses = new LinkedList<>();
//when
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if ("age".equals(fieldname)) {
jParser.nextToken();
parsedAge = jParser.getIntValue();
return;
}
}
jParser.close();
//then
assertNull(parsedName);
assertEquals(parsedAge, (Integer) 25);
assertTrue(addresses.isEmpty());
}
}

3
java-websocket/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [A Guide to the Java API for WebSocket](http://www.baeldung.com/java-websockets)

View File

@ -22,19 +22,40 @@
<artifactId>javaslang</artifactId>
<version>2.1.0-alpha</version>
</dependency>
<dependency>
<groupId>io.javaslang</groupId>
<artifactId>javaslang-test</artifactId>
<version>${javaslang.test.version}</version>
</dependency>
</dependencies>
<properties>
<javaslang.test.version>2.0.5</javaslang.test.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,71 @@
package com.baeldung.javaslang;
import javaslang.CheckedFunction1;
import javaslang.collection.Stream;
import javaslang.test.Arbitrary;
import javaslang.test.CheckResult;
import javaslang.test.Property;
import org.junit.Test;
import java.util.function.Predicate;
import static javaslang.API.*;
public class PropertyBasedLongRunningUnitTest {
private static Predicate<Integer> divisibleByTwo = i -> i % 2 == 0;
private static Predicate<Integer> divisibleByFive = i -> i % 5 == 0;
private Stream<String> stringsSupplier() {
return Stream.from(0).map(i -> Match(i).of(
Case($(divisibleByFive.and(divisibleByTwo)), "DividedByTwoAndFiveWithoutRemainder"),
Case($(divisibleByFive), "DividedByFiveWithoutRemainder"),
Case($(divisibleByTwo), "DividedByTwoWithoutRemainder"),
Case($(), "")));
}
@Test
public void givenArbitrarySeq_whenCheckThatEverySecondElementIsEqualToString_thenTestPass() {
//given
Arbitrary<Integer> multiplesOf2 = Arbitrary
.integer()
.filter(i -> i > 0)
.filter(i -> i % 2 == 0 && i % 5 != 0);
//when
CheckedFunction1<Integer, Boolean> mustEquals = i -> stringsSupplier()
.get(i)
.equals("DividedByTwoWithoutRemainder");
//then
CheckResult result = Property
.def("Every second element must equal to DividedByTwoWithoutRemainder")
.forAll(multiplesOf2)
.suchThat(mustEquals)
.check(10_000, 100);
result.assertIsSatisfied();
}
@Test
public void givenArbitrarySeq_whenCheckThatEveryFifthElementIsEqualToString_thenTestPass() {
//given
Arbitrary<Integer> multiplesOf5 = Arbitrary
.integer()
.filter(i -> i > 0)
.filter(i -> i % 5 == 0 && i % 2 == 0);
//when
CheckedFunction1<Integer, Boolean> mustEquals = i -> stringsSupplier()
.get(i)
.endsWith("DividedByTwoAndFiveWithoutRemainder");
//then
Property
.def("Every fifth element must equal to DividedByTwoAndFiveWithoutRemainder")
.forAll(multiplesOf5)
.suchThat(mustEquals)
.check(10_000, 1_000)
.assertIsSatisfied();
}
}

View File

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>jee7schedule</artifactId>
<artifactId>jee7</artifactId>
<version>1.0-SNAPSHOT</version>
<description>JavaEE 7 Arquillian Archetype Sample</description>
<packaging>war</packaging>

View File

@ -0,0 +1,67 @@
About the application
---------------------
This application demonstrates the usage of JavaEE Web Annotations.
Contents of the application
---------------------------
1. AccountServlet.java - Demonstrates the @WebServlet and @ServletSecurity annotation.
NOTES: @WebServlet annotation designates the AccountServlet class as a Servlet component.
The usage of its parameters 'urlPatterns' & 'initParams' can be observed.
An initialization parameter 'type' is being set to denote the type of the bank account.
@ServletSecurity annotation imposes security constraints on the AccountServlet based on
the tomcat-users.xml (this code assumes there is a role 'admin' in your tomcat-users.xml)
N.B : To see @ServletSecurity annotation in action, please uncomment the annotation code
for @ServletSecurity.
2. BankAppServletContextListener.java - Demonstrates the @WebListener annotation for denoting a class as a ServletContextListener.
NOTES: Sets a Servlet context attribute ATTR_DEFAULT_LANGUAGE to 'english' on web application start up,
which can then be used throughout the application.
3. LogInFilter.java - Demonstrates the @WebFilter annotation.
NOTES: @WebFilter annotation designates the LogInFilter class as a Filter component.
It filters all requests to the bank account servlet and redirects them to
the login page.
N.B : To see @WebFilter annotation in action, please uncomment the annotation code for @WebFilter.
4. UploadCustomerDocumentsServlet.java - Demonstrates the @MultipartConfig annotation.
NOTES: @MultipartConfig anotation designates the UploadCustomerDocumentsServlet Servlet component,
to handle multipart/form-data requests.
To see it in action, deploy the web application an access the url: http://<your host>:<your port>/JavaEEAnnotationsSample/upload.jsp
Once you upload a file from here, it will get uploaded to D:/custDocs (assuming such a folder exists).
5. index.jsp - This is the welcome page.
NOTES: You can enter a deposit amount here and click on the 'Deposit' button to see the AccountServlet in action.
6. login.jsp - All requests to the AccountServlet are redirected to this page, if the LogInFilter is imposed.
7. upload.jsp - Demonstrates the usage of handling multipart/form-data requests by the UploadCustomerDocumentsServlet.
Building and Running the application
------------------------------------
To build the application:
1. Open the project in eclipse
2. Right click on it in eclispe and choose Run As > Maven build
3. Give 'clean install' under Goals
4. This should build the WAR file of the application
To run the application:
1. Right click on the project
2. Run as > Run on Server
3. This will start you Tomcat server and deploy the application (Provided that you have configured Tomcat in your eclipse)
4. You should now be able to access the url : http://<your host>:<your port>/JavaEEAnnotationsSample

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