AngularJS Intensive Workshop by Robin Böhm/Symetics GmbH

Last week I attended an AngularJS Intensive Workshop by Robin Böhm/Symetics GmbH. Symetics is the company behind www.angularjs.de and provides consulting and training all around JavaScript, AngularJS (1/2) and TypeScript.

original-93d514756bd905adaf57c9033f69be39

The location

The 3-days workshop was located in the UNPERFEKT Haus in Essen. The UNPERFEKT Haus is an open space for artists, students and musicians and provides rooms, WLAN and a lot of creative environment. It was a really great location for the seminar and we all felt comfortable.

The trainer

Our trainer was Robin Böhm who is the CEO/founder of Symetics GmbH. He works as a freelancer and does consulting, in-house training and workshops all around web technologies like AngularJS. During the 3-days he provided a lot of information and made a really intense workshop. However, the atmosphere was always relaxed and Robin was open for discussions and questions – even during the lunch break.

The workshop

The workshop was divided into two parts: (1) a round trip about JavaScript and (2) a dive-deep on AngularJS. It was a good mix of presentations and hands-on sessions on a prepared sample project. Robin managed to cover an huge amount of topics:

  • components vs. directives
  • routing (with the new router from AngularJS 1.5)
  • testing (with Jasmine)
  • the promise API
  • build tools
  • books to continue

Robin also tried to give us an outlook on AngularJS 2 and how we can prepare our current projects for it.

My opinion

Actually, there wasn’t much I didn’t like. The workshop covered all relevant topics and gave us a lot of useful insights into AngularJS and related stuff.

I can really recommend it!

It was fast, well prepared and very practical (we wrote code for about 1/3 of the time). The group was medium-sized, maybe 14 people (mostly Java developers). The only downside was that Robin sometimes provided to much detail on a particular topic. I’m more comfortable with staying by the underlying concepts of a technology and dive into the nitty gritty details when I’m working on it.

I’m looking forward to the next workshop! Thanks!

Thomas.

More

Using the console on Windows

I tell you a secret: I’m a Windows user. I don’t use OSX, I don’t use Linux, I use Windows. And I tell you something more: I like it 😉

Usually I develop Java or JavaScript applications which perfectly run under Windows, Linux, OSX or what so ever. So developing under Windows is no problem at all. Runtime environments, IDEs, editors – Windows has it all. However, people keep wondering how I can do the most simple task:

How do you connect to another server? Do you use Putty? – Argh, no, I just type ssh some.server.com and I’m done.

Or:

Do you use your IDE to work with GIT? Or do you have Source Tree? – Argh, no, I just type git add . and git commit -m "..." and I’m done.

But I also know, that not everybody is doing it like this. People use the weirdest tools and techniques when working under Windows. A lot of people use that f***ing small Windows CMD, Putty with its broken key-format or CygWin to be a little bit more Linux-like. But I don’t like all of these. The Windows CMD is unusable, Putty is unnecessary and CygWin is a monster you don’t need. Here is what I do.

Don’t use the Windows default CMD

The first thing I do, is to don’t use Windows’ default CMD. Why? It can’t even mark and copy things! However, there’s an easy and open-source alternative: ConEmu. ConEmu has all the simple things you expect: colors, tabs, resizable, copy-and-paste and much more. You can get it from GitHub and it even works without installation.

2016-05-21 21_51_21-Settings

Use GIT as a toolbox for Windows

The other thing I do, is to use GIT as a toolbox for Windows. When people are talking about using the console, they are actually talking about using tools. They talks about SCP, SSH or CURL like they come with their console – but they don’t! All of those things are just individual programs installed on their machine. They are not related to the command line! So why don’t install them on Windows?

If you use GIT, you already have everything you need in the bin folder (e.g. on C:\Program Files (x86)\Git\bin\):

ssh, scp, curl, cat, grep, less, sh, bash, ls, mv, cp, diff, gzip, and much more…

2016-05-21 22_09_29-Using the console on Windows – Thomas Uhrig

The only thing you need to do is to put GIT’s bin folder to your Windows variable path. You will have everything at a fingertip in your console.

2016-05-21 22_26_43-Environment Variables

Put my SSH-certificates to my user-folder

The last thing I usually do is to put my SSH-certificates to my user folder at C:\Users\tug\.ssh, so that SSH can find them.

