Skip to content

Feed aggregator

URL Encoding and Decoding Using Java

It is a common requirement to implement URL encoding and decoding in Java while creating crawlers or downloaders. This post focuses on creating modules for encoding and decoding of a passed URL. You can take a look at the source code on GitHub.

Main Method
 public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           String url="\u0026itag=43\u0026type=video%2Fwebm%3B+codecs%3D%22vp8.0%2C+vorbis%22\u0026quality=medium";  
           String url2="; codecs=\"vp8.0, vorbis\"&quality=medium";  
           String decodeURL = decode(url);  
           System.out.println("Decoded URL: "+decodeURL);  
           String encodeURL = encode(url2);  
           System.out.println("Encoded URL2: "+encodeURL);  

How It Works
  1. url is the variable containing the encoded URL that we want to decode.

Categories: Communities

New: JDK 9 Jigsaw Modular Projects in NetBeans IDE

The NetBeans IDE 9 development builds now enable you to create Java Modular Projects, i.e., Jigsaw projects that can contain multiple Jigsaw modules, which can be compiled together as a unit:

They're visualized as follows, for example, in this case, for the Jigsawified Anagram Game (discussed here):


Categories: Open Source

Spring Tips: Servlet Container Deployment Options [Video]

Speaker: Josh Long

Hi, Spring fans! In this tip, we’ll look at deploying to, and integrating with, embedded (like Apache Tomcat, Eclipse Jetty, and RedHat’s Undertow) and standalone Servlet containers (like the WildFly application server) in a Spring Boot application.

Categories: Communities

Java Streams groupingBy Examples

Have you wanted to perform SQL-like operations on data in a List or a Map? Maybe computing a sum or average? Or perhaps performing an aggregate operation such as summing a group? Well, with Java 8 streams operations, you are covered for some of these.

A previous article covered sums and averages on the whole data set. In this article, we show how to use Collectors.groupingBy() to perform SQL-like grouping on tabular data.

Categories: Communities

Ratpacked: Add Ratpack to Spring Boot Applications

In a previous post, we saw how we can use Spring Boot in a Ratpack application. But the integration can also be the other way around: using Ratpack in a Spring Boot application. This way, we can use Ratpack's power to handle requests sent to our Spring Boot application and still use all Spring Boot features in our application. The easiest way to add Ratpack to a Spring Boot application is adding a Ratpack dependency and using the @EnableRatpack annotation. With this annotation, a RatpackServer instance is created and started along with configuration options.

Let's see an example Spring Boot application with Ratpack enabled. First, we add Ratpack as a dependency to our Spring Boot application. In our example, we also add Ratpack's Dropwizard module as a dependency. We use Gradle in our example:

Categories: Communities

The Open-Closed Principle Is Often Not What You Think

jOOQ is a library that loves making everything internal final and package private. We have tons of classes like these:

