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 *.class
# Package Files # # Package Files #

View File

@ -1,11 +1,13 @@
language: java 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: jdk:
- oraclejdk8 - oraclejdk8
sudo: false
addons: addons:
apt: apt:
packages: packages:
@ -15,3 +17,5 @@ cache:
directories: directories:
- .autoconf - .autoconf
- $HOME/.m2 - $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) - [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
- [Introduction to Cobertura](http://www.baeldung.com/cobertura) - [Introduction to Cobertura](http://www.baeldung.com/cobertura)
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization) - [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> <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version> <exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
<lombok.version>1.16.12</lombok.version> <lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <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

@ -5,12 +5,12 @@ package com.baeldung.automata;
*/ */
public interface FiniteStateMachine { public interface FiniteStateMachine {
/** /**
* Follow a transition, switch the state of the machine. * Follow a transition, switch the state of the machine.
* @param c Char. * @param c Char.
* @return A new finite state machine with the new state. * @return A new finite state machine with the new state.
*/ */
FiniteStateMachine switchState(final CharSequence c); FiniteStateMachine switchState(final CharSequence c);
/** /**
* Is the current state a final one? * Is the current state a final one?

View File

@ -6,25 +6,25 @@ package com.baeldung.automata;
*/ */
public final class RtFiniteStateMachine implements FiniteStateMachine { public final class RtFiniteStateMachine implements FiniteStateMachine {
/** /**
* Current state. * Current state.
*/ */
private State current; private State current;
/** /**
* Ctor. * Ctor.
* @param initial Initial state of this machine. * @param initial Initial state of this machine.
*/ */
public RtFiniteStateMachine(final State initial) { public RtFiniteStateMachine(final State initial) {
this.current = initial; this.current = initial;
} }
public FiniteStateMachine switchState(final CharSequence c) { public FiniteStateMachine switchState(final CharSequence c) {
return new RtFiniteStateMachine(this.current.transit(c)); return new RtFiniteStateMachine(this.current.transit(c));
} }
public boolean canStop() { public boolean canStop() {
return this.current.isFinal(); return this.current.isFinal();
} }
} }

View File

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

View File

@ -6,26 +6,26 @@ package com.baeldung.automata;
*/ */
public final class RtTransition implements Transition { public final class RtTransition implements Transition {
private String rule; private String rule;
private State next; private State next;
/** /**
* Ctor. * Ctor.
* @param rule Rule that a character has to meet * @param rule Rule that a character has to meet
* in order to get to the next state. * in order to get to the next state.
* @param next Next state. * @param next Next state.
*/ */
public RtTransition (String rule, State next) { public RtTransition (String rule, State next) {
this.rule = rule; this.rule = rule;
this.next = next; this.next = next;
} }
public State state() { public State state() {
return this.next; return this.next;
} }
public boolean isPossible(CharSequence c) { public boolean isPossible(CharSequence c) {
return this.rule.equalsIgnoreCase(String.valueOf(c)); return this.rule.equalsIgnoreCase(String.valueOf(c));
} }
} }

View File

@ -5,12 +5,12 @@ package com.baeldung.automata;
*/ */
public interface State { public interface State {
/** /**
* Add a Transition to this state. * Add a Transition to this state.
* @param tr Given transition. * @param tr Given transition.
* @return Modified State. * @return Modified State.
*/ */
State with(final Transition tr); State with(final Transition tr);
/** /**
* Follow one of the transitions, to get * Follow one of the transitions, to get

View File

@ -5,16 +5,16 @@ package com.baeldung.automata;
*/ */
public interface Transition { public interface Transition {
/** /**
* Is the transition possible with the given character? * Is the transition possible with the given character?
* @param c char. * @param c char.
* @return true or false. * @return true or false.
*/ */
boolean isPossible(final CharSequence c); boolean isPossible(final CharSequence c);
/** /**
* The state to which this transition leads. * The state to which this transition leads.
* @return State. * @return State.
*/ */
State state(); State state();
} }

View File

@ -9,74 +9,74 @@ import com.baeldung.automata.*;
*/ */
public final class RtFiniteStateMachineTest { public final class RtFiniteStateMachineTest {
@Test @Test
public void acceptsSimplePair() { public void acceptsSimplePair() {
String json = "{\"key\":\"value\"}"; String json = "{\"key\":\"value\"}";
FiniteStateMachine machine = this.buildJsonStateMachine(); FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i=0;i<json.length();i++) { for (int i=0;i<json.length();i++) {
machine = machine.switchState(String.valueOf(json.charAt(i))); machine = machine.switchState(String.valueOf(json.charAt(i)));
} }
assertTrue(machine.canStop()); assertTrue(machine.canStop());
} }
@Test @Test
public void acceptsMorePairs() { public void acceptsMorePairs() {
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
FiniteStateMachine machine = this.buildJsonStateMachine(); FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i=0;i<json.length();i++) { for (int i=0;i<json.length();i++) {
machine = machine.switchState(String.valueOf(json.charAt(i))); machine = machine.switchState(String.valueOf(json.charAt(i)));
} }
assertTrue(machine.canStop()); assertTrue(machine.canStop());
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void missingColon() { public void missingColon() {
String json = "{\"key\"\"value\"}"; String json = "{\"key\"\"value\"}";
FiniteStateMachine machine = this.buildJsonStateMachine(); FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i=0;i<json.length();i++) { for (int i=0;i<json.length();i++) {
machine = machine.switchState(String.valueOf(json.charAt(i))); machine = machine.switchState(String.valueOf(json.charAt(i)));
} }
} }
/** /**
* Builds a finite state machine to validate a simple * Builds a finite state machine to validate a simple
* Json object. * Json object.
* @return * @return
*/ */
private FiniteStateMachine buildJsonStateMachine() { private FiniteStateMachine buildJsonStateMachine() {
State first = new RtState(); State first = new RtState();
State second = new RtState(); State second = new RtState();
State third = new RtState(); State third = new RtState();
State fourth = new RtState(); State fourth = new RtState();
State fifth = new RtState(); State fifth = new RtState();
State sixth = new RtState(); State sixth = new RtState();
State seventh = new RtState(); State seventh = new RtState();
State eighth = new RtState(true); State eighth = new RtState(true);
first.with(new RtTransition("{", second)); first.with(new RtTransition("{", second));
second.with(new RtTransition("\"", third)); second.with(new RtTransition("\"", third));
//Add transitions with chars 0-9 and a-z //Add transitions with chars 0-9 and a-z
for (int i = 0; i < 26; i++) { for (int i = 0; i < 26; i++) {
if(i<10) { if(i<10) {
third = third.with( third = third.with(
new RtTransition(String.valueOf(i), third) new RtTransition(String.valueOf(i), third)
);
sixth = sixth.with(
new RtTransition(String.valueOf(i), sixth)
); );
} sixth = sixth.with(
third = third.with( new RtTransition(String.valueOf(i), sixth)
new RtTransition(String.valueOf((char) ('a' + i)), third) );
); }
sixth = sixth.with( third = third.with(
new RtTransition(String.valueOf((char) ('a' + i)), sixth) new RtTransition(String.valueOf((char) ('a' + i)), third)
); );
} sixth = sixth.with(
third.with(new RtTransition("\"", fourth)); new RtTransition(String.valueOf((char) ('a' + i)), sixth)
fourth.with(new RtTransition(":", fifth)); );
fifth.with(new RtTransition("\"", sixth)); }
sixth.with(new RtTransition("\"", seventh)); third.with(new RtTransition("\"", fourth));
seventh.with(new RtTransition(",", second)); fourth.with(new RtTransition(":", fifth));
seventh.with(new RtTransition("}", eighth)); fifth.with(new RtTransition("\"", sixth));
return new RtFiniteStateMachine(first); sixth.with(new RtTransition("\"", seventh));
} seventh.with(new RtTransition(",", second));
seventh.with(new RtTransition("}", eighth));
return new RtFiniteStateMachine(first);
}
} }

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 *.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) - [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) - [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/) - [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) - [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 LinkedHashMap in Java](http://www.baeldung.com/java-linked-hashmap)
- [A Guide to TreeMap in Java](http://www.baeldung.com/java-treemap) - [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> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration> <configuration>
<excludes> <excludes>
<exclude>**/*IntegrationTest.java</exclude> <exclude>**/*IntegrationTest.java</exclude>
@ -250,6 +249,7 @@
<goal>single</goal> <goal>single</goal>
</goals> </goals>
<configuration> <configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive> <archive>
<manifest> <manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> <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 java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
public class CountdownLatchExampleTest { public class CountdownLatchExampleIntegrationTest {
@Test @Test
public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException { public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException {
// Given // Given

View File

@ -1,5 +1,6 @@
package com.baeldung.enums; package com.baeldung.enums;
import com.baeldung.enums.Pizza.PizzaStatusEnum;
import org.junit.Test; import org.junit.Test;
import java.util.ArrayList; import java.util.ArrayList;
@ -69,11 +70,31 @@ public class PizzaUnitTest {
} }
@Test @Test
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() { public void whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
Pizza pz = new Pizza(); Pizza pz = new Pizza();
pz.setStatus(Pizza.PizzaStatusEnum.READY); pz.setStatus(Pizza.PizzaStatusEnum.READY);
pz.deliver(); pz.deliver();
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED); 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 @Test
public void givenEmployeeArray_whenUsingComparing_thenCheckingSort() { public void whenComparing_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName); Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Arrays.sort(employees, employeeNameComparator); Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
@ -68,7 +68,7 @@ public class Java8ComparatorTest {
} }
@Test @Test
public void givenEmployeeArray_whenUsingComparingWithComparator_thenCheckingSort() { public void whenComparingWithComparator_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName, (s1, s2) -> { Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName, (s1, s2) -> {
return s2.compareTo(s1); return s2.compareTo(s1);
}); });
@ -78,7 +78,16 @@ public class Java8ComparatorTest {
} }
@Test @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); Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
Arrays.sort(employees, employeeAgeComparator); Arrays.sort(employees, employeeAgeComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
@ -86,7 +95,7 @@ public class Java8ComparatorTest {
} }
@Test @Test
public void givenEmployeeArray_whenUsingComparingLong_thenCheckingSort() { public void whenComparingLong_thenSortedByMobile() {
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile); Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
Arrays.sort(employees, employeeMobileComparator); Arrays.sort(employees, employeeMobileComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
@ -94,7 +103,7 @@ public class Java8ComparatorTest {
} }
@Test @Test
public void givenEmployeeArray_whenUsingComparingDouble_thenCheckingSort() { public void whenComparingDouble_thenSortedBySalary() {
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary); Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
Arrays.sort(employees, employeeSalaryComparator); Arrays.sort(employees, employeeSalaryComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
@ -102,7 +111,7 @@ public class Java8ComparatorTest {
} }
@Test @Test
public void givenEmployeeArray_whenUsingNaturalOrder_thenCheckingSort() { public void whenNaturalOrder_thenSortedByName() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder(); Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
Arrays.sort(employees, employeeNameComparator); Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
@ -110,7 +119,7 @@ public class Java8ComparatorTest {
} }
@Test @Test
public void givenEmployeeArray_whenUsingReverseOrder_thenCheckingSort() { public void whenReverseOrder_thenSortedByNameDesc() {
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder(); Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
Arrays.sort(employees, employeeNameComparator); Arrays.sort(employees, employeeNameComparator);
// System.out.println(Arrays.toString(employees)); // System.out.println(Arrays.toString(employees));
@ -118,7 +127,7 @@ public class Java8ComparatorTest {
} }
@Test @Test
public void givenEmployeeArray_whenUsingNullFirst_thenCheckingSort() { public void whenNullsFirst_thenSortedByNameWithNullsFirst() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName); Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator); Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst); Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
@ -127,7 +136,7 @@ public class Java8ComparatorTest {
} }
@Test @Test
public void givenEmployeeArray_whenUsingNullLast_thenCheckingSort() { public void whenNullsLast_thenSortedByNameWithNullsLast() {
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName); Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator); Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast); Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
@ -136,7 +145,7 @@ public class Java8ComparatorTest {
} }
@Test @Test
public void givenEmployeeArray_whenUsingThenComparing_thenCheckingSort() { public void whenThenComparing_thenSortedByAgeName() {
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName); Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator); Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
@ -145,7 +154,7 @@ public class Java8ComparatorTest {
} }
@Test @Test
public void givenEmployeeArray_whenUsingThenComparingInt_thenCheckingSort() { public void whenThenComparing_thenSortedByNameAge() {
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge); Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator); Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
@ -153,40 +162,6 @@ public class Java8ComparatorTest {
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge)); 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; package com.baeldung.list.flattennestedlist;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import org.junit.Before; import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FlattenNestedListTest { 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); @Test
private FlattenNestedList flol; public void givenNestedList_thenFlattenNestedListImperative() {
List<String> ls = flattenListOfListsImperatively(lol);
@Before assertNotNull(ls);
public void setup() { assertTrue(ls.size() == 8);
flol = new FlattenNestedList(); // assert content
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
} }
@Test @Test
public void givenListOfListOfString_flattenNestedList() { public void givenNestedList_thenFlattenNestedListStream() {
List<String> ls = flattenListOfListsStream(lol);
// 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);
assertNotNull(ls); assertNotNull(ls);
assertTrue(ls.size() == 9); assertTrue(ls.size() == 8);
// assert content
// show flattened list assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
LOGGER.debug("\nFlattened list:");
ls.forEach((l) -> LOGGER.debug(l));
} }
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.concurrent.Executors;
import java.util.function.Consumer; 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 final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
private static class StreamGobbler implements Runnable { 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.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class ThreadPoolInParallelStreamTest { public class ThreadPoolInParallelStreamIntegrationTest {
@Test @Test
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException { public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {

View File

@ -145,6 +145,7 @@
<goal>single</goal> <goal>single</goal>
</goals> </goals>
<configuration> <configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive> <archive>
<manifest> <manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> <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 RangeSet](http://www.baeldung.com/guava-rangeset)
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap) - [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
- [Guide to Guava Table](http://www.baeldung.com/guava-table) - [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> <groupId>org.apache.hbase</groupId>
<artifactId>hbase</artifactId> <artifactId>hbase</artifactId>
<version>${hbase.version}</version> <version>${hbase.version}</version>
<type>pom</type>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <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) - [Inheritance with Jackson](http://www.baeldung.com/jackson-inheritance)
- [Guide to @JsonFormat in Jackson](http://www.baeldung.com/jackson-jsonformat) - [Guide to @JsonFormat in Jackson](http://www.baeldung.com/jackson-jsonformat)
- [A Guide to Optional with Jackson](http://www.baeldung.com/jackson-optional) - [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> <properties>
<!-- marshalling --> <!-- marshalling -->
<jackson.version>2.8.6</jackson.version> <jackson.version>2.8.7</jackson.version>
<!-- logging --> <!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version> <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);
}
}

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