Builder in practice

In this blog post I’m going to explain how to construct a builder for constructing objects. To be clear from the beginning, what I’m going to describe is not the official builder pattern, however, in practice this is often referred to as the builder pattern nevertheless.

A builder is used to construct complex objects with many constructor parameters where some of them are optional. An alternative to handle optional parameters is the telescoping constructor pattern. For each possibility an object can be constructed, a constructor is provided. This has the drawback that it blows up the code and it is quite hard to read. From time to time, this is seen in practice and can be eliminated by bringing a builder into action. A second alternative is the JavaBeans pattern, in which a parameter-less constructor is called whereafter the properties are set via setter methods. However, this pattern has the disadvantages that the object may be in inconsistent state through its construction and it precludes the possibility to make the class immutable. Builders are by far the best approach to deal with optional parameters. Furthermore, I also have often used builders in tests to construct test objects. Builders are quite popular as it allows one to construct a fluent API.

So let’s create a builder for a Airplane object. The object has one mandatory parameter seats. Mandatory parameters  usally set directly in the constructor. Furthermore, there are two optional parameters named engine and rescue and an optional List of instruments. The builder is implemented as a static nested inner class. The constructor of the Airplane is private. Note that most IDE can generate exactly this code for you!


public final class Airplane {
private final int seats;
private final int engine;
private final int rescue;
private final List<Instrument> instruments;
private Airplane(Builder builder){
this.seats = builder.seats;
this.engine = builder.engine;
this.rescue = builder.rescue;
this.instruments = builder.instruments;
}
public static class Builder {
private final int seats;
private int engine;
private int rescue;
private List<Instrument> instruments = new ArrayList<>();
public Builder(int seats){
this.seats = seats;
}
public Builder withEngine(int engine) {
this.engine = engine;
return this;
}
public Builder withRescue(int rescue) {
this.rescue = rescue;
return this;
}
public Builder withInstrumentList(List<Instrument> instruments) {
this.instruments = instruments;
return this;
}
public Airplane build(){
return new Airplane(this);
}
}
}

view raw

Airplane.java

hosted with ❤ by GitHub

An airplane object is then constructed as follows:


List<Instrument> instruments = new ArrayList<>();
instruments.add(new Instrument("Altimeter"));
instruments.add(new Instrument("Velocity"));
Airplane airplane = new Airplane.Builder(4).withEngine(375).withRescue(2).withInstrumentList(instruments).build();

So far so good. But it would be nice if we have not to construct a list before the builder is called. It would be much more elegant if we could create the instruments list by means of the builder. In the following section we are going to dive into this problem. The goal is to construct an airplane object, that encompasses a list of instruments, as follows:


Airplane airplane = new Airplane.Builder(4).withEngine(375).withRescue(2).addList().add().withName("Altimeter").toList().add().withName("Velocity").toList().done().build();

The concept behind this construct is to have parent and child builders. There is an Instrument builder that has a ListBuilder and the ListBuilder has again a Airplane builder.

The Airplane class has just slightly changed. There were only added two method called addList. The first method gets the child builder and hands over the parent builder. The second method is just a setter which is used in the child builder.


public final class Airplane {
private final int seats;
private final int engine;
private final int rescue;
private final List<Instrument> instruments;
private Airplane(Builder builder){
this.seats = builder.seats;
this.engine = builder.engine;
this.rescue = builder.rescue;
this.instruments = builder.instruments;
}
public static class Builder {
private final int seats;
private int engine;
private int rescue;
private List<Instrument> instruments;
public Builder(int seats){
this.seats = seats;
}
public Builder withEngine(int engine) {
this.engine = engine;
return this;
}
public Builder withRescue(int rescue) {
this.rescue = rescue;
return this;
}
// get child builder and hands over parent builder
public Instrument.ListBuilder addList(){
return new Instrument.ListBuilder().setAirplaneBuilder(this);
}
public void addList(List<Instrument> instruments){
this.instruments = instruments;
}
public Airplane build(){
return new Airplane(this);
}
}
}

