Blog by Sergej Jevsejev

Java libraries you can't miss in 2017

· Read in about 7 min · (1482 Words)

Hello,

This blog post is heavily inspired by this presentation by Andres Almiray.

This was so good, that I needed to groom it as the reference list. Sharing it with short feature lists and examples.

Enjoy!

Guice

Guice (pronounced ‘juice’) is a lightweight dependency injection framework for Java 6 and above, brought to you by Google.

# Typical dependency injection
public class DatabaseTransactionLogProvider implements Provider<TransactionLog> {
  @Inject Connection connection;

  public TransactionLog get() {
    return new DatabaseTransactionLog(connection);
  }
}
# FactoryModuleBuilder generates factory using your interface
public interface PaymentFactory {
   Payment create(Date startDate, Money amount);
 }

GitHub, JavaDoc, User guide, FactoryModuleBuilder

OkHttp

HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.

OkHttp is an HTTP client that’s efficient by default:

  • HTTP/2 support allows all requests to the same host to share a socket.
  • Connection pooling reduces request latency (if HTTP/2 isn’t available).
  • Transparent GZIP shrinks download sizes.
  • Response caching avoids the network completely for repeat requests.
OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

GitHub, Website

Retrofit

Type-safe HTTP client for Android and Java by Square, Inc. Retrofit turns your HTTP API into a Java interface.

Retrofit turns your HTTP API into a Java interface.

public interface GitHubService {
    @GET("users/{user}/repos")
    Call<List<Repo>listRepos(@Path("user") String user);
}

The Retrofit class generates an implementation of the GitHubService interface.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();
 
GitHubService service = retrofit.create(GitHubService.class);

Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver.

Call<List<Repo>> repos = service.listRepos("octocat");

GitHub, Website

JDeferred

Java Deferred/Promise library similar to JQuery

  • Deferred object and Promise
  • Promise callbacks: .then(…), .done(…), .fail(…), .progress(…), .always(…)
  • Multiple promises - .when(p1, p2, p3, …).then(…)
  • Callable and Runnable - wrappers.when(new Runnable() {…})
  • Uses Executor Service
  • Java Generics support: Deferred<Integer, Exception, Doubledeferred;, deferred.resolve(10);, deferred.reject(new Exception());,deferred.notify(0.80);,
  • Android Support
  • Java 8 Lambda friendly

GitHub, Website

RxJava

RxJava – Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.

It extends the observer pattern to support sequences of data/events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety and concurrent data structures.

One of the common use cases for RxJava is to run some computation, network request on a background thread and show the results (or error) on the UI thread:

Flowable.fromCallable(() -{
    Thread.sleep(1000); //  imitate expensive computation
    return "Done";
})
  .subscribeOn(Schedulers.io())
  .observeOn(Schedulers.single())
  .subscribe(System.out::println, Throwable::printStackTrace);

Thread.sleep(2000); // <--- wait for the flow to finish

GitHub, Wiki

MBassador

MBassador is a light-weight, high-performance event bus implementing the publish-subscribe pattern. It is designed for ease of use and aims to be feature rich and extensible while preserving resource efficiency and performance.

The core of MBassador’s high performance is a specialized data structure that provides non-blocking readers and minimizes lock contention for writers such that performance degradation of concurrent read/write access is minimal.

  • Annotation driven
  • Delivers everything, respects type hierarchy
  • Synchronous and asynchronous message delivery
  • Configurable reference types
  • Message filtering
  • Enveloped messages
  • Handler priorities
  • Custom error handling
  • Extensibility
// Define your listener
class SimpleFileListener{
    @Handler
    public void handle(File msg){
      // do something with the file
    }
}

// somewhere else in your code
MBassador bus = new MBassador();
Object listener = new SimpleFileListener();
bus.subscribe (listener);
bus.post(new File("/tmp/smallfile.csv")).now();
bus.post(new File("/tmp/bigfile.csv")).asynchronously();

GitHub, Javadoc

Project Lombok

Uses annotation to reduce repetitive code in your Java such as getters setters, not null checks, generated Builder and etc.

  • val - Finally! Hassle-free final local variables.
  • @NonNull - or: How I learned to stop worrying and love the NullPointerException.
  • @Cleanup - Automatic resource management: Call your close() methods safely with no hassle.
  • @Getter / @Setter - Never write public int getFoo() {return foo;} again.
  • @ToString - No need to start a debugger to see your fields: Just let Lombok generate a toString for you!
  • @EqualsAndHashCode - Equality made easy: Generates hashCode and equals implementations from the fields of your object.
  • @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor - Constructors made to order: Generates constructors that take no arguments, one argument per final / non-null field, or one argument for every field.
  • @Data - All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor!
  • @Value - Immutable classes made very easy.
  • @Builder - … and Bob’s your uncle: No-hassle fancy-pants APIs for object creation!
  • @SneakyThrows - To boldly throw checked exceptions where no one has thrown them before!
  • @Synchronized - synchronized done right: Don’t expose your locks.
  • @Getter(lazy=true) Laziness is a virtue!
  • @Log - Captain’s Log, stardate 24435.7: “What was that line again?”

