Project Lombok

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

Project Lombok webpage: https://projectlombok.org/

How Lombok Works

  • Hooks in via the Annotation processor API
  • The AST (raw source code) is passed to Lombok for code generation before java continues.
  • Thus, produces properly compiled Java code in conjunction with the Java compiler

Project Lombok and IDEs

  • Since compiled code is changed, and source files are not, IDE’s can get confused by this.
  • Modern IDEs such as IntelliJ, Eclipse, Netbeans support Project Lombok
  • Plugin Installation may be necessary

Project Lombok Features

  • @Getter – Creates getter methods for all properties
  • @Setter – Creates setter for all non-final properties
  • @ToString – Generates String of classname, and each field separated by commas; Optional parameter to include field names; Optional parameter to include the call to the super toString method
  • @EqualsAndHashCode – Generates implementations of ‘equals(Object other) and hashCode(); By default will use all non-static, non-transient properties; Can optionally exclude specific properties.
  • @NoArgsConstructor – Generates no-args constructor; Will cause compiler error if there are final fields; Can optionally force, which will initialize final fields with 0 / false / null
  • @RequiredArgsContructor – Generates a constructor for all fields that are final or marked @NonNull; Constructor will throw a NullPointerException if any @NonNull fields are null.
  • @Data – Generates typical boilerplate code for POJOs, Combines – @Getter, @Setter, @ToString, @EqualsAndHashCode, @RequiredArgsConstructor; No constructor is generated if constructors have been explicitly declared.
  • @Value – The immutable variant of @Data; All fields are made private and final by default.
  • @NotNull – Set on a parameter of method or constructor and a NullPointerException will be thrown if the parameter is null.
  • @Builder – Implements the ‘builder’ pattern for object creation.
  • @SneakyThrows – Throw checked exceptions without declaring in calling method’s throws clause.
  • @Syncronized – A safer implementation of Java’s synchronized
  • @Log – Creates a Java util logger.
  • @Slf4j – Creates a SLF4J logger.

Difference between HashMap and HashSet in Java

HashSet

  1. HashSet class implements the Set interface
  2. In HashSet, we store objects(elements or values) e.g. If we have a HashSet of string elements then it could depict a set of HashSet elements: {“Hello”, “Hi”, “Bye”, “Run”}
  3. HashSet does not allow duplicate elements that mean you can not store duplicate values in HashSet.
  4. HashSet permits to have a single null value.
  5. HashSet is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly.[similarity]

HashSet example:

 

