Chocolatey

If you are a Windows OS user and you would like to install your favorite software without downloading and launching the installer, you will like Chocolatey.

Chocolatey is a Machine Package Manager, somewhat like apt-get for linux OS, but built with Windows in mind.

   

You can find all about Chocolaty in this web page chocolatey.org.

In this post, I presents how to install Chromium with chocolaty without building it as described in the project web site www.chromium.org

Install chocolatey

To install chocolatey, run cmd.exe command prompt and paste the text below and press enter.

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin

Install chromium

To install chromium web browser, you have just to run this command line.

C:\> choco install chromium

Chocolaty provide many development and utilities software as packages. You have just to search for them in this link chocolatey.org/packages.

Posted in open source | Tagged , , , | Leave a comment

Develop a web application with AngularJS and Spring MVC

Nowadays customers have a rich web experience with Gmail, Google Apps, Facebook and Twitter. A basic server side rendered web pages doesn’t fit anymore to the new HMI (human-machine interface) needs.

AngularJs is one of the most successful front-end frameworks for RIA (Rich Internet Application Development) development.

   
Denver Art Museum / Daniel Libeskind

AngularJs encourages the use of the Model-View-Controller (MVC) design pattern to decouple the code and to separate concerns. Despite the Javascript language specificities, a JEE developer will appreciate having some best practice and design patterns that he’s familiar with.

This article illustrate how to integrate AngularJs to a Spring MVC project. I hope this article will help developers to take the plunge and start using AngularJs.

The sample project source code is available on this link github.com/samer-abdelkafi/ng-project.
The sample IHM Demo is available in this Link tomcat7-samerabdelkafi.rhcloud.com/ng-project.

1. Add AngularJs librery

I adopted Webjars as a way to manage static web resources via the Maven dependency management mechanism. This could be done by front package manager like Bower. Java projects have already Maven dependencies manager, we don’t need extra tool to manage front libraries dependencies.

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>angularjs</artifactId>
    <version>1.3.8</version>
</dependency>


Add ResourceHandler for webjars to your Spring configuration file if it isn’t already done.

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.mycompany.myproject.web.controller" })
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    // Non shown code
}

2. Develop the business logic

In this sample project, we have a simple business logic. The front-end get a list from a rest web service and display it.
The code bellow presents our business logic implementation.

Add a new javasvript file app.js.

angular
    .module('myApp', ['ngResource'])
    .service('UsersService', function ($log, $resource) {
        return {
            getAll: function () {
                var userResource = $resource('users', {}, {
                    query: {method: 'GET', params: {}, isArray: true}
                });
                return userResource.query();
            }
        }
    })
    .controller('UsersController', function ($scope, $log, UsersService) {
        $scope.users = UsersService.getAll();
    });

myApp : root module for the project.
UsersService : service for executing the http request
UsersController : controller executed when the page is loaded.

3. Develop the view part

AngularJs implements MVC pattern. The html page is the view part, the controller is developed client side by java script and the model is Json object to get from the server side.

Import AngularJs library to your Html code.

<!DOCTYPE html ng-app="myApp">
<html ng-controller="UsersController">
<!-- header code -->
<body>

<div ng-repeat="user in users">{{user.firstName}} {{user.familyName}}</div>

<script type="text/javascript" src="webjars/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript" src="webjars/angularjs/1.3.8/angular.min.js"></script>
<script type="text/javascript" src="webjars/angularjs/1.3.8/angular-resource.min.js"></script>
</body>
</html>

4. Deploy and run the application

Now we will deploy and run the application to verify the configuration.

5. Application enhancement

5.1 Design enhancement

To enhance the application design, we use twitter bootstrap librery with a material design theme.

  • first step, add dependency for jquery, bootstrap and bootstrap-material-design using webjars.
  • Next, import css and js files to the html page.
  • finally, modify html code for displaying the list.

5.2 Functional enhancement

AngularJS comes with many handy filters built-in. We use “filter:string” to add search function. All strings or objects with string properties in array that match this string will be returned.

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="webjars/bootstrap/3.2.0/css/bootstrap.css">
    <link rel="stylesheet" href="webjars/bootstrap-material-design/0.2.1/css/material.css">
    <title></title>
</head>
<body ng-controller="UsersController">

