Flexible Content in CSS

Prevent Overlapping

Let’s have the following website that displays the CSS logo as an image. The image is displayed in its original size.

flexible_content_1

The page is produced by the the following html and css file:


<!DOCTYPE html>
<html>
<head>
<title>CSS overlapping</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div class="imageholder">
<div class="centering">
<img class="img" src="css.jpg">
</div>
</div>
</body>
</html>

view raw

index.html

hosted with ❤ by GitHub


html, body {
background-color: lightgrey;
margin: 0;
}
.imageholder {
position: absolute;
margin: 10% auto;
width: 100%;
height: 60%;
background-color: darkblue;
}
.centering {
margin: 0 auto;
width: 40%;
height: 100%;
background-color: black;
}

view raw

main.css

hosted with ❤ by GitHub

As soon as the page is decreased, the image overlaps its intended area (black area) which is not desired.

flexible_content_2

The solution to this problem is to introduce both the properties max-width and max-height. They will prevent the image from overlapping to other areas.


.img {
max-width: 100%;
max-height: 100%;
}

view raw

main.css

hosted with ❤ by GitHub

Keeping aspect ratio

Keeping aspect ratios in responsive websites is primarily important for videos and images. In the following it is show how the aspect ratio can be kept. Again there is a index.html and a main.css:


<!DOCTYPE html>
<html>
<head>
<title>CSS aspect ratio</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div class="container">
<div class="element">
</div>
</div>
</body>
</html>

view raw

index.html

hosted with ❤ by GitHub


html, body {
background-color: lightgrey;
margin: 0;
}
.container {
position: relative;
height: 0;
padding-bottom: 25%;
background-color: red;
}
.element {
position: absolute;
height: 100%;
width: 100%;
background-color: darkblue;
}

view raw

main.css

hosted with ❤ by GitHub

The relevant part here is to set height:0 and padding-bottom: 25% in the container selector. This will create a container that is 4 times as width as height because a padding is always calculated of the elements width. The aspect ratio is even kept if the browser size is changed.

Werbung

Understanding Docker volumes

Docker volumes was one of the last things I understood of Docker. As you can get started with Docker quite conveniently without using any volumes I never took the time to really understand them. But using volumes gives you the opportunity to work with data in Docker. Primarily, volumes offer persistent storage and shared state. So it’s high time to have a look at Docker volumes.

Volumes are used to persist data like database files, log files or any other container-independent data outside of a Docker container. Volumes map directories in a container to a defined directory on the host.

There exist two types of Docker volumes, bind-mount volume and managed volume. The former maps any user-specified directory or file on the host operating system. The latter uses internal Docker locations that are managed by Docker itself.

A bind-mount volume is created via the v-flag in the docker run command as follows:

docker run -it -v ~/shared:/tmp/data ubuntu /bin/bash

This will map the /tmp/data directory inside the container to the shared directory inside the local users directory on the host (~ is the shortcut for the local users directory in windows). All locations must be specified with absolute paths. This can be checked via:

docker inspect --format='{{json .Mounts}}'

Once the container is started, you can navigate to the /tmp/data directory and all files contained in the ~/shared directory on the host will be displayed. In the same way, single files can be mapped as well. Read-only volumes can be specified by appending :ro to the docker volume.

Bind-mount volumes have the disadvantage that they make the container not portable to any other host and volumes of different containers can conflict with each other. Thus, its best to avoid these volumes in generalized platforms and use Docker-managed volumes instead. Managed volumes are created via the v-flag as well, but without specifying a directory inside the container:

docker run -it -v ~/shared: /bin/bash

Besides persistent storage, volumes are used to share data between different containers. This can be achieved in two ways. Either each container has a bind-mount volume to the same location or managed volumes are shared between them. The former is quite straightforward whereas for the latter the —–volumes-from flag is used. This flag is used to copy a managed volume by a so called volume container into each container. A volume container is a single container that only defines a volume. This looks as follows:

docker run -d --volumes-from vc_shared ubuntu

Docker can’t delete bind-mount volumes because this is outside of its scope. However, care must be taken to always remove managed volumed when a container is deleted. This is done via the v-flag:

docker rm -v ubuntu

Using this v-flag option is really important. If deleting a container without this option, the managed volume becomes orphan and subsequently requires any manual steps to be removed.

Centering elements in CSS

