New Post

Rss

Tampilkan postingan dengan label Google Guava. Tampilkan semua postingan
Tampilkan postingan dengan label Google Guava. Tampilkan semua postingan
Senin, 30 September 2013
no image

Review of the Getting Started with Guava book

Hi!

I didn't have much time to write posts recently (beacuse of work and my book "Mockito Instant") but I came across Bill Bejeck's book entitled "Getting Started with Guava". After having read it I decided that I will try also to blog about computer science related books. So without any futher ado let's move to the review :)


To begin with I really enjoyed the book's structure – one can see that the author had a clear view of the book: introduction to the functionality, its presentation with examples and a short review. By keeping such a fixed structure the reader wasn't surprised by the content in each of the chapters what made reading even more pleasant.

Let's move quickly through the book content chapter by chapter. 


Basic Guava Utilities

First of all you will be able to increase your knowledge about joining and splitting operations on collections by means of the Joiner and Splitter classes - no more unnecessary writing of loops! You will be able also to learn how to operate on Strings using  CharMatcher, Charsets, Strings which often is extremely tidious and produces a lot of boilerplate code. Next you will be able to learn about Preconditions - you won't have to write those cascades of if's in terms of defensive programming. Instead how about checking a condition and throw a runtime exception? To end with the author shows how to use Guava's utility classes to create implementation of toString, hashCode and compareTo methods.

Functional Programming with Guava

In this chapter the author shows how to introduce some functional approach to your Object oriented Java code with the Function, Predicate and Supplier interfaces and their corresponding utility classes Functions, Predicates and Suppliers.

Working with Collections

Since the Guava library emerged from issues related with collection manipulation the author could show the best examples in this chapter. You will learn about the Collections, FluentIterables, and Iterables utility classes. The author also mentions the Range class that you can use to represent boundaries. You will also be able to find information on other types of collections such as Bimaps (maps that aside from being navigated in the standard key to value way can be navigated from values to keys), Tables (replacement for map of maps), Multimaps (values are collections). There is also a part of the chapter related to the Ordering class that fives you additional posisbilities of working with Comparators.

Concurrency

The issue of concurrency is a very difficult issue as such. Guava can assist you in this difficult subject in a number of was that the author depicts: the Monitor class (version of a Mutex) can help you provide the serial access to part of your code, the Futures utility class to work with Future instances and many more cool solutions ;)

Guava Cache

The author shows several ways of creating caches, showing their statistics and how to configure them. You will also be able to learn how to register listeners for different cashe related types of events. 

The Event Bus

The author shows how to subscribe to events by using the Google Guava's Event Bus. What I really liked about this chapter was the presentation of the reason for incorporating it in a project (loose coupling) and a sample of using it in a Spring based application.

Working with Files

You will be able to find presentations of the utility classes and helpful solutions related to working with IO such as Files, CharStreams, ByteStreams, Readers , Writers the Closer class (elegant way of ensuring that the Closeable instance gets properly closed). The author presents the concept behind source and sinks too. So if you work a lot with files you will find plenty of cool stuff here.

Odds and Ends

Useful classes related to creating hash codes, working with Throwables and creating your applications in a null safe way.

I would never say that I know every aspect of Guava but I tend to use a lot of its functionalities at work. That's why I was really curious about the level of details that the author wanted to present in his book and whether I would find some really interesting details of the library that I wasn't aware of. What I found in the book was very satisfactory for me because although I was already familliar with the majority of the presented examples and functionalities, still I found plenty of those „little things” that I can use to improve my code and remove more boilerplate.

Speaking of which, what I really wanted to look at from the very beginning where the code samples showing how cool and helpful Guava really is. Being a true fan of unit testing I was very happy to see that the author put a lot of effort in those examples - the majority of functionalities were described by means of unit tests and showing some real life situations.

To sum it up I think that Bill Bejeck has put a tremendous effort in writing his book and he has done the job exceptionally well. I would recommend „Getting Started with Guava” for both newbies and experts – for sure both of these groups will be very satisfied.
Kamis, 03 Januari 2013
no image

Hamcrest Matchers, Guava Predicate and Builder design pattern



Hi coding addicts :)

Often, while coding we have to deal with some POJO objects that have dozens of fields in them. Many times we initialize those classes through a constructor having dozens of arguments which is terrible in any possibly imaginable way :) Apart from that the functions that use those constructors are hardly testable. Let's take a closer look at using a Builder to change that situation, together with Hamcrest matchers and Guava Predicates to unit test it.

Let's start off with taking a look at the POJO class.




SomeBigPojo.java