<div class="row">
    <br>
    <div class="container">
        <div id="userList" class="col-sm-offset-1 col-sm-10">
            <div class="input-group">
                <input class="form-control" id="search" name="search" placeholder="Search for" ng-model="query"
                       required="required"/>
              <span class="input-group-btn">
                  <button type="submit" class="btn btn-default">
                      <i class="glyphicon glyphicon-search"></i>
                  </button>
              </span>
            </div>
            <div class="list-group">
                <div class="list-group-item">
                    <div ng-repeat="user in users | filter:query" class="list-group-item" style="margin-top:16px">
                        <div class="row-picture">
                            <img class="circle"
                                 src="http://i.forbesimg.com/media/lists/people/{{user.firstName | lowercase}}-{{user.familyName | lowercase}}_50x50.jpg"
                                 alt="icon">
                        </div>
                        <div class="row-content">
                            <h4 class="list-group-item-heading">{{user.firstName}} {{user.familyName}}</h4>

                            <p class="list-group-item-text"><i class="glyphicon glyphicon-envelope"></i> {{user.email}}
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="webjars/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript" src="webjars/angularjs/1.3.8/angular.min.js"></script>
<script type="text/javascript" src="webjars/angularjs/1.3.8/angular-resource.min.js"></script>
<script type="text/javascript" src="webjars/bootstrap-material-design/0.2.1/js/material.js"></script>
<script type="text/javascript" src="resources/js/app.js"></script>
</body>
</html>

The picture bellow presents a print screen for the application.

I think AngularJs, is one of the best front-end framework. It has many great features like data binding, dependency injection, MVC pattern implementation and page templates.

The major new version 2.0 of AngularJS has a significant deference from version 1.X, but it doesn’t seem to have migration path. AngularJs developers will encounter a drastically different looking framework and will need to learn a new architecture.

Even though there is no compatibility with the version 2.0, actual version has many good features and it’s still a good choice as a front-end framework.

Posted in Architecture, Java, JEE, WEB | Tagged , , , , , , , , | 4 Comments

Beautify your Java web application with Bootstrap

Bootstrap is one of the most popular front-end framework for developing responsive web design. It includes buttons, form inputs, links, columns, and tons of other pre-formatted page objects.

The mixt of Bootstrap and Spring MVC gives a powerfull toolbox to develop a web application running in both desktop and mobile devices.

   

This post presents a very concise and easy way to integrate Bootstrap to a Spring MVC web project.

Add bootstrap to your project dependency

You can add Bootstrap to your project by downloading a zip file from the project web site http://getbootstrap.com, then unzip the content and copy it to the webapp resources directory.
But it is more interesting to get it as project a maven dependency to your project. This is made possible by the client-side web libraries webjars

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>3.2.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>2.1.1</version>
</dependency>

Bootstrap javascript components needs JQuery. That’s why Bootstrap has a dependency to JQuery.
In this post we made the choice to exclude Bootstrap version and to import 2.1.1 version of JQuery.
You can manage the version by defining a dependency management to the project pom.

Configure Spring

We need to add a resource handler for /webjars/** to associate it with classpath:/META-INF/resources/webjars/ located in the bootstrap-3.2.0.jar

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.mycompany.myproject.web.controller" })
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
.................
..............

}

Add a bootstrap reference to the web page.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1">
    <link rel='stylesheet' href='webjars/bootstrap/3.2.0/css/bootstrap.min.css'>
</head>
<body>
    
    <!-- YOUR CODE HERE -->

<script type="text/javascript" src="webjars/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="webjars/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>

Jboss config

JBoss has a specific library management and in some cases it can’t find files in webjars dependency.
This problem can be solved by unpackaging webjars jars using maven dependency plugin.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
        <execution>
            <id>unpack</id>
            <phase>compile</phase>
            <goals>
                 <goal>unpack</goal>
            </goals>
            <configuration>
                 <artifactItems>
                      <artifactItem>
                          <groupId>org.webjars</groupId>
                          <artifactId>bootstrap</artifactId>
                          <overWrite>false</overWrite>
                          <outputDirectory>${project.build.directory}/classes</outputDirectory>
                          <excludes>**/maven/**, **/*.MF</excludes>
                      </artifactItem>
                 </artifactItems>
            </configuration>
        </execution>
    </executions>