final class Concat extends AbstractFunction<String> {
    // ...

Categories: Communities

A Look at IntelliJ IDEA's Support for Java 9 Modules

IntelliJ IDEA 2017.1 brings support for Java 9‚Äôs new modularity (Project Jigsaw). In this latest version, support includes code completion in the file, and quick fixes for adding modules to your project.

Let‚Äôs take a look at a basic example of a modular project. To start with, we just have an ordinary IntelliJ IDEA module that contains a simple ‚ÄúHello World‚ÄĚ type application.

Categories: Communities

Preparing Your Code for JDK 9

Java TV - Thu, 03/23/2017 - 18:58
Java 9 is packed with lot of new features aimed at improving developer experience and at improving Java applications. Apart from the widely talked about Jigsaw, Java 9 also features the Multi-Release JAR files for ensuring backwards compatibility while upgrading, decreased memory consumption through Compact String, Java 9 REPL- JShell, Version String upgrade and so […]
Categories: Blogs

Introduction to Testing with Spock and Groovy

baeldung - Coding and Testing Stuff - Thu, 03/23/2017 - 17:03
1. Introduction

In this article, we’ll take a look at Spock,¬†a Groovy testing framework. Mainly, Spock¬†aims to be a more powerful alternative to the traditional JUnit stack, by leveraging Groovy features.

Groovy is a JVM-based language which seamlessly integrates with Java. On top of interoperability, it offers additional language concepts such as being a dynamic, having optional types and meta-programming.

By making use of¬†Groovy, Spock¬†introduces new and expressive ways of testing our Java applications, which¬†simply¬†aren’t possible in ordinary Java code.¬†We’ll explore some of¬†Spock’s high-level concepts during this article, with some practical step by step examples.

2. Maven Dependency

Before we get started, let’s add our Maven dependencies:


We’ve added both¬†Spock and Groovy¬†as we would any standard library. However, as Groovy is a new JVM language, we need to include¬†the gmavenplus¬†plugin in order to be able to compile and run it:


Now we are ready to write our first Spock test, which will be written in Groovy code. Note that we are using Groovy and Spock only for testing purposes and this is why those dependencies are test-scoped.

3. Structure of a Spock Test 3.1. Specifications and Features

As we are writing our tests in Groovy, we need to add them to the¬†src/test/groovy¬†directory, instead of¬†src/test/java. Let’s create our first test in this directory, naming¬†it¬†Specification.groovy:

class FirstSpecification extends Specification {


Note that we are extending the Specification interface. Each Spock class must extend this¬†in order to make the framework available to it. It’s doing so¬†that allows us to¬†implement our first feature:

def "one plus one should equal two"() {
  1 + 1 == 2

Before explaining the code, it’s also worth noting that in Spock, what we refer to as a¬†feature¬†is¬†somewhat synonymous to what we see as a test in JUnit. So whenever we refer to a feature¬†we are actually¬†referring to a test.

Now, let’s analyze our feature. In doing so, we should immediately be¬†able to see some differences between it and¬†Java.

The first difference is that the feature method name is written as an ordinary string. In JUnit, we would have had a method name which uses camelcase or underscores to separate the words, which would not have been as expressive or human readable.

The next is that our test code lives in an expect block. We will cover blocks in more detail shortly, but essentially they are a logical way of splitting up the different steps of our tests.

Finally,¬†we¬†realize that there are no assertions. That’s because the assertion is implicit, passing when¬†our statement equals¬†true and failing¬†when it equals false. Again, we’ll cover assertions in more details shortly.

3.2. Blocks

Sometimes when writing JUnit a test, we might notice there isn’t an expressive way of breaking it up into parts. For example, if we were following behavior driven development, we might end up denoting the given when then¬†parts using comments:

public void givenTwoAndTwo_whenAdding_thenResultIsFour() {
   // Given
   int first = 2;
   int second = 4;

   // When
   int result = 2 + 2;

   // Then
   assertTrue(result == 4)

Spock addresses this problem with blocks. Blocks are a Spock native way of breaking up the phases of our test using labels. They give us labels for given when then and more:

  1. Setup (Aliased by Given) РHere we perform any setup needed before a test is run. This is an implicit block, with code not in any block at all becoming part of it
  2. When РThis is where we provide a stimulus to what is under test. In other words, where we invoke our method under test
  3. Then РThis is where the assertions belong. In Spock, these are evaluated as plain boolean assertions, which will be covered later
  4. Expect РThis is a way of performing our stimulus and assertion within the same block. Depending on what we find more expressive, we may or may not choose to use this block
  5. Cleanup РHere we tear down any test dependency resources which would otherwise be left behind. For example, we might want to remove any files from the file system or remove test data written to a database

Let’s try implementing our test again, this time making full use of blocks:

def "two plus two should equal four"() {
        int left = 2
        int right = 2

        int result = left + right

        result == 4

As we can see, blocks help our test become more readable.

3.3. Leveraging Groovy Features for Assertions

Within the then and expect blocks, assertions are implicit.

Mostly, every¬†statement is evaluated and then fails if it is not true. When coupling this with various Groovy features, it does a good job of¬†removing¬†the need for an¬†assertion library. Let’s try a list¬†assertion to demonstrate this:

def "Should be able to remove from list"() {
        def list = [1, 2, 3, 4]


        list == [2, 3, 4]

While we’re only touching briefly on Groovy in this article, it’s worth explaining what is happening here.

First, Groovy gives us simpler ways of creating lists. We can just able to declare our elements with square brackets, and internally a list will be instantiated.

Secondly, as Groovy is dynamic, we can use¬†def¬†which just means we aren’t declaring a type for our variables.

Finally, in the context of simplifying our test, the most useful feature demonstrated is operator overloading. This means that internally, rather than making a reference comparison like in Java, the equals() method will be invoked to compare the two lists.

It’s also worth demonstrating what happens when our test fails. Let’s make it break and then view what’s output to the¬†console:

Condition not satisfied:

list == [1, 3, 4]
|    |
|    false
[2, 3, 4]
 <Click to see difference>

at FirstSpecification.Should be able to remove from list(FirstSpecification.groovy:30)

While all that’s going on is¬†calling equals()¬†on two lists, Spock is intelligent enough to perform a breakdown of the failing assertion, giving¬†us useful information for debugging.

3.4. Asserting Exceptions

Spock also provides us¬†with¬†an expressive way of checking for exceptions. In JUnit, some our options might be using¬†a try-catch¬†block, declare¬†expected¬†at the top of our test, or¬†making use of a third party library. Spock’s native assertions come with a way of dealing with exceptions out of the box:

def "Should get an index out of bounds when removing a non-existent item"() {
        def list = [1, 2, 3, 4]

        list.size() == 4

Here, we’ve¬†not had to¬†introduce an additional library. Another advantage is¬†that¬†the thrown() method¬†will assert the type of the exception, but not halt execution of the test.

4. Data Driven Testing 4.1. What is a Data Driven Testing?

Essentially, data driven testing is when we test the same behaviour multiple times with different parameters and assertions. A classic example of this would be testing a mathematical operation such as squaring a number. Depending on the various permutations of operands, the result will be different. In Java, the term we may be more familiar with is parameterized testing.

4.2. Implementing a Parameterized Test in Java

For some context, it’s worth¬†implementing a parameterized¬†test using¬†JUnit:

public class FibonacciTest {
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {     
          { 1, 1 }, { 2, 4 }, { 3, 9 }  

    private int input;

    private int expected;

    public ToThePowerOfTwo(int input, int expected) {
        this.input = input;
        this.expected = expected;

    public void test() {
        assertEquals(fExpected, Math.pow(3, 2));

As we can see there’s quite a lot of verbosity, and the code isn’t very readable. We’ve had to create a two dimensional object array that lives outside of the test,¬†and even a wrapper object for¬†injecting the various test values.

4.3. Using Datatables in Spock

One easy win for Spock when compared to JUnit is how it cleanly it implements parameterized tests. Again, in¬†Spock this is known as Data Driven Testing.¬†Now, let’s implement the same test again, only this time we’ll use Spock with Data Tables, which provides a far more convenient way of performing a parameterized test:

def "numbers to the power of two"(int a, int b, int c) {
      Math.pow(a, b) == c

      a | b | c
      1 | 2 | 1
      2 | 2 | 4
      3 | 2 | 9

As we can see, we just have a straightforward and expressive Data table containing all our parameters.

Also, it belongs where it should do, alongside the test, and there is no boilerplate. The test is expressive, with a human readable name, and pure expect and where block to break up the logical sections.

4.4. When a Datatable Fails

It’s also worth seeing what happens when our test fails:

Condition not satisfied:

Math.pow(a, b) == c
     |   |  |  |  |
     4.0 2  2  |  1

Expected :1

Actual   :4.0

Again, Spock gives us a very informative error message. We can see exactly what row of our Datatable caused a failure and why.

5. Mocking 5.1. What is Mocking?

Mocking is a way of¬†changing the behaviour of a class¬†which our service under test collaborates with. It’s a helpful way of being able to test business logic¬†in isolation of it’s dependencies.

A classic example¬†of this would¬†be replacing a class which makes a network call with something which simply pretends to. For a more in-depth explanation, it’s worth reading¬†this¬†article.

5.2. Mocking using Spock

Spock has it’s own mocking framework, making use of interesting concepts brought to the JVM by Groovy. First, let’s instantiate a Mock:

PaymentGateway paymentGateway = Mock()

In this case, the type of our mock is inferred by the variable type. As Groovy is a dynamic language, we can also provide a type argument, allow us to not have to assign our mock to any particular type:

def paymentGateway = Mock(PaymentGateway)

Now, whenever we call a method on our PaymentGateway mock, a default response will be given, without a real instance being invoked:

    def result = paymentGateway.makePayment(12.99)

    result == false

The term for this is lenient mocking. This means that mock methods which have not been defined will return sensible defaults, as opposed to throwing an exception. This is by design in Spock, in order to make mocks and thus tests less brittle.

5.3. Stubbing Method calls on Mocks

We can also¬†configure¬†methods called on our mock to respond in a certain way to different arguments.¬†Let’s try getting our¬†PaymentGateway¬†mock to return true¬†when we make a payment of¬†20:

    paymentGateway.makePayment(20) >> true

    def result = paymentGateway.makePayment(20)

    result == true

What’s interesting here, is how Spock makes use of Groovy’s operator overloading¬†in order to stub method calls. With Java, we have to call real methods, which¬†arguably means that the resulting code is more verbose and potentially less expressive.

Now, let’s try a few more types of stubbing.

If we stopped caring about our method argument and always wanted to return true, we could just use an underscore:

paymentGateway.makePayment(_) >> true

If we wanted to alternate between different responses, we could provide a list, for which each element will be returned in sequence:

paymentGateway.makePayment(_) >>> [true, true, false, true]

There are more possibilities, and these may be covered in a more advanced future article on mocking.

5.4. Verification

Another thing we might want to do with mocks is assert that various methods were called on them with expected parameters. In other words, we ought to verify interactions with our mocks.

A typical use case for verification¬†would be if a¬†method on our mock had a void¬†return type.¬†In this case,¬†by there being no result for us to operate on, there’s no inferred behavior for us to test¬†via the method under test. Generally, if¬†something was returned, then the method under test could operate on it, and it’s the result of that operation would be what we¬†assert.

Let’s try verifying that a method with a void return type is called:

def "Should verify notify was called"() {
        def notifier = Mock(Notifier)


        1 * notifier.notify('foo')

Spock is leveraging Groovy operator overloading again. By multiplying our mocks method call by one, we are saying how many times we expect it to have been called.

If our method had not¬†been called at all or alternatively¬†had not been called as many times as we specified, then our test would have failed to give us an informative Spock error message. Let’s prove this by expecting it to have been called twice:

2 * notifier.notify('foo')

Following this, let’s¬†see what the error message looks like. We’ll¬†that as usual; it’s quite informative:

Too few invocations for:

2 * notifier.notify('foo')   (1 invocation)

Just like stubbing, we can also perform looser¬†verification matching. If we didn’t care what our method parameter was, we could use an underscore:

2 * notifier.notify(_)

Or if we wanted to make sure it wasn’t called with a particular argument, we could¬†use the not operator:

2 * notifier.notify(!'foo')

Again, there are more possibilities, which may be covered in a future more advanced article.

6. Conclusion

In this article, we’ve given a¬†quick slice through testing with Spock.

We’ve¬†demonstrated how, by leveraging Groovy, we can make our tests more expressive than the typical JUnit stack. We’ve explained the structure of specifications and features.

And we’ve shown how easy it is to perform data-driven testing, and also how mocking and assertions are easy via¬†native Spock functionality.

The implementation of these examples can be found over on GitHub. This is a Maven-based project, so should be easy to run as is.

Categories: Blogs

This Week in Spring: DDD, Spring Cloud Updates, and RabbitMQ

Welcome to another installment of This Week in Spring! This week I’m visiting with customers and am presenting at the first Devoxx US event in San Jose, California. If you’re around, don’t hesitate to stop by and say hi at the Pivotal booth in the expo hall.

As usual, we’ve got a lot to cover so let’s get to it!

Categories: Communities

Java Web Weekly, Issue 169

baeldung - Coding and Testing Stuff - Thu, 03/23/2017 - 14:44

Lots of interesting writeups on Java 9 this week.

Here we go…

1. Spring and Java >> A Nice API Design Gem: Strategy Pattern With Lambdas []

The introduction of lambda expressions and functional interfaces allows us to rethink the design and simplify the Strategy Design Pattern (and many other).

>> Spring Boot and Security Events with Actuator []

Spring Boot Actuator comes with user-friendly support for handling audit and security events.

Simply put, all we need to do is to define a listener for the predefined events.

>> Project Amber will revolutionize Java []

A lot of new changes are finally coming to Java. These include Local Variable Type Inference, Generic Enums, Data Classes and Pattern Matching.

“We’ve had those in other languages ten years ago” posts are coming.

>> Fully configurable mappings for Spring MVC []

With a little bit of effort, we can bring the features of Boot Actuators to non-Boot applications as well.

>> Spring Data Improvements in IntelliJ IDEA 2017.1 []

IntelliJ IDEA is getting even more Spring-oriented features.

>> The Open-Closed Principle is Often Not What You Think it Is []

The pragmatic approach to the Open-Closed Principle does not involve aiming for openness at any costs.

>> JDK 9 Rampdown Phase 2: Process proposal []

The 2nd phase of JDK 9 rampdown just started.

>> Better tools for adjusting to strong encapsulation []

The internal APIs in the JDK should not have been used but they were by multiple frameworks which are experiencing errors now.

JDK 9 will feature a special workaround for these situations.

Also worth reading:

Webinars and presentations:

Time to upgrade:

2. Technical >> The State of Browser Caching, Revisited []

An interesting write-up on the basics of browser caching.

>> Acing the technical interview []

That’s how you make interviewers hate you

Categories: Blogs

Do You View Your AppSec Tools as an Inhibitor to Innovation or a Safety Measure?

Sonatype Blog - Thu, 03/23/2017 - 14:00
DevOps is all about making better software faster.  It also requires making it more safely while compressing the time between ideation to realisation. I hear IT organisations tell me time and time again of their ambitions to be the innovation power-house for their business - so it‚Äôs great news...

To read more, visit our blog at
Categories: Companies

DevSecOps: Eat Carrots, Not Cupcakes

Sonatype Blog - Thu, 03/23/2017 - 14:00
You Are What You Eat.   When it comes to food, we all know what‚Äôs considered ‚Äúgood‚ÄĚ and what‚Äôs ‚Äúbad‚ÄĚ.

To read more, visit our blog at
Categories: Companies

Lazy Loading With Vaadin 8

One of my favorite new features in Vaadin 8 is the Grid::setDataProvider method, which makes it remarkably easy to implement lazy loading in Grids. In earlier versions of Vaadin, you had to implement a rather complex Container interface. Vaadin 8 not only removes this interface, but also provides a modern API that takes advantage of many Java 8 features.

In this article, you will learn how to implement lazy loading to show a sortable list of people in a Grid component by simply providing two lambda expressions. You can find two ‚Äúflavors‚ÄĚ of the example application: One for people who use Spring (Spring Boot), and one for people who use Java EE (CDI and WildFly Swarm):

Categories: Communities

Introduction to JSONassert

baeldung - Coding and Testing Stuff - Thu, 03/23/2017 - 11:00
1. Overview

In this article, we’ll have a look at the¬†JSONAssert library¬†– a library focused on understanding JSON data and writing complex¬†JUnit¬†tests using that data.

2. Maven Dependency

First, let’s add the Maven dependency:


Please check out the latest version of the library here.

3. Working with Simple JSON Data 3.1. Using the LENIENT Mode

Let’s start our tests with a simple JSON string comparison:

String actual = "{id:123, name:\"John\"}";
  "{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT);

The test will pass as the expected JSON string, and the actual JSON string are the same.

The comparison mode LENIENT means that even if the actual JSON contains extended fields, the test will still pass:

String actual = "{id:123, name:\"John\", zip:\"33025\"}";
  "{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT);

As we can see, the real variable contains an additional field zip which is not present in the expected String. Still, the test will pass.

This concept is useful in the application development. This means that our APIs can grow, returning additional fields as required, without breaking the existing tests.

3.2. Using the STRICT Mode

The behavior mentioned in the previous sub-section can be easily changed by using the STRICT comparison mode:

String actual = "{id:123,name:\"John\"}";
  "{name:\"John\"}", actual, JSONCompareMode.STRICT);

Please note the use of assertNotEquals() in the above example.

3.3. Using a Boolean Instead of JSONCompareMode

The compare mode can also be defined by using an overloaded method that takes boolean instead of JSONCompareMode where LENIENT = false and STRICT = true:

String actual = "{id:123,name:\"John\",zip:\"33025\"}";
  "{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT);
  "{id:123,name:\"John\"}", actual, false);

actual = "{id:123,name:\"John\"}";
  "{name:\"John\"}", actual, JSONCompareMode.STRICT);
  "{name:\"John\"}", actual, true);
3.4. The Logical Comparison

As described earlier, JSONAssert makes a logical comparison of the data. This means that the ordering of elements does not matter while dealing with JSON objects:

String result = "{id:1,name:\"John\"}";
  "{name:\"John\",id:1}", result, JSONCompareMode.STRICT);
  "{name:\"John\",id:1}", result, JSONCompareMode.LENIENT);

Strict or not, the above test will pass in both the cases.

Another example of logical comparison can be demonstrated by using different types for the same value:

JSONObject expected = new JSONObject();
JSONObject actual = new JSONObject();
expected.put("id", Integer.valueOf(12345));
actual.put("id", Double.valueOf(12345));

JSONAssert.assertEquals(expected, actual, JSONCompareMode.LENIENT);

The first thing to note here is that we are using JSONObject instead of a String as we did for earlier examples. The next thing is that we have used Integer for expected and Double for actual. The test will pass irrespective of the types because the logical value 12345 for both of them is same.

Even in the case when we have nested object representation, this library works pretty well:

String result = "{id:1,name:\"Juergen\", 
  address:{city:\"Hollywood\", state:\"LA\", zip:91601}}";
  address:{city:\"Hollywood\", state:\"LA\", zip:91601}}", result, false);
3.5. Assertions with User Specified Messages

All the assertEquals() and assertNotEquals() methods accept a String message as the first parameter. This message provides some customization to our test cases by providing a meaningful message in the case of test failures:

String actual = "{id:123,name:\"John\"}";
String failureMessage = "Only one field is expected: name";
try {
      "{name:\"John\"}", actual, JSONCompareMode.STRICT);
} catch (AssertionError ae) {

In the case of any failure, the entire error message will make more sense:

Only one field is expected: name 
Unexpected: id

The first line is the user specified message and the second line is the additional message provided by the library.

4. Working with JSON Arrays

The comparison rules for JSON arrays differ a little, compared to JSON objects.

4.1. The Order of the Elements in an Array

The first difference is that the order of elements in an array has to be exactly same in STRICT comparison mode. However, for LENIENT comparison mode, the order does not matter:

String result = "[Alex, Barbera, Charlie, Xavier]";
  "[Charlie, Alex, Xavier, Barbera]", result, JSONCompareMode.LENIENT);
  "[Alex, Barbera, Charlie, Xavier]", result, JSONCompareMode.STRICT);
  "[Charlie, Alex, Xavier, Barbera]", result, JSONCompareMode.STRICT);

This is pretty useful in the scenario where the API returns an array of sorted elements, and we want to verify if the response is sorted.

4.2. The Extended Elements in an Array

Another difference is that extended elements are not allowed when the dealing with JSON arrays:

String result = "[1,2,3,4,5]";
  "[1,2,3,4,5]", result, JSONCompareMode.LENIENT);
  "[1,2,3]", result, JSONCompareMode.LENIENT);
  "[1,2,3,4,5,6]", result, JSONCompareMode.LENIENT);

The above example clearly demonstrates that even with the LENIENT comparison mode, the items in the expected array has to match the items in the real array exactly. Adding or removing, even a single element, will result in a failure.

4.3. Array Specific Operations

We also have a couple of other techniques to verify the contents of the arrays further.

Suppose we want to verify the size of the array. This can be achieved by using a concrete syntax as the expected value:

String names = "{names:[Alex, Barbera, Charlie, Xavier]}";
  new ArraySizeComparator(JSONCompareMode.LENIENT));

The¬†String¬†“{names:[4]}”¬†specifies the expected size of the array.

Let’s have a look at another comparison technique:

String ratings = "{ratings:[3.2,3.5,4.1,5,1]}";
  new ArraySizeComparator(JSONCompareMode.LENIENT));

