Feed aggregator

Happy Packaging!

Javalobby Syndicated Feed - Thu, 21-Dec-17 01:01

Creating packages, assigning classes to packages, and creating a package hierarchy is usually not a top priority in software design. This, however, presents a missed opportunity to make your design more readable and maintainable. This article helps you take your Java class packaging skills to the next level, and not just for the holiday season.

Packages as Namespaces

The very first and basic usage for packages is to have them as namespaces for projects. Each project, module, or library lives in its own naming scheme, which makes all classes they contain uniquely named among all projects of the world, which enables a global marketplace of libraries like the Maven Central Repository.

Categories: Java

Secure Your Spring Boot Web App With Single Sign-on From Okta

Javalobby Syndicated Feed - Wed, 20-Dec-17 22:01

You can spin up an enterprise-quality REST server with complete user identity and authorization management in less than 20 minutes, with Spring Boot and Okta. Spring Boot and its Starter packages supply the production-ready Tomcat server, and Okta secures your APIs with OAuth. This tutorial walks you through the complete process. Once you’ve got Okta online, it’s easy to also add fully featured client authentication and user administration with just a few lines of code and config! Also in this tutorial, I’ll show you how your secured Spring Boot server will be able to serve web content or function as a backend API, but only to users who have registered with you. Ready? Let’s go!

This post assumes some basic familiarity with Java, including an understanding of a typical Java project structure, packages, JAR files, annotations, generics, etc. No prior use of Spring, Maven, or any other Java framework is necessary.

Categories: Java

Design Gotchas in the JDK's Functional Interfaces

Javalobby Syndicated Feed - Wed, 20-Dec-17 14:01

Because of a course I prepared, I recently had a closer look at the java.util.function package in JDK 8 and discovered a couple of interesting design choices.

Callable Is Not a Supplier

Their respective definitions are:

Categories: Java

IntelliJ IDEA 2017.3: New Preview Panel for SVG Editor and Multiple Soft Limits

Javalobby Syndicated Feed - Wed, 20-Dec-17 10:01

The release of IntelliJ IDEA 2017.3 is just around the corner. And we have some more features that we would like to tell you about. Check them out!

Multiple Soft Limits

In IntelliJ IDEA in the Editor, there is a guideline that indicates a suggested maximum line length, so the code is hard wrapped to the Right margin while typing or after Code Reformatting. We have enhanced this feature in IntelliJ IDEA 2017.3 — now you can add multiple soft limits. This lets you сonfigure several visual guides that will help control the width of the code.

Categories: Java

Intro to Spring Cloud Config Server

Javalobby Syndicated Feed - Wed, 20-Dec-17 04:01

In this tutorial, we will review the basics of Spring Cloud Config Server. We will set up a Config Server and then build a client application that consumes the configuration on startup and then refreshes the configuration without restarting. The application we are building is the same “Hello World” application discussed in the Centralized Configuration Getting Started Guide, but we go into more depth about the concepts of Spring Cloud Config Server in this article.

The full source code for the tutorial is on GitHub.

Categories: Java

What to Expect in Java JDK 10

Javalobby Syndicated Feed - Wed, 20-Dec-17 01:01

As we are just getting used to the release of Java 9 from September, we only have a few more months to go before the next generation of Java comes out. Just this month, the planned Java Development Kit 10 upgrade has moved into a major rampdown phase of development. In the first initial phase, 1-3 bugs can be fixed.

JDK 10, the implementation of Java Standard Edition 10, is due for gold release (production) on March 20, 2018. The key improvements that were proposed include a local type reference and a clean interface for garbage collection.

Categories: Java

Stretch the Old Rules, Please

Javalobby Syndicated Feed - Tue, 19-Dec-17 22:01

In my programming career, I heard plenty discussions about single vs. multiple return statements in methods. In the past, I was sure that single exit was the only valid way, which led me to one return per method. Now, I still think that a single exit point is good, but the meaning of it is completely different for me.

In the original definition, which is "A function should have one point of entry and one point of exit," we have two hidden rules. In modern OOP languages like Java, it is hard to imagine that you can start your method from the middle, so the first rule is quite outdated (in older languages, you can use "goto" or something like "jump"), so we should cut this rule into "A function should have one point of exit."

Categories: Java

Organizing Resource Files for Tests Using Maven and Java