A common problem in CSS is centering elements wherefore various approaches exist. But often if I need one at a time, no one comes to mind. So I summarize here briefly how to center elements in CSS horizontally and vertically.

Consider the following simple website, which shows a colored box.

website_centering

The code for the index.html looks as follows


<!DOCTYPE html>
<html>
<head>
<title>CSS centering</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div class="box bluebox"></div>
</body>
</html>

view raw

index.html

hosted with ❤ by GitHub

and the code for the cascading style sheet named main.css is as follows:


body {
height: 2000px;
}
.box {
height: 100px;
width: 100px;
margin-bottom: 10px;
}
.bluebox {
background-color: blue;
}

view raw

main.css

hosted with ❤ by GitHub

By the way, a modern text editor for web design is brackets. I’m using this editor for designing webpages and highly recommend it.

My preferred way to horizontally center the box is by adding the margin property to the selector. The updated CSS looks as follows:


body {
height: 2000px;
}
.box {
height: 100px;
width: 100px;
margin-bottom: 10px;
}
.bluebox {
background-color: blue;
margin: 0 auto;
}

view raw

main.css

hosted with ❤ by GitHub

The values of the property are set to 0 and auto. 0 means that the top and bottom margin are equal to 0. Auto says move left and right in the equal amount that finally centers the box on the page.

Centering the box vertically on the page is as easy as follows:


body {
height: 2000px;
}
.box {
height: 100px;
width: 100px;
margin-bottom: 10px;
}
.bluebox {
background-color: blue;
position: absolute;
top: 50%;
margin-top: -50px;
}

view raw

main.css

hosted with ❤ by GitHub

Centering the box horizontally as well as vertically is a bit more complicated. But the trick here is to add a container element which is vertically centered and its width is set to 100%. The box is contained in this container and then can be horizontally centered. The code looks as follows:


<!DOCTYPE html>
<html>
<head>
<title>CSS centering</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div class="container">
<div class="box bluebox"></div>
</div>
</body>
</html>

view raw

index.html

hosted with ❤ by GitHub


body {
height: 2000px;
}
.box {
height: 100px;
width: 100px;
margin-bottom: 10px;
}
.container {
position: absolute;
top: 50%;
margin-top: -50px;
width: 100%;
}
.bluebox {
background-color: blue;
margin: 0 auto;
}

view raw

main.css

hosted with ❤ by GitHub

Whenever, one is playing with CSS and trying to achieve such things, it it often very helpful to set a background color for the different elements.This gives a good way the „optically“ debug the code and seeing exactly what is going on.

npm cheat sheet

I am not happy with the official npm documentation as  I never find quickly what I am looking for. So I decided to write a short npm cheat sheet with the most often commands I use.

Get npm help

npm -h or npm -h

Generate package.json in a module directory, based on npm parameters.

npm init
npm init -y (accept all default answers)

Install a package and also update package.json with the installed version and package name.

npm install --save
npm install @1.8.2 --save --save-exact (specific version)

Install a package and also update package.json with the installed version and package name, but into the devDependencies section.

npm install --save-dev

Uninstall package (A nice thing about npm is you can always just rm -rf ./node_modules/)

npm uninstall --save

List installed packages with dependency tree depth of zero.

npm ls --depth 0

List outdated libraries compared to currently installed node_modules.

npm outdated

Update dependencies.

npm update
npm update --prod (only prod dependencies)
npm update --dev (only dev dependencies)

List all npm configuration flags.

npm config ls -l

Setting, getting and deleting defaults.

npm set 'value'
npm get 
npm config delete 

Update the global npm version.

npm update npm -g (run this command with admin privileges)

⇒ Note that this is not working under windows. The best way to update npm is to install npm-windows-upgrade and do the update with this tool.

npm install -g npm-windows-upgrade
npm-windows-upgrade

npm shortcuts.

https://docs.npmjs.com/misc/config#shorthands-and-other-cli-niceties

Docker in Docker for Jenkins

If  Jenkins is running inside a Docker container and the CI build is setup to create Docker images, you have to find a way how to use Docker inside Docker. Indeed, there exists such a way to run Docker-in-Docker as described here. However, the primary purpose of this mechanism was the help with development of Docker itself. Although this Docker-in-Docker mechanism generates many problems which are listed in this blog, it is often abused to run a CI inside a container that creates Docker images.

A better way to miles is to run Docker inside Docker by bind-mounting the Docker socket of the Docker host into the Docker Jenkins container. This can be achieved by installing Docker binaries into the Jenkins container and then mapping the Docker socket as volume from the Docker host to the Jenkins container.