The above example verifies that all the elements in the array must have a value between [1,5], both 1 and 5 inclusive. If there is any value less than 1 or greater than 5, the above test will fail.

5. Advanced Comparison Example

Consider the use case where our API returns multiple¬†ids, each one being an¬†Integer¬†value. This means that all the¬†ids can be verified using a simple regular expression ‘\d‘.

The above regex can be combined with a CustomComparator and applied to all the values of all the ids. If any of the ids does not match the regex, the test will fail:

JSONAssert.assertEquals("{entry:{id:x}}", "{entry:{id:1, id:2}}", 
  new CustomComparator(
  new Customization("", 
  new RegularExpressionValueMatcher<Object>("\\d"))));

JSONAssert.assertNotEquals("{entry:{id:x}}", "{entry:{id:1, id:as}}", 
  new CustomComparator(JSONCompareMode.STRICT, 
  new Customization("", 
  new RegularExpressionValueMatcher<Object>("\\d"))));

The “{id:x}” in the above example is nothing but a placeholder – the¬†x¬†can be replaced by anything. As it¬†is the place where the regex pattern ‘\d‘ will be applied. Since the¬†id¬†itself is inside another field¬†entry, the¬†Customization¬†specifies the position of the¬†id, so that the¬†CustomComparator¬†can perform the comparison.