view raw

Airplane.java

hosted with ❤ by GitHub

The Instrument class now comprises two nested static classes, namely the Builder and the ListBuilder. Both these classes are structurally built in the same way and in each of them there exists a parent builder.


public class Instrument {
private String name;
private Instrument(Builder builder) {
this.name = builder.name;
}
public static class Builder {
private String name;
private ListBuilder listBuilder; // parent builder
public Builder withName(String name) {
this.name = name;
return this;
}
public Instrument build() {
return new Instrument(this);
}
// setter for parent builder
public Builder setListBuilder(ListBuilder builder) {
this.listBuilder = builder;
return this;
}
// build it and get parent builder again
public ListBuilder toList(){
this.listBuilder.add(this.build());
return this.listBuilder;
}
}
public static class ListBuilder {
private List<Instrument> instruments = new ArrayList<>();
private Airplane.Builder airplaneBuilder; // parent builder
public ListBuilder add(Instrument instrument){
this.instruments.add(instrument);
return this;
}
public List<Instrument> build(){
return this.instruments;
}
// get child builder and hands over parent builder
public Instrument.Builder add() {
return new Instrument.Builder().setListBuilder(this);
}
// setter for parent builder
public ListBuilder setAirplaneBuilder(Airplane.Builder builder){
this.airplaneBuilder = builder;
return this;
}
// build it and get parent builder again
public Airplane.Builder done() {
this.airplaneBuilder.addList(this.build());
return airplaneBuilder;
}
}
}

view raw

Instrument.java

hosted with ❤ by GitHub

With the help of generics and reflections, these builders could be constructed more generically. Maybe I will explain this some when later.

SQL Injection

SQL injections are one of the greatest risk on the web today. It is not difficult to rebuild existing programs so that SQL injections are no longer possible. The main problem of most programmers is lack of knowledge about this type of attack. Understanding it and identify risks in your applications is absolutely critical.

A SQL injection is nothing more than the manipulation of the SQL command on the victim’s side. It is the exploitation of a vulnerability in connection with SQL databases. The attacker attempts to infiltrate its own database commands on the application. Its aim is to spy or change data, to gain control of the server, or simply to inflict maximum damage .

Let’s look the following naive approach how a login is implemented. The email and password is replaced with the data entered in the SQL string. The so generated SQL statement is then sent to the database. If a value is returned, the user is considered as logged in.


String email = request.getParameter("email");
String password = request.getParameter("password");
String sql = "select * from users where (email ='" + email +"' and password ='" + password + "')";
Connection connection = pool.getConnection();
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql);
if (result.next()) {
loggedIn = true;
// # Successfully logged in and redirect to user's profile page
} else {
// # Auth failure – Redirect to Login Page
}

A SQL injection can be made quite easily. We only need to inject characters interpreted by the database in order that the SQL string is modified. If ‚ or 1=1)- – is entered as password, the generated SQL look as follows:


select * from users where (email ='' and password ='' or 1=1)–')

view raw

modifiedSQL

hosted with ❤ by GitHub

The SQL above is a completely valid statement. It will return all rows from the table users, since 1=1 is always true. The — is a comment and causes that everything behind is ignored. A second possibility to start a SQL injection attack is to enter ‚ or “=“ as email and as password. The generated SQL looks then as follows:


select * from users where (email ='' or ''='' and password ='' or ''='');

view raw

modifiedSQL2nd

hosted with ❤ by GitHub

This statement will also return all users since “=“ is always true. In this manner one get access to all the user names and passwords in a database.

But how can SQL injections be avoided? An application can be protected from SQL injection attacks by using SQL parameters. For this purpose, so-called prepared statements are used in Java, that means the data is passed as a parameter to an already compiled statement. The data is therefore not interpreted and thus prevents SQL injection attacks. The changed code looks then as follows:


String sql = "select * from users where (email =? and password =?)";
Connection connection = pool.getConnection();
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, email);
pstmt.setString(2, password);
ResultSet result = pstmt.executeQuery();

The ? is used as a placeholder. By using the PreparedStatement class, the program may even experience a gain in performance if the statement is used multiple times.

 

Exception Testing with JUnit

Testing exceptions can be done with the @Test annotation and its expected property. The message of the exception has to be asserted in a catch-block. This test seems a bit cumbersome.


@Test(expected = IllegalArgumentException.class)
public void exceptionTesting() {
try {
throw new IllegalArgumentException("id must not be null");
}
catch(IllegalArgumentException iae) {
assertEquals("id must not be null", iae.getMessage());
throw iae;
}
}

Since JUnit 4.7, it is possible to use the @Rule annotation to expect exceptions. In this way, the test can be expressed quite more elegantly.


@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldThrowExpectedException(){
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("id must not be null");
throw new IllegalArgumentException("id must not be null");
}

In JUnit 5, we use Java 8 Lambdas to describe the same test.


@Test
void exceptionTesting() {
Throwable exception = expectThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("id must not be null");
});
assertEquals("id must not be null", exception.getMessage());
}

Open/Closed Principle

The Open/Closed Principle (OCP) states that classes should be open for extension, but closed for modification. The goal is to allow classes to be easily extended to incorporate new behavior without modifying existing code. This means when extending your software you should not need to go and dig around in its internals just to change its behavior. You should be able to extend it by adding to it new classes without the need to change the existing code.

Open to Extension = New behavior can be added in the future

Closed for Modification = Changes to code are not required

But applying the OCP everywhere is wasteful and unnecessary. The OCP leads to more complex designs and to harder understandable code especially for beginners. It is said that the OCP should not be applied at first. If the class is changed, we should accept it. If it changes a second time, we should refactor it to OCP.

Let’s look at an example. Assume we have a web shop where there is a function that calculates the total amount of all items in a shopping cart. As shown in the code below, there are different type of rules how the total amount is calculated depending on the item.


public double totalAmount(List<Items> items) {
double total = 0.0;
for (item : items) {
if (item.getCategory() == "DISCOUNT") {
total += 0.95 * item.getPrice();
}
else if (item.getCategory() == "WEIGHT") {
total += item.getQuantity()*5/1000);
}
else if (item.getCategory() =="SPECIAL") {
total += 0.8*item.getPrice();
}
// more rules are coming!
}
return total;
}

Every time a new rule is added or the way how items are priced is modified requires changes to the class an its method. Each change can introduce bug and requires re-testing. At this point, we know that there are more rules coming. So we must think about how we can refactor this code in such a way that we don’t have to go in and edit this particular method every time. The way that we can introduce new behavior is through new classes. They are less likely to introduce new problems since nothing depends on them yet.

There are typical two approaches in an object-oriented programming language to achieve OCP. The first possibility is using the template pattern. This pattern encompasses an abstract base class that provides a default behavior. Items in our example inherit from this base class and override the default. The second possibility is to use the strategy pattern. This pattern allows to change the class behavior or its algorithm at run time. Maybe, this pattern would be a bit over-engineered in our simple example. However, the resulting calculation can be shortened with both patterns to the following:


public double totalAmount(List<Items> items) {
double total = 0.0;
for (item : items) {
total += item.getPrice();
}
return total;
}

 

Groove your Jenkins

Jenkins jobs are part of the infrastructure and shall be considered as a code according to the paradigm of „Infrastructure as Code“. Jenkins allows to create build jobs with Groovy Job DSL. Jobs are no longer created manually through the graphical console, but code is written and checked in. The configuration of the jobs with the whole history can be seen in the version management. In this blog post I want to briefly show how this works in order to facilitate the entry .