package pl.grzejszczak.marcin.junit.matchers.pojo;

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 03.01.13
* Time: 21:05
*/
public class SomeBigPojo {
private String stringField0;
private Integer integerField0;
private Boolean booleanField0;
private String stringField1;
private Integer integerField1;
private Boolean booleanField1;
private String stringField2;
private Integer integerField2;
private Boolean booleanField2;
private String stringField3;
private Integer integerField3;
private Boolean booleanField3;
private String stringField4;
private Integer integerField4;
private Boolean booleanField4;
private String stringField5;
private Integer integerField5;
private Boolean booleanField5;
private String stringField6;
private Integer integerField6;
private Boolean booleanField6;
private String stringField7;
private String stringField8;
private String stringField9;

public SomeBigPojo(String stringField0, Integer integerField0, Boolean booleanField0, String stringField1, Integer integerField1, Boolean booleanField1, String stringField2, Integer integerField2, Boolean booleanField2, String stringField3, Integer integerField3, Boolean booleanField3, String stringField4, Integer integerField4, Boolean booleanField4, String stringField5, Integer integerField5, Boolean booleanField5, String stringField6, Integer integerField6, Boolean booleanField6, String stringField7, String stringField8, String stringField9) {
this.stringField0 = stringField0;
this.integerField0 = integerField0;
this.booleanField0 = booleanField0;
this.stringField1 = stringField1;
this.integerField1 = integerField1;
this.booleanField1 = booleanField1;
this.stringField2 = stringField2;
this.integerField2 = integerField2;
this.booleanField2 = booleanField2;
this.stringField3 = stringField3;
this.integerField3 = integerField3;
this.booleanField3 = booleanField3;
this.stringField4 = stringField4;
this.integerField4 = integerField4;
this.booleanField4 = booleanField4;
this.stringField5 = stringField5;
this.integerField5 = integerField5;
this.booleanField5 = booleanField5;
this.stringField6 = stringField6;
this.integerField6 = integerField6;
this.booleanField6 = booleanField6;
this.stringField7 = stringField7;
this.stringField8 = stringField8;
this.stringField9 = stringField9;
}

public String getStringField0() {
return stringField0;
}

public void setStringField0(String stringField0) {
this.stringField0 = stringField0;
}

public Integer getIntegerField0() {
return integerField0;
}

public void setIntegerField0(Integer integerField0) {
this.integerField0 = integerField0;
}

public Boolean getBooleanField0() {
return booleanField0;
}

public void setBooleanField0(Boolean booleanField0) {
this.booleanField0 = booleanField0;
}

public String getStringField1() {
return stringField1;
}

public void setStringField1(String stringField1) {
this.stringField1 = stringField1;
}

public Integer getIntegerField1() {
return integerField1;
}

public void setIntegerField1(Integer integerField1) {
this.integerField1 = integerField1;
}

public Boolean getBooleanField1() {
return booleanField1;
}

public void setBooleanField1(Boolean booleanField1) {
this.booleanField1 = booleanField1;
}

public String getStringField2() {
return stringField2;
}

public void setStringField2(String stringField2) {
this.stringField2 = stringField2;
}

public Integer getIntegerField2() {
return integerField2;
}

public void setIntegerField2(Integer integerField2) {
this.integerField2 = integerField2;
}

public Boolean getBooleanField2() {
return booleanField2;
}

public void setBooleanField2(Boolean booleanField2) {
this.booleanField2 = booleanField2;
}

public String getStringField3() {
return stringField3;
}

public void setStringField3(String stringField3) {
this.stringField3 = stringField3;
}

public Integer getIntegerField3() {
return integerField3;
}

public void setIntegerField3(Integer integerField3) {
this.integerField3 = integerField3;
}

public Boolean getBooleanField3() {
return booleanField3;
}

public void setBooleanField3(Boolean booleanField3) {
this.booleanField3 = booleanField3;
}

public String getStringField4() {
return stringField4;
}

public void setStringField4(String stringField4) {
this.stringField4 = stringField4;
}

public Integer getIntegerField4() {
return integerField4;
}

public void setIntegerField4(Integer integerField4) {
this.integerField4 = integerField4;
}

public Boolean getBooleanField4() {
return booleanField4;
}

public void setBooleanField4(Boolean booleanField4) {
this.booleanField4 = booleanField4;
}

public String getStringField5() {
return stringField5;
}

public void setStringField5(String stringField5) {
this.stringField5 = stringField5;
}

public Integer getIntegerField5() {
return integerField5;
}

public void setIntegerField5(Integer integerField5) {
this.integerField5 = integerField5;
}

public Boolean getBooleanField5() {
return booleanField5;
}

public void setBooleanField5(Boolean booleanField5) {
this.booleanField5 = booleanField5;
}

public String getStringField6() {
return stringField6;
}

public void setStringField6(String stringField6) {
this.stringField6 = stringField6;
}

public Integer getIntegerField6() {
return integerField6;
}

public void setIntegerField6(Integer integerField6) {
this.integerField6 = integerField6;
}

public Boolean getBooleanField6() {
return booleanField6;
}

public void setBooleanField6(Boolean booleanField6) {
this.booleanField6 = booleanField6;
}

public String getStringField7() {
return stringField7;
}

public void setStringField7(String stringField7) {
this.stringField7 = stringField7;
}

public String getStringField8() {
return stringField8;
}

public void setStringField8(String stringField8) {
this.stringField8 = stringField8;
}

public String getStringField9() {
return stringField9;
}

public void setStringField9(String stringField9) {
this.stringField9 = stringField9;
}

@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("SomeBigPojo");
sb.append("{stringField0='").append(stringField0).append('\'');
sb.append(", integerField0=").append(integerField0);
sb.append(", booleanField0=").append(booleanField0);
sb.append(", stringField1='").append(stringField1).append('\'');
sb.append(", integerField1=").append(integerField1);
sb.append(", booleanField1=").append(booleanField1);
sb.append(", stringField2='").append(stringField2).append('\'');
sb.append(", integerField2=").append(integerField2);
sb.append(", booleanField2=").append(booleanField2);
sb.append(", stringField3='").append(stringField3).append('\'');
sb.append(", integerField3=").append(integerField3);
sb.append(", booleanField3=").append(booleanField3);
sb.append(", stringField4='").append(stringField4).append('\'');
sb.append(", integerField4=").append(integerField4);
sb.append(", booleanField4=").append(booleanField4);
sb.append(", stringField5='").append(stringField5).append('\'');
sb.append(", integerField5=").append(integerField5);
sb.append(", booleanField5=").append(booleanField5);
sb.append(", stringField6='").append(stringField6).append('\'');
sb.append(", integerField6=").append(integerField6);
sb.append(", booleanField6=").append(booleanField6);
sb.append(", stringField7='").append(stringField7).append('\'');
sb.append(", stringField8='").append(stringField8).append('\'');
sb.append(", stringField9='").append(stringField9).append('\'');
sb.append('}');
return sb.toString();
}
}