6. Conclusion

In this quick article, we looked at various scenarios where JSONAssert can be helpful. We started with a super simple example and moved to more complex comparisons.

Of course, as always, the full source code of all the examples discussed here can be found over on GitHub.

Categories: Blogs

New Stream, Comparator and Collector Functionality in Guava 21

baeldung - Coding and Testing Stuff - Thu, 03/23/2017 - 10:55
1. Introduction

This article is first in the series about the new features launched with Version 21 of the Google Guava library. We’ll discuss newly added classes and some major changes from previous versions of Guava.

More specifically, we’ll discuss additions and changes in the common.collect package.

Guava 21 introduces some new and useful functionality in the¬†common.collect package; let’s have a quick look at some of these new utilities and how we can get the most out of them.

2. Streams

We’re all excited about the latest addition of in Java 8. Well, Guava is now making good use of streams and provides what Oracle may have missed.

Streams is a static utility class, with some much-needed utilities for handling Java 8 streams.


Streams class provides four ways to create streams using Iterable, Iterator, Optional and Collection.

Though, stream creation using Collection is deprecated, as it’s provided by Java 8 out of the box:

List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Stream<Integer> streamFromCollection =;
Stream<Integer> streamFromIterator =;
Stream<Integer> streamFromIterable =<Integer>) numbers);
Stream<Integer> streamFromOptional =;