A so-called seed job has to be created. If this job is built, a build job is generated from the the seed job which can be run to build the project as usual. Unfortunately, the build job is not automatically updated if the seed job is changed and rerun.

First you need the Job DSL Plugin. The plugin allows to describe build jobs in a Groovy script. Next, a freestyle project is created that will be the seed job. In the configuration you can leave everything empty. In the section Build click the Add build step and then select Process Job DSLs.
process_job_dsl

Then select Use the provided DSL script. The code for the job can directly typed in to the console as shown in the picture below. When selecting Look on Filesystem instead, you have the opportunity to load job DSL scripts from the workspace. This is the recommended option because the scripts can be checked in and managed in the version control.

dsl_config

Before the JDK and Mavenversion can be set in the DSL script, they must first be configured in the settings under Global Configuration Tools.

 

Funny Jenkins Plugins

There are some funny Jenkins plugins that can spice up a little the builds . In addition, they can even increase the motivation to have good builds. high time to mention them briefly here.

The first plugin is probably the best known . It is the Chuck Norris plugin . When enabled, on every build page Build Chuck Norris appears with one of his saying and keeps things more fun.chuck_wisdom

chuck_norris

The second plugin is the Emotional Jenkins plugin . When a build fails, Jenkins gets visibly upset. Depending on the build state, one of the Jenkins below is displayed on the build page. If the build is successful, Jenkins is satisfied . If a test fails, Jenkins looks a bit sadly . And if there is a compilation error , then Jenkins is angry.

emotional_jenkins

The third plugin is the Continuous Integration Game. Points are gained for fixing broken builds, writing new unit tests, fixing static analysis violation errors etc. On the other side points are loosed for braking the build or producing new testing errors. On Jenkins home, a leaderboard with the current ranking is displayed. The plugin is intended to stimulate a kind of competition among developers, and thus lead to a good build quality.leaderboard

build_points
The last plugin that I want to mention here is the Claim plugin . If a build fails, someone can claim it. The bad build is then assigned to the the appropriate person and all are informed that someone takes care of the build. Not just funny, but even useful.

claim_build

claim_report

Once the plugins are installed, they have to be enabled on per-job basis. To enable the plugins for a specific job, go to the job configuration page, click Add post-build action and select the corresponding feature from the list.

activate_plugins

Recap Linux

Permissions

I work very irregularly with Linux. When I do, however, I often have to change the permissions of a file. And almost every time it happens that I can not remember the rough concepts and the commands. Therefore, I have decided to write it down here very briefly . Maybe it will help even someone else..

Show permissions of a file or folder:

ls -ld filename

What does all the following mean?

linux_permissions

ModeFields Hardlinks Owner Group Filesize Date&Time Filename

The first mode field is the „special file“ designator. It basically marks the type of the file Regular files display as – (none). Then, the mode field has three triples of format rwx . The first triple determines the permissions for the user , the second for the group and the third for others. r ⇒ read access, w ⇒ write access , x ⇒ executable.

Give all permissions to everyone:

chmod 777 filename

chmod means change mode fields. 7 is 4+2+1 that is 111.

Installing and updating software

http://superuser.com/questions/125933/what-is-the-difference-between-yum-apt-get-rpm-configure-make-install

 

Command line aliases in Windows

Aliases are nicknames for command calls and thus supersede a lot of typing. In Linux there exist the command alias, in Windows there is doskey. An alias can be defined as follows:

doskey ls=dir

Typed aliases are volatile , that means, these are no longer available after a recall of the command line console. In order to make them persistent two steps are necessary. Firstly, create a bat-script containing all aliases and save it to an arbitrary location. Secondly, insert a corresponding string value in the Windows registry.

  1. Open Registry by searching „regedit“
  2. Open HKEY_CURRENT_USER → SOFTWARE → Microsoft → Command Processor
  3. Add new String Value called AutoRun with the path to the created bat-script.registry_value

