New Angular 2 / Java Docker image

January 24, 2017 angular, docker, example, Spring Boot, tutorial No comments

Quick post to announce the new docker image of the angular / spring boot example.

https://hub.docker.com/r/javaee/angular2-java-hello-world/

Here the command to install locally: docker pull javaee/angular2-java-hello-world

The app is still very simple and it is visible here: http://mycv.host:8082.

You can start the docker image with the following command:
docker run --name angular -d -p 8080:8082 javaee/angular2-java-hello-world

The app will be visible on http://localhost:8080

I will add soon new features with the comments that explains how to implement them:
– Spring security
– Database
– REST unit tests
– Forms
– Complex pagination
– Machine learning

If you want to see something implemented you can write a comment.

Angular, Spring Boot, REST, Security and OAuth2 – Part 1 – How to protect your app

January 19, 2017 AngularJS, OAuth, Security, Spring Boot No comments

Project NewWebApp, requirements:

Architect : ‚We have to implement REST Services, everything should be stateless and the client is a JS Framework. All the last techs, isn’t it cool? And avoid cookies, they are not safe, they have a bad reputation and there are too many policies against them.‘

Business analyst: ‚There is a welcome page, the user has to login to access the local secured resources. I suggest to avoid cookies too, they are bad for the health and they can ruin our marketing campaign.’

You : ‚ No session?! Rest services?! No cookies?! How I verify the identity of the user? I have to request his identity at every request?‘

OAuth 2 can be a solution to your problem

The client has to login with the Authorization Server, this can be connected to your LDAP in the company or with an external service like Google or Amazon. This server generate a Token that is stored by the javascript client. This token has to be sent in every request from the client to your Java application. Your application ask to the server if the token is valid, in case it is affirmative the user has the authorization.
Here described the communication:

 

Where to store the token?

The cookies are not safe and they can give a lot of troubles. One solution is to store the token in the session storage of the browser. In this case when the user will close the browser the session will be closed.

saveMyToken(accessTokenYouReceivedFromTheServer) {
    yourService.$window.sessionStorage.setItem('myToken', accessTokenYouReceivedFromTheServer)
}

When you need it you can retrieve the token easily:

getMyStoredToken() {
yourService.$window.sessionStorage.getItem('myToken');
}

How to prepare a request with the token received from the server:

sendRequestToTheBackend() {
    return this.$http(method:'GET', url:'http://yourBackend/restResourceURL',
    headers: this.getHeaders()
})}