Best regards,
Thomas

More

Expression based security with Spring Security

Many web apps have a very simple security concept based on user roles. You might have some admin, some common users and maybe some more roles like a moderator or a super-user. Such a role concept can be easily implemented with Spring Security. For example, you could secure your app based on routes which are available for certain roles:

If you want to be more flexible, you could also annotate your controllers instead of making a central configuration. While a central security configuration can become quite complex if you have a lot of routes with different security rules, using the @PreAuthorize annotation is very simple. All security constraints are right at the method where they apply.

But what if your security model has more constraints than roles?

Spring Security makes it easy to handle roles. But there are a lot of situations where roles are not enough. Imagine an order system (something like Amazon) where an user can cancel an order. To do this, you would introduce an user role which will have the permission to cancel an order. So anonymous users will not be allowed to cancel an order. That’s good, but only half of the story! There is one more (maybe the most important) security constraint: An user can only cancel those orders which belongs to him! And not orders of somebody else!

Such a rule is a typical business rule which can be handled by a service. The service might load all orders which belongs to a customer from the database, iterate over them and check if the given order ID is contained in the list. This could look like this:

If we have such a service which simply returns true or false we can easily use it together with Spring Security:

By using the @PreAuthorize annotation, you can use any Spring Bean. In the example above, we use the OrderService: @orderService.ownsOrder(#orderId). We pass the input parameter directly from the request mapping. The service simply returns true or false and Spring will either allow or forbid the access to the controller method.

It’s also possible to combine those rules:

This makes it possible to build complex security expressions which can use roles as well as Spring beans. By using Spring beans you can implement all types of security checks.

Best regards,
Thomas

More

Inject mocks with Spring’s @ContextConfiguration

One of the biggest strengths of Spring is its ability to make your code testable. By using dependency injection and inversion of control, the Spring context defines which objects will be wired into your beans. This makes it easy to wire services, repositories or what ever you like. But how to wire mocks in your tests?

Example

Let’s create a simple test setup: we have a service called OrderService which handles orders from customers. To do this, the OrderService needs a BillingService.

A typical test setup would run the Spring context, auto-wire the OrderService and test it. But if we would do so, we would also need to include the BillingService into the Spring context. And if the BillingService would need some other service, we would need to include this too and each and every transitiv dependency. Maybe we would end up by loading your whole app just to test one simple service.

A test setup with mocks

Whenever you want Spring to inject our beans, you must create a Spring context. Every bean you want to use must be part of this context as well as every transitiv bean. In this case we need two bean: (1) the OrderService which we want to test and the (2) BillingService which is a transitiv dependency. Both beans must be part of the Spring context!

However, we don’t want to use the real BillingService but a mock. To do this, we provide a dedicated @Configuration for our test which returns such a mock (with Mockito). If we would have other dependencies, we would do this for every bean used by the OrderService.

This makes it possible to load a very small Spring context: We only need our class to test and a mock very each of its dependencies. This is more like an unit test but an integration test and will run very fast. But the nice thing is, that you can decide which dependencies you want to mock and which not. If you would like to mock the BillingService but not the CustomerService it fine. You can control the amount of mocks very easily.

Best regards,
Thomas

Use ranges with ngRepeat

ngRepeat

Angular’s ngRepeat directive provides a simple way to iterate over collections to produce HTML dynamically. You probably know it when you have ever worked with lists or arrays in your Angular app:

Drawbacks

However, there is a small drawback when working with ngRepeat: You can only iterate over collections of the current scope. Loop definitions (like a typical for-loop) are not supported. This means you cannot to something like this:

The solution

But there is a simple trick to build a workaround for this. If you use a library like Lodash.js or Underscore.js the trick becomes even more simple: As ngRepeat requires a function on the scope, we just provide such a function!

That’s all we need. If we append Lodash/Underscore to our scope, we can use the library within our partials. This might looks like this:

Keep in mind

With great power comes great responsibility. When we append Lodash/Underscore to the Angular scope, we not only pollute the scope with more functionality, we also put program logic from the controller to the partial. And we shouldn’t do that! A partial should be as easy as possible and all application logic should be in the controller or services. But this is also a trade-off, as this solution might be fine for small and simple problems.

Best regards,
Thomas

Testing AngularJS directives with Jasmine

Directives

AngularJS provides a mechanism called directives. Directives are markers in our HTML which Angular will read and use to inject some special behavior to our HTML code. As this sounds a little bit theoretically, let’s look at an example:

In this example the directive ng-model is used which will bind the value of the input field to a field called name in the current $scope. This directive already comes with AngularJS, but it’s also possible to write your own directive. That’s what we do right now.

A custom directive

In order to have an useful example to test, we write our own directive. In this case we will use a directive which will listen for an “on-enter-event” on an element. It looks like that:

And you use it like that:

The example creates a directive called onEnter which you must refer as on-enter in your HTML. The directive takes a single argument which is a function in the current scope (e.g.: showNotification()). So when we type in your input field and press enter the directive will be called. It will get an event and it will check if the event comes from “enter” or another key. If it was an “enter”, the directive will call our method. Looks good? So let’s test it.

Testing

Testing this directive isn’t a big thing, but it will bring us the evidence that it works like we expect it. A Jasmine test might look like this:

What does the test do?

The test does the following: First we load the module which contains our directive and inject AngularJS’ $rootScope and $compile service. As a directive is attached to the HTML, we need to take some HTML and compile it with AngularJS in order to make the directive work like in a real life scenario.

Now we create our actual test case. First we create a spy function (jasmine.createSpy('test');) and attach it to our scope (which is simply the root scope). This function should be called by the directive if it works correctly. Now we create some HTML which uses the directive and compile it. The last thing we need to do is to create an on-enter-event and fire it up on the compiled element. This simulates the user pressing enter.

Last but not least we verify that the on-enter directive worked and has invoked our test function on the root scope.

What the test doesn’t do

The test only verifies the happy path. It tests if the function is called when enter is pressed, but it doesn’t verify the opposite: Is the directive only listening on “enter” or will it also call our function if another key is pressed? However, implementing this test shouldn’t be a big thing now.

Best regards,
Thomas

More

https://docs.angularjs.org/guide/directive

A mocked Spring security configuration for testing

Spring security is great! It gives you the possibility to secure your app and to create a login with a few simple lines of code. However, it could also become annoying during development, when you have to log yourself in again and again. So why not create a mocked Spring authentication for development and testing?

Create a new profile to active the mock

Before we implement the actual mock, we first create a new profile to active or deactive it. Spring profiles give you the opportunity to decide which bean Spring should use when starting your app. This means you can say “Hey Spring! Use my mock!” or “Hey Spring! Use my production implementation!”. Let’s call our profile “SECURITY_MOCK”. First, we add the profile to our production security configuration, so that we can switch it off and use the mock instead. Note that this is the only change we need to do to our already existing code!

Now we create our mock configuration:

Using a profile like shown above, we can decide which implementation Spring will use. We just need to pass the profile to our application properties:

A mocked authentication provider

Now that we have defined a profile to switch our mock on and off, we need to do the actual implementation. The first thing we do, is to write a mocked authentication provider. Spring will use this authentication provider to check the user, validate its password and to return the user details. The authentication provider depends on our own implementation, but it might look like that:

A couple of things are important right here:

  • Use the SECURITY_MOCK profile again and annotate the class with @Primary so it will replace any other bean when using the mock profile!
  • As I’m pretty sure you want to use a custom user class, set it to the details!

The mocked security config

After you implemented the mocked authentication provider, the actual security config will be very easy. The only thing you need to do is to use your authentication provider:

Usage

After you implemented both, the mocked security config and the authentication provider mock, the usage is straight forward. You just activate the profile (in your application properties) and then you can use the authenticated user in our code:

Best regards,
Thomas

Gradle’s bootRun and Window’s command length limit

Sometimes Gradle’s bootRun and Window’s command length limit are two opponents. If you use bootRun to start your Spring Boot app from Gradle all class path dependencies will be added to the start command. Gradle will run something like this in the end:

That’s fine and will work for a really long time. But as longer you work on your project you will add more and more dependencies. And it might happen that you cross a secret line of no return: 32767. That’s the number of characters which Windows’ CreateProcess function will accept. Any additional character will cause an exception:

Sh*t! So how to start your app? With Gradle, you can use a simple work around: Instead of appending all your dependencies to the start command, you create a JAR file with a manifest file. This manifest file contains all dependencies and will be the only dependency in your start command:

In Gradle code, this looks like this:

The pathingJar task creates a JAR file with a manifest file containing all our dependencies. This file will become pretty big, but that’s totally fine. Now we only extend the bootRun task to use this pathing JAR. This will solve the problem.

Best regards,
Thomas

More

Resizing Vagrant box disk space

Vagrant is a great tool to provision virtual machines! As I’m a passionated Windows user, Vagrant is the weapon of my choice whenever I need to use some Linux-only tools such as Docker. I spinn up a new Linux VM, already configured with the things I need and start working. However, when it comes to resizing a disk, Vagrant is not nice to you…

The problem

Vagrant doesn’t provide any out-of-the-box option to configure or to change the disk size. The disk size of a VM totally depends on the base image used for the VM. There are base images with a 10 GB disk, some with a 20 GB disk and some other with a 40 GB disk. There is no Vagrant option to change this – and even worse: most Vagrant boxes use VMDK disks which cannot be resized!

Resizing (manually) with VirtualBox

As Vagrant doesn’t provide any out-of-the-box functionality, we need to do the resizing “manually”. Of course, we can write a script for this, too, but for now we keep it simple and do it by hand.

  1. First we need to convert the VMDK disk to a VDI disk which can be resized. We do this with the VBoxManage tool which comes with the VirtualBox installation:
  2. Now we can easily resize this VDI disk, e.g. to 50 GB:
  3. The last step we need to do is just to use the new disk instead of the old one. We can do this by cloning the VDI disk back to the original VMDK disk or within a view clicks in VirtualBox:

    2016-01-06 16_32_02-Oracle VM VirtualBox Manager

That’s it! Now start your VM with vagrant up and check the disk space. It’s at 50 GB and we have new free space again!

Best regards,
Thomas

More

Anti Pattern: Don’t use Optionals for data repositories

Java 8 Optionals

Java 8 introduced a new feature call Optionals. Optionals are an easy way to force the caller of a method to deal with a possible null return value:

If you use an Optional as the return type of your method, whoever calls the method will be reminded that it might return null. If you use Optionals, you don’t need to think about NotFoundExceptions, special return types or JavaDoc comments which state that the method might return null. An Optional says more than a thousand comments!

Optionals might just postpone the problem

But an Optional doesn’t do one thing: it doesn’t answer the question what to do if there is no method result. It just postpones the problem to the caller. This might be OK if null is a quite expected result of the method, but in most cases null means something went wrong. Don’t postpone this!

An example

Nearly every application stores data. Whenever data is stored, it will be loaded again which might go wrong as the data simply couldn’t be found. That sounds like a good use case for Optionals! Let’s see how it could look like:

Nice! If there is no Person with the given ID the repository will return an empty Optional and the caller has to deal with it. Technically, this is a nice and clean solution. But from the business perspective it isn’t. The real question is: Can it happen that we look for an ID which is not present? If yes, than an Optional is a good solution, but I would doubt that in many case.

Whenever you attempt to load data by its ID, it must be present! There are hardly any cases where you guess or search for an ID. Such IDs are like references or pointers in a programming language: they must point to something and returning an ID which points to nothing is a very bad idea. A typical situation where you load data by its ID goes like this: You provide a list of data (maybe a result of a search) and you provide a detail view on a single entry. So, you show the list in your UI and on a click on of the elements, the details of ID XYZ-123 are shown. This set of data must be there! Don’t use an optional here!

Never return null

Back in the days (which means before Java 8), there was a rule which said that you shall never return null. This rule was always a bit tricky to follow as it might lead to a lot of hidden traps. People started to return empty objects, special objects, return codes and other crazy stuff. If you did this in the past and you are using Optionals now, you definitely improved! But you should still ask you, why there might be no result and if it is OK to have no result. Not only from a technical perspective but also from the business perspective.

Optional is just a new name for null.

When to use Optionals

The actual use case for Optionals is functional programming in Java 8. If you use this, you will filter, map or reduce data and you will often come to the point where there might be the possibility that no data exists. It’s a good idea to use Optionals here, as you often write this code in a fluent style. A null pointer is really ugly to handle here. But the main difference is another: You do a search or filtering which perfectly could have no result. This is the main point for using an Optional. Don’t use an Optional, because you don’t want to deal with null (you need to do it anyway later!), use it because you have a really good reason to return null.

Best regards,
Thomas