GitHub, Website

Simple Logging Facade for Java

The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end-user to plug in the desired logging framework at deployment time.

In short, libraries and other embedded components should consider SLF4J for their logging needs because libraries cannot afford to impose their choice of logging framework on the end-user. On the other hand, it does not necessarily make sense for stand-alone applications to use SLF4J. Stand-alone applications can invoke the logging framework of their choice directly. In the case of logback, the question is moot because logback exposes its logger API via SLF4J.

Website, GitHub, FAQ

JUnitParams

Parameterized tests that don’t suck

       @Test
       @Parameters({"17, false", 
                    "22, true" })
       public void personIsAdult(int age, boolean valid) throws Exception {
         assertThat(new Person(age).isAdult(), is(valid));
       }

Main differences to standard JUnit Parametrised runner:

  • More explicit - params are in test method params, not class fields
  • Less code - you don’t need a constructor to set up parameters
  • You can mix parametrised with non-parametrised methods in one class
  • Params can be passed as a CSV string or from a parameters provider class
  • Parameters provider class can have as many parameters providing methods as you want so that you can group different cases
  • You can have a test method that provides parameters (no external classes or statics anymore)
  • You can see actual parameter values in your IDE (in JUnit’s Parametrised it’s only consecutive numbers of parameters):

Website, GitHub, Quickstart

Mockito

Tasty mocking framework for unit tests in Java

 //You can mock concrete classes, not just interfaces
 LinkedList mockedList = mock(LinkedList.class);

 //stubbing
 when(mockedList.get(0)).thenReturn("first");
 when(mockedList.get(1)).thenThrow(new RuntimeException());

 //following prints "first"
 System.out.println(mockedList.get(0));

 //following throws runtime exception
 System.out.println(mockedList.get(1));

 //following prints "null" because get(999) was not stubbed
 System.out.println(mockedList.get(999));

 //Although it is possible to verify a stubbed invocation, usually it's just redundant
 //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
 //If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See here.
 verify(mockedList).get(0);

Website, GitHub, Documentation

Jukito

The combined power of JUnit, Guice, and Mockito. Plus it sounds like a cool martial art.

  • Greatly reduces boilerplate via automocking, leading to easier to read tests
  • Leads to tests that are more resilient to API changes in the tested objects
  • Fields annotated with @Inject are automatically injected, no risk to forget them
  • Makes it easy to wire objects together, so you can scale a unit test to a partial integration test
@RunWith(JukitoRunner.class)
public class EmailSystemTest {

  @Inject EmailSystemImpl emailSystem;
  Email dummyEmail;

  @Before
  public void setupMocks(
      IncomingEmails incomingEmails,
      EmailFactory factory) {
    dummyEmail = factory.createDummy();
    when(incomingEmails.count()).thenReturn(1);
    when(incomingEmails.get(0)).thenReturn(dummyEmail);
  }

  @Test
  public void shouldFetchEmailWhenStarting(
      EmailView emailView) {
    // WHEN
    emailSystem.start();

    // THEN
    verify(emailView).addEmail(dummyEmail);
  }
}

GitHub, Website

Awaitility

Awaitility is a small Java DSL for synchronizing asynchronous operations.

Testing asynchronous systems is hard. Not only does it require handling threads, timeouts and concurrency issues, but the intent of the test code can be obscured by all these details. Awaitility is a DSL that allows you to express expectations of an asynchronous system in a concise and easy to read manner.

@Test
public void updatesCustomerStatus() throws Exception {
    // Publish an asynchronous event:
    publishEvent(updateCustomerStatusEvent);
    // Awaitility lets you wait until the asynchronous operation completes:
    await().atMost(5, SECONDS).until(customerStatusIsUpdated());
    ...
}

GitHub, Getting started, User guide

Spock

The Enterprise-ready testing and specification framework.

class HelloSpockSpec extends spock.lang.Specification {
  def "length of Spock's and his friends' names"() {
    expect:
    name.size() == length

    where:
    name     | length
    "Spock"  | 5
    "Kirk"   | 4
    "Scotty" | 6
  }
}  

GitHub, Website

WireMock

A tool for mocking HTTP services

  • HTTP response stubbing, matchable on URL, header and body content patterns
  • Request verification
  • Runs in unit tests, as a standalone process or as a WAR app
  • Configurable via a fluent Java API, JSON files and JSON over HTTP
  • Record/playback of stubs
  • Fault injection
  • Per-request conditional proxying
  • Browser proxying for request inspection and replacement
  • Stateful behavior simulation
  • Configurable response delays
{
    "request": {
        "method": "GET",
        "url": "/some/thing"
    },
    "response": {
        "status": 200,
        "statusMessage": "Everything was just fine!"
    }
}

GitHub, Website

Thanks

Thanks for reading!