Javalobby Syndicated Feed - Tue, 19-Dec-17 01:01

Resources are a very useful concept in Java. They are essentially files in projects that are compiled into your JAR. Java also has commands for finding them (.getResource) and reading them (.getResourceAsStream). Very Handy. But they can be hard to wrap your head around, as evidenced by my own experiences trying to use them and the number of queries on StackOverflow.

What Is a Resource?

A resource is a file in the class path folder structure for your project.

Categories: Java

Running an Infinispan server using Testcontainers

codecentric Blog - Mon, 18-Dec-17 23:00

Recently I discovered a library called Testcontainers. I already wrote about using it on my current project here. It helps you run software that your application depends on in a test context by providing an API to start docker containers. It’s implemented as a JUnit 4 rule currently, but you can also use it manually with JUnit 5. Native support for JUnit 5 is on the roadmap for the next major release. Testcontainers comes with a few pre-configured database- and selenium-containers, but most importantly it also provides a generic container that you can use to start whatever docker image you need to.

In my project we are using Infinispan for distributed caching. For some of our integration tests caching is disabled, but others rely on a running Infinispan instance. Up until now we have been using a virtual machine to run Infinispan and other software on developer machines and build servers. The way we are handling this poses a few problems and isolated Infinispan instances would help mitigate these. This post shows how you can get Infinispan running in a generic container. I’ll also try to come up with a useful abstraction that makes running Infinispan as a test container easier.

Configuring a generic container for Infinispan

Docker Hub provides a readymade Infinispan image: jboss/infinispan-server. We’ll be using the latest version at this time, which is 9.1.3.Final. Our first attempt to start the server using Testcontainers looks like this:

public static GenericContainer infinispan =
      new GenericContainer("jboss/infinispan-server:9.1.3.Final");