Now take a look at the builder class that was used in order to get rid of usage of the humongous constructor. What is more you can set whatever you want to without the need to enter nulls for the undesired fields.

SomeBigPojoBuilder.java

package pl.grzejszczak.marcin.junit.matchers.builder;

import pl.grzejszczak.marcin.junit.matchers.pojo.SomeBigPojo;

import static com.google.common.base.Preconditions.checkNotNull;

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 03.01.13
* Time: 21:08
*/
public class SomeBigPojoBuilder {
/** A field with some default value */
private String stringField0 = "defaultValueForString0";
/** A field with some default value */
private Integer integerField0 = 100;
/** A field with some default value */
private Boolean booleanField0 = true;
private String stringField1;
private Integer integerField1;
private Boolean booleanField1;
private String stringField2;
private Integer integerField2;
private Boolean booleanField2;
private String stringField3;
private Integer integerField3;
private Boolean booleanField3;
private String stringField4;
private Integer integerField4;
private Boolean booleanField4;
private String stringField5;
private Integer integerField5;
private Boolean booleanField5;
private String stringField6;
private Integer integerField6;
private Boolean booleanField6;
private String stringField7;
private String stringField8;
private String stringField9;

public SomeBigPojoBuilder setStringField0(String stringField0) {
this.stringField0 = stringField0;
return this;
}

public SomeBigPojoBuilder setIntegerField0(Integer integerField0) {
this.integerField0 = integerField0;
return this;
}

public SomeBigPojoBuilder setBooleanField0(Boolean booleanField0) {
this.booleanField0 = booleanField0;
return this;
}

public SomeBigPojoBuilder setStringField1(String stringField1) {
this.stringField1 = stringField1;
return this;
}

public SomeBigPojoBuilder setIntegerField1(Integer integerField1) {
this.integerField1 = integerField1;
return this;
}

public SomeBigPojoBuilder setBooleanField1(Boolean booleanField1) {
this.booleanField1 = booleanField1;
return this;
}

public SomeBigPojoBuilder setStringField2(String stringField2) {
this.stringField2 = stringField2;
return this;
}

public SomeBigPojoBuilder setIntegerField2(Integer integerField2) {
this.integerField2 = integerField2;
return this;
}

public SomeBigPojoBuilder setBooleanField2(Boolean booleanField2) {
this.booleanField2 = booleanField2;
return this;
}

public SomeBigPojoBuilder setStringField3(String stringField3) {
this.stringField3 = stringField3;
return this;
}

public SomeBigPojoBuilder setIntegerField3(Integer integerField3) {
this.integerField3 = integerField3;
return this;
}

public SomeBigPojoBuilder setBooleanField3(Boolean booleanField3) {
this.booleanField3 = booleanField3;
return this;
}

public SomeBigPojoBuilder setStringField4(String stringField4) {
this.stringField4 = stringField4;
return this;
}

public SomeBigPojoBuilder setIntegerField4(Integer integerField4) {
this.integerField4 = integerField4;
return this;
}

public SomeBigPojoBuilder setBooleanField4(Boolean booleanField4) {
this.booleanField4 = booleanField4;
return this;
}

public SomeBigPojoBuilder setStringField5(String stringField5) {
this.stringField5 = stringField5;
return this;
}

public SomeBigPojoBuilder setIntegerField5(Integer integerField5) {
this.integerField5 = integerField5;
return this;
}

public SomeBigPojoBuilder setBooleanField5(Boolean booleanField5) {
this.booleanField5 = booleanField5;
return this;
}

public SomeBigPojoBuilder setStringField6(String stringField6) {
this.stringField6 = stringField6;
return this;
}

public SomeBigPojoBuilder setIntegerField6(Integer integerField6) {
this.integerField6 = integerField6;
return this;
}

public SomeBigPojoBuilder setBooleanField6(Boolean booleanField6) {
this.booleanField6 = booleanField6;
return this;
}

public SomeBigPojoBuilder setStringField7(String stringField7) {
this.stringField7 = stringField7;
return this;
}

public SomeBigPojoBuilder setStringField8(String stringField8) {
this.stringField8 = stringField8;
return this;
}

public SomeBigPojoBuilder setStringField9(String stringField9) {
this.stringField9 = stringField9;
return this;
}

/**
* Some function checking the state of our POJO
*/
private void checkState(){
checkNotNull(stringField1, "StringField1 must not be null!");
}

public SomeBigPojo createSomeBigPojoWithBuilder() {
checkState();
return new SomeBigPojo(stringField0, integerField0, booleanField0, stringField1, integerField1, booleanField1, stringField2, integerField2, booleanField2, stringField3, integerField3, booleanField3, stringField4, integerField4, booleanField4, stringField5, integerField5, booleanField5, stringField6, integerField6, booleanField6, stringField7, stringField8, stringField9);
}
}