Streams class also provides flavors with OptionalDouble, OptionalLong and OptionalInt. These methods return a stream containing only that element otherwise empty stream:

LongStream streamFromOptionalLong =;
IntStream streamFromOptionalInt =;
DoubleStream streamFromOptionalDouble =;
2.2. Streams.concat()

Streams class provides methods for concating more than one homogeneous streams.

Stream<Integer> concatenatedStreams = Streams.concat(streamFromCollection, streamFromIterable,streamFromIterator);

The concat¬†functionality comes in a few flavors –¬†LongStream, IntStream and DoubleStream.

2.3. Streams.findLast()

Streams have a utility method to find the last element in the stream by using findLast() method.

This method either returns last element or Optional.empty() if the stream is there are no elements in the stream:

List<Integer> integers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Optional<Integer> lastItem = Streams.findLast(;

The findLast() method works for LongStream, IntStream and DoubleStream.

2.4. Streams.mapWithIndex()

By using mapWithIndex() method, each element of the stream carries information about their respective position (index):

mapWithIndex( Stream.of("a", "b", "c"), (str, index) -> str + ":" + index)

This will return Stream.of(“a:0″,”b:1″,”c:2”).

Same can be achieved with IntStream, LongStream and DoubleStream using overloaded mapWithIndex().


In order to map corresponding elements of two streams using some function, just use zip method of Streams:
  Stream.of("candy", "chocolate", "bar"),
  Stream.of("$1", "$2","$3"),
  (arg1, arg2) -> arg1 + ":" + arg2

This will return Stream.of(“candy:$1″,”chocolate:$2″,”bar:$3”);

The resulting stream will only be as long as the shorter of the two input streams; if one stream is longer, its extra element will be ignored.

3. Comparators

Guava Ordering class is deprecated and in the phase of deletion in newer versions. Most of the functionalities of Ordering class are already enlisted in JDK 8.

Guava introduces Comparators to provide additional features of Ordering which are not yet provided by the Java 8 standard libs.

Let’s have a quick look at these.

3.1. Comparators.isInOrder()

This method returns true if each element in the Iterable is greater than or equal to the preceding one, as specified by the Comparator:

List<Integer> integers = Arrays.asList(1,2,3,4,4,6,7,8,9,10);
boolean isInAscendingOrder = Comparators.isInOrder(
  integers, new AscedingOrderComparator());
3.2. Comparators.isInStrictOrder()

Quite similar to the isInOrder() method but it strictly holds the condition, the element cannot be equal to the preceding one, it has to be greater than. The previous code will return false for this method.

3.3. Comparators.lexicographical()

This API returns a new Comparator instance Рwhich sorts in lexicographical (dictionary) order comparing corresponding elements pairwise. Internally, it creates a new instance of LexicographicalOrdering<S>().

4. MoreCollectors

MoreCollectors contains some very useful Collectors which are not present in Java 8 and are not associated with type.

Let’s go over a few of these.

4.1. MoreCollectors.toOptional()

Here, Collector converts a stream containing zero or one element to an Optional:

List<Integer> numbers = Arrays.asList(1);
Optional<Integer> number =
  .map(e -> e * 2)

If the stream contains more than one elements – the collector will throw IllegalArgumentException.

4.2. MoreCollectors.onlyElement()

With this API, the Collector takes a stream containing just one element and returns the element; if the stream contains more than one element it throws IllegalArgumentException or if the stream contains zero element it throws NoSuchElementException.

5. Interners.InternerBuilder

This is an internal builder class to already existing Interners in Guava library. It provides some handy method to define concurrency level and type (weak or strong) of Interner you prefer:

Interners interners = Interners.newBuilder()
6. Conclusion

In this quick article, we explored the newly added functionality in the common.collect package of Guava 21.

The code for this article can be found on Github, as always.

Categories: Blogs

Dealing With Maven Dependencies When Switching to Git

So we're moving to Git and we like git-flow. Now what? Let's test it all out! My team is great. They threw together a hit list of developer workflows in Confluence, all based on what we had been doing as a team and all of the weird things they thought we might have to do in the future. Then, in a project structure mirroring our own (but with no code in it ‚ÄĒ just a pom.xml), tried every workflow.

Maven dependencies were about to prove themselves to be our biggest problem in all of this.

Categories: Communities

Object-Oriented Solutions: Accounts and Currencies

This article is about a simplified version of real code running at a financial institution and how maintenance problems with this code can be avoided by using Object-Oriented Design. The purpose of the code is to represent retail money Accounts and enable transferring money, define recurring transfers and to support the usual functionality you find at any bank.

First, there is an Account interface and a Money class:

Categories: Communities

Distributed Scheduling and Servicing in Java

The usage of task schedulers is a pertinent necessity in enterprise solutions. There are numerous articles on the Internet discussing the usability of such services/libraries, so we won't explore that any further.

Instead, we will try to address a recurring issue in scheduler-based solution design.

Categories: Communities

Java EE @ DevNexus 2017 [Slides]

DevNexus 2017 was held in historic Atlanta on February 22-24. For those of you not familiar with it, DevNexus is the most significant Java-centric conference in the southeastern US and now perhaps even at a national level. It was started by JBoss Java Champion Burr Sutter and organized by the Atlanta JUG (currently lead by Vincent Mayers, Gunnar Hillert, Pratik Patel, et al). I guess at this point I am somewhat of a DevNexus veteran myself. As usual, DevNexus attracted a bevy of world-class speakers including Ed Burns, David Blevins, Ivar Grimstad, Simon Ritter, Heather VanCura, Stephen Chin, Simon Maple, Geertjan Wielenga, Victor Orozco, Edson Yanaga, and Enrique Zamudio. This was another solid year for DevNexus. Java EE had a strong showing at the conference as usual, including my own sessions.

I am very proud to say my company CapTech sponsored DevNexus for the very first time. We had a fully manned booth that saw very good traffic and we also sponsored a well-attended happy hour.

Categories: Communities