HashMap

  1. HashMap class implements the Map interface
  2. HashMap is used for storing key & value pairs. In short, it maintains the mapping of key & value (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This is how you could represent HashMap elements if it has integer key and value of String type: e.g. {1->”Hello”, 2->”Hi”, 3->”Bye”, 4->”Run”}
  3. HashMap does not allow duplicate keys however it allows having duplicate values.
  4. HashMap permits single null key and any number of null values.
  5. HashMap is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly.[similarity]

HashMap example:

 

Difference between HashSet and HashMap in Java

HashMap Hash Set
HashMap  is an implementation of Map interface HashSet is an implementation of Set Interface
HashMap Stores data in form of  key-value pair HashSet Store only objects
Put method is used to add element in map Add method is used to add element is Set
In hash map hashcode value is calculated using key object Here member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality if it returns false that means two objects are different.
HashMap is faster than HashSet because unique key is used to access object HashSet is slower than Hashmap

 

NoClassDefFoundError vs ClassNotFoundException

ClassNotFoundException and NoClassDefFoundError occur when a particular class is not found at runtime. However, they occur at different scenarios.

NoClassDefFoundError:

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

ClassNotFoundException:

Thrown when an application tries to load in a class through its string name using:

  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader.
  • The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found. For example, you may have come across this exception when you try to connect to MySQL or Oracle databases and you have not updated the classpath with required JAR files. Most of the time, this exception occurs when you try to run an application without updating the classpath with required JAR files.

ClassNotFoundException NoClassDefFoundError
It is an exception. It is of type java.lang.Exception. It is an error. It is of type java.lang.Error.
It occurs when an application tries to load a class at run time which is not updated in the classpath. It occurs when java runtime system doesn’t find a class definition, which is present at compile time, but missing at run time.
It is thrown by the application itself. It is thrown by the methods like Class.forName(), loadClass() and findSystemClass(). It is thrown by the Java Runtime System.
It occurs when classpath is not updated with required JAR files. It occurs when required class definition is missing at runtime.

 

 

Default Methods in Java 8

In this article, I’ll try to explain what are default methods in Java 8, why they are useful and how they can be used to enhance the design of your code.

Default methods are added to Java 8 largely to support library designers by enabling them to write more evolvable interfaces. Java 8 introduces “Default Method” or (Defender methods) new feature, which allows developers to add new methods to the interfaces without breaking the existing implementation of these interfaces. Default methods are non-abstract and marked by the modifier default. It provides flexibility to allow the interface define implementation which will use as default in the situation where a concrete class fails to provide an implementation for that method.

Let’s consider this piece of code to understand how it works, in this example, I’ve just added a new default method newDefaultMethod() to the existing ‘old’ interface.

An existing implementation of that interface will successfully compile without errors.

 

Why Default Method?

Reengineering an existing JDK framework is always very complex. Modify one interface in JDK framework breaks all classes that extends the interface which means that adding any new method could break millions of lines of code. Therefore, default methods have introduced as a mechanism to extending interfaces in a backwards compatible way.

Default methods can be provided to an interface without affecting implementing classes as it includes an implementation. If each added method in an interface defined with implementation then no implementing class is affected. An implementing class can override the default implementation provided by the interface.

For Java 8, the JDK collections have been extended and forEach method is added to the entire collection (which work in conjunction with lambdas).

The same mechanism has been used to add Stream in JDK interface without breaking the implementing classes.

When to Use Default Method Over Abstract Classes?

After introducing Default Method, it seems that interfaces and abstract classes are same. However, they are still a different concept in Java 8.

Abstract classes can still do more in comparison to Java 8 interfaces:

  • An abstract class can have a constructor.
  • Abstract classes are more structured and can hold a state.

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.

However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.

With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.

Conceptually, the main purpose of defender methods is a backwards compatibility after an introduction of new features (as lambda functions) in Java 8.

Are the abstract classes still useful in that scenario?

Yes. They are still useful. They can contain non-static, non-final methods and attributes (protected, private in addition to public), which is not possible even with Java-8 interfaces.

Default Method and Multiple Inheritance Ambiguity Problems.

Since java class can implement multiple interfaces and each interface can define default method with same method signature, therefore, the inherited methods can conflict with each other.

Let’s check this example:

The above code will fail to compile with the following error:

java: class Impl inherits unrelated defaults for defaultMethod() from types InterfaceA and InterfaceB

In order to fix this class, we need to provide default method implementation:

Further, if we want to invoke default implementation provided by any of super interface rather than our own implementation, we can do so as follows:

 

Difference Between Default Method and Regular Method

Default Method is different from the regular method in the sense that default method comes with default modifier. Additionally, methods in classes can use and modify method arguments as well as the fields of their class but default method, on the other hand, can only access its arguments as interfaces do not have any state.

 

In summary, Default methods enable to add new functionality to existing interfaces without breaking older implementation of these interfaces.

When we extend an interface that contains a default method, we can perform following,

  • Not override the default method and will inherit the default method.
  • Override the default method similar to other methods we override in a subclass.
  • Redeclare default method as abstract, which force a subclass to override it.

Watching a Directory for Changes

Watch Service Overview

The WatchService API is fairly low level, allowing you to customise it. You can use it as is, or you can choose to create a high-level API on top of this mechanism so that it is suited to your particular needs. The WatchService API lets you receive notification events upon changes to the subject (directory or file).

The steps involved in implementing the API are:

  • Create a WatchService. This service consists of a queue to holdWatchKeys
  • Register the directory/file you wish to monitor with this WatchService
  • While registering, specify the types of events you wish to receive (create, modify or delete events)
  • You have to start an infinite loop to listen to events
  • When an event occurs, a WatchKey is placed into the queue
  • Consume the WatchKey and invoke queries on it

Let’s follow this via an example. We create a DirWatcher Java program whose responsibility is to watch a particular directory (Downloads in my case). The steps are provided below:

1. Creating an WatchService object:

2. Obtain a path reference to your watchable directory. I suggest you parameterize this directory so you don’t hard code the file name.

3. The next step is to register the directory with the WatchService for all types of events:

When registering an object with the watch service, you specify the types of events that you want to monitor. The supported StandardWatchEventKinds event types follow:

  • ENTRY_CREATE – A directory entry is created.
  • ENTRY_DELETE – A directory entry is deleted.
  • ENTRY_MODIFY – A directory entry is modified.
  • OVERFLOW – Indicates those events might have been lost or discarded. You do not have to register for the OVERFLOW event to receive it.

4. Initiate the infinite loop and start taking the events:

 

5. Run through the events on the key:

For example, if you modify or delete the Download directory, you would see statement as shown below on the console respectively:

 

Example source code:

 

 

Simple Jersey example with Intellij IDEA Ultimate and Tomcat

Jersey

RESTful Web Services in Java.

Jersey is a reference implementation of the JAX-RS 2.0 API. Jersey provides it’s own API that extends the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and client development.

In this example I will be using:

  • IntelliJ Idea Ultimate 2016.2
  • Jersey 2.23.2 (latest stable release of Jersey as of time of writing)
  • JDK 8
  • Tomcat 8.0.35

Create new project

To create a new project, open up the New Project dialog in IntelliJ. In the left menu, select Java Enterprise. To the right, select Web Application and ensure that Create web.xml is checked.

newproject

 

Add Maven support

To add Maven to your project, right-click on your project’s name in the Project sidebar and select Add Framework Support.

In the Add Frameworks Support, select Maven.

Once this is done, the pom.xml file will open in the editor. You will need to enter at least a groupId, usually your package name. At this point, it is helpful to enable auto-importing for library dependencies.

maven

Add Jersey dependencies to the Maven pom.xml file

 

Create a Resource

Inside of the src/main/java directory, create a new package matching your groupId.

And then create a simple java class – MyResource in my case.

Modify index.jsp file by adding a link to the Jersey resource

 

Check if Tomcat is configured properly.

tomcat-configuration

tomcat-deployment

 

Configure your servlet

Modify your web.xml file

 

Before we run our application, first we need to add Jersey jars to the /WEB-INF/lib directory

add-artifacts

After selecting all jars right click and choose “Put into /WEB-INF/lib

Run your Application

jersey-resource
got-it

 

DONE!

 

 

Git for an absolute beginners

Before I started using Git on my personal and then on commercial projects, I was using for many years  Subversion – svn in short. SVN is still very popular but Git earned its strong position as well by being used in large and small projects for more than 10 years already.

Installing Git

The official website of Git has detailed information about installing on Linux, Mac, or Windows. In this case, I will be using Ubuntu 16.04 for demonstration purposes, and installing git in Linux (Ubuntu) is simple as typing:

Before we dive into configuration and will start using Git a bit of terminology introduction is necessary.

Here’s the git terminology:

  • master – the repository’s main branch. Depending on the workflow it is the one people work on or the one where the integration happens
  • clone – copies an existing git repository, normally from some remote location to your local environment.
  • commit – submitting files to the repository (the local one); in other VCS it is often referred to as “checkin”
  • fetch or pull – is like “update” or “get latest” in other VCS. The difference between fetch and pull is that pull combines both, fetching the latest code from a remote repo as well as performs the merging.
  • push – is used to submit the code to a remote repository
  • remote – these are “remote” locations of your repository, normally on some central server.
  • SHA – every commit or node in the Git tree is identified by a unique SHA key. You can use them in various commands in order to manipulate a specific node.
  • head – is a reference to the node to which our working space of the repository currently points.
  • branch – is just like in other VCS with the difference that a branch in Git is actually nothing more special than a particular label on a given node. It is not a physical copy of the files as in other popular VCS.

Initial Configuration

We need to configure our name and email. You can do it as follows, replacing the values with your own name and email.

It is important to note that if you do not set your name and email, certain default values will be used.

Create a new Git Repository

Before starting, let’s create a new directory where the git repository will be created and ‘move’ into it.

Now we can initialize our first git repository.

To check the status of our repository git status command can be used.

Create and commit a new file

The next step is to create a new file and add some content to it.

Let’s check what happen in our git repository.

To “register” the file for committing we need to add it to git using:

And again, let’s check what happen in our git repository.

 

We can now commit it to the repository.

Let’s add another file to the project.

 

Create a (feature) branch

Branching and merging is what makes Git so powerful and for what it has been optimised, being a distributed version control system (VCS). Indeed, feature branches are quite popular to be used with Git. Feature branches are created for every new kind of functionality you’re going to add to your system and they have usually deleted afterwards once the feature is merged back into the main integration branch (normally the master branch). The advantage is that you can experiment with new functionality in a separate, isolated “playground” and quickly switch back and forth to the original “master” branch when needed. Moreover, it can be easily discarded again (in case it is not needed) by simply dropping the feature branch. But let’s get started and create the new feature branch:

To see a list of all branches we need to use git branch command.

A star next to master branch indicates that this is a current branch.

Let’s switch to this newly created branch and modify one of the files.

And then add and commit it to the branch.

 

Ok, it’s time to complicate it and cause some conflicts. To do this we need to switch to ‘master’ branch and modify the blogpost.txt file.

 

If you need to commit a file that was already added to the git repository you can use command ‘commit -a -m’

Merge and resolve conflicts

The next step would be to merge our feature branch back into ‘master’. This is done by using the merge command.

Edit file and resolve conflict and commit changes to the branch.

 

Rollback

What if we want to undo everything back to the state before the commit?

First, we need to get SHA identifiers (unique ‘id’ for each node in git tree).

 

and then move back in time to the desired node/commit

 

 

And that’s it. It is everything that is needed to start using git. I have covered here only simple commands. For more advanced commands and explanations I highly recommend reading this book: Pro GIT.

JUnit – assertThat (Hamcrest) – part 1

Hamcrest is a framework for creating matcher objects. These matcher objects are predicates and are used to write rules which can be satisfied under certain conditions. They are most often used in testing. Hamcrest lets us step beyond simple JUnit asserts and enables us to craft very specific and readable verification code. Hamcrest has the target to make tests as readable as possible. In general, the Hamcrest error messages are also much easier to read. Using Hamcrest matchers also provides more type safety as these matchers uses generics.

Simple Matchers

  • any()

  • anything()

  • arrayContaining()

Does the array contain all given items in the order in which they are input to the matcher?

  • arrayContainingInAnyOrder()

Does the array contain all the given items? Length of the array must match the number of matchers, but their order is not important.

  • arrayWithSize()

Does the input array have exactly the specified length?

  • closeTo()

Matcher which can be used with either Double or BigDecimal to check if a value is within a specified error margin of an expected value.

 

 

 

 

JUnit – basics introduction

The JUnit framework

JUnit (http://junit.org/) in version 4.x is a test framework which uses annotations to identify methods that specify a test.

A unit test is a fundamental test to quickly assess whether the result of a computation can possibly go wrong or not. It is a straightforward check to verify the basis of the computation result. To define a method as a unit test, you annotate it with the @org.junit.Test annotation. You use an assert method, provided by JUnit or another assert framework, to check an expected result versus the actual result.

Recommended practice

Generally, we don’t mix production code with the test code, so unit tests are kept in the same project, but under a different directory or source folder.

In widespread use is to use the name of the class under test and to add the “Test” suffix to the test class.

As a general rule, a test name should explain what the test does. If that is done correctly, it helps to avoid reading the actual implementation.

JUnit code constructs

JUnit 4.x uses annotations to mark methods as test methods and to configure them.

The @Test annotation signifies a test. We can annotate any public method with @Test to make it a JUnit test method.

JUnit 4 defines two method-level annotations, @BeforeClass and @AfterClass, for public static methods. Being static, they get executed only once per test class. Any public static method annotated with @BeforeClass gets executed prior to the first test, and any public static method annotated with @AfterClass gets executed following the last test.

Other mostly used JUnit annotations:

@Test (expected = Exception.class) – Fails if the method does not throw the named exception.

@Before – This method is executed before each test. It is used to prepare the test environment (e.g., read input data, initialize the class).

@After – This method is executed after each test. It is used to cleanup the test environment (e.g., delete temporary data, restore defaults).

@Ignore – Sometimes you want to temporarily disable a test or a group of tests. Methods annotated with @Test that are also annotated with @Ignore will not be executed as tests. Also, you can annotate a class containing test methods with @Ignore and none of the containing tests will be executed. It is best practice to provide the optional description, why the test is disabled.

And result is:

As you probably noticed tests execution order is different from the order of test methods.By design, JUnit does not specify the execution order of test method invocations. Well-written test code would not assume any order.

From version 4.11, JUnit will by default use a deterministic, but not predictable, order(MethodSorters.DEFAULT). To change the test execution order simply annotate your test class using @FixMethodOrder and specify one of the available MethodSorters:

@FixMethodOrder(MethodSorters.JVM): Leaves the test methods in the order returned by the JVM. This order may vary from run to run.

@FixMethodOrder(MethodSorters.NAME_ASCENDING): Sorts the test methods by method name, in lexicographic order.

Assert statements

Verifying an expectation with an assertion. JUnit provides static methods to test for certain conditions via the Assertclass. These assert statementstypically start with assert . They allow you to specify the error message, the expected and the actual result. An assertion method compares the actual value returned by a test to the expected value. It throws an AssertionExceptionif the comparison fails.

Mostly used assert methods:

fail(message) – Let the method fail. Might be used to check that a certain part of the code is not reached or to have a failing test before the test code is implemented. The message parameter is optional.

assertTrue([message,] boolean condition) – Asserts that a condition is true.

assertFalse([message,] boolean condition) – Asserts that a condition is false.

assertEquals([message,] expected, actual) – Asserts that two objects are equal. If they are not, an AssertionError is thrown with the given message. If expected and actual are null, they are considered equal. For arrays the reference is checked not the content of the arrays.

assertNull([message,] object) – Checks that the object is null.

assertNotNull([message,] object) – Checks that the object is not null.

assertSame([message,] expected, actual) – Checks that both variables refer to the same object.

assertNotSame([message,] expected, actual) – Checks that both variables refer to different objects.

Examining exception handling

In a JUnit test, when a test method throws an exception, the test fails, and the test method marks the test as erroneous. We should be allowed to unit test the exceptional condition such that an API takes two objects and throws an exception if any argument is passed as null . If we pass
a null value to the API, the test fails with an error, but actually, an exception is not an error. Rather, it is desirable, and the test should fail if the API doesn’t throw an exception.

JUnit 4 provides a mechanism to handle the preceding situation.
The @Test annotation takes an expected=<<Exception class name>>.class argument.
When we annotate a test method with @Test and pass an expected exception to the annotation, but during execution, the expected exception doesn’t match the real exception thrown from the test method or the test method doesn’t throw an exception, the test fails.

This exception handling mechanism doesn’t allow you to verify the error message. JUnit 4 provides several other mechanisms that are usually considered to be better solutions, such as @Rule , an ExpectedException rule that lets you examine the message as well as the type.

Test suits

A test suite groups and executes multiple tests. To run multiple tests together, we need a test suite. To achieve this, JUnit 4 offers the Suite.class class and the @Suite.SuiteClasses annotation. This annotation accepts a comma-separated array of test classes. Add a Java class named TestSuite and annotate it with @RunWith(Suite.class). As a result, the suite runner will be responsible for executing the test class. Annotate the TestSuite class with @Suite.SuiteClasses and pass a comma-separated array of other test classes, such as ({ ClientTest.class,
ClientOrder.class, ShoppingBasket.class }) .

When we execute the TestSuite class, it, in turn, executes all the test classes passed to the @Suite.SuiteClasses annotation.

 

Spring – Conditional annotation

Spring 4 has introduced a new annotation @Conditional. It is used to develop an “If-Then-Else” type of conditional checking for bean registration. Let us see how we can use @Conditional annotation to check a property value is dev or prod from environment. For learning we will use Java based configurations in this example.

Create Project Domain class with id, name and duration properties with getters only as shown below.

Create Utility classes to represent in-memory Databases. For simplicity, we are not interacting with Databases. DevDatabaseUtil class represents DEV database and ProductionDatabaseUtil class represents PROD database with some data.

Create a ProjectDAO class to represent DAO Layer.

Now it’s time to implement Conditional checking by using@Conditional annotation. Both condition checking classes implements Spring’s Condition interface matches() method. Both Conditional classes checks for “database.name” from environment. If this values is “dev”, then DevDataSourceCondition’s matches() method returns true. Otherwise false. In the same way, if this property value is “prod”, then ProdDataSourceCondition’s matches() method returns true. Otherwise false.

Create Spring’s Java-based configuration classes

Now it’s time to write JUnits to test Spring’s @Conditional classes.