├── Guava-Lessons.iml ├── README ├── pom.xml └── src ├── main └── java │ └── pl │ └── tomaszdziurko │ └── guava │ ├── PreconditionsLesson.java │ ├── UserProfile.java │ ├── eventbus │ ├── DeadEventListener.java │ ├── EventListener.java │ ├── EventReader.java │ ├── IntegerListener.java │ ├── LonelyEvent.java │ ├── MultipleListener.java │ ├── NumberListener.java │ ├── OurTestEvent.java │ ├── StringEventListener.java │ └── StringTestEvent.java │ └── geo │ ├── Continent.java │ └── Country.java └── test └── java └── pl └── tomaszdziurko └── guava ├── base ├── CaseFormatTest.java ├── CharMatcherTest.java ├── CharsetsTest.java ├── FunctionsTest.java ├── JoinerTest.java ├── ObjectsTest.java ├── PreconditionsTest.java ├── PredicateTest.java ├── SplitterTest.java ├── StopwatchTest.java ├── StringsTest.java └── ThrowablesTest.java ├── collect ├── BiMapTest.java ├── Collections2Test.java ├── ConstraintsTest.java ├── DiscreteDomainTest.java ├── ForwardingListTest.java ├── ImmutableMapTest.java ├── IterablesTest.java ├── MultimapTest.java ├── MultisetTest.java ├── ObjectArraysTest.java └── RangesTest.java ├── eventbus └── EventBusTest.java ├── math └── IntMathTest.java └── primitives └── PrimitivesTest.java /Guava-Lessons.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | Code examples created during my learning Google Guava library. 2 | 3 | Slides and more details are available here: http://tomaszdziurko.pl/2012/02/google-guava/ -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | pl.tomaszdziurko 8 | guava-lessons 9 | 1.0 10 | 11 | 12 | com.google.guava 13 | guava 14 | 11.0.1 15 | 16 | 17 | 18 | com.google.code.findbugs 19 | jsr305 20 | 1.3.9 21 | 22 | 23 | 24 | 25 | org.testng 26 | testng 27 | 5.12.1 28 | test 29 | 30 | 31 | 32 | org.mockito 33 | mockito-all 34 | 1.8.5 35 | test 36 | 37 | 38 | 39 | org.slf4j 40 | slf4j-log4j12 41 | 1.5.10 42 | test 43 | 44 | 45 | 46 | org.easytesting 47 | fest-assert 48 | 1.3 49 | test 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/PreconditionsLesson.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava; 2 | 3 | import com.google.common.base.Preconditions; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Class to learn Preconditions 9 | */ 10 | public class PreconditionsLesson { 11 | 12 | public enum Weather { 13 | WINDY, 14 | RAINY, 15 | SHINY, 16 | DOWNPOUR, 17 | CLOUDY 18 | } 19 | 20 | public void getSomeSuntan(Weather weather) { 21 | Preconditions.checkState(weather.equals(Weather.SHINY), "Weather is not the best for a sunbath"); 22 | } 23 | 24 | public void displayFootballTeamMembers(List teamMembers) { 25 | Preconditions.checkNotNull(teamMembers, "Team can not be null"); 26 | Preconditions.checkArgument(teamMembers.size() == 11, "Full team should consist of 11 players"); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/UserProfile.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava; 2 | 3 | import com.google.common.base.Objects; 4 | 5 | /** 6 | * Class to play with some features from Objects class 7 | */ 8 | public class UserProfile { 9 | 10 | private String name; 11 | private String nickname; 12 | private Integer age; 13 | 14 | public UserProfile(String name, String nickname, Integer age) { 15 | this.name = name; 16 | this.nickname = nickname; 17 | this.age = age; 18 | } 19 | 20 | @Override 21 | public boolean equals(Object o) { 22 | if (this == o) return true; 23 | if (!(o instanceof UserProfile)) return false; 24 | 25 | UserProfile objectsLesson = (UserProfile) o; 26 | return Objects.equal(this.name, objectsLesson.name) && 27 | Objects.equal(this.age, objectsLesson.age) && 28 | Objects.equal(this.nickname, objectsLesson.nickname); 29 | } 30 | 31 | @Override 32 | public int hashCode() { 33 | return Objects.hashCode(name, age, nickname); 34 | } 35 | 36 | public String toString() { 37 | return Objects.toStringHelper(this).add("name", name) 38 | .add("nickname", nickname) 39 | .addValue(age).toString(); 40 | } 41 | 42 | public String getDisplayName() { 43 | return Objects.firstNonNull(nickname, name); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/eventbus/DeadEventListener.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.eventbus; 2 | 3 | import com.google.common.eventbus.DeadEvent; 4 | import com.google.common.eventbus.Subscribe; 5 | 6 | /** 7 | * Listener waiting for the event that any message was posted but not delivered to anyone 8 | */ 9 | public class DeadEventListener { 10 | 11 | boolean notDelivered = false; 12 | 13 | @Subscribe 14 | public void listen(DeadEvent event) { 15 | notDelivered = true; 16 | } 17 | 18 | public boolean isNotDelivered() { 19 | return notDelivered; 20 | } 21 | } 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/eventbus/EventListener.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.eventbus; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | 5 | /** 6 | * Another class which can subscribe to events 7 | */ 8 | public class EventListener { 9 | 10 | public int lastMessage = 0; 11 | 12 | @Subscribe 13 | public void listen(OurTestEvent event) { 14 | lastMessage = event.getMessage(); 15 | } 16 | 17 | public int getLastMessage() { 18 | return lastMessage; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/eventbus/EventReader.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.eventbus; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | 5 | /** 6 | * Another class which can subscribe to events 7 | */ 8 | public class EventReader { 9 | 10 | public int lastMessage = 0; 11 | 12 | @Subscribe 13 | public void read(OurTestEvent event) { 14 | lastMessage = event.getMessage(); 15 | } 16 | 17 | public int getLastMessage() { 18 | return lastMessage; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/eventbus/IntegerListener.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.eventbus; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | 5 | /** 6 | * Class listening for Integers 7 | */ 8 | public class IntegerListener { 9 | 10 | private Integer lastMessage; 11 | 12 | @Subscribe 13 | public void listen(Integer integer) { 14 | lastMessage = integer; 15 | } 16 | 17 | public Integer getLastMessage() { 18 | return lastMessage; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/eventbus/LonelyEvent.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.eventbus; 2 | 3 | /** 4 | * Event without listeners 5 | */ 6 | public class LonelyEvent { 7 | 8 | private String message; 9 | 10 | public LonelyEvent(String message) { 11 | this.message = message; 12 | } 13 | 14 | public String getMessage() { 15 | return message; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/eventbus/MultipleListener.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.eventbus; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | 5 | public class MultipleListener { 6 | 7 | public Integer lastInteger; 8 | public Long lastLong; 9 | 10 | @Subscribe 11 | public void listenInteger(Integer event) { 12 | lastInteger = event; 13 | } 14 | 15 | @Subscribe 16 | public void listenLong(Long event) { 17 | lastLong = event; 18 | } 19 | 20 | public Integer getLastInteger() { 21 | return lastInteger; 22 | } 23 | 24 | public Long getLastLong() { 25 | return lastLong; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/eventbus/NumberListener.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.eventbus; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | 5 | /** 6 | * Listener waiting for Number class events 7 | */ 8 | public class NumberListener { 9 | 10 | private Number lastMessage; 11 | 12 | @Subscribe 13 | public void listen(Number integer) { 14 | lastMessage = integer; 15 | } 16 | 17 | public Number getLastMessage() { 18 | return lastMessage; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/eventbus/OurTestEvent.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.eventbus; 2 | 3 | /** 4 | * Test event class 5 | */ 6 | public class OurTestEvent { 7 | 8 | private final int message; 9 | 10 | public OurTestEvent(int message) { 11 | this.message = message; 12 | } 13 | 14 | public int getMessage() { 15 | return message; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/eventbus/StringEventListener.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.eventbus; 2 | 3 | import com.google.common.eventbus.Subscribe; 4 | 5 | /** 6 | * String event listener 7 | */ 8 | public class StringEventListener { 9 | 10 | 11 | public String lastMessage; 12 | 13 | @Subscribe 14 | public void listen(StringTestEvent event) { 15 | lastMessage = event.getMessage(); 16 | } 17 | 18 | public String getLastMessage() { 19 | return lastMessage; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/eventbus/StringTestEvent.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.eventbus; 2 | 3 | /** 4 | * Event with String as a message 5 | */ 6 | public class StringTestEvent { 7 | 8 | private String message; 9 | 10 | public String getMessage() { 11 | return message; 12 | } 13 | 14 | public StringTestEvent(String message) { 15 | 16 | this.message = message; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/geo/Continent.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.geo; 2 | 3 | public enum Continent { 4 | 5 | EUROPE("Europe"), 6 | ASIA("Asia"), 7 | AFRICA("Africa"), 8 | SOUTH_AMERICA("South America"), 9 | NORTH_AMERICA("North America"), 10 | AUSTRALIA_OCEANIA("Australia and Oceania"); 11 | private String label; 12 | 13 | Continent(String label) { 14 | this.label = label; 15 | } 16 | 17 | public String getLabel() { 18 | return label; 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/java/pl/tomaszdziurko/guava/geo/Country.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.geo; 2 | 3 | 4 | import com.google.common.base.Objects; 5 | import com.google.common.collect.Lists; 6 | 7 | import java.util.List; 8 | 9 | public class Country { 10 | 11 | public static final Country POLAND = new Country(1L, "Poland", "Warsaw", 38.186, Continent.EUROPE, 313); 12 | public static final Country BELGIUM = new Country(2L, "Belgium", "Brussels", 11.007, Continent.EUROPE, 30); 13 | public static final Country SPAIN = new Country(3L, "Spain", "Madrid", 46.0, Continent.EUROPE, 508); 14 | public static final Country ENGLAND = new Country(4L, "England", "London", 51.446, Continent.EUROPE, 130); 15 | public static final Country FINLAND_WITHOUT_CAPITAL_CITY = new Country(5L, "Finland", null, null, Continent.EUROPE, null); 16 | public static final Country SOUTH_AFRICA = new Country(9L, "South Africa", "Pretoria", 50.586, Continent.AFRICA, 1221); 17 | public static final Country ICELAND = new Country(8L, "Iceland", "Reykjavik", 0.318, Continent.EUROPE, 103); 18 | 19 | private Long id; 20 | private String name; 21 | private String capitalCity; 22 | private Double population; 23 | private Continent continent; 24 | private Integer area; 25 | 26 | 27 | public Country(Long id, String name, String capitalCity, Double population, Continent continent, Integer area) { 28 | this.id = id; 29 | this.name = name; 30 | this.capitalCity = capitalCity; 31 | this.population = population; 32 | this.continent = continent; 33 | this.area = area; 34 | } 35 | 36 | public static List getSomeCountries() { 37 | List countries = Lists.newArrayList(); 38 | 39 | countries.add(POLAND); 40 | countries.add(BELGIUM); 41 | countries.add(SPAIN); 42 | countries.add(ENGLAND); 43 | countries.add(new Country(6L, "Sweden", "Stockholm", 9.354, Continent.EUROPE, 450)); 44 | countries.add(new Country(7L, "Croatia", "Zagreb", 4.290, Continent.EUROPE, 57)); 45 | countries.add(ICELAND); 46 | countries.add(SOUTH_AFRICA); 47 | countries.add(new Country(10L, "Egypt", "Cairo", 80.801, Continent.AFRICA, 1002)); 48 | countries.add(new Country(11L, "Tanzania", "Dodoma", 41.048, Continent.AFRICA, 945)); 49 | countries.add(new Country(12L, "Tunisia", "Tunis", 10.486, Continent.AFRICA, 163)); 50 | countries.add(new Country(13L, "Togo", "Lome", 6.019, Continent.AFRICA, 57)); 51 | countries.add(new Country(14L, "Gambia", "Banjul", 1.782, Continent.AFRICA, 11)); 52 | 53 | return countries; 54 | } 55 | 56 | public Long getId() { 57 | return id; 58 | } 59 | 60 | public void setId(Long id) { 61 | this.id = id; 62 | } 63 | 64 | public String getName() { 65 | return name; 66 | } 67 | 68 | public void setName(String name) { 69 | this.name = name; 70 | } 71 | 72 | public String getCapitalCity() { 73 | return capitalCity; 74 | } 75 | 76 | public void setCapitalCity(String capitalCity) { 77 | this.capitalCity = capitalCity; 78 | } 79 | 80 | public Double getPopulation() { 81 | return population; 82 | } 83 | 84 | public void setPopulation(Double population) { 85 | this.population = population; 86 | } 87 | 88 | public Continent getContinent() { 89 | return continent; 90 | } 91 | 92 | public void setContinent(Continent continent) { 93 | this.continent = continent; 94 | } 95 | 96 | public Integer getArea() { 97 | return area; 98 | } 99 | 100 | public void setArea(Integer area) { 101 | this.area = area; 102 | } 103 | 104 | @Override 105 | public String toString() { 106 | return Objects.toStringHelper(this) 107 | .add("name", name) 108 | .add("capital city", capitalCity) 109 | .add("population", population).toString(); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/base/CaseFormatTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.base; 2 | 3 | import com.google.common.base.CaseFormat; 4 | import org.testng.annotations.Test; 5 | 6 | import static org.fest.assertions.Assertions.assertThat; 7 | 8 | /** 9 | * CaseFormat features 10 | */ 11 | public class CaseFormatTest { 12 | 13 | @Test 14 | public void shouldConvertToUpperUnderscore() throws Exception { 15 | 16 | // then 17 | assertThat(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "HelloWorld")) 18 | .isEqualTo("HELLO_WORLD"); 19 | } 20 | 21 | @Test 22 | public void shouldConvertToLowerCamel() throws Exception { 23 | 24 | // then 25 | assertThat(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "HELLO_WORLD")) 26 | .isEqualTo("helloWorld"); 27 | } 28 | 29 | @Test 30 | public void shouldConvertToLowerHyphen() throws Exception { 31 | 32 | // then 33 | assertThat(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, "helloWorld")) 34 | .isEqualTo("hello-world"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/base/CharMatcherTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.base; 2 | 3 | import com.google.common.base.CharMatcher; 4 | import org.testng.annotations.Test; 5 | 6 | import static org.fest.assertions.Assertions.assertThat; 7 | 8 | /** 9 | * Class to learn some features of CharMatcher 10 | */ 11 | public class CharMatcherTest { 12 | 13 | @Test 14 | public void shouldMatchChar() throws Exception { 15 | assertThat(CharMatcher.anyOf("gZ").matchesAnyOf("anything")).isTrue(); 16 | } 17 | 18 | @Test 19 | public void shouldNotMatchChar() throws Exception { 20 | assertThat(CharMatcher.noneOf("xZ").matchesAnyOf("anything")).isTrue(); 21 | } 22 | 23 | @Test 24 | public void shouldMatchAny() throws Exception { 25 | assertThat(CharMatcher.ANY.matchesAllOf("anything")).isTrue(); 26 | } 27 | 28 | @Test 29 | public void shouldMatchBreakingWhitespace() throws Exception { 30 | assertThat(CharMatcher.BREAKING_WHITESPACE.matchesAllOf("\r\n\r\n")).isTrue(); 31 | } 32 | 33 | @Test 34 | public void shouldMatchDigits() throws Exception { 35 | assertThat(CharMatcher.DIGIT.matchesAllOf("1231212")).isTrue(); 36 | } 37 | 38 | @Test 39 | public void shouldMatchDigitsWithWhitespace() throws Exception { 40 | assertThat(CharMatcher.DIGIT.matchesAnyOf("1231 aa212")).isTrue(); 41 | } 42 | 43 | @Test 44 | public void shouldRetainOnlyDigits() throws Exception { 45 | assertThat(CharMatcher.DIGIT.retainFrom("Hello 1234 567")).isEqualTo("1234567"); 46 | } 47 | 48 | @Test 49 | public void shouldRetainDigitsOrWhiteSpaces() throws Exception { 50 | assertThat(CharMatcher.DIGIT.or(CharMatcher.WHITESPACE).retainFrom("Hello 1234 567")).isEqualTo(" 1234 567"); 51 | } 52 | 53 | @Test 54 | public void shouldRetainNothingAsConstrainsAreExcluding() throws Exception { 55 | assertThat(CharMatcher.DIGIT.and(CharMatcher.JAVA_LETTER).retainFrom("Hello 1234 567")).isEqualTo(""); 56 | } 57 | 58 | @Test 59 | public void shouldRetainLettersAndDigits() throws Exception { 60 | assertThat(CharMatcher.DIGIT.or(CharMatcher.JAVA_LETTER).retainFrom("Hello 1234 567")).isEqualTo("Hello1234567"); 61 | } 62 | 63 | @Test 64 | public void shouldCollapseAllDigitsByX() throws Exception { 65 | assertThat(CharMatcher.DIGIT.collapseFrom("Hello 1234 567", 'x')).isEqualTo("Hello x x"); 66 | } 67 | 68 | @Test 69 | public void shouldReplaceAllDigitsByX() throws Exception { 70 | assertThat(CharMatcher.DIGIT.replaceFrom("Hello 1234 567", 'x')).isEqualTo("Hello xxxx xxx"); 71 | } 72 | 73 | @Test 74 | public void shouldCountDigits() throws Exception { 75 | assertThat(CharMatcher.DIGIT.countIn("Hello 1234 567")).isEqualTo(7); 76 | } 77 | 78 | @Test 79 | public void shouldReturnFirstIndexOfFirstWhitespace() throws Exception { 80 | assertThat(CharMatcher.WHITESPACE.indexIn("Hello 1234 567")).isEqualTo(5); 81 | } 82 | 83 | @Test 84 | public void shouldReturnLastIndexOfFirstWhitespace() throws Exception { 85 | assertThat(CharMatcher.WHITESPACE.lastIndexIn("Hello 1234 567")).isEqualTo(10); 86 | } 87 | 88 | @Test 89 | public void shouldRemoveDigitsBetween3and6() throws Exception { 90 | assertThat(CharMatcher.inRange('3', '6').removeFrom("Hello 1234 567")).isEqualTo("Hello 12 7"); 91 | } 92 | 93 | @Test 94 | public void shouldRemoveAllExceptDigitsBetween3and6() throws Exception { 95 | assertThat(CharMatcher.inRange('3', '6').negate().removeFrom("Hello 1234 567")).isEqualTo("3456"); 96 | } 97 | 98 | @Test 99 | public void shouldRemoveStartingAndEndingDollarsAndKeepOtherUnchanged() throws Exception { 100 | assertThat(CharMatcher.is('$').trimFrom("$$$ This is a $ sign $$$")).isEqualTo(" This is a $ sign "); 101 | } 102 | 103 | @Test 104 | public void shouldRemoveOnlyStartingDollarsAndKeepOtherUnchanged() throws Exception { 105 | assertThat(CharMatcher.is('$').trimLeadingFrom("$$$ This is a $ sign $$$")).isEqualTo(" This is a $ sign $$$"); 106 | } 107 | 108 | @Test 109 | public void shouldRemoveStartingEndEndingDollarsAndReplaceOthersWithX() throws Exception { 110 | assertThat(CharMatcher.is('$').trimAndCollapseFrom("$$$This is a $ sign$$$", 'X')).isEqualTo("This is a X sign"); 111 | } 112 | 113 | @Test 114 | public void shouldRemoveOnlyEndingDollarsAndKeepOtherUnchanged() throws Exception { 115 | assertThat(CharMatcher.is('$').trimTrailingFrom("$$$ This is a $ sign $$$")).isEqualTo("$$$ This is a $ sign "); 116 | } 117 | 118 | @Test 119 | public void shouldRemoveStartingAndEndingDollarsOrWhitespaceAndKeepOtherUnchanged() throws Exception { 120 | assertThat(CharMatcher.is('$').or(CharMatcher.is(' ')).trimFrom("$$$ This is a $ sign $$$")).isEqualTo("This is a $ sign"); 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/base/CharsetsTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.base; 2 | 3 | import com.google.common.base.Charsets; 4 | import org.testng.annotations.Test; 5 | 6 | import java.nio.charset.Charset; 7 | 8 | import static org.fest.assertions.Assertions.assertThat; 9 | 10 | /** 11 | * Classs to show how to use Charsets class 12 | */ 13 | public class CharsetsTest { 14 | 15 | @Test 16 | public void shouldCreateSupportedInJavaCharset() throws Exception { 17 | 18 | // given 19 | Charset charset = Charset.forName("UTF-8"); 20 | 21 | // when 22 | Charset charsetFromGuava = Charsets.UTF_8; 23 | 24 | // then 25 | assertThat(charset.name()).isEqualTo(charsetFromGuava.name()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/base/FunctionsTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.base; 2 | 3 | import com.google.common.base.Function; 4 | import com.google.common.base.Functions; 5 | import com.google.common.collect.Collections2; 6 | import com.google.common.collect.Lists; 7 | import com.google.common.collect.Maps; 8 | import com.google.inject.internal.Nullable; 9 | import org.testng.annotations.Test; 10 | import pl.tomaszdziurko.guava.geo.Country; 11 | 12 | import java.util.Collection; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | import static org.fest.assertions.Assertions.assertThat; 17 | 18 | /** 19 | * Class to show how Functions in Guava works 20 | */ 21 | 22 | public class FunctionsTest { 23 | 24 | @Test 25 | public void shouldPrintCountryWithCapitalCityUpperCase() throws Exception { 26 | 27 | // given 28 | Function capitalCityFunction = new Function() { 29 | public String apply(@Nullable Country country) { 30 | if (country == null) { 31 | return ""; 32 | } 33 | return country.getCapitalCity(); 34 | } 35 | }; 36 | 37 | // when 38 | Collection capitalCities = Collections2.transform(Country.getSomeCountries(), capitalCityFunction); 39 | 40 | // then 41 | assertThat(capitalCities).contains("Warsaw", "Madrid"); 42 | } 43 | 44 | @Test 45 | public void shouldComposeTwoFunctions() throws Exception { 46 | Function upperCaseFunction = new Function() { 47 | public String apply(@Nullable Country country) { 48 | if (country == null) { 49 | return ""; 50 | } 51 | return country.getCapitalCity().toUpperCase(); 52 | } 53 | }; 54 | 55 | Function reverseFunction = new Function() { 56 | public String apply(String string) { 57 | if(string == null) { 58 | return null; 59 | } 60 | return new StringBuilder(string).reverse().toString(); 61 | } 62 | }; 63 | Function composedFunction = Functions.compose(reverseFunction, upperCaseFunction); 64 | 65 | // when 66 | Collection reversedCapitalCities = Collections2.transform(Country.getSomeCountries(), composedFunction); 67 | 68 | // then 69 | assertThat(reversedCapitalCities).contains("WASRAW", "DIRDAM"); 70 | } 71 | 72 | @Test 73 | public void shouldUseForMapFunction() throws Exception { 74 | 75 | // given 76 | Map map = Maps.newHashMap(); 77 | map.put(Country.POLAND.getName(), Country.POLAND.getCapitalCity()); 78 | map.put(Country.BELGIUM.getName(), Country.BELGIUM.getCapitalCity()); 79 | map.put(Country.SPAIN.getName(), Country.SPAIN.getCapitalCity()); 80 | map.put(Country.ENGLAND.getName(), Country.ENGLAND.getCapitalCity()); 81 | 82 | // when 83 | Function capitalCityFromCountryName = Functions.forMap(map); 84 | 85 | List countries = Lists.newArrayList(); 86 | countries.add(Country.POLAND.getName()); 87 | countries.add(Country.BELGIUM.getName()); 88 | 89 | // then 90 | Collection capitalCities = Collections2.transform(countries, capitalCityFromCountryName); 91 | 92 | assertThat(capitalCities).containsOnly(Country.POLAND.getCapitalCity(), Country.BELGIUM.getCapitalCity()); 93 | } 94 | 95 | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Key 'Belgium' not present in map") 96 | public void shouldUseForMapFunctionWithNonExistingKey() throws Exception { 97 | 98 | // given 99 | Map map = Maps.newHashMap(); 100 | map.put(Country.POLAND.getName(), Country.POLAND.getCapitalCity()); 101 | 102 | // we omit this one intentionally 103 | // map.put(Country.BELGIUM.getName(), Country.BELGIUM.getCapitalCity()); 104 | map.put(Country.SPAIN.getName(), Country.SPAIN.getCapitalCity()); 105 | map.put(Country.ENGLAND.getName(), Country.ENGLAND.getCapitalCity()); 106 | 107 | // when 108 | Function capitalCityFromCountryName = Functions.forMap(map); 109 | 110 | List countries = Lists.newArrayList(); 111 | countries.add(Country.POLAND.getName()); 112 | countries.add(Country.BELGIUM.getName()); 113 | 114 | // then 115 | Collection capitalCities = Collections2.transform(countries, capitalCityFromCountryName); 116 | 117 | assertThat(capitalCities).containsOnly(Country.POLAND.getCapitalCity(), Country.BELGIUM.getCapitalCity()); 118 | } 119 | 120 | @Test 121 | public void shouldUseForMapFunctionWithDefaultValue() throws Exception { 122 | 123 | // given 124 | Map map = Maps.newHashMap(); 125 | map.put(Country.POLAND.getName(), Country.POLAND.getCapitalCity()); 126 | 127 | // we omit this one intentionally 128 | // map.put(Country.BELGIUM.getName(), Country.BELGIUM.getCapitalCity()); 129 | map.put(Country.SPAIN.getName(), Country.SPAIN.getCapitalCity()); 130 | map.put(Country.ENGLAND.getName(), Country.ENGLAND.getCapitalCity()); 131 | 132 | // when 133 | Function capitalCityFromCountryName = Functions.forMap(map, "Unknown"); 134 | 135 | List countries = Lists.newArrayList(); 136 | countries.add(Country.POLAND.getName()); 137 | countries.add(Country.BELGIUM.getName()); 138 | 139 | // then 140 | Collection capitalCities = Collections2.transform(countries, capitalCityFromCountryName); 141 | 142 | assertThat(capitalCities).containsOnly(Country.POLAND.getCapitalCity(), "Unknown"); 143 | } 144 | } -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/base/JoinerTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.base; 2 | 3 | import com.google.common.base.Joiner; 4 | import org.testng.annotations.Test; 5 | 6 | import java.util.Arrays; 7 | import java.util.HashMap; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | import static org.fest.assertions.Assertions.assertThat; 12 | 13 | /** 14 | * Test class to show some features of Joiners 15 | */ 16 | public class JoinerTest { 17 | 18 | 19 | 20 | 21 | 22 | public static List languages = Arrays.asList("Java", "Haskell", "Scala", "Brainfuck"); 23 | 24 | @Test 25 | public void shouldJoinWithCommas() throws Exception { 26 | assertThat(Joiner.on(",").join(languages)).isEqualTo("Java,Haskell,Scala,Brainfuck"); 27 | } 28 | 29 | // interesting use case :) 30 | @Test(expectedExceptions = NullPointerException.class) 31 | public void shouldThrowNullPointerException() throws Exception { 32 | assertThat(Joiner.on(",").join(countriesWithNullValue)).isEqualTo("Poland,Brasil,Ukraine,null,England,Croatia"); 33 | } 34 | 35 | public static List countriesWithNullValue = Arrays 36 | .asList("Poland", "Brasil", "Ukraine", null, "England", "Croatia"); 37 | 38 | @Test 39 | public void shouldJoinWithCommasAndOmitNulls() throws Exception { 40 | assertThat(Joiner.on(",").skipNulls().join(countriesWithNullValue)) 41 | .isEqualTo("Poland,Brasil,Ukraine,England,Croatia"); 42 | } 43 | 44 | @Test 45 | public void shouldJoinWithCommasAndReplaceNullsWithWordNothing() throws Exception { 46 | assertThat(Joiner.on(",").useForNull("NONE").join(countriesWithNullValue)) 47 | .isEqualTo("Poland,Brasil,Ukraine,NONE,England,Croatia"); 48 | } 49 | 50 | public static Map numbersWords = new HashMap(); 51 | 52 | static { 53 | numbersWords.put(1, "one"); 54 | numbersWords.put(2, "two"); 55 | numbersWords.put(3, null); 56 | numbersWords.put(4, "four"); 57 | } 58 | 59 | @Test 60 | public void shouldJoinMap() throws Exception { 61 | assertThat(Joiner.on(" | ").withKeyValueSeparator(" -> ") 62 | .useForNull("Unknown").join(numbersWords)) 63 | .isEqualTo("1 -> one | 2 -> two | 3 -> Unknown | 4 -> four"); 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/base/ObjectsTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.base; 2 | 3 | 4 | import org.testng.annotations.Test; 5 | import pl.tomaszdziurko.guava.UserProfile; 6 | 7 | import static org.fest.assertions.Assertions.assertThat; 8 | 9 | @Test 10 | public class ObjectsTest { 11 | 12 | UserProfile objectsLesson = new UserProfile("name", "nickname", 20); 13 | UserProfile objectsLesson2 = new UserProfile("name", "nickname", 20); 14 | UserProfile nullNicknameObject = new UserProfile("name", null, 20); 15 | 16 | @Test 17 | public void shouldTestEquals() throws Exception { 18 | 19 | assertThat(objectsLesson).isEqualTo(objectsLesson2); 20 | } 21 | 22 | @Test 23 | public void shouldTestHashcode() throws Exception { 24 | 25 | assertThat(objectsLesson.hashCode()).isEqualTo(objectsLesson2.hashCode()); 26 | } 27 | 28 | @Test 29 | public void shouldRenderNameAsDisplayableName() throws Exception { 30 | 31 | // then 32 | assertThat(nullNicknameObject.getDisplayName()).isEqualTo("name"); 33 | } 34 | 35 | @Test 36 | public void shouldShowHowToStringMethodWorks() throws Exception { 37 | 38 | assertThat(objectsLesson.toString()) 39 | .isEqualTo("UserProfile{name=name, nickname=nickname, 20}"); 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/base/PreconditionsTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.base; 2 | 3 | import org.testng.annotations.Test; 4 | import pl.tomaszdziurko.guava.PreconditionsLesson; 5 | 6 | import java.util.Arrays; 7 | 8 | public class PreconditionsTest { 9 | 10 | PreconditionsLesson preconditionsLesson = new PreconditionsLesson(); 11 | 12 | @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = 13 | "Weather is not the best for a sunbath") 14 | public void shouldThrowIllegalState() throws Exception { 15 | 16 | preconditionsLesson.getSomeSuntan(PreconditionsLesson.Weather.CLOUDY); 17 | } 18 | 19 | @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = 20 | "Team can not be null") 21 | public void shouldNotAcceptNullFootballTeam() throws Exception { 22 | 23 | // when 24 | preconditionsLesson.displayFootballTeamMembers(null); 25 | } 26 | 27 | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = 28 | "Full team should consist of 11 players") 29 | public void shouldNotAcceptNotFullFootballTeam() throws Exception { 30 | 31 | // when 32 | preconditionsLesson.displayFootballTeamMembers(Arrays.asList("Casillas", "Pepe", "Ramos", "Marcelo")); 33 | } 34 | 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/base/PredicateTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.base; 2 | 3 | import com.google.common.base.Predicate; 4 | import com.google.common.base.Predicates; 5 | import com.google.common.base.Strings; 6 | import com.google.common.collect.Iterables; 7 | import com.google.common.collect.Lists; 8 | import org.testng.annotations.Test; 9 | import pl.tomaszdziurko.guava.geo.Continent; 10 | import pl.tomaszdziurko.guava.geo.Country; 11 | 12 | import javax.annotation.Nullable; 13 | import java.util.Arrays; 14 | 15 | import static org.fest.assertions.Assertions.assertThat; 16 | import static org.testng.Assert.assertFalse; 17 | 18 | 19 | /** 20 | * Features of Predicates class 21 | */ 22 | public class PredicateTest { 23 | 24 | @Test 25 | public void shouldUseCustomPredicate() throws Exception { 26 | 27 | // given 28 | Predicate capitalCityProvidedPredicate = new Predicate() { 29 | 30 | @Override 31 | public boolean apply(@Nullable Country country) { 32 | return !Strings.isNullOrEmpty(country.getCapitalCity()); 33 | } 34 | }; 35 | 36 | // when 37 | boolean allCountriesSpecifyCapitalCity = Iterables.all( 38 | Lists.newArrayList(Country.POLAND, Country.BELGIUM, Country.FINLAND_WITHOUT_CAPITAL_CITY), 39 | capitalCityProvidedPredicate); 40 | 41 | // then 42 | assertFalse(allCountriesSpecifyCapitalCity); 43 | } 44 | 45 | @Test 46 | public void shouldComposeTwoPredicates() throws Exception { 47 | 48 | // given 49 | Predicate fromEuropePredicate = new Predicate() { 50 | 51 | @Override 52 | public boolean apply(@Nullable Country country) { 53 | return Continent.EUROPE.equals(country.getContinent()); 54 | } 55 | }; 56 | 57 | Predicate populationPredicate = new Predicate() { 58 | 59 | @Override 60 | public boolean apply(@Nullable Country country) { 61 | return country.getPopulation() < 20; 62 | } 63 | }; 64 | 65 | Predicate composedPredicate = Predicates.and(fromEuropePredicate, populationPredicate); 66 | 67 | // when 68 | Iterable filteredCountries = Iterables.filter(Country.getSomeCountries(), composedPredicate); 69 | 70 | // then 71 | assertThat(filteredCountries).contains(Country.BELGIUM, Country.ICELAND); 72 | } 73 | 74 | @Test 75 | public void shouldCheckPattern() throws Exception { 76 | 77 | // given 78 | Predicate twoDigitsPredicate = Predicates.containsPattern("\\d\\d"); 79 | 80 | // then 81 | assertThat(twoDigitsPredicate.apply("Hello world 40")).isTrue(); 82 | } 83 | 84 | @Test 85 | public void shouldFindObjectInCollection() throws Exception { 86 | 87 | // given 88 | Predicate elevenInCollectionPredicate = Predicates.in(Arrays.asList(11L, 22L, 33L, 44L)); 89 | 90 | // then 91 | assertThat(elevenInCollectionPredicate.apply(11L)).isTrue(); 92 | } 93 | 94 | 95 | } 96 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/base/SplitterTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.base; 2 | 3 | import com.google.common.base.CharMatcher; 4 | import com.google.common.base.Splitter; 5 | import org.testng.annotations.Test; 6 | import org.testng.collections.Lists; 7 | 8 | import java.util.Iterator; 9 | import java.util.List; 10 | 11 | import static org.fest.assertions.Assertions.assertThat; 12 | 13 | /** 14 | * Class to show some features of Splitter class 15 | */ 16 | public class SplitterTest { 17 | 18 | public static String textWithDigitsAsADelimeter = "Java1Scala2Haskell3444Brainfuck452Kotlin"; 19 | public static String textWithDigitsFrom3To5AsADelimeter = "Java3Scala4Haskell0Brainfuck5Kotlin"; 20 | public static String textWithFiveCharactersWords = "HorseHouseGroupDemosScrum"; 21 | 22 | public static String textWithSemicolonAsADelimeterWithEmptyElementsAndSpaces = "Java;; ;Scala;;;Haskell;Brainfuck;Kotlin"; 23 | 24 | 25 | @Test 26 | public void shouldSplitOnSemicolons() throws Exception { 27 | // when 28 | Iterable iterable = Splitter.on(";").split("Java;Scala;Haskell;Brainfuck;Kotlin"); 29 | List splittedList = convertToList(iterable.iterator()); 30 | 31 | // then 32 | assertThat(splittedList.size()).isEqualTo(5); 33 | assertThat(splittedList.get(3)).isEqualTo("Brainfuck"); 34 | } 35 | 36 | private List convertToList(Iterator iterator) { 37 | List list = Lists.newArrayList( ); 38 | 39 | while(iterator.hasNext()) { 40 | list.add(iterator.next()); 41 | } 42 | 43 | return list; 44 | } 45 | 46 | @Test 47 | public void shouldSplitOnRegExp() throws Exception { 48 | // when 49 | Iterable iterable = Splitter.onPattern("\\d+").split("Java3Scala4Haskell0Brainfuck5Kotlin"); 50 | List splittedList = convertToList(iterable.iterator()); 51 | 52 | // then 53 | assertThat(splittedList.size()).isEqualTo(5); 54 | assertThat(splittedList.get(2)).isEqualTo("Haskell"); 55 | } 56 | 57 | 58 | 59 | @Test 60 | public void shouldSplitUsingCharMatcher() throws Exception { 61 | 62 | // when 63 | Iterable iterable = Splitter 64 | .on(CharMatcher.inRange('3', '5')).split("Java3Scala4Haskell0Brainfuck5Kotlin"); 65 | List splittedList = convertToList(iterable.iterator()); 66 | 67 | // then 68 | assertThat(splittedList.size()).isEqualTo(4); 69 | assertThat(splittedList.get(2)).isEqualTo("Haskell0Brainfuck"); 70 | 71 | } 72 | 73 | @Test 74 | public void shouldSplitAndOmitEmptyElementsAndWhitespaces() throws Exception { 75 | // when 76 | Iterable iterable = Splitter.on(";").omitEmptyStrings() 77 | .trimResults().split("Java;; ;Scala;;;Haskell;Brainfuck;Kotlin"); 78 | List splittedList = convertToList(iterable.iterator()); 79 | 80 | // then 81 | assertThat(splittedList.size()).isEqualTo(5); 82 | assertThat(splittedList.get(1)).isEqualTo("Scala"); 83 | 84 | } 85 | 86 | @Test 87 | public void shouldSplitForEqualLength() throws Exception { 88 | 89 | // when 90 | Iterable iterable = Splitter.fixedLength(5).split("HorseHouseGroupDemosScrum"); 91 | List splittedList = convertToList(iterable.iterator()); 92 | 93 | // then 94 | assertThat(splittedList.size()).isEqualTo(5); 95 | assertThat(splittedList.get(4)).isEqualTo("Scrum"); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/base/StopwatchTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.base; 2 | 3 | import com.google.common.base.Stopwatch; 4 | import com.google.common.base.Ticker; 5 | import org.testng.annotations.Test; 6 | 7 | import java.util.concurrent.TimeUnit; 8 | 9 | import static org.fest.assertions.Assertions.assertThat; 10 | import static org.mockito.Mockito.*; 11 | 12 | /** 13 | * Class showing how Stopwatch works 14 | */ 15 | public class StopwatchTest { 16 | 17 | @Test 18 | public void shouldCalculateIterationsTime() throws Exception { 19 | 20 | // given 21 | Ticker ticker = mock(Ticker.class); 22 | when(ticker.read()).thenReturn(0L, 2000000000L); 23 | Stopwatch stopwatch = new Stopwatch(ticker); 24 | 25 | // when 26 | stopwatch.start(); 27 | // some method is called here 28 | stopwatch.stop(); 29 | 30 | // then 31 | assertThat(stopwatch.elapsedMillis()).isEqualTo(2000L); 32 | } 33 | 34 | @Test 35 | public void shouldPrintIterationsTime() throws Exception { 36 | 37 | // given 38 | Ticker ticker = mock(Ticker.class); 39 | when(ticker.read()).thenReturn(0L, 2*60*60*1000000000L); // 2 hours 40 | Stopwatch stopwatch = new Stopwatch(ticker); 41 | 42 | // when 43 | stopwatch.start(); 44 | // some method is called here 45 | stopwatch.stop(); 46 | 47 | // then 48 | assertThat(stopwatch.toString()).isEqualTo("7200 s"); 49 | assertThat(stopwatch.elapsedTime(TimeUnit.MINUTES)).isEqualTo(120); 50 | assertThat(stopwatch.elapsedTime(TimeUnit.HOURS)).isEqualTo(2); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/base/StringsTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.base; 2 | 3 | import com.google.common.base.Strings; 4 | import org.testng.annotations.Test; 5 | 6 | import static org.fest.assertions.Assertions.assertThat; 7 | 8 | /** 9 | * Class to show features of Strings class 10 | */ 11 | public class StringsTest { 12 | 13 | @Test 14 | public void shouldReturnTrueOnNullString() throws Exception { 15 | assertThat(Strings.isNullOrEmpty(null)).isTrue(); 16 | } 17 | 18 | @Test 19 | public void shouldConvertNullToEmpty() throws Exception { 20 | assertThat(Strings.nullToEmpty(null)).isEqualTo(""); 21 | } 22 | 23 | @Test 24 | public void shouldConvertEmptyToNull() throws Exception { 25 | assertThat(Strings.emptyToNull("")).isNull(); 26 | } 27 | 28 | @Test 29 | public void shouldPadEnd() throws Exception { 30 | 31 | assertThat(Strings.padEnd("Nothing special", 20, '*')).isEqualTo("Nothing special*****"); 32 | } 33 | 34 | @Test 35 | public void shouldPadStart() throws Exception { 36 | assertThat(Strings.padStart("Nothing special", 20, ' ')).isEqualTo(" Nothing special"); 37 | } 38 | 39 | @Test 40 | public void shouldRepeatGivenString() throws Exception { 41 | assertThat(Strings.repeat("Hello ", 3)).isEqualTo("Hello Hello Hello "); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/base/ThrowablesTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.base; 2 | 3 | import com.google.common.base.Throwables; 4 | import org.testng.annotations.Test; 5 | 6 | import java.sql.SQLException; 7 | import java.util.List; 8 | 9 | import static org.fest.assertions.Assertions.assertThat; 10 | 11 | /** 12 | * Throwables showcase 13 | */ 14 | public class ThrowablesTest { 15 | 16 | @Test 17 | public void shouldListAllExceptionsChain() throws Exception { 18 | 19 | try { 20 | try { 21 | try { 22 | throw new RuntimeException("Innermost exception"); 23 | } 24 | catch(Exception e) { 25 | throw new SQLException("Middle tier exception", e); 26 | } 27 | } 28 | catch(Exception e) { 29 | throw new IllegalStateException("Last exception", e); 30 | } 31 | } 32 | catch(Exception e) { 33 | List exceptionsChain = Throwables.getCausalChain(e); 34 | assertThat(exceptionsChain).onProperty("message") 35 | .containsExactly("Last exception", "Middle tier exception", "Innermost exception"); 36 | } 37 | } 38 | 39 | @Test 40 | public void shouldExtractInnermostException() throws Exception { 41 | 42 | try { 43 | try { 44 | try { 45 | throw new RuntimeException("Innermost exception"); 46 | } 47 | catch(Exception e) { 48 | throw new SQLException("Middle tier exception", e); 49 | } 50 | } 51 | catch(Exception e) { 52 | throw new IllegalStateException("Last exception", e); 53 | } 54 | } 55 | catch(Exception e) { 56 | assertThat(Throwables.getRootCause(e).getMessage()).isEqualTo("Innermost exception"); 57 | } 58 | } 59 | 60 | @Test 61 | public void shouldGetStackTrace() throws Exception { 62 | 63 | try { 64 | try { 65 | try { 66 | throw new RuntimeException("Innermost exception"); 67 | } 68 | catch(Exception e) { 69 | throw new SQLException("Middle tier exception", e); 70 | } 71 | } 72 | catch(Exception e) { 73 | throw new IllegalStateException("Last exception", e); 74 | } 75 | } 76 | catch(Exception e) { 77 | assertThat(Throwables.getStackTraceAsString(e)) 78 | .contains("Caused by: java.lang.RuntimeException: Innermost exception"); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/collect/BiMapTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.collect; 2 | 3 | import com.google.common.collect.BiMap; 4 | import com.google.common.collect.HashBiMap; 5 | import org.testng.annotations.Test; 6 | 7 | import static org.fest.assertions.Assertions.assertThat; 8 | import static org.testng.Assert.fail; 9 | 10 | /** 11 | * BiMap showcase 12 | */ 13 | public class BiMapTest { 14 | 15 | @Test 16 | public void shouldInverseBiMap() throws Exception { 17 | 18 | BiMap bimap = HashBiMap.create(); 19 | 20 | // when 21 | bimap.put(1, "one"); 22 | bimap.put(2, "two"); 23 | bimap.put(10, "ten"); 24 | 25 | BiMap inversedBiMap = bimap.inverse(); 26 | 27 | // then 28 | assertThat(inversedBiMap.get("one")).isEqualTo(1); 29 | } 30 | 31 | @Test(expectedExceptions = IllegalArgumentException.class, 32 | expectedExceptionsMessageRegExp = "value already present: one") 33 | public void shouldNotAllowToPutExistingValue() throws Exception { 34 | 35 | BiMap bimap = HashBiMap.create(); 36 | 37 | // when 38 | bimap.put(1, "one"); 39 | bimap.put(2, "two"); 40 | bimap.put(10, "ten"); 41 | bimap.put(10, "one"); 42 | 43 | fail("Should throw IllegalArgumentException"); 44 | } 45 | 46 | @Test 47 | public void shouldAllowToPutExistingValueWithForcePut() throws Exception { 48 | 49 | BiMap bimap = HashBiMap.create(); 50 | 51 | // when 52 | bimap.put(1, "one"); 53 | bimap.put(2, "two"); 54 | bimap.put(10, "ten"); 55 | bimap.forcePut(10, "one"); 56 | 57 | assertThat(bimap.get(10)).isEqualTo("one"); 58 | assertThat(bimap.get(1)).isNull(); 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/collect/Collections2Test.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.collect; 2 | 3 | import com.google.common.base.Function; 4 | import com.google.common.base.Predicate; 5 | import com.google.common.collect.Collections2; 6 | import com.google.common.collect.Lists; 7 | import org.testng.annotations.Test; 8 | import pl.tomaszdziurko.guava.geo.Continent; 9 | import pl.tomaszdziurko.guava.geo.Country; 10 | 11 | import javax.annotation.Nullable; 12 | import java.util.ArrayList; 13 | import java.util.Collection; 14 | 15 | import static org.fest.assertions.Assertions.assertThat; 16 | 17 | /** 18 | * Collections2 showcase 19 | */ 20 | public class Collections2Test { 21 | 22 | @Test 23 | public void shouldTransformCollection() throws Exception { 24 | 25 | // given 26 | ArrayList countries = Lists.newArrayList(Country.POLAND, Country.BELGIUM, Country.ENGLAND); 27 | 28 | // when 29 | Collection capitalCities = Collections2.transform(countries, 30 | new Function() { 31 | 32 | @Override 33 | public String apply(@Nullable Country country) { 34 | return country.getCapitalCity(); 35 | } 36 | }); 37 | 38 | // then 39 | assertThat(capitalCities).containsOnly("Warsaw", "Brussels", "London"); 40 | } 41 | 42 | @Test 43 | public void shouldFilterCountriesOnlyFromAfrica() throws Exception { 44 | 45 | // given 46 | ArrayList countries = Lists.newArrayList(Country.POLAND, Country.BELGIUM, Country.SOUTH_AFRICA); 47 | 48 | // when 49 | Collection countriesFromAfrica = Collections2.filter(countries, new Predicate() { 50 | 51 | @Override 52 | public boolean apply(@Nullable Country country) { 53 | return Continent.AFRICA.equals(country.getContinent()); 54 | } 55 | }); 56 | 57 | // then 58 | assertThat(countriesFromAfrica).containsOnly(Country.SOUTH_AFRICA); 59 | } 60 | 61 | @Test 62 | public void shouldShowThatResultIsOnlyAView() throws Exception { 63 | 64 | // given 65 | ArrayList countries = Lists.newArrayList(Country.POLAND, Country.BELGIUM, Country.ENGLAND); 66 | 67 | // when 68 | Collection capitalCities = Collections2.transform(countries, 69 | new Function() { 70 | 71 | @Override 72 | public String apply(@Nullable Country country) { 73 | return country.getCapitalCity(); 74 | } 75 | }); 76 | 77 | // then 78 | assertThat(capitalCities).containsOnly("Warsaw", "Brussels", "London"); 79 | assertThat(capitalCities).excludes("Pretoria"); 80 | 81 | countries.add(Country.SOUTH_AFRICA); 82 | 83 | assertThat(capitalCities).contains("Pretoria"); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/collect/ConstraintsTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.collect; 2 | 3 | import com.google.common.base.Preconditions; 4 | import com.google.common.collect.Constraint; 5 | import com.google.common.collect.Constraints; 6 | import com.google.common.collect.Lists; 7 | import org.testng.annotations.Test; 8 | 9 | import java.util.List; 10 | 11 | import static org.testng.Assert.fail; 12 | 13 | /** 14 | * Constraints showcase 15 | */ 16 | public class ConstraintsTest { 17 | 18 | @Test(expectedExceptions = NullPointerException.class) 19 | public void shouldThrowExceptionOnNullAdd() throws Exception { 20 | 21 | // given 22 | List numbers = Constraints 23 | .constrainedList(Lists.newArrayList(1, 2, 3), Constraints.notNull()); 24 | 25 | // when 26 | numbers.add(null); 27 | 28 | // then 29 | fail("Should throw a NullPointerException"); 30 | } 31 | 32 | @Test(expectedExceptions = IllegalArgumentException.class) 33 | public void shouldThrowExceptionOnInvalidAdd() throws Exception { 34 | 35 | // given 36 | List userAgesList = Constraints.constrainedList(Lists.newArrayList(1, 2, 3), new Constraint() { 37 | 38 | @Override 39 | public Integer checkElement(Integer age) { 40 | Preconditions.checkNotNull(age); 41 | Preconditions.checkArgument(age.intValue() > 0); 42 | return age; 43 | } 44 | }); 45 | 46 | // when 47 | userAgesList.add(-2); 48 | 49 | // then 50 | fail("Should throw a IllegalArgumentException"); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/collect/DiscreteDomainTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.collect; 2 | 3 | import com.google.common.collect.DiscreteDomain; 4 | import com.google.common.collect.DiscreteDomains; 5 | import org.testng.annotations.Test; 6 | 7 | import static org.fest.assertions.Assertions.assertThat; 8 | 9 | /** 10 | * Showcas of discrete domains interface 11 | */ 12 | public class DiscreteDomainTest { 13 | 14 | 15 | @Test 16 | public void shouldReturnNextInt() throws Exception { 17 | 18 | // given 19 | DiscreteDomain integers = DiscreteDomains.integers(); 20 | 21 | // when 22 | Integer next = integers.next(new Integer(100)); 23 | 24 | // then 25 | assertThat(next).isEqualTo(101); 26 | } 27 | 28 | @Test 29 | public void shouldReturnPreviousInt() throws Exception { 30 | 31 | // given 32 | DiscreteDomain integers = DiscreteDomains.integers(); 33 | 34 | // when 35 | Integer next = integers.previous(new Integer(100)); 36 | 37 | // then 38 | assertThat(next).isEqualTo(99); 39 | } 40 | 41 | @Test 42 | public void shouldReturnDistance() throws Exception { 43 | 44 | // given 45 | DiscreteDomain integers = DiscreteDomains.integers(); 46 | 47 | // when 48 | long distance = integers.distance(100, 150); 49 | 50 | // then 51 | assertThat(distance).isEqualTo(50L); 52 | } 53 | 54 | @Test 55 | public void shouldReturnMaxAndMinInt() throws Exception { 56 | 57 | // given 58 | DiscreteDomain integers = DiscreteDomains.integers(); 59 | 60 | // when 61 | long min = integers.minValue(); 62 | long max = integers.maxValue(); 63 | 64 | // then 65 | assertThat(min).isEqualTo(Integer.MIN_VALUE); 66 | assertThat(max).isEqualTo(Integer.MAX_VALUE); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/collect/ForwardingListTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.collect; 2 | 3 | import com.google.common.collect.ForwardingCollection; 4 | import com.google.common.collect.Lists; 5 | import org.testng.annotations.Test; 6 | 7 | import java.util.Collection; 8 | import java.util.List; 9 | 10 | import static org.fest.assertions.Assertions.assertThat; 11 | 12 | /** 13 | * ForwardingListTest showcase 14 | */ 15 | public class ForwardingListTest { 16 | 17 | @Test 18 | public void shouldAddOppositeNumber() throws Exception { 19 | 20 | // given 21 | Collection numbersList = new ForwardingCollection() { 22 | private List list = Lists.newArrayList(); 23 | 24 | @Override 25 | protected List delegate() { 26 | return list; 27 | } 28 | 29 | @Override 30 | public boolean add(Integer element) { 31 | if(element == null) { 32 | return super.add(element); 33 | } 34 | if(element.intValue() == 0) { 35 | return super.add(element); 36 | } 37 | else { 38 | return super.add(element) && super.add(-element); 39 | } 40 | } 41 | 42 | @Override 43 | public boolean addAll(Collection integers) { 44 | if(integers == null) { 45 | return add(null); 46 | } 47 | boolean result = true; 48 | for (Integer element : integers) { 49 | result = result && add(element); 50 | } 51 | return result; 52 | } 53 | }; 54 | 55 | numbersList.add(10); 56 | numbersList.add(12); 57 | numbersList.add(0); 58 | numbersList.add(null); 59 | 60 | assertThat(numbersList).containsOnly(10, 12, -10, -12, 0, null); 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/collect/ImmutableMapTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.collect; 2 | 3 | import com.google.common.collect.ImmutableMap; 4 | import org.testng.annotations.Test; 5 | 6 | import static org.fest.assertions.Assertions.assertThat; 7 | 8 | /** 9 | * Immutable Map showcase 10 | */ 11 | public class ImmutableMapTest { 12 | 13 | 14 | @Test 15 | public void shouldUseMapBuilder() throws Exception { 16 | 17 | // when 18 | ImmutableMap numbersMap = new ImmutableMap.Builder() 19 | .put("one", 1) 20 | .put("two", 2) 21 | .put("three", 3) 22 | .put("four", 4) 23 | .build(); 24 | 25 | // then 26 | assertThat(numbersMap.get("two")).isEqualTo(2); 27 | } 28 | 29 | @Test 30 | public void shouldUseQuickMapCreator() throws Exception { 31 | 32 | // when 33 | ImmutableMap numbersMap = ImmutableMap.of("one", 1, 34 | "two", 2, "three", 3, "four", 4, "five", 5); 35 | 36 | 37 | assertThat(numbersMap.get("two")).isEqualTo(2); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/collect/IterablesTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.collect; 2 | 3 | import com.google.common.base.Predicate; 4 | import com.google.common.base.Strings; 5 | import com.google.common.collect.Iterables; 6 | import com.google.common.collect.Lists; 7 | import org.fest.assertions.Condition; 8 | import org.testng.annotations.Test; 9 | 10 | import javax.annotation.Nullable; 11 | import java.util.Iterator; 12 | import java.util.List; 13 | 14 | import static org.fest.assertions.Assertions.assertThat; 15 | 16 | /** 17 | * Iterables class demonstration 18 | */ 19 | public class IterablesTest { 20 | 21 | @Test 22 | public void shouldCheckLengthOfAllElements() throws Exception { 23 | 24 | // given 25 | Predicate lengthPredicate = new Predicate () { 26 | @Override 27 | public boolean apply(@Nullable String input) { 28 | if(input == null) { 29 | return false; 30 | } 31 | return input.length() > 3; 32 | } 33 | }; 34 | 35 | // then 36 | assertThat(Iterables.all(Lists.newArrayList("Java", "Scala", "Haskell", "Groovy", "Java", "Lisp"), 37 | lengthPredicate)).isTrue(); 38 | } 39 | 40 | @Test 41 | public void shouldCheckIfAtLeastOneElementIsEmptyOrNull() throws Exception { 42 | 43 | // given 44 | Predicate emptyOrNullPredicate = new Predicate () { 45 | 46 | @Override 47 | public boolean apply(@Nullable String input) { 48 | return Strings.isNullOrEmpty(input); 49 | } 50 | }; 51 | 52 | // then 53 | assertThat(Iterables.any(Lists.newArrayList("Java", "Scala", 54 | "Haskell", "Groovy", "Java", "Lisp"), emptyOrNullPredicate)).isFalse(); 55 | } 56 | 57 | @Test 58 | public void shouldConcat() throws Exception { 59 | 60 | // when 61 | Iterable concatenatedIterable = Iterables.concat( 62 | Lists.newArrayList("Java", "Scala", "Haskell", "Groovy", "Java", "Lisp"), 63 | Lists.newArrayList("Spring", "Hibernate", "JSF", "Wicket", "CDI", "Wicket")); 64 | 65 | 66 | // then 67 | assertThat(concatenatedIterable).hasSize(12); 68 | } 69 | 70 | @Test 71 | public void shouldCycleOverIterable() throws Exception { 72 | 73 | Iterable cycleIterables = Iterables.cycle("Right", "Left"); 74 | 75 | // then 76 | Iterator iterator = cycleIterables.iterator(); 77 | 78 | for(int i = 0; i < 100; i++) { 79 | iterator.next(); 80 | } 81 | 82 | assertThat(iterator.next()).is(new Condition() { 83 | @Override 84 | public boolean matches(String value) { 85 | return "Left".equals(value) || "Right".equals(value); 86 | } 87 | }); 88 | } 89 | 90 | @Test 91 | public void shouldFilterOnlyLongs() throws Exception { 92 | 93 | // given 94 | List numbersList = Lists.newArrayList(); 95 | 96 | numbersList.add(1L); 97 | numbersList.add(2); 98 | numbersList.add(3L); 99 | numbersList.add(4); 100 | 101 | // when 102 | Iterable filteredList = Iterables.filter(numbersList, Long.class); 103 | 104 | // then 105 | assertThat(filteredList).hasSize(2).contains(1L, 3L); 106 | } 107 | 108 | @Test 109 | public void shouldFilterOutSomeNumbers() throws Exception { 110 | 111 | // given 112 | List numbersList = Lists.newArrayList(1, 2, 3, 0, -12, 22, 430, -1024); 113 | 114 | // when 115 | Iterable filteredList = Iterables.filter(numbersList, new Predicate() { 116 | @Override 117 | public boolean apply(@Nullable Integer input) { 118 | if (input == null) { 119 | return false; 120 | } 121 | return input < 0; 122 | } 123 | }); 124 | 125 | 126 | // then 127 | assertThat(filteredList).hasSize(2).contains(-12, -1024); 128 | } 129 | 130 | @Test 131 | public void shouldCountElementsInIterable() throws Exception { 132 | 133 | // given 134 | List numbersList = Lists.newArrayList(1, 2, 3, 0, -2, 2, 430, 2); 135 | 136 | int frequency = Iterables.frequency(numbersList, 2); 137 | 138 | 139 | // then 140 | assertThat(frequency).isEqualTo(3); 141 | } 142 | 143 | @Test 144 | public void shouldReturnSelectedElementWithDefValue() throws Exception { 145 | 146 | // given 147 | List numbersList = Lists.newArrayList(1, 2, 3, 0, -12, 22, 430, -1024); 148 | 149 | // when 150 | 151 | 152 | // then 153 | assertThat(Iterables.get(numbersList, 100, -999)).isEqualTo(-999); 154 | } 155 | 156 | @Test 157 | public void shouldGetFirstAndLast() throws Exception { 158 | 159 | // given 160 | List numbersList = Lists.newArrayList(1, 2, 3, 0, -12, 22, 430, -1024); 161 | 162 | // when 163 | Integer first = Iterables.getFirst(numbersList, null); 164 | Integer last = Iterables.getLast(numbersList); 165 | 166 | // then 167 | assertThat(first).isEqualTo(1); 168 | assertThat(last).isEqualTo(-1024); 169 | } 170 | 171 | @Test 172 | public void shouldPartition() throws Exception { 173 | 174 | // given 175 | List numbersList = Lists.newArrayList(1, 2, 3, 0, -12, 22, 430, -1024); 176 | 177 | // when 178 | Iterable> partitionedLists = Iterables.partition(numbersList, 5); 179 | 180 | // then 181 | assertThat(Iterables.size(partitionedLists)).isEqualTo(2); 182 | Iterator> iterator = partitionedLists.iterator(); 183 | assertThat(iterator.next().size()).isEqualTo(5); 184 | assertThat(iterator.next().size()).isEqualTo(3); 185 | 186 | } 187 | 188 | @Test 189 | public void shouldConvertToArray() throws Exception { 190 | 191 | // given 192 | List numbersList = Lists.newArrayList(1, 2, 3, 0, -12, 22, 430, -1024); 193 | 194 | // when 195 | Number[] numbers = Iterables.toArray(numbersList, Number.class); 196 | Number[] numbersWithTraditionalWay = numbersList.toArray(new Number[] {}); 197 | 198 | 199 | // then 200 | assertThat(numbers).contains(1, 2, 3, 0, -12, 22, 430, -1024); 201 | } 202 | 203 | @Test 204 | public void shouldRemoveNegativeNumbers() throws Exception { 205 | 206 | // given 207 | List numbersList = Lists.newArrayList(1, 2, 3, 0, -12, 22, 430, -1024); 208 | 209 | // when 210 | Iterables.removeIf(numbersList, new Predicate() { 211 | @Override 212 | public boolean apply(@Nullable Integer input) { 213 | return input < 0; 214 | } 215 | }); 216 | 217 | // then 218 | assertThat(numbersList).excludes(-12, -1024); 219 | } 220 | 221 | 222 | } 223 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/collect/MultimapTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.collect; 2 | 3 | import com.google.common.collect.ArrayListMultimap; 4 | import com.google.common.collect.Multimap; 5 | import org.testng.annotations.Test; 6 | 7 | import static org.fest.assertions.Assertions.assertThat; 8 | 9 | /** 10 | * Test class for Multimap 11 | */ 12 | 13 | @Test 14 | public class MultimapTest { 15 | 16 | @Test 17 | public void shouldTestHowMultimapWorks() throws Exception { 18 | 19 | // given 20 | Multimap multimap = ArrayListMultimap.create(); 21 | 22 | // when 23 | multimap.put("Poland", "Warsaw"); 24 | multimap.put("Poland", "Cracow"); 25 | multimap.put("Poland", "Plock"); 26 | multimap.put("Poland", "Gdansk"); 27 | 28 | multimap.put("Germany", "Berlin"); 29 | multimap.put("Germany", "Bremen"); 30 | multimap.put("Germany", "Dortmund"); 31 | multimap.put("Germany", "Koln"); 32 | 33 | multimap.put("Portugal", "Lisbone"); 34 | multimap.put("Portugal", "Porto"); 35 | multimap.put("Portugal", "Leira"); 36 | multimap.put("Portugal", "Funchal"); 37 | multimap.put("Portugal", "Funchal"); 38 | 39 | 40 | // then 41 | assertThat(multimap.get("Poland").size()).isEqualTo(4); 42 | assertThat(multimap.get("Portugal").size()).isEqualTo(5); // duplicate values are fine 43 | assertThat(multimap.get("Poland")).contains("Warsaw", "Plock"); 44 | assertThat(multimap.keys().size()).isEqualTo(13); // keys can have duplicates 45 | 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/collect/MultisetTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.collect; 2 | 3 | import com.google.common.collect.HashMultiset; 4 | import com.google.common.collect.Multiset; 5 | import org.testng.annotations.Test; 6 | 7 | import java.util.Arrays; 8 | 9 | import static org.fest.assertions.Assertions.assertThat; 10 | 11 | /** 12 | * Test class for Multiset 13 | */ 14 | 15 | @Test 16 | public class MultisetTest { 17 | 18 | 19 | @Test 20 | public void shouldAddElementTwoTimes() throws Exception { 21 | 22 | // given 23 | Multiset multiset = HashMultiset.create(); 24 | 25 | // when 26 | multiset.add("nothing"); 27 | multiset.add("nothing"); 28 | 29 | // then 30 | assertThat(multiset.count("nothing")).isEqualTo(2); 31 | assertThat(multiset.count("something")).isEqualTo(0); 32 | } 33 | 34 | @Test 35 | public void shouldUserCustomAddRemoveAndSetCount() throws Exception { 36 | 37 | // given 38 | Multiset multiset = HashMultiset.create(); 39 | 40 | // when 41 | multiset.add("ball"); 42 | multiset.add("ball", 10); 43 | 44 | // then 45 | assertThat(multiset.count("ball")).isEqualTo(11); 46 | 47 | 48 | // when 49 | multiset.remove("ball", 5); 50 | 51 | // then 52 | assertThat(multiset.count("ball")).isEqualTo(6); 53 | 54 | 55 | // when 56 | multiset.setCount("ball", 2); 57 | 58 | // then 59 | assertThat(multiset.count("ball")).isEqualTo(2); 60 | } 61 | 62 | 63 | @Test 64 | public void shouldRetainOnlySelectedKeys() throws Exception { 65 | 66 | // given 67 | Multiset multiset = HashMultiset.create(); 68 | 69 | multiset.add("ball"); 70 | multiset.add("ball"); 71 | multiset.add("cow"); 72 | multiset.setCount("twelve", 12); 73 | 74 | // when 75 | multiset.retainAll(Arrays.asList("ball", "horse")); 76 | 77 | assertThat(multiset.count("ball")).isEqualTo(2); 78 | assertThat(multiset.count("twelve")).isEqualTo(0); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/collect/ObjectArraysTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.collect; 2 | 3 | import com.google.common.collect.ObjectArrays; 4 | import org.testng.annotations.Test; 5 | 6 | import static org.fest.assertions.Assertions.assertThat; 7 | 8 | /** 9 | * ObjectArrays showcase 10 | */ 11 | public class ObjectArraysTest { 12 | 13 | String[] array1 = new String[] {"one", "two", "three"}; 14 | String[] array2 = new String[] {"four", "five"}; 15 | 16 | @Test 17 | public void shouldContactTwoArrays() throws Exception { 18 | 19 | // when 20 | String[] newArray = ObjectArrays.concat(array1, array2, String.class); 21 | 22 | // then 23 | assertThat(newArray.length).isEqualTo(5); 24 | } 25 | 26 | @Test 27 | public void shouldAppendElement() throws Exception { 28 | 29 | // when 30 | String[] newArray = ObjectArrays.concat(array2, "six"); 31 | 32 | // then 33 | assertThat(newArray.length).isEqualTo(3); 34 | assertThat(newArray[2]).isEqualTo("six"); 35 | } 36 | 37 | @Test 38 | public void shouldPrependElement() throws Exception { 39 | 40 | // when 41 | String[] newArray = ObjectArrays.concat("zero", array1); 42 | 43 | // then 44 | assertThat(newArray.length).isEqualTo(4); 45 | assertThat(newArray[0]).isEqualTo("zero"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/collect/RangesTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.collect; 2 | 3 | import com.google.common.collect.DiscreteDomains; 4 | import com.google.common.collect.Lists; 5 | import com.google.common.collect.Range; 6 | import com.google.common.collect.Ranges; 7 | import org.testng.annotations.Test; 8 | 9 | import java.util.ArrayList; 10 | import java.util.Set; 11 | 12 | import static org.fest.assertions.Assertions.assertThat; 13 | 14 | /** 15 | * Range and Ranges showcase 16 | */ 17 | public class RangesTest { 18 | 19 | @Test 20 | public void shouldCheckThatElementIsInRange() throws Exception { 21 | 22 | // given 23 | Range range = Ranges.closed(2, 20); 24 | Range rangeWithRightOpen = Ranges.closedOpen(2, 20); 25 | 26 | // then 27 | assertThat(range.contains(20)).isTrue(); 28 | assertThat(rangeWithRightOpen.contains(20)).isFalse(); 29 | } 30 | 31 | @Test 32 | public void shouldCheckThatRangeIsEnclosedInAnotherOne() throws Exception { 33 | 34 | // given 35 | Range range = Ranges.openClosed(10L, 20L); 36 | Range smallerRange = Ranges.closed(10L, 15L); 37 | 38 | // then 39 | assertThat(range.encloses(smallerRange)).isFalse(); 40 | } 41 | 42 | @Test 43 | public void shouldCheckThatAllElementAreInRange() throws Exception { 44 | 45 | // given 46 | Range range = Ranges.closed(2, 20); 47 | 48 | // then 49 | assertThat(range.containsAll(Lists.newArrayList(3, 4, 5, 6, 7, 8, 9, 10))).isTrue(); 50 | } 51 | 52 | @Test 53 | public void shouldGenerateSetOfElementsInRange() throws Exception { 54 | 55 | // given 56 | Range range = Ranges.open(2, 20); 57 | 58 | // when 59 | Set integersInRange = range.asSet(DiscreteDomains.integers()); 60 | 61 | // then 62 | assertThat(integersInRange).contains(3); 63 | assertThat(integersInRange).contains(19); 64 | assertThat(integersInRange).excludes(2, 20); 65 | } 66 | 67 | @Test 68 | public void shouldCreateRangeForGivenNumbers() throws Exception { 69 | 70 | // given 71 | ArrayList numbers = Lists.newArrayList(4, 3, 10, 30, 20); 72 | 73 | // when 74 | Range range = Ranges.encloseAll(numbers); 75 | 76 | // then 77 | assertThat(range.lowerEndpoint()).isEqualTo(3); 78 | assertThat(range.upperEndpoint()).isEqualTo(30); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/eventbus/EventBusTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.eventbus; 2 | 3 | import com.google.common.eventbus.EventBus; 4 | import org.testng.annotations.Test; 5 | 6 | import static org.fest.assertions.Assertions.assertThat; 7 | 8 | /** 9 | * Events subscribe and publish showcase 10 | */ 11 | public class EventBusTest { 12 | 13 | @Test 14 | public void shouldReceiveEvent() throws Exception { 15 | 16 | // given 17 | EventBus eventBus = new EventBus("test"); 18 | EventListener listener = new EventListener(); 19 | 20 | eventBus.register(listener); 21 | 22 | // when 23 | eventBus.post(new OurTestEvent(200)); 24 | 25 | // then 26 | assertThat(listener.getLastMessage()).isEqualTo(200); 27 | } 28 | 29 | @Test 30 | public void shouldReceiveMultipleEvents() throws Exception { 31 | 32 | // given 33 | EventBus eventBus = new EventBus("test"); 34 | MultipleListener multiListener = new MultipleListener(); 35 | 36 | eventBus.register(multiListener); 37 | 38 | 39 | // when 40 | eventBus.post(new Integer(100)); 41 | eventBus.post(new Long(800)); 42 | 43 | // then 44 | assertThat(multiListener.getLastInteger()).isEqualTo(100); 45 | assertThat(multiListener.getLastLong()).isEqualTo(800L); 46 | } 47 | 48 | @Test 49 | public void shouldReceiveMultipleEventTypesFromBus() throws Exception { 50 | 51 | // given 52 | EventBus eventBus = new EventBus("test"); 53 | EventListener listener = new EventListener(); 54 | EventReader reader = new EventReader(); 55 | StringEventListener stringEventListener = new StringEventListener(); 56 | 57 | eventBus.register(listener); 58 | eventBus.register(reader); 59 | eventBus.register(stringEventListener); 60 | 61 | // when 62 | eventBus.post(new OurTestEvent(200)); 63 | eventBus.post(new StringTestEvent("Hello events!")); 64 | 65 | 66 | // then 67 | assertThat(reader.getLastMessage()).isEqualTo(200); 68 | assertThat(listener.getLastMessage()).isEqualTo(200); 69 | assertThat(stringEventListener.getLastMessage()).isEqualTo("Hello events!"); 70 | } 71 | 72 | @Test 73 | public void shouldNotReceiveEventAfterUnsubscribe() throws Exception { 74 | 75 | // given 76 | EventBus eventBus = new EventBus("test"); 77 | EventListener listener = new EventListener(); 78 | EventReader reader = new EventReader(); 79 | 80 | eventBus.register(listener); 81 | eventBus.register(reader); 82 | 83 | // when 84 | eventBus.post(new OurTestEvent(200)); 85 | 86 | 87 | // then 88 | assertThat(reader.getLastMessage()).isEqualTo(200); 89 | assertThat(listener.getLastMessage()).isEqualTo(200); 90 | 91 | 92 | //when 93 | eventBus.unregister(reader); 94 | eventBus.post(new OurTestEvent(300)); 95 | 96 | 97 | // then 98 | assertThat(listener.getLastMessage()).isEqualTo(300); 99 | // this one was unregistered 100 | assertThat(reader.getLastMessage()).isEqualTo(200); 101 | } 102 | 103 | @Test 104 | public void shouldDetectEventWithoutListeners() throws Exception { 105 | 106 | // given 107 | EventBus eventBus = new EventBus("test"); 108 | 109 | DeadEventListener deadEventListener = new DeadEventListener(); 110 | eventBus.register(deadEventListener); 111 | 112 | // when 113 | eventBus.post(new OurTestEvent(200)); 114 | 115 | assertThat(deadEventListener.isNotDelivered()).isTrue(); 116 | } 117 | 118 | @Test 119 | public void shouldGetEventsFromSubclass() throws Exception { 120 | 121 | // given 122 | EventBus eventBus = new EventBus("test"); 123 | IntegerListener integerListener = new IntegerListener(); 124 | NumberListener numberListener = new NumberListener(); 125 | eventBus.register(integerListener); 126 | eventBus.register(numberListener); 127 | 128 | // when 129 | eventBus.post(new Integer(100)); 130 | 131 | // then 132 | assertThat(integerListener.getLastMessage()).isEqualTo(100); 133 | assertThat(numberListener.getLastMessage()).isEqualTo(100); 134 | 135 | //when 136 | eventBus.post(new Long(200L)); 137 | 138 | // then 139 | // this one should has the old value as it listens only for Integers 140 | assertThat(integerListener.getLastMessage()).isEqualTo(100); 141 | assertThat(numberListener.getLastMessage()).isEqualTo(200L); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/math/IntMathTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.math; 2 | 3 | import com.google.common.math.IntMath; 4 | import org.testng.annotations.Test; 5 | 6 | import java.math.RoundingMode; 7 | 8 | import static org.fest.assertions.Assertions.assertThat; 9 | 10 | /** 11 | * com.google.common.math package showcase with IntMath as an example 12 | */ 13 | public class IntMathTest { 14 | 15 | @Test(expectedExceptions = ArithmeticException.class, expectedExceptionsMessageRegExp = "overflow") 16 | public void shouldThrowExceptionWhenOverflow() throws Exception { 17 | 18 | // given 19 | int numberOne = Integer.MAX_VALUE - 4; 20 | int numberTwo = 6; 21 | 22 | // when 23 | int resultOldWay = numberOne + numberTwo; 24 | 25 | // silent overflow here 26 | assertThat(resultOldWay).isEqualTo(Integer.MIN_VALUE + 1); 27 | 28 | int result = IntMath.checkedAdd(numberOne, numberTwo); 29 | } 30 | 31 | @Test 32 | public void shouldDivideWithRoundingMode() throws Exception { 33 | 34 | // when 35 | int roundedUp = IntMath.divide(10, 4, RoundingMode.HALF_UP); 36 | int roundedDown = IntMath.divide(10, 4, RoundingMode.HALF_DOWN); 37 | 38 | // then 39 | assertThat(roundedUp).isEqualTo(3); 40 | assertThat(roundedDown).isEqualTo(2); 41 | } 42 | 43 | @Test 44 | public void shouldCalculateFactorial() throws Exception { 45 | // when 46 | int factorial = IntMath.factorial(5); 47 | 48 | // then 49 | assertThat(factorial).isEqualTo(1 * 2 * 3 * 4 * 5); 50 | } 51 | 52 | @Test 53 | public void shouldCalculateGreatestCommonDivisor() throws Exception { 54 | // when 55 | int gcd = IntMath.gcd(20, 15); 56 | 57 | // then 58 | assertThat(gcd).isEqualTo(5); 59 | } 60 | 61 | @Test 62 | public void shouldCalculateLogarithms() throws Exception { 63 | 64 | // when 65 | int log2Result = IntMath.log2(17, RoundingMode.HALF_UP); 66 | int log10Result = IntMath.log10(100, RoundingMode.UNNECESSARY); 67 | 68 | // then 69 | assertThat(log2Result).isEqualTo(4); 70 | assertThat(log10Result).isEqualTo(2); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/test/java/pl/tomaszdziurko/guava/primitives/PrimitivesTest.java: -------------------------------------------------------------------------------- 1 | package pl.tomaszdziurko.guava.primitives; 2 | 3 | import com.google.common.primitives.Ints; 4 | import org.testng.annotations.Test; 5 | 6 | import static org.fest.assertions.Assertions.assertThat; 7 | 8 | /** 9 | * Class showing features of one of primitves class from Guava: Ints 10 | */ 11 | public class PrimitivesTest { 12 | 13 | 14 | 15 | @Test 16 | public void shouldFindGivenNumberInArray() throws Exception { 17 | 18 | assertThat(Ints.contains(array, 22)).isTrue(); 19 | } 20 | 21 | @Test 22 | public void shouldFindIndexOfGivenNumber() throws Exception { 23 | 24 | assertThat(Ints.indexOf(array, 5)).isEqualTo(0); 25 | } 26 | 27 | final int[] array2 = new int[] {0, 14, 99}; 28 | 29 | 30 | 31 | @Test 32 | public void shouldConcatArrays() throws Exception { 33 | assertThat(Ints.concat(array, array2).length).isEqualTo(array.length + array2.length); 34 | } 35 | 36 | @Test 37 | public void shouldJoinArrayUsingSeparator() throws Exception { 38 | assertThat(Ints.join(":", array2)).isEqualTo("0:14:99"); 39 | } 40 | 41 | final int[] array = new int[] {5, 2, 4, -12, 100, 450, 22, 7}; 42 | 43 | @Test 44 | public void shouldFindMaxAndMinInArray() throws Exception { 45 | 46 | assertThat(Ints.min(array)).isEqualTo(-12); 47 | assertThat(Ints.max(array)).isEqualTo(450); 48 | 49 | } 50 | 51 | 52 | } 53 | --------------------------------------------------------------------------------