Take a look at the function checkState that verifies whether the object is of a desired state. In this way we may disallow the creation of an object if some conditions where not fullfiled. For that case we are using the Guava's Predicate - checkNotNull method.

Note that the concept behind the Builder pattern is to delegate creation of an object to a Builder. In fact in the pure Builder design pattern implementation we would have to have a Director, some abstraction over a Builder and the concrete implementation of the Builder as such. In our case we have a simplification of that pattern - I used the refactoring option of IntelliJ. What can be done to make it look even better is to remove the constructor from the POJO and pass the values only by setters (that's what in fact I did in one of my projects ;) )

Now let's take a look at some usage examples:

SomeServiceImpl.java

package pl.grzejszczak.marcin.junit.matchers.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.grzejszczak.marcin.junit.matchers.builder.SomeBigPojoBuilder;
import pl.grzejszczak.marcin.junit.matchers.pojo.SomeBigPojo;

import static java.lang.String.format;

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 03.01.13
* Time: 21:25
*/
public class SomeServiceImpl implements SomeService {
private static final Logger LOGGER = LoggerFactory.getLogger(SomeServiceImpl.class);

/** Could be an abstraction of builders injected by a setter - possible to mock */
private SomeBigPojoBuilder someBigPojoBuilder;

/**
* Hard to unit test
*/
@Override
public void someLogicForAPojoWithoutBuilder() {
LOGGER.debug("SomeLogicForAPojoWithoutBuilder executed");
SomeBigPojo someBigPojo = new SomeBigPojo("string", 1, false, "other string", 123, true, "something else", 321, false, "yet another string", 111, true, "something", 2, false, "More", 3, true, "String", 12, false, "some", "value", "ofString");
// Any chance of knowing what is the value of stringField8 basing on the constructor?
LOGGER.debug(format("StringField8 is equal [%s]%n", someBigPojo.getStringField8()));
// Print the object
LOGGER.debug(someBigPojo.toString());
}

@Override
public void someLogicForAPojoWithBuilder() {
LOGGER.debug("SomeLogicForAPojoWithBuilder executed");
SomeBigPojo someBigPojo = someBigPojoBuilder
.setStringField0("string")
.setIntegerField0(1)
.setBooleanField0(false)
.setStringField1("other string")
.setIntegerField1(123)
.setBooleanField1(true)
.setStringField2("something else")
.setIntegerField2(321)
.setBooleanField2(false)
.setStringField3("yet another string")
.setIntegerField3(111)
.setBooleanField3(false)
.setStringField4("something")
.setIntegerField4(2)
.setBooleanField4(false)
.setStringField5("More")
.setIntegerField5(3)
.setBooleanField5(true)
.setStringField6("String")
.setIntegerField6(12)
.setBooleanField6(false)
.setStringField7("some")
.setStringField8("value")
.setStringField9("ofString")
.createSomeBigPojoWithBuilder();
// Looking at the builder now I guess it's obvious what the value of StringField8
LOGGER.debug(format("StringField8 is equal [%s]%n", someBigPojo.getStringField8()));
// Print the object
LOGGER.debug(someBigPojo.toString());
}

@Override
public void someLogicForAPojoWithBuilderBadArgument() {
LOGGER.debug("someLogicForAPojoWithBuilderBadArgument executed");
SomeBigPojo someBigPojo = someBigPojoBuilder
.setStringField0("string")
.setIntegerField0(1)
.setBooleanField0(true)
.setIntegerField1(123)
.setBooleanField1(true)
.setStringField2("something else")
.setIntegerField2(321)
.setBooleanField2(false)
.setStringField3("yet another string")
.setIntegerField3(111).setBooleanField3(false)
.setStringField4("something")
.setIntegerField4(2)
.setBooleanField4(false)
.setStringField5("More")
.setIntegerField5(3)
.setBooleanField5(true)
.setStringField6("String")
.setIntegerField6(12)
.setBooleanField6(false)
.setStringField7("some")
.setStringField8("value")
.setStringField9("ofString")
.createSomeBigPojoWithBuilder();
// Print the object - will we even see an output
LOGGER.debug(someBigPojo.toString());
}

public void setSomeBigPojoBuilder(SomeBigPojoBuilder someBigPojoBuilder) {
this.someBigPojoBuilder = someBigPojoBuilder;
}
}




Notice how clear it is now to create an object and how easy is to define if a field has been set or not.

Let's move on to Hamcrest matchers that will help us in unit testing of our classes. I will not try to do the complete, 100% code coverage - the idea behind this post is to show how Hamcrest Matchers can become an addition to your unit tests.

Often unit tests are quite unclear and look like this:

SomeBigPojoBuilderNoMatchersAndNoRefactoringTest.java


package pl.grzejszczak.marcin.junit.matchers.builder;

import org.junit.Before;
import org.junit.Test;
import pl.grzejszczak.marcin.junit.matchers.pojo.SomeBigPojo;

import static junit.framework.Assert.assertTrue;
import static org.apache.commons.lang.StringUtils.isNumeric;
import static pl.grzejszczak.marcin.junit.matchers.pojo.SomePojoConstants.*;

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 03.01.13
* Time: 23:02
*/
public class SomeBigPojoBuilderNoMatchersAndNoRefactoringTest {

private SomeBigPojoBuilder objectUnderTest;

@Before
public void setUp() {
objectUnderTest = new SomeBigPojoBuilder();
}

@Test
public void testCreateSomeBigPojoWithBuilder() throws Exception {
SomeBigPojo someBigPojo = objectUnderTest
.setBooleanField1(true)
.setStringField0("1")
.setStringField1("12")
.setStringField2("123")
.setStringField3("1234")
.setStringField4("12345")
.setStringField5("123456")
.setStringField6("1234567")
.setStringField7("12345678")
.setStringField8("123456789")
.setStringField9("1234567890")
.createSomeBigPojoWithBuilder();

isPojoProperlyBuilt(someBigPojo);
}

@Test(expected = AssertionError.class)
public void testCreateSomeBigPojoWithBuilderWrongFields() throws Exception {
SomeBigPojo someBigPojo = objectUnderTest
.setStringField0("0")
.setStringField1("Too long")
.createSomeBigPojoWithBuilder();

isPojoProperlyBuilt(someBigPojo);
}

private void isPojoProperlyBuilt(SomeBigPojo someBigPojo) {
assertTrue(someBigPojo.getStringField0().length() == STRING_FIELD_0_LENGTH);
assertTrue(isNumeric(someBigPojo.getStringField0()));

assertTrue(someBigPojo.getStringField1().length() == STRING_FIELD_1_LENGTH);
assertTrue(isNumeric(someBigPojo.getStringField0()));

assertTrue(someBigPojo.getStringField2().length() == STRING_FIELD_2_LENGTH);
assertTrue(isNumeric(someBigPojo.getStringField0()));

assertTrue(someBigPojo.getStringField3().length() == STRING_FIELD_3_LENGTH);
assertTrue(isNumeric(someBigPojo.getStringField0()));

assertTrue(someBigPojo.getStringField4().length() == STRING_FIELD_4_LENGTH);
assertTrue(isNumeric(someBigPojo.getStringField0()));

assertTrue(someBigPojo.getStringField5().length() == STRING_FIELD_5_LENGTH);

assertTrue(someBigPojo.getStringField6().length() == STRING_FIELD_6_LENGTH);

assertTrue(someBigPojo.getStringField7().length() == STRING_FIELD_7_LENGTH);

assertTrue(someBigPojo.getStringField8().length() == STRING_FIELD_8_LENGTH);

assertTrue(someBigPojo.getStringField9().length() == STRING_FIELD_9_LENGTH);

}
}


Simple refactoring can make them look nicer...

SomeBigPojoBuilderNoMatchersTest.java


package pl.grzejszczak.marcin.junit.matchers.builder;

import org.junit.Before;
import org.junit.Test;
import pl.grzejszczak.marcin.junit.matchers.pojo.SomeBigPojo;

import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import static org.apache.commons.lang.StringUtils.isNumeric;
import static pl.grzejszczak.marcin.junit.matchers.pojo.SomePojoConstants.*;

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 03.01.13
* Time: 23:02
*/
public class SomeBigPojoBuilderNoMatchersTest {

private SomeBigPojoBuilder objectUnderTest;

@Before
public void setUp() {
objectUnderTest = new SomeBigPojoBuilder();
}

@Test
public void testCreateSomeBigPojoWithBuilder() throws Exception {
SomeBigPojo someBigPojo = objectUnderTest
.setBooleanField1(true)
.setStringField0("1")
.setStringField1("12")
.setStringField2("123")
.setStringField3("1234")
.setStringField4("12345")
.setStringField5("123456")
.setStringField6("1234567")
.setStringField7("12345678")
.setStringField8("123456789")
.setStringField9("1234567890")
.createSomeBigPojoWithBuilder();

isPojoProperlyBuilt(someBigPojo);
}

@Test(expected = AssertionError.class)
public void testCreateSomeBigPojoWithBuilderWrongFields() throws Exception {
SomeBigPojo someBigPojo = objectUnderTest
.setStringField0("0")
.setStringField1("too long")
.createSomeBigPojoWithBuilder();

isPojoProperlyBuilt(someBigPojo);
}

private void isPojoProperlyBuilt(SomeBigPojo someBigPojo) {
isOfGivenLength(someBigPojo.getStringField0(), STRING_FIELD_0_LENGTH);
isFieldOfNumericValue(someBigPojo.getStringField0());

isOfGivenLength(someBigPojo.getStringField1(), STRING_FIELD_1_LENGTH);
isFieldOfNumericValue(someBigPojo.getStringField0());

isOfGivenLength(someBigPojo.getStringField2(), STRING_FIELD_2_LENGTH);
isFieldOfNumericValue(someBigPojo.getStringField0());

isOfGivenLength(someBigPojo.getStringField3(), STRING_FIELD_3_LENGTH);
isFieldOfNumericValue(someBigPojo.getStringField0());

isOfGivenLength(someBigPojo.getStringField4(), STRING_FIELD_4_LENGTH);
isFieldOfNumericValue(someBigPojo.getStringField0());

isOfGivenLength(someBigPojo.getStringField5(), STRING_FIELD_5_LENGTH);

isOfGivenLength(someBigPojo.getStringField6(), STRING_FIELD_6_LENGTH);

isOfGivenLength(someBigPojo.getStringField7(), STRING_FIELD_7_LENGTH);

isOfGivenLength(someBigPojo.getStringField8(), STRING_FIELD_8_LENGTH);

isOfGivenLength(someBigPojo.getStringField9(), STRING_FIELD_9_LENGTH);

}

private void isOfGivenLength(String pojo, final Integer expectedLength) {
assertNotNull(pojo);
assertTrue(expectedLength == pojo.length());
}

private void isFieldOfNumericValue(String field) {
assertTrue(isNumeric(field));
}
}



That looks nice, doesn't it? :) And how about using Matchers instead of functions?

SomeBigPojoBuilderTest.kava

package pl.grzejszczak.marcin.junit.matchers.builder;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import pl.grzejszczak.marcin.junit.matchers.pojo.SomeBigPojo;

import static java.lang.String.format;
import static junit.framework.Assert.assertTrue;
import static org.apache.commons.lang.StringUtils.isNumeric;
import static org.junit.Assert.assertThat;
import static pl.grzejszczak.marcin.junit.matchers.pojo.SomePojoConstants.*;

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 03.01.13
* Time: 23:02
*/
public class SomeBigPojoBuilderTest {

private SomeBigPojoBuilder objectUnderTest;

@Before
public void setUp(){
objectUnderTest = new SomeBigPojoBuilder();
}

@Test
public void testCreateSomeBigPojoWithBuilder() throws Exception {
SomeBigPojo someBigPojo = objectUnderTest
.setBooleanField1(true)
.setStringField0("1")
.setStringField1("12")
.setStringField2("123")
.setStringField3("1234")
.setStringField4("12345")
.setStringField5("123456")
.setStringField6("1234567")
.setStringField7("12345678")
.setStringField8("123456789")
.setStringField9("1234567890")
.createSomeBigPojoWithBuilder();

assertThat(someBigPojo, isPojoProperlyBuilt());
}

@Test(expected = AssertionError.class)
public void testCreateSomeBigPojoWithBuilderWrongFields() throws Exception {
SomeBigPojo someBigPojo = objectUnderTest
.setStringField0("0")
.setStringField1("Too long")
.createSomeBigPojoWithBuilder();

assertThat(someBigPojo, isPojoProperlyBuilt());
}

/**
* Let us assume that there is a specific business case that we have to take into consideration regarding some particular field
*
* @return
*/
private static Matcher isPojoProperlyBuilt() {

return new BaseMatcher() {

@Override
public boolean matches(Object o) {
assertTrue(o instanceof SomeBigPojo);
SomeBigPojo someBigPojo = (SomeBigPojo) o;
assertThat(someBigPojo.getStringField0(), isOfGivenLength(STRING_FIELD_0_LENGTH));
assertThat(someBigPojo.getStringField0(), isFieldOfNumericValue());

assertThat(someBigPojo.getStringField1(), isOfGivenLength(STRING_FIELD_1_LENGTH));
assertThat(someBigPojo.getStringField1(), isFieldOfNumericValue());

assertThat(someBigPojo.getStringField2(), isOfGivenLength(STRING_FIELD_2_LENGTH));
assertThat(someBigPojo.getStringField2(), isFieldOfNumericValue());

assertThat(someBigPojo.getStringField3(), isOfGivenLength(STRING_FIELD_3_LENGTH));
assertThat(someBigPojo.getStringField3(), isFieldOfNumericValue());

assertThat(someBigPojo.getStringField4(), isOfGivenLength(STRING_FIELD_4_LENGTH));
assertThat(someBigPojo.getStringField4(), isFieldOfNumericValue());

assertThat(someBigPojo.getStringField5(), isOfGivenLength(STRING_FIELD_5_LENGTH));

assertThat(someBigPojo.getStringField6(), isOfGivenLength(STRING_FIELD_6_LENGTH));

assertThat(someBigPojo.getStringField7(), isOfGivenLength(STRING_FIELD_7_LENGTH));

assertThat(someBigPojo.getStringField8(), isOfGivenLength(STRING_FIELD_8_LENGTH));

assertThat(someBigPojo.getStringField9(), isOfGivenLength(STRING_FIELD_9_LENGTH));

return true;
}

@Override
public void describeTo(Description description) {
description.appendText("Lengths of fields are limited and the first 4 fields are numeric");
}
};
}

private static Matcher isOfGivenLength(final Integer expectedLength) {

return new BaseMatcher() {

public boolean matches(Object o) {
assertTrue(o instanceof String);
return expectedLength == String.valueOf(o).length();
}

public void describeTo(Description description) {
description.appendText(format("String's length should be equal to [%d]", expectedLength));
}
};
}

private static Matcher isFieldOfNumericValue() {

return new BaseMatcher() {

public boolean matches(Object o) {
assertTrue(o instanceof String);
return isNumeric(String.valueOf(o));
}

public void describeTo(Description description) {
description.appendText("The value of the field should be numeric");
}
};
}
}


The following main method executes the functions of the Service:


package pl.grzejszczak.marcin.junit.matchers;

import pl.grzejszczak.marcin.junit.matchers.builder.SomeBigPojoBuilder;
import pl.grzejszczak.marcin.junit.matchers.service.SomeServiceImpl;

/**
* Created with IntelliJ IDEA.
* User: mgrzejszczak
* Date: 03.01.13
* Time: 22:38
*/
public class MatcherMain {
public static void main(String[] args){
SomeServiceImpl someService = new SomeServiceImpl();

someService.setSomeBigPojoBuilder(new SomeBigPojoBuilder());
someService.someLogicForAPojoWithoutBuilder();

someService.setSomeBigPojoBuilder(new SomeBigPojoBuilder());
someService.someLogicForAPojoWithBuilder();

someService.setSomeBigPojoBuilder(new SomeBigPojoBuilder());
someService.someLogicForAPojoWithBuilderBadArgument();
}
}


And the logs are:


pl.grzejszczak.marcin.junit.matchers.service.SomeServiceImpl:27 SomeLogicForAPojoWithoutBuilder executed
pl.grzejszczak.marcin.junit.matchers.service.SomeServiceImpl:30 StringField8 is equal [value]

pl.grzejszczak.marcin.junit.matchers.service.SomeServiceImpl:32 SomeBigPojo{stringField0='string', integerField0=1, booleanField0=false, stringField1='other string', integerField1=123, booleanField1=true, stringField2='something else', integerField2=321, booleanField2=false, stringField3='yet another string', integerField3=111, booleanField3=true, stringField4='something', integerField4=2, booleanField4=false, stringField5='More', integerField5=3, booleanField5=true, stringField6='String', integerField6=12, booleanField6=false, stringField7='some', stringField8='value', stringField9='ofString'}
pl.grzejszczak.marcin.junit.matchers.service.SomeServiceImpl:37 SomeLogicForAPojoWithBuilder executed
pl.grzejszczak.marcin.junit.matchers.service.SomeServiceImpl:65 StringField8 is equal [value]

pl.grzejszczak.marcin.junit.matchers.service.SomeServiceImpl:67 SomeBigPojo{stringField0='string', integerField0=1, booleanField0=false, stringField1='other string', integerField1=123, booleanField1=true, stringField2='something else', integerField2=321, booleanField2=false, stringField3='yet another string', integerField3=111, booleanField3=false, stringField4='something', integerField4=2, booleanField4=false, stringField5='More', integerField5=3, booleanField5=true, stringField6='String', integerField6=12, booleanField6=false, stringField7='some', stringField8='value', stringField9='ofString'}
pl.grzejszczak.marcin.junit.matchers.service.SomeServiceImpl:72 someLogicForAPojoWithBuilderBadArgument executed
Exception in thread "main" java.lang.NullPointerException: StringField1 must not be null!
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:208)
at pl.grzejszczak.marcin.junit.matchers.builder.SomeBigPojoBuilder.checkState(SomeBigPojoBuilder.java:166)
at pl.grzejszczak.marcin.junit.matchers.builder.SomeBigPojoBuilder.createSomeBigPojoWithBuilder(SomeBigPojoBuilder.java:170)
at pl.grzejszczak.marcin.junit.matchers.service.SomeServiceImpl.someLogicForAPojoWithBuilderBadArgument(SomeServiceImpl.java:73)
at pl.grzejszczak.marcin.junit.matchers.MatcherMain.main(MatcherMain.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

In my opinion that looks really nice :) And what is yours?