</plugin>

Samples and components

You can find many samples and plugins for bootstrap that can gives you inspiration for your web application design.
I recommend those sites and projects:

The picture bellow presents a screenshot for a demo web application using bootstrap.
user-list

Posted in JEE, WEB | Tagged , , , , , , , , , , | 1 Comment

Spring MVC – Full java based config

Spring MCV is a very powerful and flexible framework for web application development.

It doesn’t just implement the MVC pattern, it allows you to develop Rest web services.

   

This post presents a web project sample with a full java configuration using Spring MVC 4 and Servlet 3 api. The code source is available in this link.

This project implements client side for the persistence sample presented in Spring-Data-JPA article

1 – Add project dependenciesimlmplements

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.0.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

2 – Spring MVC config class

import org.springframework.context.annotation.*;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.mycompany.myproject.web.controller" })
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver jspViewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        bean.setPrefix("/WEB-INF/views/");
        bean.setSuffix(".jsp");
        return bean;
    }

    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver getMultipartResolver() {
        return new CommonsMultipartResolver();
    }

    @Bean(name = "messageSource")
    public ReloadableResourceBundleMessageSource getMessageSource() {
        ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
        resource.setBasename("classpath:messages");
        resource.setDefaultEncoding("UTF-8");
        return resource;
    }

}


3 – Webapp initializer

With servlet 3 API you can use a class to configure your web project instead of the classic web.xml file.
You have to check if your application server or your servlet container supports servlet 3 spec. For Tomcat you can have this information in this link:
tomcat.apache.org/whichversion

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;

public class WebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
        dispatcherServlet.register(MvcConfig.class);
            
        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
        
    }

 }


4 – Model class.

public class User {
 
    private Long id;

    private String firstName;

    private String familyName;

    private String email;

    // add extra attributes
    	
    // add getters and setters
	
}

5 – Add view as jsp page
We create a usersView.jsp page with code source bellow to display users list.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<div class="col-sm-offset-1 col-sm-10">

    <legend>
        <spring:message code="table.user.title" />
    </legend>

    <div>
        <table id="dataTable" class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th><spring:message code="table.user.id" /></th>
                    <th><spring:message code="table.user.firstName" /></th>
                    <th><spring:message code="table.user.falilyName" /></th>
                    <th><spring:message code="table.user.email" /></th>
                </tr>
            <thead>
            <tbody>
                <c:forEach var="u" items="${usersModel}">
                    <tr>
                        <td>${u.id}</td>
                        <td>${u.firstName}</td>
                        <td>${u.familyName}</td>
                        <td>${u.email}</td>
                    <tr>
                </c:forEach>
            </tbody>
        </table>
    </div>
</div>

6 – Develop your controller

The @Controller annotation indicates that a particular class serves the role of a controller.
The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
 
    /**
    * Request mapping for user
    */
    @RequestMapping(value = "users", method = RequestMethod.GET)
    public ModelAndView getUsersView() {
        ModelAndView mv= new ModelAndView("usersView");
        mv.addObject("usersModel", userService.findAll());
        return mv;
    }
    
    /**
    * Rest web service
    */
    @RequestMapping(value = "/usersList", method = RequestMethod.GET)
    public @ResponseBody List<UserDto> getUsersRest() {
        return userService.findAll();
    }
}

7 – Test web project
When building your project you may have maven error telling you that the web.xml file is missing.
You can fix it by configuring the maven war plugin as presented bellow.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
</plugin>

  • Test display users
    http://localhost:8080/myproject/users
    spring_mvc_test

  • Test rest web service
    http://localhost:8080/myproject/usersList
    You will get json reponse.

    [
        {
            "id": 1,
            "firstName": "adminName",
            "familyName": "adminFamily",
            "email": "admin@maycompany.com",
            "phone": "0033 1 23 45 67 89",
            "language": "en",
            "login": "admin",
            "password": "admin",
            "burthDate": null,
            "authorities": [
                {"id": 3, "name": "user"},
                {"id": 2, "name": "technical user"},
                {"id": 1, "name": "admin"}
            ],
            "enabled": true,
            "pictureId": null,
            "authoritiesAsString": "user, technical user, admin"
        },
        ..........
    ]
    

Posted in Java, JEE | Tagged , , , , , , , , | 9 Comments