First of all, we need to have a Jenkins Docker image. Therefore, I created the Dockerfile shown below. It comprises a couple of useful tools and Jenkins itself. Furthermore, it installs the Docker binaries, docker-compose and docker-machine. The latter two are not really needed here, but I added them for completeness.


FROM renewinkler/ubuntu-oraclejdk:8
ENV DOCKER_VERSION 1.12.0
ENV DOCKER_COMPOSE_VERSION 1.8.0
ENV DOCKER_MACHINE_VERSION 0.8.0
# tools
RUN apt-get update -qq && apt-get install -qq curl wget git subversion nano nodejs npm iputils-ping && apt-get clean
# Maven
RUN curl -sf -o /opt/apache-maven-bin.tar.gz http://archive.apache.org/dist/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz; \
tar xzf /opt/apache-maven-bin.tar.gz -C /opt/; \
rm /opt/apache-maven-bin.tar.gz; \
ln -s /opt/apache-maven-3.3.9 /opt/maven
ENV MAVEN_HOME /opt/maven
#Docker bins
WORKDIR /home/toolbox/
RUN curl -L -o /tmp/docker-latest.tgz https://get.docker.com/builds/Linux/x86_64/docker-${DOCKER_VERSION}.tgz && \
tar -xvzf /tmp/docker-latest.tgz && \
mv docker/* /usr/bin/
#Docker compose
RUN curl -L https://github.com/docker/compose/releases/download/1.8.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose && \
chmod +x /usr/local/bin/docker-compose
#Docker machine
RUN curl -L https://github.com/docker/machine/releases/download/v${DOCKER_MACHINE_VERSION}/docker-machine-`uname -s`-`uname -m` > /usr/local/bin/docker-machine && \
chmod +x /usr/local/bin/docker-machine
# Jenkins
ENV JENKINS_HOME /opt/jenkins
ENV JENKINS_MIRROR http://mirrors.jenkins-ci.org
RUN mkdir -p $JENKINS_HOME
RUN curl -sf -o /opt/jenkins/jenkins.war -L $JENKINS_MIRROR/war/latest/jenkins.war
RUN mkdir -p $JENKINS_HOME/plugins; for plugin in greenballs; \
do curl -sf -o $JENKINS_HOME/plugins/${plugin}.hpi -L $JENKINS_MIRROR/plugins/${plugin}/latest/${plugin}.hpi; done
VOLUME $JENKINS_HOME/data
WORKDIR $JENKINS_HOME
EXPOSE 8080
CMD [ "java", "-jar", "jenkins.war" ]

view raw

Dockerfile

hosted with ❤ by GitHub

Once the image is built, it can be started. In this step the Docker socket of the Docker host has to be bind-mounted by the -v flag via /var/run/docker.sock:/var/run/docker.sock. The volume instruction from within a Dockerfile doesn’t allow to do a host mount. We just can do this from a Docker run command. This is the reason why this volume mapping is not done in the Dockerfile directly. Simply put, when you start the container, start it as follows:

docker run -itd —-name jenkins -p 8080:8080 -v /var/run/docker.sock:/var/run/docker.sock renewinkler/jenkins-oraclejdk

That’s basically all. If you enter the container and type e.g. ‚docker images‘ you should see all images of your Docker host.

Lastly, I want to demonstrate a way how to create a Docker image in a Jenkins build. For this purpose, there exist several maven plugins. One of the better is the maven-plugin-docker from Spotify. There also exist the maven Docker plugin of fabric8 which is great too. I configured the former plugin in my maven build as follows:


<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.4.11</version>
<executions>
<execution>
<id>build-image</id>
<phase>package</phase>
<goals>
<goal>build</goal>
</goals>
</execution>
<execution>
<id>push-image</id>
<phase>deploy</phase>
<goals>
<goal>push</goal>
</goals>
<configuration>
<imageName>registry.example.com/app_name:${project.version}</imageName>
</configuration>
</execution>
</executions>
<configuration>
<imageName>app_name</imageName>
<imageTags>
<imageTag>${project.version}</imageTag>
<imageTag>latest</imageTag>
</imageTags>
<baseImage>java:8</baseImage>
<entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
<!– copy the service's jar file from target into the root directory of the image –>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>

view raw

pom.xml

hosted with ❤ by GitHub

The plugin is bind to the package phase which builds the image as well as to the deploy phase which pushes the image to the configured registry. The built images is based on the java:8 base image and two tags latest and current project version are created. The generated jar file of my application will be the entrypoint of the image. As soon as the build mvn clean install is finished, a newly generated Docker image should be visible in the local Docker host registry.

Docker shortcuts

After a while working with Docker, you get tired of always typing the relatively long command ‚docker‘ or of remembering more complicated commands. Thus, I was wondering how I can setup some aliases to make me more productive. I found a good references on github from where I was inspired and took or derived my shortcuts. The shortcuts consist of aliases and functions.


# Docker
alias d='docker'
# Get container process
alias dps='docker ps'
# Get process including stopped containers
alias dpsa='docker ps -a'
# Get images
alias di='docker images'
# Start container
dstart() { docker start $1; }
# Stop container
dstop() { docker stop $1; }
# Stop all running containers
dstopa() { docker stop $(docker ps); }
# Remove container
alias drm='docker rm'
# Remove image
alias drmi='docker rmi'
# Removing all stopped containers
drma() { docker rm $(docker ps -a -q); }
# Removing all images
drmia() { docker rmi $(docker images -q); }
# Getting the IP address
alias dip="docker inspect –format '{{ .NetworkSettings.IPAddress }}'"
# Build from dockerfile
db() { docker build -t=$1 .; }
# Enter into a running container with bash
dbash() { docker exec -it $1 /bin/bash; }

view raw

.bash_profile

hosted with ❤ by GitHub

All these shortcuts have to be placed in the .bash_profile file. This file has to be created in the local user’s home if it  does not exist yet. In order to find out which is the user’s home type in cd ~ in the Docker client which will jump to this directory. Whenever the Docker client is launched, the file is loaded and all commands are executed. After that, all these shortcuts are available in the Docker client.

Creating and running a Docker Jenkins image

In this blog post, I’m going to quickly summarize how to create a Docker Jenkins image and how to make it working. I’m going to demonstrate how to create two images, the first with OpenJDK 8 and the second with Oracle JDK 8 installed. So let’s get started.

The following Dockerfile creates a Docker Jenkins image based on the OpenJDK image. First, it updates existing packages, installs curl, git and nano as a text editor. Next, Maven and Jenkins are downloaded and installed. The only Jenkins plugin that is installed, is the greenball plugin. All other required plugins are easier to install via the Jenkins GUI console as this will also resolve plugin dependencies. Lastly, port 8080 is exposed and Jenkins is run.


FROM openjdk:8
RUN apt-get update -qq && apt-get install -qq curl git nano && apt-get clean
RUN curl -sf -o /opt/apache-maven-bin.tar.gz http://archive.apache.org/dist/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz; \
tar xzf /opt/apache-maven-bin.tar.gz -C /opt/; \
rm /opt/apache-maven-bin.tar.gz; \
ln -s /opt/apache-maven-3.3.9 /opt/maven
ENV MAVEN_HOME /opt/maven
ENV JENKINS_HOME /opt/jenkins
ENV JENKINS_MIRROR http://mirrors.jenkins-ci.org
RUN mkdir -p $JENKINS_HOME
RUN curl -sf -o /opt/jenkins/jenkins.war -L $JENKINS_MIRROR/war/latest/jenkins.war
RUN mkdir -p $JENKINS_HOME/plugins; for plugin in greenballs; \
do curl -sf -o $JENKINS_HOME/plugins/${plugin}.hpi -L $JENKINS_MIRROR/plugins/${plugin}/latest/${plugin}.hpi; done
VOLUME $JENKINS_HOME/data
WORKDIR $JENKINS_HOME
EXPOSE 8080
CMD [ "java", "-jar", "jenkins.war" ]

view raw

Dockerfile

hosted with ❤ by GitHub

Creating a Oracle JDK image is a bit more costly. First of all, an Ubuntu image with Oracle JDK has to be created. Launchpad offers a Oracle Java installer which automatically downloads and installs Java.


FROM ubuntu:latest
RUN apt-get update -qq && apt-get install -qq software-properties-common && apt-get clean
RUN \
echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | debconf-set-selections && \
add-apt-repository -y ppa:webupd8team/java && \
apt-get update && \
apt-get install -y oracle-java8-installer && \
rm -rf /var/lib/apt/lists/* && \
rm -rf /var/cache/oracle-jdk8-installer

view raw

Dockerfile

hosted with ❤ by GitHub

In order to indicate that this image contains Oracle JDK 8, it can be tagged (on github) with version 8. This image is the base image for the following Jenkins image. which exactly looks the same as the one with OpenJDK configured.


FROM renewinkler/ubuntu-oraclejdk:8
RUN apt-get update -qq && apt-get install -qq curl git nano && apt-get clean
RUN curl -sf -o /opt/apache-maven-bin.tar.gz http://archive.apache.org/dist/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz; \
tar xzf /opt/apache-maven-bin.tar.gz -C /opt/; \
rm /opt/apache-maven-bin.tar.gz; \
ln -s /opt/apache-maven-3.3.9 /opt/maven
ENV MAVEN_HOME /opt/maven
ENV JENKINS_HOME /opt/jenkins
ENV JENKINS_MIRROR http://mirrors.jenkins-ci.org
RUN mkdir -p $JENKINS_HOME
RUN curl -sf -o /opt/jenkins/jenkins.war -L $JENKINS_MIRROR/war/latest/jenkins.war
RUN mkdir -p $JENKINS_HOME/plugins; for plugin in greenballs; \
do curl -sf -o $JENKINS_HOME/plugins/${plugin}.hpi -L $JENKINS_MIRROR/plugins/${plugin}/latest/${plugin}.hpi; done
VOLUME $JENKINS_HOME/data
WORKDIR $JENKINS_HOME
EXPOSE 8080
CMD [ "java", "-jar", "jenkins.war" ]

view raw

Dockerfile

hosted with ❤ by GitHub

Of course, it would have been possible to configure this image with only one Dockerfile. However, that would have less corresponded to the modular idea. In this way, one is flexible and the base image can be reused.

The most eleagnt way to create Docker images out of dockerfiles is to configure an automated build on Dockerhub. I’m not going in these details here, but I show you how to build the image manually. The docker image can be build

docker build . -t jenkins-oraclejdk

and then run as follows

docker run -itd -p 8080:8080 --name jenkins jenkins-oraclejdk

Next, open a web browser and type in http://192.168.99.100:8080/ Once Jenkins is started, an input will appear to create a first user:

firstuser

Next, Jenkins has to be unlocked.

unlockJenkins.png

In order to this, one have to connect to the docker container and get the initial admin password. The following docker command, let you connect to the container.

docker exec -it jenkins /bin/bash

Navigate to the corresponding folder and open the intialAdminPassword file with nano.

nano intialAdminPassword

Double click the password and press enter to copy the password and leave the editor via Ctrl+X. Exit the container by typing in ‚exit‘ and paste the password to the corresponding input field to unlock Jenkins. That’s all. At last, you have the opportunity to customize Jenkins, e.g. by installing additional plugins.

 

Email Testing with MailHog

MailHog is an email testing tool for developers. It allows to configure your application to use MailHog for SMTP delivery. MailHog catches all outgoing emails and sends them to itselfs. All emails can then be viewed in a web UI or they can be retrieved with a JSON API. It is also optionally possible to release messages to real SMTP servers. The easiest way to get started with MailHog is to pull the docker image:


docker pull mailhog/mailhog

view raw

docker_mailhog

hosted with ❤ by GitHub


docker pull mailhog/mailhog

view raw

docker_mailhog

hosted with ❤ by GitHub

Once downloaded, MailHog can be started as follows:


docker run -d \
–restart unless-stopped \
–name mailhog \
-p 1025:1025 \
-p 8025:8025 \
mailhog/mailhog


docker run -d \
–restart unless-stopped \
–name mailhog \
-p 1025:1025 \
-p 8025:8025 \
mailhog/mailhog

Port 1025 is the SMTP port and port 8025 is the HTTP server for the web UI. As MailHog is running in a docker container, we have to use the local docker IP instead of localhost. The web UI can be called via http://192.168.99.100:8025/

mailhog_webui

Among other things, I’m using MailHog for configuring email notification from Jenkins. So, I had to set up MailHog for Jenkins. I’m using the email extension plugin that allows to configure a lot more aspects of email notifications than the default normal mailer plugin. At Manage Jenkins → Configure System under Extended Email Notification you have to configure the following:

extendedemail

As SMTP Server we also need to enter the local docker IP. Setting the Content Type to HTML allows to use HTML tags in emails that makes them more flexible.

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.