getHeaders() {
return {
'Authorization': 'Bearer ' + this.getMyStoredToken,
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}

What is this ‘Bearer’ thing? Here your answer

How to implement the complete solution? Soon I will update the Angular / Spring Boot tutorial with a simple implementation.

A simple Node.js REST server simulator for Testing

October 19, 2016 AngularJS, Demo Application, JSON, Node.js, REST, Uncategorized 2 comments

Problem

You are developing a client application (AngularJS) and you need to receive the data from a REST API service.
Often you don’t have the access to the remote service or it doesn’t have the required data for your tests (dinamically generated data).

A direct access to a test .json file is not possible from the client because of security restrictions of the browser (the browser should not be able to play with the filesystem).

Solution – Concept

A client app can request (GET) a pre-defined page to a local server and receive the JSON file for the test.
The server can be implemented in Node.js and it serves static files content as response to http requests.

 

Solution – Implementation

The code and the installation procedure are here: https://github.com/marco76/node_rest_server/

The structure of the code is very simple:

Here an example of response:

 

Solution – Details

The file server.js create a new http server and waits for http requests.
It instantiates a loaderModule that contain the class that will retrieve the JSON data.

// import the function from the module
    var loaderModule = require('./ResponseLoader.js');
    // create an instance of the prototype
    var loader = new loaderModule("loader");

    function requestService(request, response){
        // url == filename without extension 
        var url = request.url;
        
        // home page called
        if (url=="/"){
            url = "/index";
        }
        
        // call the method that load the static page 
        loader.load(url);
        
        // prepare the http response
        response.statusCode = 200;
        response.setHeader('Content-Type', 'application/json');
        // add the JSON content
        response.end(loader.getJson());
    }

The second important Javascript file is the function that receives the request to load a file and retrieves the content:

function ResponseLoader (name){

    // the content of the file is stored in this variable
    var json;

    // method that load the file on the base of the URL
    ResponseLoader.prototype.load = function(url){
        console.log("requested file: " + url);
        // url: hello -> file: [current directory]/json/hello.json
        fs.readFile( __dirname + '/json' +url+'.json', function (err, data) {
            if (err) {
                console.log('error');
                throw err;
            }
            // the content of the file is assigned to the variable
            json = data;

            console.log(name + " : " +data.toString());
        })
    };

    // give me the json content
    ResponseLoader.prototype.getJson = function (){
        console.log(name + " : return json");

        return json;
    };

The features are very basic but they can be easily extended. The code is modularized using the ‚module‘ feature of node.js.
If you come from Java / .NET : the import of modules is not standard in JavaScript until ECMAScript 6.

Scrum and Java projects. Why they tend to fail?

October 11, 2016 agile development, java, Project management, scrum No comments , ,

As consultant I saw a lot of client passionate about scrum:

‚Scrum works very well!‘ ‚Scrum sucks!‘ ‚We partially (?!) adopt Scrum‘ and so on.

Many people think that scrum is a methodology but in reality is only a framework.
Spring is a framework too. It sucks? It’s productive? Well it depends how you use it, how you know it. The same is true for every framework.

When the motivation goes away Scrum is counterproductive

I have seen teams that were simply not motivated to use it or simply bored after few weeks. The 15 (or more) minutes of daily meeting was a simple routine that required a simple answer for the greatest happiness of all the participants :

‚I worked on that feature. No blocking issues.‘

During those meeting I saw participants continuing to work at their laptop, eating, watching TV series (!), chatting with the neighbour, reading the news on the smartphone … but everybody was certainly multitasking and listening with attention the other talking.

The notion of (almost) done

What about the notion of done? ‘The task is done!‘ (Developer 1) ‚Cool! Update excel, if we have time somebody will do a peer review‘ (Developer 2). Result: the task was more or less ‚done’ and the peer review will be realized by the client on their validation system or, probably, on their production environment.

The issues in a Java project?

The more frequent issues in my experience are:

Communication between developers

most of the wonderful talent in IT are not the best in communication, scrum try to help but the human nature is hard to change.

Specifications and users

they change all the time, they are incomplete most of the time, they are often impossible to implement. Agile methodologies try to help. The notion of product owner helps a lot but the artifacts will continue to change. The users are becoming more and more client oriented consultants and are losing their specific business skills. The developer need a lot more business information. Every exception has to be managed, in development we often spend more time implementing solutions to problems that the user will never see. Invite a user in a technical meeting … he will get a new perspective on his own activity. The analysts? If you are lucky they were skilled developers, otherwise … good luck!

Time and budget

a sales guy sold a project based on an estimation of the total cost of the project based on a draft of business concept. A developer (that is not currently involved in the project) initially estimated the effort at 100 (‚it’s easy‘), the project manager added a risk margin of 50% (‚150 should be ok‘).
As we know the initial estimation is in 90% of the projects completely wrong. This issue is not solved by the common project frameworks that assume endless time or feature stop at the end of the time. The pure agile is good for internal and continuous development. When you face clients that pay for your solution endless budget and feature stop are simply not realistic.

Technical decisions

today there are hundreds of frameworks, every year a new trend impact the new development projects for few years. Those frameworks survive only a couple of years before to ‚disappear‘ but their cost is immense for many years : Flex, Grails, GWT, ExtJS, JSF, AngularJS (1.x) are a few example. The result is that the projects today are a toxic mix of old and new technologies glued together.

Technical skills

many developers know the syntax (Java, .Net, JS) and they are correctly qualified as ‚developers‘. The problem is that to build quality the syntax is not enough. You need to know the grammar and the rhetoric too. Is this enough? Not yet, ask 5 author to write a chapter of the same book. The result is inconsistency, repetition and so on. The architecture and the lead are very important in this context.

All developers equals? The team is not the sum

some (agile) theories say that the developers will find the best solution themselves in an agile context. Is it true? Not according to my experience. The alpha guys will try to impose their view, arguing if necessary. Without a lead everybody will fill his tasks without caring how the others are working. A structure in the code has to be implemented and somebody has to take the lead on this. The structure can be challenged to improve the quality and productivity. To improve the maintanability everybody in the team has to be able to read the code of the others.

Individualities

often the management think that all the developers are the same, same skills, same productivity. ‚We are late? We add 5 new developer for 2 weeks and the project is finished‘. The new Fordism applied to the development. In reality the situation is more similar to a football (or soccer or any other sport) team. Some people are excellent defenders but unskilled strikers. Soft skills, technical skills, personal constraints are important factors that can define the success or the failure of a project. If you have Messi and Ronaldo in your team you are lucky. If Messi will play as goalkeeper and Ronaldo as central defender … well … disaster announced.

Solutions?

‘Ok, thanks! We already know it. Do you have any practical solution?‘

Well scrum is a generic framework that can be used in a Java project as well in a house building project or prepare a new recipe.
A complete solution require time to be elaborated. There are some techniques that I can suggest to improve the work for/in a team. My question is the following:

To increase the quality of our Java (or language X) project why we don’t use a Java-oriented (or language X) dedicated framework?

You can leave any comment about your direct experience.

The Javascript and AngularJS build procedure

October 5, 2016 First Steps, javascript, Uncategorized 2 comments

A Java developer we have the good habits to split the building process of a project in steps.
In Javascript we use the same approach with some differences. An example of simplified build procedure:

Java build Angular / Javascript build
code code
compile transpile
test test
  concatenate
  minification
package package
deploy deploy

 

Differences between Java and Javascript
1. In Java we compile, in Javascript we transpile. This step is needed only if you are not using the scripting language of the target platform. If you use TypeScript you need to convert your code in a code compatible with your target interpreter (i.e. ECMA5).

2. Concatenation: when an application is distributed is easier to manage only one file than dozens. The concatenation is used to merge multiple files in only one. This is similar to the concept of FatJar in Java.

3. Minification: the code file used in a JS project contains many useless characters (for the interpreter). The minification process try to optimize the code reducing the size of the JS file. In Java is the compile that optimize the code.

Tools
In Java the common used tools for the building process are : maven, gradle and ant

In Javascript we can split this tools in 3 categories:
Package manager to handle the dependencies: npm, bower
Task Runners: Grunt, Gulp.js
Module bundlers: WebPack

Java and AngularJS 1.5x: Spring Boot tutorial

September 27, 2016 Demo Application, Intermediate, Uncategorized No comments , ,

Few months ago I created a demo application with Java EE, Angular JS and MongoDB. The article is here: http://javaee.ch/2016/03/14/openshift-angularjs-javaee-mongodb-css-mycv/

The result is visible here: myCv.host

I like a lot Angular 2 but I know that the market is still Angular 1.5x dominated. For this reason I will maintain and upgrade this demo, maybe using it to shows the differences between AngularJS and Angular 2.

I converted the example to be a simple auto deploy tomcat jar file. MongoDB has been replaced with H2. The Git Repository is here: https://github.com/marco76/myCv_spring

 

After ‘mvn package’ you can launch the application with this command: java –jar ./target/ROOT.jar

If you go to http://localhost:8080 you should see this:

mycv

The technical details will follow!

Angular JS and Java : dictionary

September 26, 2016 First Steps, Uncategorized No comments , ,

Angular and Java are full stack frameworks, for this reason the applications implemented with the 2 technologies tend to have similar logical layers.

The following table try to match the different terminology of Angular and Java. The match is not 100% correct but the goal is to help the developer to quickly find himself in the other technology.

AngularJS and Angular 2 Definition In Java
Template HTML with additional markup JSP or JSF page
Directive custom attributes for HTML custom tags in JSP, custom component in JSF
Model data showed in the view Model in Spring, Managed Bean in JSF
Scope context in where the model is stored Request / Session etc.
Filter formatting for the screen JSTL formatter in JSP, converter in JSF
Controller logic behind the screens @Controller in Spring, @RequestScoped
Injector retrieve object instances from the provider @Inject
Module container for a part of the app (services, directives, …) Package artifact
Service business logic @Service, @EJB

 

Don’t hesitate to suggest other terms or send corrections.

Deployment strategies for an Angular / Java application.

September 25, 2016 Intermediate, Uncategorized No comments

We want to show how to deploy an application that uses Java as back end and Angular as front end.
It’s a common problem to correctly integrate the 2 technologies because they have their own building system.
You have many options for the deployment.

Option 1. Java .war in 1 server

We use the traditional approach and we deploy our application in a Java EE / Servlet server.

The final maven build should place correctly the web resources as showed in the image:

Angular directory structure

In this case we called the package ROOT.war to deploy the package directly in the context root (e.g. http://localhost:8080/).

Option 2. Multiple servers

It’s even possible to manage the front end and the back end separately.
For the development this is maybe the easiest solution (node.js for the web and tomcat for the back end services).
The 2 servers can be on the same machine.

angular_2_servers

Java and JavaScript differences. Learn to think in JavaScript!

September 25, 2016 First Steps, Uncategorized No comments

When you switch from Java to JS and TypeScript is good to pay attention to this differences:

[Post in continuous improvement …]

1. Equals are not equals

Coming from Java pay attention to the comparison operators in JavaScript. They behave differently from Java!
TypeScript requires explicit conversions and is much more similar to Java.

JavaScript Comment JS Typescript
== 5 == 5 : true
5 == ‘5’: true
’’== 0 : true
Automatic conversion of the type 5 == 5 : true
5 == ‘5’: compiler error
’’== 0 : compiler error
=== 5 === 5 : true
5 === ‘5’: false
’’ === 0: false
Type and value are compared 5 === 5 : true
5 === ‘5’: compiler error
’’ === 0: compiler error

 

2. Null is not undefined

In Java ‘null’ values are assigned to objects without value or undefined.
In JS and TS a variable without value is ‘undefined’ but not ‘null’. null is a value and can be assigned to a variable.
To add more complexity:

null == undefined :  true
null === undefined : false
null == null : true
null === null: true
undefined === undefined : true

First docker version of the Java Spring Boot and Angular 2 ‘Hello World’ tutorial

September 20, 2016 Uncategorized 2 comments

I updated the basic example that you can find here: http://javaee.ch/2016/02/23/spring-boot-angularjs-2-typescript-hello-world-tutorial/

Now it is compatible with docker. You can download the first version of the dockerfile here:

https://github.com/marco76/SpringAngular2TypeScript/blob/master/Dockerfile

It’s only a first test and a lot of work is still needed but you can build it:

docker build -t my-java-app .

The source code and the dependencies are downloaded. When the build end you can launch the application:

docker run –rm -it -p 8080:8080  my-java-app java -jar /usr/src/myapp/angular2.jar

davis_1

You can see the result on localhost:8080

davis_2

 

Many people asked how to compile the project in eclipse … well, no need of eclipse or other IDE.
The procedure of creation of a unique war/jar is a bit complicated at the moment but only maven and npm are used. Typescript and npm compile the Angular files. Maven compile the java classes and build the jar/war including the backend (java) and frontend (javascript).

Personally I think that the frontend and backend should be developed in 2 separated projects.