Sources are available here at Too Much Codings code repository.

UPDATE


I've made some code changes and cleaning (not much though cause I didn't have too much time) and the code is available at github - https://github.com/marcingrzejszczak/too-much-coding/tree/master/Unit_Testing_-_Matchers

Senin, 24 Desember 2012
no image

Google Guava Cache with regular expression patterns



Hi! Merry Christmas everyone :) Quite recently I've seen a nice presentation about Google Guava and we came to the conclusion in our project that it could be really interesting to use the its Cache functionallity. Let us take a look at the regexp Pattern class and its compile function. Quite often in the code we can see that each time a regular expression is being used a programmer is repeatidly calling the aforementioned Pattern.compile() function with the same argument thus compiling the same regular expression over and over again. What could be done however is to cache the result of such compilations - let us take a look at the RegexpUtils utility class:

RegexpUtils.java

package pl.grzejszczak.marcin.guava.cache.utils;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.String.format;

public final class RegexpUtils {

private RegexpUtils() {
throw new UnsupportedOperationException("RegexpUtils is a utility class - don't instantiate it!");
}

private static final LoadingCache<String, Pattern> COMPILED_PATTERNS =
CacheBuilder.newBuilder().build(new CacheLoader<String, Pattern>() {
@Override
public Pattern load(String regexp) throws Exception {
return Pattern.compile(regexp);
}
});

public static Pattern getPattern(String regexp) {
try {
return COMPILED_PATTERNS.get(regexp);
} catch (ExecutionException e) {
throw new RuntimeException(format("Error when getting a pattern [%s] from cache", regexp), e);
}
}

public static boolean matches(String stringToCheck, String regexp) {
return doGetMatcher(stringToCheck, regexp).matches();
}

public static Matcher getMatcher(String stringToCheck, String regexp) {
return doGetMatcher(stringToCheck, regexp);
}

private static Matcher doGetMatcher(String stringToCheck, String regexp) {
Pattern pattern = getPattern(regexp);
return pattern.matcher(stringToCheck);
}

}