Whenever a command line console is opened, the script is loaded and automatically executed in the current session.

Transpiling and bundling modules with webpack

Webpack is a newer module bundler continuously gaining popularity. It can be basically viewed as a replacement for grunt or gulp. Webpack has a broad feature set: It can be used to bundle AMD, CommonJS and ES2015 modules. Further, it provides a feature known as code splitting that allows to group the code in multiple bundles in order to optimize how it is downloaded. Moreover, webpack can be used to bundle javascript, css, images and other assets. It also provides loaders that can be used to preprocess files before bundling them. In this blog post, I’m going to scratch the surface of loaders. I like to demonstrate how to configure the babel-loader with webpack in order that the files are transpiled whenever webpack is called.

First of all, we need to install webpack in the project as well as globally using npm.


npm install webpack –save-dev
npm install webpack -g

Next, we need to install the babel-loader as well as the babel-core. These are 3rd party components provided by babel. If babel-cli and babel-preset-es2015 in not yet installed, install them as well.


npm install babel-loader babel-core –save-dev
npm install babel-cli babel-preset-es2015 –save-dev

Next, we have to configure the webpack.config.js which contains the configuration for webpack. It is basically a CommonJS module.


module.exports = {
entry: './js/app.js',
output: {
path: './build',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}
]
}
};

The input file is assumed to be app.js placed in the folder js. The transpiled and bundled file will be located in the folder build and is called bundle.js. Without going into the details, the loader will look for all files ending with .js  exluding the files in the node_modules. Then, it will manipulate the files and turn them from es6 to es5. To make all this happen, we only need start a command line in the project and type in webpack.

There are a lot more useful loaders that can be configured. For example, there exist a css-loader which bundles all css files, a saas-loader that does the same for saas files and a url-loader that can be used to bundle images and fonts. Without further explanation, they are inserted below.


{
test: /\.css$/,
exclude: /node_modules/,
loader: 'style-loader!css-loader'
},
{
test: /\.scss$/,
exclude: /node_modules/,
loader: 'style-loader!css-loader!saas-loader'
},
{
test: /\.(png|jpg|ttf|eot)/,
exclude: /node_modules/,
loader: 'url-loader?limit=10000'
}

view raw

webpack_loaders

hosted with ❤ by GitHub

Spring Boot devtools with IntelliJ

The overall goal of Spring Boot devtools is to improve the development time. It’s available since Spring Boot version 1.3 and it includes different features among others property default, live reload, automatic restart etc.

Spring Boot devtools works by watching the classpath for any build changes and then automatically restarts the application. In Eclipse or most other IDE, every time you save, it actually builds the code. In IntelliJ, however, the code is not every time fully built when it is saved or automatically saved. In this short post, I like to demonstrate how you can configure automatic restart with IntelliJ.

First of all, you need to add devtools to your dependencies. Note that the dependency is optional in order that it is not transitively included in other projects.


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>

view raw

devtools.xml

hosted with ❤ by GitHub

Next, we record a macro by selecting Edit → Macros → Start Macro Recording. Thereafter the following two steps must be recorded:

  1. File → Save All
  2. Build → Make Project

Once this is done, you can stop the recording via Edit → Macros → Stop Macro Recording and give a name, e.g. „Spring Boot Automatic Restart“ to the recorded macro. Next, go to keymap in the settings (File → Settings ). Copy the current keymap and rename it to „Spring Boot Keymap“ for example. Scroll down to macros and select your recorded macro. Via the context menu (right-click) add a keyboard shortcut like CTRL + S.

Whenever your Spring Boot application is running and CTRL + S is pressed, an automatic restart is done. Spring Boot devtools works with two classloaders. One that loads all the classes in the beginning and another one that only loads the changes. Thus, a startup improvement can be achieved. I observed on my machine, that the startup time is more than halved by using devtools and its automatic restart.