public void setup(){
    cacheManager = new RemoteCacheManager(new ConfigurationBuilder()
public void should_be_able_to_retrieve_a_cache() {

private String getServerAddress() {
    return infinispan.getContainerIpAddress() + ":" 
        + infinispan.getMappedPort(11222);

You can see a few things here:

  1. We’re configuring our test class with a class rule that will start a generic container. As a parameter, we use the name of the infinispan docker image alongside the required version. You could also use latest here.
  2. There’s a setup method that creates a RemoteCacheManager to connect to the Infinispan server running inside the docker container. We extract the network address from the generic container and retrieve the container IP address and the mapped port number for the hotrod port in getServerAddress()
  3. Then there’s a simple test that will make sure we are able to retrieve an unnamed cache from the server.

Waiting for Infinispan

If we run the test, it doesn’t work and throws a TransportException, though. It mentions an error code that hints at a connection problem. Looking at other pre-configured containers, we see that they have some kind of waiting strategy in place. This is important so that the test only starts after the container has fully loaded. The PostgreSQLContainer waits for a log message, for example. There’s other wait strategies available and you can implement your own, as well. One of the default strategies is the HostPortWaitStrategy and it seems like a straightforward choice. With the Infinispan image at least, it doesn’t work though: one of the commands that is used to determine the readiness of the tcp port has a subtle bug in it and the other relies on the netcat command line tool being present in the docker image. We’ll stick to the same approach as the PostgreSQLContainer rule and check for a suitable log message to appear on the container’s output. We can determine a message by manually starting the docker container on the command line using:

docker run -it jboss/infinispan-server:9.1.3.Final.

The configuration of our rule then changes to this:

public static GenericContainer container =
    new GenericContainer("jboss/infinispan-server:9.1.3.Final")
      .waitingFor(new LogMessageWaitStrategy()
         .withRegEx(".*Infinispan Server.*started in.*\\s"));

After this change, the test still doesn’t work correctly. But at least it behaves differently: It waits for a considerable amount of time and again throws a TransportException before the test finishes. Since the underlying TcpTransportFactory swallows exceptions on startup and returns a cache object anyway, the test will still be green. Let’s address this first. I don’t see a way to ask the RemoteCacheManager or the RemoteCache about the state of the connection, so my approach here is to work with a timeout:

private ExecutorService executorService = Executors.newCachedThreadPool();

public void should_be_able_to_retrieve_a_cache() throws Exception {
    Future> result = 
             executorService.submit(() -> cacheManager.getCache());
    assertNotNull(result.get(1500, TimeUnit.MILLISECONDS));

The test will now fail should we not be able to retrieve the cache within 1500 milliseconds. Unfortunatly, the resulting TimeoutException will not be linked to the TransportException, though. I’ll take suggestions for how to better write a failing test and leave it at that, for the time being.

Running Infinispan in standalone mode

Looking at the stacktrace of the TransportException we see the following output:

INFO: ISPN004006: localhost:33086 sent new topology view (id=1, age=0) containing 1 addresses: []
Dez 14, 2017 19:57:43 AM org.infinispan.client.hotrod.impl.transport.tcp.TcpTransportFactory updateTopologyInfo
INFO: ISPN004014: New server added(, adding to the pool.

It looks like the server is running in clustered mode and the client gets a new server address to talk to. The IP address and port number seem correct, but looking more closely we notice that the hotrod port 11222 refers to a port number inside the docker container. It is not reachable from the host. That’s why Testcontainers gives you the ability to easily retrieve port mappings. We already use this in our getServerAddress() method. Infinispan, or rather the hotrod protocol, however is not aware of the docker environment and communicates the internal port to the cluster clients overwriting our initial configurtation.

To confirm this analysis we can have a look at the output of the server when we start the image manually:

19:12:47,368 INFO [org.infinispan.remoting.transport.jgroups.JGroupsTransport] (MSC service thread 1-6) ISPN000078: Starting JGroups channel clustered
19:12:47,371 INFO [org.infinispan.CLUSTER] (MSC service thread 1-6) ISPN000094: Received new cluster view for channel cluster: [9621833c0138|0] (1) [9621833c0138]
Dez 14, 2017 19:12:47,376 AM org.infinispan.client.hotrod.impl.transport.tcp.TcpTransportFactory updateTopologyInfo
INFO: ISPN004016: Server not in cluster anymore(localhost:33167), removing from the pool.

The server is indeed starting in clustered mode and the documentation on Docker Hub also confirms this. For our tests we need a standalone server though. On the command line we can add a parameter when starting the container (again, we get this from the documentation on Docker Hub):

$ docker run -it jboss/infinispan-server:9.1.3.Final standalone

The output now tells us that Infinispan is no longer running in clustered mode. In order to start Infinispan as a standalone server using Testcontainers, we need to add a command to the container startup. Once more we change the configuration of the container rule:

public static GenericContainer container =
    new GenericContainer("jboss/infinispan-server:9.1.3.Final")
      .waitingFor(new LogMessageWaitStrategy()
         .withRegEx(".*Infinispan Server.*started in.*\\s"))

Now our test now has access to an Infinispan instance running in a container.

Adding a specific configuration

The applications in our project use different caches, these can be configured in the Infinispan standalone configuration file. For our tests, we need them to be present. One solution is to use the .withClasspathResourceMapping() method to link a configuration file from the (test-)classpath into the container. This configuration file contains the cache configurations. Knowing the location of the configuration file in the container, we can once again change the testcontainer configuration:

public static GenericContainer container =
    new GenericContainer("jboss/infinispan-server:9.1.3.Final")
      .waitingFor(new LogMessageWaitStrategy()
         .withRegEx(".*Infinispan Server.*started in.*\\s"))

public void should_be_able_to_retrieve_a_cache() throws Exception {
    Future> result = 
         executorService.submit(() -> cacheManager.getCache("testCache"));
    assertNotNull(result.get(1500, TimeUnit.MILLISECONDS));

Now we can retrieve and work with a cache from the Infinispan instance in the container.

Simplifying the configuration

You can see how it can be a bit of a pain getting an arbitrary docker image to run correctly using a generic container. For Infinispan we now know what we need to configure. But I really don’t want to think of all this every time I need an Infinispan server for a test. However, we can create our own abstraction similar to the PostgreSQLContainer. It contains the configuration bits that we discovered in the first part of this post and since it is an implementation of a GenericContainer, we can also use everything that’s provided by the latter.

public class InfinispanContainer extends GenericContainer {

  private static final String IMAGE_NAME = "jboss/infinispan-server";

  public InfinispanContainer() {
    this(IMAGE_NAME + ":latest");

  public InfinispanContainer(final String imageName) {
    waitingFor(new LogMessageWaitStrategy().withRegEx(".*Infinispan Server.*started in.*\\s"));


In our tests we can now create an Infinispan container like this:

public static InfinispanContainer infinispan = new InfinispanContainer();

That’s a lot better than dealing with a generic container.

Adding easy cache configuration

You may have noticed that I left out the custom configuration part here. We can do better by providing builder methods to create caches programatically using the RemoteCacheManager. Creating a cache is as easy as this:

cacheManager.administration().createCache("someCache", null);

In order to let the container automatically create caches we facilitate the callback method containerIsStarted(). We can overload it in our abstraction, create a RemoteCacheManager and use its API to create caches that we configure upfront:

private RemoteCacheManager cacheManager;
private Collection cacheNames;

public InfinispanContainer withCaches(final Collection cacheNames) {
    this.cacheNames = cacheNames;
    return this;

protected void containerIsStarted(final InspectContainerResponse containerInfo) {
    cacheManager = new RemoteCacheManager(new ConfigurationBuilder()

    this.cacheNames.forEach(cacheName -> 
        cacheManager.administration().createCache(cacheName, null));

public RemoteCacheManager getCacheManager() {
    return cacheManager;

You can also retrieve the CacheManager from the container and use it in your tests.
There’s also a problem with this approach: you can only create caches through the API if you use Hotrod protocol version 2.0 or above. I’m willing to accept that as it makes the usage in test really comfortable:

public static InfinispanContainer infinispan =
      new InfinispanContainer()

public void should_get_existing_cache() {

If you need to work with a protocol version below 2.0, you can still use the approach from above, linking a configuration file into the container.


While it sounds very easy to run any docker image using Testcontainers, there’s a lot of configuration details to know, depending on the complexity of the software that you need to run. In order to effectivly work with such a container, it’s a good idea to encapsulate this in your own specific container. Ideally, these containers will end up in the Testcontainers repository and others can benefit of your work as well.
I hope this will be useful for others, if you want to see the full code, have a look at this repository.

The post Running an Infinispan server using Testcontainers appeared first on codecentric AG Blog.

Categories: Agile, Java, TDD & BDD

Spring Boot as a Windows Service in 5 Minutes

Javalobby Syndicated Feed - Mon, 18-Dec-17 14:01

I recently had to deploy a Spring Boot application as a Windows service and am surprised how easy it was using winsw. I’d previously written about using procrun – Java Programs as Windows Services, but winsw is much easier

Getting Started

 Section 59 of the Spring Boot documentation is about Installing Spring Boot applications, and it points you toward a GitHub page. This example uses that project for inspiration.

Categories: Java

JAX-RS List Generic Type Erasure

Javalobby Syndicated Feed - Mon, 18-Dec-17 10:01

Want to maintain a List's generic type? The problem is that when you want to return a List from a JAX-RS resource method, the generic type is lost.

The following code results in type loss:

Categories: Java

Java 9 on Java EE 8 Using Eclipse and Open Liberty

Javalobby Syndicated Feed - Mon, 18-Dec-17 08:52

I wrote a post a few weeks ago titled Which IDE’s and Server’s support Java EE 8 and Java 9, which looked at the current state of play between Java 9 and Java EE 8. As you would expect things have moved quickly and we now have some alpha and development builds supporting Java 9 and Java EE 8. These are –

Adam Bein posted a video, Java EE 8 on Java 9, on how to deploy a Java 9 application on Open Liberty using netbeans. It's a great video and worth a look.

Categories: Java

10 Tricky Interview Questions for Java Devs

Javalobby Syndicated Feed - Mon, 18-Dec-17 04:01

Here is a list of 10 tricky/popular interview questions and answers for Java developers. I got these questions out from StackOverflow. You are a junior or intermediate level Java developer and are planning to appear for interviews in the near future, you would probably find these questions to be useful enough.

Q1: Is Java “pass-by-reference” or “pass-by-value”?

Categories: Java

OOP Concept for Beginners: What Is Abstraction?

Javalobby Syndicated Feed - Mon, 18-Dec-17 01:01

<!-- Google Tag Manager (noscript) --> <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-PDSRGWC" height="0" width="0" style="display:none;visibility:hidden"></iframe>

Abstraction is one of the key concepts of object-oriented programming (OOP) languages. Its main goal is to handle complexity by hiding unnecessary details from the user. That enables the user to implement more complex logic on top of the provided abstraction without understanding or even thinking about all the hidden complexity.

Categories: Java

Refactoring Algorithmic Code using a Golden Master Record

codecentric Blog - Sun, 17-Dec-17 23:00


There are days when I find a piece of code I simply have to refactor. Sometimes because I actually have to for project-related reasons, sometimes because it’s easy to, and sometimes because I just want to. One definition of a nice day is when all these reasons meet.

Enter the Portuguese tax number verification.

For those who don’t know, in most countries the tax number has one or more check digits which are calculated according to some algorithm the country’s legislators think is up for the task. If you have a frontend where customers enter tax numbers, it’s a good first step to actually check the validity of the number according to the check digit in order to provide fast feedback to the user.

Usually I don’t do the research on the algorithms we implement for this myself. Someone else on my team calls someone from the country in the same organization and we code monkeys usually get code snippets, such as this one. In this case I got curious. The portuguese wiki contains a nice explanation of the check digit algorithm, which is a variation of an algorithm called (according to google) the modulus 11 check digit algorithm.

  • Implementing this from scratch probably would have been straightforward, but I decided to refactor for several reasons:
    Sometimes web sources can be wrong. Take, for example, this community wiki: Here they seem to have forgotten about a part of the algorithm. If this had been my first source, I’d have had a bug report. Thus I usually try to stay near the scripts my customers provide me with.
  • Refactoring this very isolated piece of code would be easy.
  • Sometimes the scripts we get from our colleagues contain a little bit of extra logic which make sense in the context where we use them. In this one, for example, I was told to “just don’t worry about the extra cases at the beginning. We are not interested in these and it’s okay to delete them.”

Side note: For the purposes of this exercise, I used ES6 transpiled with Babel. For my tests, I use mocha and chai.

Enough introduction! Let’s have a look at:

The Code

I admit I did a tiny bit of untested refactoring first: Returning true or false instead of an alert, exporting the function and deleting the, as per our definition unnecessary, lines.

export function validaContribuinte(contribuinte) {
// algoritmo de validação do NIF de acordo com
// http://pt.wikipedia.org/wiki/N%C3%BAmero_de_identifica%C3%A7%C3%A3o_fiscal
    let comparador;
    var temErro = 0;

    var check1 = contribuinte.substr(0, 1) * 9;
    var check2 = contribuinte.substr(1, 1) * 8;
    var check3 = contribuinte.substr(2, 1) * 7;
    var check4 = contribuinte.substr(3, 1) * 6;
    var check5 = contribuinte.substr(4, 1) * 5;
    var check6 = contribuinte.substr(5, 1) * 4;
    var check7 = contribuinte.substr(6, 1) * 3;
    var check8 = contribuinte.substr(7, 1) * 2;

    var total = check1 + check2 + check3 + check4 + check5 + check6 + check7 + check8;
    var divisao = total / 11;
    var modulo11 = total - parseInt(divisao) * 11;
    if (modulo11 == 1 || modulo11 == 0) {
        comparador = 0;
    } // excepção
    else {
        comparador = 11 - modulo11;

    var ultimoDigito = contribuinte.substr(8, 1) * 1;
    if (ultimoDigito != comparador) {
        temErro = 1;

    if (temErro == 1) {
        return false;
    return true;

Where to start

The first thing you want to do when you refactor code is have unit tests for the code. Since most code to refactor is hard to understand, a lot of people prefer to not even try and rather create a Golden Master test. A detailed explanation as well as a walkthrough in Java can be found here.

Creating a Golden Master

So the steps to creating a Golden Master test are:

  1.  Create a number of random inputs for your testee
  2. Use these inputs to generate a number of outputs
  3. Record the inputs and outputs.

Why are we doing this?

If the number of random inputs is high enough, it’s very probable that we have all test cases in there somewhere. If we capture the state of the testee before we start changing anything, we can be sure we won’t break anything later.

There’s one thing I want to say now: A Golden Master record should in most cases be only a temporary solution. You do not really want files or databases full of randomly generated crap to clog your server, and you don’t want long-running tests with way too many redundant test cases on your CI server.

Step 1: Create A Number Of Random Inputs

For this, we have to actually look at the code to be refactored. A quick glance says: “This function takes strings of length 9 which contain only digits as valid input”.

My first instinct was to try and calculate all of them. After a few frustrating minutes which I spent discussing with my computer’s memory, I did a small back-of-an-envelope calculation (16 Bit x 9 x 899999999 > 15 TB). So this turned out to be a Bad Idea™.

The next best thing was to create some random numbers between 100000000 and 99999999. After a bit of experimentation, because I “have no idea of the algorithm” for the purpose of this exercise, I settled on 10000 random fake tax numbers, which corresponded to three seconds overall test runtime on my machine. The code to generate these is wrapped in a testcase for easy access (remember, this is temporary):

describe('validatePortugueseTaxNumber', () => {
    describe('goldenMaster', () => {
        it('should generate a golden master', () => {
            const gen = random.create('My super Golden Master seed'),
                expectedResultsAndInputs = [ ...new Array(1000000) ].map(() => {
                    const input = gen.intBetween(100000000, 999999999),

Side note: It is often recommended to use a seedable random generator. Since at that point I was not sure whether I wanted to actually save the inputs or not, I ended up using this PRNG. It’s not strictly necessary for this exercise, though.

Step 2: Use These Inputs To Generate A Number Of Outputs.

Just call the function.

    const input = gen.intBetween(100000000, 999999999),
        result = validaContribuinte(input.toString(10));

        return { input, result };

Step 3: Record The Inputs And Outputs

This also was pretty straightforward. I used the built-in mechanisms of node.js to write the output to a ~3.5MB file.

fs.writeFileSync('goldenMaster.json', JSON.stringify(expectedResultsAndInputs));

And just like that, a Golden Master was created.

Create a test based on the Golden Master

The next step is to use the Golden Master in a test case. For each input, the corresponding output has to correlate to the file.
My test looks like this:

it('should always conform to golden master test', () => {
    const buffer = fs.readFileSync('goldenMaster.json'),
    data = JSON.parse(buffer);

    data.map(({ input, result }) => {
        return expect(validaContribuinte(nextNumber.toString(10))).to.equal(result);

Side note: I stopped running the Golden Master generation every time; even though it would never produce different results unless the seed changed, it would’ve been a waste of resources to run every time.

I ran this a couple of times just for the heck of it. Then I started playing around with the code under test, deleting a line here, changing a number there, until I was confident that my Golden Master was sufficiently capturing all the cases. I encourage you to do this, it’s one of the very few times that you get to be happy about red tests.

golden master record

I was not really satisfied with the output yet. “expected false to equal true” in which case, exactly? Again, in this simple case it would probably not have been necessary, but sometimes it can be useful to also record the failing input. So, after some refactoring, this happened:

data.map(expectedResult => {
    const { input } = expectedResult;
    const result = validatePortugueseTaxNumber(input.toString(10));

    return expect({ input, result}).to.deep.equal(expectedResult);


The refactoring itself was pretty straightforward. For the sake of brevity, most of the steps are skipped in this post.
Renaming the function and a few variables:

export function validatePortugueseTaxNumber(taxNumber) {
// algoritmo de validação do NIF de acordo com
// http://pt.wikipedia.org/wiki/N%C3%BAmero_de_identifica%C3%A7%C3%A3o_fiscal
    let comparator;
    let checkDigitWrong = 0;

    const check1 = taxNumber.substr(0, 1) * 9;
    const check2 = taxNumber.substr(1, 1) * 8;
    const check3 = taxNumber.substr(2, 1) * 7;
    const check4 = taxNumber.substr(3, 1) * 6;
    const check5 = taxNumber.substr(4, 1) * 5;
    const check6 = taxNumber.substr(5, 1) * 4;
    const check7 = taxNumber.substr(6, 1) * 3;
    const check8 = taxNumber.substr(7, 1) * 2;

    const total = check1 + check2 + check3 + check4 + check5 + check6 + check7 + check8;
    const divisao = total / 11;
    const modulo11 = total - parseInt(divisao) * 11;
    if (modulo11 == 1 || modulo11 == 0) {
        comparator = 0;
    else {
        comparator = 11 - modulo11;

    const ultimoDigito = taxNumber.substr(8, 1) * 1;
    if (ultimoDigito != comparator) {
        checkDigitWrong = 1;

    if (checkDigitWrong == 1) {
        return false;
    return true;

Simplifying (a lot):

export function validatePortugueseTaxNumber(taxNumber) {
    const checkSumMod11 = taxNumber.substr(0,8)
                                       (digit, index) => {
                                       return parseInt(digit, 10) * (9 - index);
                                   .reduce((a, b) => a + b) % 11,
          comparator = checkSumMod11 > 1? 11 - checkSumMod11 : 0;

    return parseInt(taxNumber.substr(8, 1), 10) === comparator;

This is where I stopped.

Writing unit tests

By now I had a better understanding of what my piece of code did. And, as was said above, it’s a good idea to get rid of a golden master, so the time had come to think about valid test inputs.

Apparently a remainder of 0 and 1 was important. To this, I added the edge case of remainder 10, and some remainder in the middle range just to be sure. As for generating the corresponding inputs, I cheated a little:

if (checkSumMod11 === 0 && lastDigit === comparator) {

Using this generator function, I created the final unit tests for the portugueseTaxNumberValidator:

describe('validatePortugueseTaxNumber', () => {
    it('should return false for 520363144 (case checkSum % 11 === 0) ', () => {

    it('should return false for 480073977 (case checkSum % 11 === 1) ', () => {

    it('should return false for 291932333 (case checkSum % 11 === 2) ', () => {

    it('should return false for 872711478 (case checkSum % 11 === 10) ', () => {

    it('should return true for 504917951 (case checkSum % 11 === 0) ', () => {

    it('should return true for 850769990 (case checkSum % 11 === 2) ', () => {

    it('should return true for 504917951 (case checkSum % 11 === 10) ', () => {


Creating a Golden Master and using it during refactoring feels like you’re wrapped in a big, fluffy cotton ball. If the Golden Master record is detailed enough, nothing can go wrong. Or rather, if it does, you will notice in an instant. There are no qualms about deleting code, replacing it with something you think will do the same, because it’s a safe experiment. It was a fun exercise and I would do it again in an instant.

The post Refactoring Algorithmic Code using a Golden Master Record appeared first on codecentric AG Blog.

Categories: Agile, Java, TDD & BDD

Spring Component Scan

Javalobby Syndicated Feed - Sun, 17-Dec-17 22:01

When developing Spring Boot applications, you need to tell the Spring Framework where to look for Spring components. Using component scan is one method of asking Spring to detect Spring-managed components. Spring needs the information to locate and register all the Spring components with the application context when the application starts.

Spring can auto scan, detect, and instantiate components from pre-defined project packages. Spring can auto scan all classes annotated with the stereotype annotations @Component, @Controller, @Service, and @Repository

Categories: Java

Java Remote Debugging in the Real World

Javalobby Syndicated Feed - Sat, 16-Dec-17 23:01

<!-- Google Tag Manager (noscript) --> <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-PDSRGWC" height="0" width="0" style="display:none;visibility:hidden"></iframe>

Troubleshooting a problem on a remote server, especially in production, is not an easy task. Sometimes it involves debugging the application code directly on the server.

Categories: Java

A Common Mistake When Caching Nullable Values

Javalobby Syndicated Feed - Fri, 15-Dec-17 23:01

Caching is hard in various ways. Whenever you’re caching things, you have to at least think of:

  • Memory consumption
  • Invalidation

In this article, I want to show a flaw that often sneaks into custom cache implementations, making them inefficient for some execution paths. I’ve encountered this flaw in Eclipse, recently.

Categories: Java

Spring Boot Developer Tools and LiveReload

Javalobby Syndicated Feed - Fri, 15-Dec-17 14:01

When we develop web applications with Java, we have to restart the server to pick up all our changes. This kills productivity. Spring Boot Developers Tools provides solutions to automatically pick up changes without a complete server restart. Let's get productive with Spring Boot Developer Tools.

You Will Learn

  • How to use Spring Boot Developer Tools
  • What kind of changes Spring Boot Developer Tools picks up automatically
  • How you can use Live Reload to be more productive

The Problem With Server Restarts

When we develop our applications (web or RESTful API), we want to be able to test our changes quickly.

Categories: Java

IntelliJ IDEA 2017.3: JUnit Support

Javalobby Syndicated Feed - Fri, 15-Dec-17 10:01

The JUnit 5 testing framework was released on September 10. However, IntelliJ IDEA has had support for JUnit 5 for quite some time, and the latest version, 2017.3, provides even more goodies — inspections and quick fixes to make it easier for you to migrate your JUnit 4 tests to JUnit 5.

Moreover, almost all inspections available for Java/JUnit have been updated and now work for JUnit 5 as well.

Categories: Java

Thread Slivers eBook at Amazon

Syndicate content