As you can see the Guava's LoadingCache with the CacheBuilder is being used to populate a cache with a new compiled pattern if one is not found. Due to caching the compiled pattern if a compilation has already taken place it will not be repeated ever again (in our case since we dno't have any expiry set). Now a simple test

GuavaCache.java

package pl.grzejszczak.marcin.guava.cache;


import com.google.common.base.Stopwatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.grzejszczak.marcin.guava.cache.utils.RegexpUtils;

import java.util.regex.Pattern;

import static java.lang.String.format;

public class GuavaCache {
private static final Logger LOGGER = LoggerFactory.getLogger(GuavaCache.class);
public static final String STRING_TO_MATCH = "something";

public static void main(String[] args) {
runTestForManualCompilationAndOneUsingCache(1);
runTestForManualCompilationAndOneUsingCache(10);
runTestForManualCompilationAndOneUsingCache(100);
runTestForManualCompilationAndOneUsingCache(1000);
runTestForManualCompilationAndOneUsingCache(10000);
runTestForManualCompilationAndOneUsingCache(100000);
runTestForManualCompilationAndOneUsingCache(1000000);
}

private static void runTestForManualCompilationAndOneUsingCache(int firstNoOfRepetitions) {
repeatManualCompilation(firstNoOfRepetitions);
repeatCompilationWithCache(firstNoOfRepetitions);
}

private static void repeatManualCompilation(int noOfRepetitions) {
Stopwatch stopwatch = new Stopwatch().start();
compileAndMatchPatternManually(noOfRepetitions);
LOGGER.debug(format("Time needed to compile and check regexp expression [%d] ms, no of iterations [%d]", stopwatch.elapsedMillis(), noOfRepetitions));
}

private static void repeatCompilationWithCache(int noOfRepetitions) {
Stopwatch stopwatch = new Stopwatch().start();
compileAndMatchPatternUsingCache(noOfRepetitions);
LOGGER.debug(format("Time needed to compile and check regexp expression using Cache [%d] ms, no of iterations [%d]", stopwatch.elapsedMillis(), noOfRepetitions));
}

private static void compileAndMatchPatternManually(int limit) {
for (int i = 0; i < limit; i++) {
Pattern.compile("something").matcher(STRING_TO_MATCH).matches();
Pattern.compile("something1").matcher(STRING_TO_MATCH).matches();
Pattern.compile("something2").matcher(STRING_TO_MATCH).matches();
Pattern.compile("something3").matcher(STRING_TO_MATCH).matches();
Pattern.compile("something4").matcher(STRING_TO_MATCH).matches();
Pattern.compile("something5").matcher(STRING_TO_MATCH).matches();
Pattern.compile("something6").matcher(STRING_TO_MATCH).matches();
Pattern.compile("something7").matcher(STRING_TO_MATCH).matches();
Pattern.compile("something8").matcher(STRING_TO_MATCH).matches();
Pattern.compile("something9").matcher(STRING_TO_MATCH).matches();
}
}


private static void compileAndMatchPatternUsingCache(int limit) {
for (int i = 0; i < limit; i++) {
RegexpUtils.matches(STRING_TO_MATCH, "something");
RegexpUtils.matches(STRING_TO_MATCH, "something1");
RegexpUtils.matches(STRING_TO_MATCH, "something2");
RegexpUtils.matches(STRING_TO_MATCH, "something3");
RegexpUtils.matches(STRING_TO_MATCH, "something4");
RegexpUtils.matches(STRING_TO_MATCH, "something5");
RegexpUtils.matches(STRING_TO_MATCH, "something6");
RegexpUtils.matches(STRING_TO_MATCH, "something7");
RegexpUtils.matches(STRING_TO_MATCH, "something8");
RegexpUtils.matches(STRING_TO_MATCH, "something9");
}
}

}

We are running a series of tests and checking the time of their execution. Note that the results of these tests are not precise due to the fact that the application is not being run in isolation so numerous conditions can affect the time of the execution. We are interested in showing some degree of the problem rather than showing the precise execution time. For a given number of iterations (1,10,100,1000,10000,100000,1000000) we are either compiling 10 regular expressions or using a Guava's cache to retrieve the compiled Pattern and then we match them against a string to match. These are the logs:

pl.grzejszczak.marcin.guava.cache.GuavaCache:34 Time needed to compile and check regexp expression [1] ms, no of iterations [1]
pl.grzejszczak.marcin.guava.cache.GuavaCache:40 Time needed to compile and check regexp expression using Cache [35] ms, no of iterations [1]
pl.grzejszczak.marcin.guava.cache.GuavaCache:34 Time needed to compile and check regexp expression [1] ms, no of iterations [10]
pl.grzejszczak.marcin.guava.cache.GuavaCache:40 Time needed to compile and check regexp expression using Cache [0] ms, no of iterations [10]
pl.grzejszczak.marcin.guava.cache.GuavaCache:34 Time needed to compile and check regexp expression [8] ms, no of iterations [100]
pl.grzejszczak.marcin.guava.cache.GuavaCache:40 Time needed to compile and check regexp expression using Cache [3] ms, no of iterations [100]
pl.grzejszczak.marcin.guava.cache.GuavaCache:34 Time needed to compile and check regexp expression [10] ms, no of iterations [1000]
pl.grzejszczak.marcin.guava.cache.GuavaCache:40 Time needed to compile and check regexp expression using Cache [10] ms, no of iterations [1000]
pl.grzejszczak.marcin.guava.cache.GuavaCache:34 Time needed to compile and check regexp expression [83] ms, no of iterations [10000]
pl.grzejszczak.marcin.guava.cache.GuavaCache:40 Time needed to compile and check regexp expression using Cache [33] ms, no of iterations [10000]
pl.grzejszczak.marcin.guava.cache.GuavaCache:34 Time needed to compile and check regexp expression [800] ms, no of iterations [100000]
pl.grzejszczak.marcin.guava.cache.GuavaCache:40 Time needed to compile and check regexp expression using Cache [279] ms, no of iterations [100000]
pl.grzejszczak.marcin.guava.cache.GuavaCache:34 Time needed to compile and check regexp expression [7562] ms, no of iterations [1000000]
pl.grzejszczak.marcin.guava.cache.GuavaCache:40 Time needed to compile and check regexp expression using Cache [3067] ms, no of iterations [1000000]

You can find the sources over here under the Guava/Cache directory or go to the url https://bitbucket.org/gregorin1987/too-much-coding/src
Copyright © 2012 Codding News All Right Reserved